auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public TestingJobManagerRunner createJobManagerRunner(JobGraph jobGraph, Configuration configuration, RpcService rpcService, HighAvailabilityServices highAvailabilityServices, HeartbeatServices heartbeatServices, JobManagerSharedServices jobManagerSharedServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) throws Exception { jobManagerRunnerCreationLatch.run(); TestingJobManagerRunner runner = super.createJobManagerRunner(jobGraph, configuration, rpcService, highAvailabilityServices, heartbeatServices, jobManagerSharedServices, jobManagerJobMetricGroupFactory, fatalErrorHandler); <START> if (jobMasterGateway != null) { runner.getJobMasterGateway().complete(jobMasterGateway); } <END> return runner; }</code><technical_language>this hack here. getJobMasterGateway return future</technical_language>

Target:
public TestingJobManagerRunner createJobManagerRunner(JobGraph jobGraph, Configuration configuration, RpcService rpcService, HighAvailabilityServices highAvailabilityServices, HeartbeatServices heartbeatServices, JobManagerSharedServices jobManagerSharedServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler) throws Exception { jobManagerRunnerCreationLatch.run(); TestingJobManagerRunner testingRunner = super.createJobManagerRunner( jobGraph, configuration, rpcService, highAvailabilityServices, heartbeatServices, jobManagerSharedServices, jobManagerJobMetricGroupFactory, fatalErrorHandler); TestingJobMasterGateway testingJobMasterGateway = new TestingJobMasterGatewayBuilder() .setRequestJobSupplier(() -> CompletableFuture.completedFuture(ArchivedExecutionGraph.createFromInitializingJob(jobGraph.getJobID(), jobGraph.getName(), JobStatus.RUNNING, null, 1337)) ).build(); testingRunner.completeJobMasterGatewayFuture(testingJobMasterGateway); return testingRunner; }
Source:
<code>public boolean isValid(ILaunchConfiguration config) { setErrorMessage(null); setMessage(null); if (gdbServer != null) { switch (gdbServer) { case JTAG_OPENOCD: if (groupcom.isDisposed()) { return true; } if (!isValidFileFieldEditor(fOpenOCDBinPath)) { return false; } if (ftdiDevice == FtdiDevice.CUSTOM) { if (!isValidFileFieldEditor(fOpenOCDConfigPath)) { return false; } } else { File cfg_file = new File(openocd_cfg_path); if (!cfg_file.exists()) { setErrorMessage("Default OpenOCD configuration file for this development system \'" + openocd_cfg_path + "\' must exist"); return false; } } break; case JTAG_ASHLING: if (groupcomashling.isDisposed()){ return true; } if (!isValidFileFieldEditor(fAshlingBinPath) || !isValidFileFieldEditor(fAshlingXMLPath)) { return false; } break; case NSIM: if (groupnsim.isDisposed()) { return true; } if (!isValidFileFieldEditor(fnSIMBinPath) || (fLaunchtcfButton.getSelection() && !isValidFileFieldEditor(fnSIMTCFPath)) || (fLaunchPropsButton.getSelection() && !isValidFileFieldEditor(fnSIMPropsPath))) { return false; } break; <START> default: <END> break; } } return true; }</code><technical_language>Throw error here</technical_language>

Target:
public boolean isValid(ILaunchConfiguration config) { setErrorMessage(null); setMessage(null); if (gdbServer != null) { switch (gdbServer) { case JTAG_OPENOCD: if (groupcom.isDisposed()) { return true; } if (!isValidFileFieldEditor(fOpenOCDBinPath)) { return false; } if (ftdiDevice == FtdiDevice.CUSTOM) { if (!isValidFileFieldEditor(fOpenOCDConfigPath)) { return false; } } else { File cfg_file = new File(openocd_cfg_path); if (!cfg_file.exists()) { setErrorMessage("Default OpenOCD configuration file for this development system \'" + openocd_cfg_path + "\' must exist"); return false; } } break; case JTAG_ASHLING: if (groupcomashling.isDisposed()){ return true; } if (!isValidFileFieldEditor(fAshlingBinPath) || !isValidFileFieldEditor(fAshlingXMLPath)) { return false; } break; case NSIM: if (groupnsim.isDisposed()) { return true; } if (!isValidFileFieldEditor(fnSIMBinPath) || (fLaunchtcfButton.getSelection() && !isValidFileFieldEditor(fnSIMTCFPath)) || (fLaunchPropsButton.getSelection() && !isValidFileFieldEditor(fnSIMPropsPath))) { return false; } break; case GENERIC_GDBSERVER: break; default: throw new IllegalArgumentException("Unknown enum value has been used"); } } return true; }
Source:
<code>public Mono<FunctionApp> createAsync() { if (this.isInCreateMode()) { if (inner().serverFarmId() == null) { withNewConsumptionPlan(); } if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) { withNewStorageAccount( this.manager().sdkContext().randomResourceName(name(), 20), <START> StorageAccountSkuType.fromSkuName(com.azure.resourcemanager.storage.models.SkuName.STANDARD_GRS)); <END> } } return super.createAsync(); }</code><technical_language>is existing StorageAccountSkuType.STANDARD_GRS</technical_language>

Target:
public Mono<FunctionApp> createAsync() { if (this.isInCreateMode()) { if (inner().serverFarmId() == null) { withNewConsumptionPlan(); } if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) { withNewStorageAccount( this.manager().sdkContext().randomResourceName(name(), 20), StorageAccountSkuType.STANDARD_GRS); } } return super.createAsync(); }
Source:
<code>private Mono<Void> handleFireAndForget(Payload payload) { Throwable err = checkAvailable(); if (err != null) { return Mono.error(err); } final int streamId = streamIdSupplier.nextStreamId(); ByteBuf requestFrame = RequestFireAndForgetFrameFlyweight.encode( allocator, streamId, false, payload.hasMetadata() ? payload.sliceMetadata().retain() : null, payload.sliceData().retain()); payload.release(); sendProcessor.onNext(requestFrame); return Mono.empty(); <START> } <END></code><technical_language>request* methods surrounded a try/catch catches a throwable if is exception handled. Like: Throwable err = checkAvailable(); if (err != null) { return Mono.error(err); } try { int streamId = streamIdSupplier.nextStreamId(); final UnboundedProcessor<ByteBuf> sendProcessor = this.sendProcessor; final ByteBuf requestFrame = RequestResponseFrameFlyweight.encode( allocator, streamId, false, payload.sliceMetadata().retain(), payload.sliceData().retain()); payload.release(); UnicastMonoProcessor<Payload> receiver = UnicastMonoProcessor.create(); receivers.put(streamId, receiver); sendProcessor.onNext(requestFrame); return receiver .doOnError(t -> sendProcessor.onNext(ErrorFrameFlyweight.encode(allocator, streamId, t))) .doFinally( s -> { if (s == SignalType.CANCEL) { sendProcessor.onNext(CancelFrameFlyweight.encode(allocator, streamId)); } receivers.remove(streamId); }); } catch (Throwable t) { throw Exceptions.propogate(t); }</technical_language>

Target:
private Mono<Void> handleFireAndForget(Payload payload) { Throwable err = checkAvailable(); if (err != null) { payload.release(); return Mono.error(err); } final int streamId = streamIdSupplier.nextStreamId(); return emptyUnicastMono() .doOnSubscribe( new OnceConsumer<Subscription>() { @Override public void acceptOnce(@Nonnull Subscription subscription) { ByteBuf requestFrame = RequestFireAndForgetFrameFlyweight.encode( allocator, streamId, false, payload.hasMetadata() ? payload.sliceMetadata().retain() : null, payload.sliceData().retain()); payload.release(); sendProcessor.onNext(requestFrame); } }); }
Source:
<code>private static int getPriority(final String severity) { int result = IMarker.PRIORITY_LOW; <START> if ("blocker".equalsIgnoreCase(severity) || "critical".equalsIgnoreCase(severity)) { <END> result = IMarker.PRIORITY_HIGH; } else if ("major".equalsIgnoreCase(severity)) { result = IMarker.PRIORITY_NORMAL; } else if ("minor".equalsIgnoreCase(severity) || "info".equalsIgnoreCase(severity)) { result = IMarker.PRIORITY_LOW; } return result; }</code><technical_language>a switch severity.toLowerCase more readable</technical_language>

Target:
private static int getPriority(final String severity) { switch (severity.toLowerCase(Locale.ENGLISH)) { case "blocker": case "critical": return IMarker.PRIORITY_HIGH; case "major": return IMarker.PRIORITY_NORMAL; case "minor": case "info": default: return IMarker.PRIORITY_LOW; } }
Source:
<code>String checkOutConnection() throws IOException { String connectionId = availableConnections.poll(); if (connectionId == null) { if (poolCount.incrementAndGet() <= maxConnectionsToHostPort) { connectionIdToPoolManager.put(selector .connect(new InetSocketAddress(host, port.getPort()), networkConfig.socketSendBufferBytes, networkConfig.socketReceiveBufferBytes, port.getPortType()), this); <START> connectionIdCount++; <END> } else { poolCount.decrementAndGet(); } } else { availableCount.decrementAndGet(); } return connectionId; }</code><technical_language>This is for consumption right if I wrong. So, increment connectionIdCount</technical_language>

Target:
String checkOutConnection() throws IOException { String connectionId = availableConnections.poll(); if (connectionId == null) { if (poolCount.incrementAndGet() <= maxConnectionsToHostPort) { connectionIdToPoolManager.put(selector .connect(new InetSocketAddress(host, port.getPort()), networkConfig.socketSendBufferBytes, networkConfig.socketReceiveBufferBytes, port.getPortType()), this); totalManagedConnectionsCount++; } else { poolCount.decrementAndGet(); } } else { availableCount.decrementAndGet(); } return connectionId; }
Source:
<code>public Map<SystemStreamPartition, String> getOffsetsAfter(Map<SystemStreamPartition, String> offsets) { <START> return new HashMap<>(); <END> }</code><technical_language>Do methods get used? If not, throw UnsupportedOperationException instead. Then, if them, quickly exception thrown</technical_language>

Target:
public Map<SystemStreamPartition, String> getOffsetsAfter(Map<SystemStreamPartition, String> offsets) { throw new UnsupportedOperationException("getOffsetsAfter not supported for AzureBlobSystemAdmin"); }
Source:
<code>public Map<String, Criterion> getKilledByTeamMappings() { <START> return killedByTeamMappings; <END> }</code><technical_language>this</technical_language>

Target:
public Map<String, Criterion> getKilledByTeamMappings() { return this.killedByTeamMappings; }
Source:
<code>public List<String> getNames() { <START> if (canAttackerRetreat() <END> || canAttackerRetreatSeaPlanes() || (battleState.isAmphibious() && (canAttackerRetreatPartialAmphib() || canAttackerRetreatAmphibPlanes()))) { return List.of(battleState.getAttacker().getName() + ATTACKER_WITHDRAW); } return List.of(); }</code><technical_language>Nitpicky - if a multi-line, I this cleaner a ternary. I context, easier, I suggest maintaining/reading code, easier grok a ternary. boolean extracted a helper method a simple tenary. WDYT</technical_language>

Target:
public List<String> getNames() { return isRetreatPossible() ? List.of(battleState.getAttacker().getName() + ATTACKER_WITHDRAW) : List.of(); }
Source:
<code>public static Map<String, byte[]> mapOfSerializableToByteArray(Map<String, Serializable> input) throws IOException { if (input == null) { return null; } HashMap<String, byte[]> answer = new HashMap<>(input.size()); for (Map.Entry<String, Serializable> entry : input.entrySet()) { answer.put(entry.getKey(), ObjectToByteConverter.ObjectStream.convert(entry.getValue())); } <START> return answer; <END> }</code><technical_language>replace this by: java return input.entrySet().stream.collect(Collectors.toMap(entry -> entry.getKey(), entry-> ObjectToByteConverter.ObjectStream.convert(entry.getValue())));</technical_language>

Target:
public static Map<String, byte[]> mapOfSerializableToByteArray(Map<String, Serializable> input) { if (input == null) { return null; } HashMap<String, byte[]> answer = new HashMap<>(input.size()); input.forEach((key, value) -> { try { answer.put(key, ObjectToByteConverter.ObjectStream.convert(value)); } catch (IOException e) { throw new RuntimeException("Error when converting variables to byte array ", e); } }); return answer; }
Source:
<code>private StoredCacheData readCacheData(File conf) throws IgniteCheckedException { try (InputStream stream = new BufferedInputStream(new FileInputStream(conf))) { return marshaller.unmarshal(stream, U.resolveClassLoader(igniteCfg)); } catch (IOException e) { throw new IgniteCheckedException("Failed to read cache configuration from disk for cache: " + conf.getAbsolutePath(), e); } catch (IgniteCheckedException e) { <START> if (e.getCause() != null && e.getCause() instanceof ClassNotFoundException) <END> throw new IgniteCheckedException("During cache configuration loading from given file occurred error. " + "Make sure that user library containing required class is valid. " + "If library is valid then delete cache configuration file and restart cache [file=" + conf.getAbsolutePath() + ']', e); else throw e; } }</code><technical_language>replaced X.hasCause(): 100% precise, work for this situation</technical_language>

Target:
private StoredCacheData readCacheData(File conf) throws IgniteCheckedException { try (InputStream stream = new BufferedInputStream(new FileInputStream(conf))) { return marshaller.unmarshal(stream, U.resolveClassLoader(igniteCfg)); } catch (IOException e) { throw new IgniteCheckedException("Failed to read cache configuration from disk for cache: " + conf.getAbsolutePath(), e); } catch (IgniteCheckedException e) { if (e.hasCause(ClassNotFoundException.class)) throw new IgniteCheckedException("An error occurred during cache configuration loading from file [file=" + conf.getAbsolutePath() + "]. You may want to remove the configuration file; cache will be running " + "after next node start if static Ignite Configuration contains correct configuration of this cache. " + "If it was started dynamically, you may need to start it again (all data will be present).", e); else throw e; } }
Source:
<code>public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { logger.entering(new Object[] { method, testResult }); try { if (ListenerManager.isCurrentMethodSkipped(this)) { logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG); return; } Class<?> cls = method.getTestMethod().getInstance().getClass(); final boolean isWebTestClass = cls.getAnnotation(WebTest.class) != null; final boolean isMobileTestClass = cls.getAnnotation(MobileTest.class) != null; final boolean isSeLionAnnotatedTestClass = isMobileTestClass || isWebTestClass; if (!method.isTestMethod() && !isSeLionAnnotatedTestClass) { return; } <START> if (isSeLionAnnotatedTestClass) { <END> if (!isValidBeforeCondition(method)) { return; } if (method.isTestMethod()) { if (isLowPriority(method)) { testSessionSharingRules(method); } else { return; } } } if (Grid.getTestSession() != null) { return; } AbstractTestSession testSession = TestSessionFactory.newInstance(method); Grid.getThreadLocalTestSession().set(testSession); InvokedMethodInformation methodInfo = TestNGUtils.getInvokedMethodInformation(method, testResult); testSession.initializeTestSession(methodInfo); if (!(testSession instanceof BasicTestSession)) { try { LocalGridManager.spawnLocalHub(testSession); } catch (NoClassDefFoundError e) { logger.log(Level.SEVERE, "You are trying to run a local server but are missing Jars. Do you have " + "SeLion-Grid and Selenium-Server in your CLASSPATH?", e); System.exit(1); } } } catch (Exception e) { logger.log(Level.WARNING, "An error occurred while processing beforeInvocation: " + e.getMessage(), e); } logger.exiting(); }</code><technical_language>PR good. is some opportunity for refactoring here. need is "isSeLionAnnotatedTestClass" put computation in a private method</technical_language>

Target:
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { logger.entering(new Object[] { method, testResult }); try { if (ListenerManager.isCurrentMethodSkipped(this)) { logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG); return; } if (!method.isTestMethod() && !isSeLionAnnotatedTestClass(method)) { return; } if (isSeLionAnnotatedTestClass(method)) { if (!isValidBeforeCondition(method)) { return; } if (method.isTestMethod()) { if (isLowPriority(method)) { testSessionSharingRules(method); } else { return; } } } if (Grid.getTestSession() != null) { return; } AbstractTestSession testSession = TestSessionFactory.newInstance(method); Grid.getThreadLocalTestSession().set(testSession); InvokedMethodInformation methodInfo = TestNGUtils.getInvokedMethodInformation(method, testResult); testSession.initializeTestSession(methodInfo); if (!(testSession instanceof BasicTestSession)) { try { LocalGridManager.spawnLocalHub(testSession); } catch (NoClassDefFoundError e) { logger.log(Level.SEVERE, "You are trying to run a local server but are missing Jars. Do you have " + "SeLion-Grid and Selenium-Server in your CLASSPATH?", e); System.exit(1); } } } catch (Exception e) { logger.log(Level.WARNING, "An error occurred while processing beforeInvocation: " + e.getMessage(), e); } logger.exiting(); }
Source:
<code>public void run() { int timeout = Integer.MAX_VALUE; int expired = 0; try { timeout = ConfigParser.parse().getInt("nodeRecycleThreadWaitTimeout"); } catch (ConfigParserException e) { } appendMsgToCustomLog("Started NodeRecycleThread to restart the node once all the sessions are completed."); <START> while ((getTotalUsed() > 0) && (expired < timeout)) { <END> try { Thread.sleep(1000); expired += 1; } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } if (expired >= timeout) { appendMsgToCustomLog("Timeout occurred while waiting for sessions to complete. Forcefully restarting the" + " node."); } else { appendMsgToCustomLog("All sessions are completed and restarting the node."); } shutdownNode(); }</code><technical_language>I point this loop suspect ill behaved tests. test for a hang a test</technical_language>

Target:
public void run() { LOGGER.entering(); running = true; int timeout = 0; int expired = 0; try { timeout = ConfigParser.parse().getInt("nodeRecycleThreadWaitTimeout"); } catch (ConfigParserException e) { } proxyLogger.fine("Started NodeRecycleThread with " + ((timeout == 0) ? "no" : "a " + timeout + " second") + " timeout for node " + nodeId); while (keepLooping(expired, timeout)) { try { sleep(1000); expired += 1; } catch (InterruptedException e) { if (running) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } running = false; proxyLogger.warning("NodeRecycleThread was interrupted."); LOGGER.exiting(); return; } } if (wasExpired(expired, timeout)) { proxyLogger.info("Timeout occurred while waiting for sessions to complete. Shutting down the node."); } else { proxyLogger.info("All sessions are complete. Shutting down the node."); } forceNodeShutdown(); LOGGER.exiting(); }
Source:
<code>public JcloudsSshMachineLocation obtain(Map<?,?> flags) throws NoMachinesAvailableException { ConfigBag setup = ConfigBag.newInstanceExtending(getConfigBag(), flags); Integer attempts = setup.get(MACHINE_CREATE_ATTEMPTS); if (attempts == null || attempts < 1) attempts = 1; for (int i = 0; i < attempts; i++) { try { return obtainImpl(flags, setup); } catch (PropagatedRuntimeException e) { LOG.warn("Attempt #{}/{} to obtain machine threw error: {}", new Object[]{i, attempts, e}); } } LOG.error("Failed to get VM after attempts.", attempts); <START> throw new NoMachinesAvailableException("Failed to get VM after "+attempts+" attempts. See logs."); <END> }</code><technical_language>include original error in new exception worth a plural check "attempt" + ( ? .. : "s" )</technical_language>

Target:
public JcloudsSshMachineLocation obtain(Map<?,?> flags) throws NoMachinesAvailableException { ConfigBag setup = ConfigBag.newInstanceExtending(getConfigBag(), flags); Integer attempts = setup.get(MACHINE_CREATE_ATTEMPTS); Exception lastThrownException = null; if (attempts == null || attempts < 1) attempts = 1; for (int i = 1; i <= attempts; i++) { try { return obtainOnce(flags, setup); } catch (RuntimeException e) { LOG.warn("Attempt #{}/{} to obtain machine threw error: {}", new Object[]{i, attempts, e}); lastThrownException = e; } } throw new NoMachinesAvailableException( String.format("Failed to get VM after %d attempt%s.", attempts, attempts == 1 ? "" : "s"), lastThrownException); }
Source:
<code>public void testInvalidOption() throws Exception { checkConfig.addAttribute("option", "invalid_option"); try { final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; <START> verify(checkConfig, getPath("InputSeparatorWrapAfter3904.java"), expected); <END> fail("exception expected"); } catch (CheckstyleException ex) { assertTrue(ex.getMessage().startsWith( "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + "Cannot set property 'option' to 'invalid_option' in module")); } }</code><technical_language>Separate file. Rename avoid misunderstanding. File name short information purpose</technical_language>

Target:
public void testInvalidOption() throws Exception { checkConfig.addAttribute("option", "invalid_option"); try { final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputSeparatorWrapForInvalidOption.java"), expected); fail("exception expected"); } catch (CheckstyleException ex) { assertTrue(ex.getMessage().startsWith( "cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker - " + "Cannot set property 'option' to 'invalid_option' in module")); } }
Source:
<code>protected void testExecute_nonExistentCourse_shouldFail() { StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); ______TS("course does not exist"); String[] nonExistingParams = new String[] { Const.ParamsNames.STUDENT_EMAIL, student1InCourse1.email, <START> Const.ParamsNames.COURSE_ID, "non-existent-course", <END> }; RegenerateStudentCourseLinksAction a = getAction(nonExistingParams); JsonResult result = getJsonResult(a); MessageOutput output = (MessageOutput) result.getOutput(); assertEquals(String.format(RegenerateStudentCourseLinksAction.STUDENT_NOT_FOUND, student1InCourse1.email, "non-existent-course"), output.getMessage()); assertEquals(HttpStatus.SC_NOT_FOUND, result.getStatusCode()); }</code><technical_language>good verify exist (in case for some reason typical bundle is changed something). assertNull(logic.getCourse("non-existent-course")); test case of existent student</technical_language>

Target:
protected void testExecute_nonExistentCourse_shouldFail() { StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); ______TS("course does not exist"); String[] nonExistingParams = new String[] { Const.ParamsNames.STUDENT_EMAIL, student1InCourse1.email, Const.ParamsNames.COURSE_ID, "non-existent-course", }; assertNull(logic.getCourse("non-existent-course")); RegenerateStudentCourseLinksAction a = getAction(nonExistingParams); JsonResult result = getJsonResult(a); MessageOutput output = (MessageOutput) result.getOutput(); assertEquals(String.format(RegenerateStudentCourseLinksAction.STUDENT_NOT_FOUND, student1InCourse1.email, "non-existent-course"), output.getMessage()); assertEquals(HttpStatus.SC_NOT_FOUND, result.getStatusCode()); }
Source:
<code>public static String join(String base, String... segments) { StringBuilder pathBuilder = new StringBuilder(); if (base != null && !base.isEmpty()) { if (base.charAt(base.length() - 1) == '/') { pathBuilder.append(base.substring(0, base.length() - 1)); } else { pathBuilder.append(base); } } <START> if (segments[0] != null) { <END> for (String segment : segments) { if (segment.charAt(0) != '/' && pathBuilder.length() > 0) { pathBuilder.append('/'); } if (segment.charAt(segment.length() - 1) == '/') { pathBuilder.append(segment.substring(0, segment.length() - 1)); } else { pathBuilder.append(segment); } } } return pathBuilder.toString(); }</code><technical_language>This is catch case calls UriUtil.join(base, null) I it? I if instead do like: for (String segment : segments) { if (segment[i] == null) { continue; } ... helpful cover this in UriUtil unit test</technical_language>

Target:
public static String join(String base, String... segments) { StringBuilder pathBuilder = new StringBuilder(); if (base != null && !base.isEmpty()) { if (base.charAt(base.length() - 1) == '/') { pathBuilder.append(base.substring(0, base.length() - 1)); } else { pathBuilder.append(base); } } int i = 0; for (String segment : segments) { i++; if (segments[i - 1] == null) { continue; } if (segment.charAt(0) != '/' && pathBuilder.length() > 0) { pathBuilder.append('/'); } if (segment.charAt(segment.length() - 1) == '/') { pathBuilder.append(segment.substring(0, segment.length() - 1)); } else { pathBuilder.append(segment); } } return pathBuilder.toString(); }
Source:
<code>private String getOperatorName(final String operatorCode) { final int boundary = operatorCode.length() -3; final String mnc = operatorCode.substring(boundary, operatorCode.length()); final String mcc = operatorCode.substring(0, boundary); <START> return OPERATOR_MAP.get(mcc).get(mnc).getOperator(); <END> }</code><technical_language>get() calls miss</technical_language>

Target:
private String getOperatorName(final String operatorCode) { if (null != operatorCode && operatorCode.length() >= 5) { final String mnc = operatorCode.substring(3, operatorCode.length()); final String mcc = operatorCode.substring(0, 3); Map<String, MccMncRecord> country = OPERATOR_MAP.get(mcc); if (null != country) { MccMncRecord match = country.get(mnc); if (null != match) { return match.getOperator(); } } } return null; }
Source:
<code>private void clearWorkerMetrics() { synchronized (workerEvalMiniBatchParams) { <START> workerEvalMiniBatchParams.clear(); <END> } }</code><technical_language>Is intended clear workerEvalEpochParams</technical_language>

Target:
private void clearWorkerMetrics() { synchronized (workerEvalMiniBatchParams) { workerEvalMiniBatchParams.clear(); } synchronized (workerEvalEpochParams) { workerEvalEpochParams.clear(); } }
Source:
<code>public static long getEntityId(String requestURL) { Matcher matcher = ENTITY_PATTERN.matcher(requestURL); if (!matcher.find()) { <START> return -1L; <END> } String entityId = matcher.group(1); if (entityId.toLowerCase().startsWith("syn")) { entityId = entityId.substring(3); } return Long.parseLong(entityId); }</code><technical_language>return null</technical_language>

Target:
public static Long getEntityId(String requestURL) { requestURL = requestURL.toLowerCase(); Matcher matcher = ENTITY_PATTERN.matcher(requestURL); if (!matcher.find()) { return null; } String entityId = matcher.group(1); if (entityId.startsWith("syn")) { entityId = entityId.substring(3); } return Long.parseLong(entityId); }
Source:
<code>public static StoragePool getStoragePool(Cluster cluster, AbstractBackendResource parent) { StoragePool pool = null; if (cluster.getDataCenter().isSetId()) { String id = cluster.getDataCenter().getId(); pool = parent.getEntity(StoragePool.class, VdcQueryType.GetStoragePoolById, new IdQueryParameters(new Guid(id)), "Datacenter: id=" + id); } else { pool = parent.getEntity(StoragePool.class, VdcQueryType.GetStoragePoolByDatacenterName, <START> new NameQueryParameters(cluster.getDataCenter().getName()), "Datacenter: name=" <END> + cluster.getDataCenter().getName()); cluster.getDataCenter().setId(pool.getId().toString()); } return pool; }</code><technical_language>please export cluster.getDataCenter().getName() a variable in places</technical_language>

Target:
public static StoragePool getStoragePool(Cluster cluster, AbstractBackendResource parent) { StoragePool pool = null; if (cluster.getDataCenter().isSetId()) { String id = cluster.getDataCenter().getId(); pool = parent.getEntity(StoragePool.class, VdcQueryType.GetStoragePoolById, new IdQueryParameters(new Guid(id)), "Datacenter: id=" + id); } else { String clusterName = cluster.getDataCenter().getName(); pool = parent.getEntity(StoragePool.class, VdcQueryType.GetStoragePoolByDatacenterName, new NameQueryParameters(clusterName), "Datacenter: name=" + clusterName); cluster.getDataCenter().setId(pool.getId().toString()); } return pool; }
Source:
<code>protected void addCNature(IProject project, IProgressMonitor monitor, boolean addMakeBuilder) throws CoreException { if (getWizard() instanceof ConversionWizard) { ConversionWizard cw = (ConversionWizard) getWizard(); <START> if (cw.getBuildSystemId() != null) { <END> CCorePlugin.getDefault().convertProjectToNewC(project, cw.getBuildSystemId(), monitor); } else { CCorePlugin.getDefault().convertProjectToC(project, monitor, cw.getProjectID()); } } }</code><technical_language>Sort of - this is unrelated change</technical_language>

Target:
protected void addCNature(IProject project, IProgressMonitor monitor, boolean addMakeBuilder) throws CoreException { if (getWizard() instanceof ConversionWizard) { ConversionWizard cw = (ConversionWizard) getWizard(); if (cw.getBuildSystemId() != null) CCorePlugin.getDefault().convertProjectToNewC(project, cw.getBuildSystemId(), monitor); else CCorePlugin.getDefault().convertProjectToC(project, monitor, cw.getProjectID()); } }
Source:
<code>public String toJson() { GSonData gd = new GSonData(); gd.candidates = candidates; <START> return GSON.toJson(gd).replaceAll(" ", " "); <END> }</code><technical_language>I tweaking pretty-print is error prone... this affect values. store minimized (my preference; jq pretty print display), store pretty-print modifications. Gson option change indent depth for pretty-printer... of both. this error prone replacing spaces beginning of line... I if issues wrapped strings in JSON</technical_language>

Target:
public String toJson() { GSonData gd = new GSonData(); gd.candidates = candidates; return GSON.toJson(gd); }
Source:
<code>private void ensureCapacity(long writeSize) throws IOException { if (segmentsByName.higherEntry(activeSegment.getName()) != null) { <START> return; <END> } long segmentCapacity = activeSegment.getCapacityInBytes(); if (segmentCapacity > remainingUnallocatedCapacity.get()) { metrics.overflowWriteError.inc(); throw new IllegalStateException( "There is no more capacity left in [" + dataDir + "]. Max capacity is [" + capacityInBytes + "]"); } if (writeSize > segmentCapacity - LogSegment.HEADER_SIZE) { metrics.overflowWriteError.inc(); throw new IllegalArgumentException("Write of size [" + writeSize + "] cannot be serviced because it is greater " + "than a single segment's capacity [" + (segmentCapacity - LogSegment.HEADER_SIZE) + "]"); } String lastSegmentName = segmentsByName.lastEntry().getKey(); String newSegmentName = LogSegmentNameHelper.getNextPositionName(lastSegmentName); File newSegmentFile = allocate(LogSegmentNameHelper.nameToFilename(newSegmentName), segmentCapacity); LogSegment newSegment = new LogSegment(newSegmentName, newSegmentFile, segmentCapacity, metrics, true); segmentsByName.put(newSegmentName, newSegment); }</code><technical_language>is this scenario</technical_language>

Target:
private void ensureCapacity(long writeSize) throws IOException { if (remainingUnallocatedSegments == 0) { metrics.overflowWriteError.inc(); throw new IllegalStateException( "There is no more capacity left in [" + dataDir + "]. Max capacity is [" + capacityInBytes + "]"); } long segmentCapacity = activeSegment.getCapacityInBytes(); if (writeSize > segmentCapacity - LogSegment.HEADER_SIZE) { metrics.overflowWriteError.inc(); throw new IllegalArgumentException("Write of size [" + writeSize + "] cannot be serviced because it is greater " + "than a single segment's capacity [" + (segmentCapacity - LogSegment.HEADER_SIZE) + "]"); } String newSegmentName = LogSegmentNameHelper.getNextPositionName(activeSegment.getName()); logger.info("Allocating new segment with name: " + newSegmentName); File newSegmentFile = allocate(LogSegmentNameHelper.nameToFilename(newSegmentName), segmentCapacity); LogSegment newSegment = new LogSegment(newSegmentName, newSegmentFile, segmentCapacity, metrics, true); segmentsByName.put(newSegmentName, newSegment); }
Source:
<code>public void add(RevCommit revCommit) { <START> assert null != revCommit; <END> checkWidget(); String shortSha1 = revCommit.getName().substring(0, 6); String message = shortSha1 + ": " + revCommit.getShortMessage(); combo.add(message); commits.add(new ComboCommitEnt(revCommit.getId(), message)); }</code><technical_language>org.eclipse.core.runtime.Assert.isNotNull(revCommit)</technical_language>

Target:
public void add(RevCommit revCommit) { Assert.isNotNull(revCommit); checkWidget(); String shortSha1 = revCommit.getName().substring(0, 6); String message = shortSha1 + ": " + revCommit.getShortMessage(); combo.add(message); commits.add(new ComboCommitEnt(revCommit.getId(), message)); }
Source:
<code>public InternalFetchConnection(PackTransport transport, final UploadPackFactory<C> uploadPackFactory, final C req, final Repository remote) throws TransportException { super(transport); final PipedInputStream in_r; final PipedOutputStream in_w; final PipedInputStream out_r; final PipedOutputStream out_w; try { in_r = new PipedInputStream(); in_w = new PipedOutputStream(in_r); out_r = new PipedInputStream() { { buffer = new byte[MIN_CLIENT_BUFFER]; } }; out_w = new PipedOutputStream(out_r); } catch (IOException err) { remote.close(); throw new TransportException(uri, JGitText.get().cannotConnectPipes, err); } worker = new Thread("JGit-Upload-Pack") { @Override public void run() { try { final UploadPack rp = uploadPackFactory.create(req, remote); rp.upload(out_r, in_w, null); } catch (ServiceNotEnabledException | ServiceNotAuthorizedException e) { } <START> catch (IOException err) { <END> err.printStackTrace(); } catch (RuntimeException err) { err.printStackTrace(); } finally { try { out_r.close(); } catch (IOException e2) { } try { in_w.close(); } catch (IOException e2) { } remote.close(); } } }; worker.start(); init(in_r, out_w); readAdvertisedRefs(); }</code><technical_language>combine this catching RuntimeException</technical_language>

Target:
public InternalFetchConnection(PackTransport transport, final UploadPackFactory<C> uploadPackFactory, final C req, final Repository remote) throws TransportException { super(transport); final PipedInputStream in_r; final PipedOutputStream in_w; final PipedInputStream out_r; final PipedOutputStream out_w; try { in_r = new PipedInputStream(); in_w = new PipedOutputStream(in_r); out_r = new PipedInputStream() { { buffer = new byte[MIN_CLIENT_BUFFER]; } }; out_w = new PipedOutputStream(out_r); } catch (IOException err) { remote.close(); throw new TransportException(uri, JGitText.get().cannotConnectPipes, err); } worker = new Thread("JGit-Upload-Pack") { @Override public void run() { try { final UploadPack rp = uploadPackFactory.create(req, remote); rp.upload(out_r, in_w, null); } catch (ServiceNotEnabledException | ServiceNotAuthorizedException e) { } catch (IOException | RuntimeException err) { err.printStackTrace(); } finally { try { out_r.close(); } catch (IOException e2) { } try { in_w.close(); } catch (IOException e2) { } remote.close(); } } }; worker.start(); init(in_r, out_w); readAdvertisedRefs(); }
Source:
<code>public Map<String, DbParameterAccessor> getAllColumns( final String tableOrViewName) throws SQLException { String qry = "SELECT COLUMNNAME AS COLUMN_NAME, COLUMNDATATYPE AS TYPE_NAME, " <START> + " ROW_NUMBER() OVER() AS ORDINAL_POSITION, " + <END> + DatabaseMetaData.procedureColumnIn + " AS COLUMN_TYPE " + "FROM SYS.SYSCOLUMNS WHERE REFERENCEID = " + "(SELECT TABLEID FROM SYS.SYSTABLES WHERE TABLENAME = ?)"; return fetchIntoParams(tableOrViewName.toUpperCase(), qry); }</code><technical_language>Hmm, new I issue in query... I rely rows order in absence of order clause. is COLUMNNUMBER column for that.</technical_language>

Target:
public Map<String, DbParameterAccessor> getAllColumns( final String tableOrViewName) throws SQLException { String qry = "SELECT COLUMNNAME AS COLUMN_NAME, COLUMNDATATYPE AS TYPE_NAME, " + " ROW_NUMBER() OVER() AS ORDINAL_POSITION, " + + DatabaseMetaData.procedureColumnIn + " AS COLUMN_TYPE " + "FROM SYS.SYSCOLUMNS WHERE REFERENCEID = " + "(SELECT TABLEID FROM SYS.SYSTABLES WHERE TABLENAME = ?)" + "ORDER BY COLUMNNUMBER"; return fetchIntoParams(tableOrViewName.toUpperCase(), qry); }
Source:
<code>public void verifyEmbedMapCode(embedMapDialogButtons button) { switch (button) { case small: waitForElementVisibleByElement(embedMapCodeSmall); break; case medium: waitForElementVisibleByElement(embedMapCodeMedium); break; case large: waitForElementVisibleByElement(embedMapCodeLarge); break; <START> } <END> }</code><technical_language>Add Pagelogging</technical_language>

Target:
public void verifyEmbedMapCode(embedMapDialogButtons button) { switch (button) { case small: waitForElementVisibleByElement(embedMapCodeSmall); break; case medium: waitForElementVisibleByElement(embedMapCodeMedium); break; case large: waitForElementVisibleByElement(embedMapCodeLarge); break; } PageObjectLogging.log("verifyEmbedMapCode", button + "embed map code was correctly displayed", true); }
Source:
<code>public ItemFile getItemFile(final ZipEntry zipEntry, final ZipFile zipFile) { Objects.requireNonNull(zipEntry, "A null ZIP entry was passed."); Objects.requireNonNull(zipFile, "A null ZIP file was passed."); return new ItemFile() { private ZipEntry itemEntry = zipEntry; private Image image = null; @Override public Object getItem() throws Exception { if (image == null) { image = createZippedImage(itemEntry, zipFile); } return ImageUtil.getScaledImage(image, getWidth(), getHeight()); <START> } <END> }; }</code><technical_language>caching scaled image long height/width change? do scale a lot</technical_language>

Target:
public ItemFile getItemFile(final ZipEntry zipEntry, final ZipFile zipFile) { Objects.requireNonNull(zipEntry, "A null ZIP entry was passed."); Objects.requireNonNull(zipFile, "A null ZIP file was passed."); return new ItemFile() { private ZipEntry itemEntry = zipEntry; private Image image = null; @Override public Object getItem() throws Exception { if (image == null) { image = ImageUtil.getScaledImage(createZippedImage(itemEntry, zipFile), getWidth(), getHeight()); } return image; } }; }
Source:
<code>protected static String extractTestXml(File xmlFile, String category, String definitionName) throws IOException, FileNotFoundException { StringBuilder xmlPart = new StringBuilder(); boolean started = false; try <START> (RandomAccessFile raf <END> = new RandomAccessFile(xmlFile, "r");) { String s = raf.readLine(); while (s != null) { if (s.equals("<Definition category=\"" + category + "\" name=\"" + definitionName + "\">")) { started = true; } if (started) { if (s.equals("</Definition>")) { break; } xmlPart.append(s); xmlPart.append('\n'); } s = raf.readLine(); } } return xmlPart.toString(); }</code><technical_language>this a bufferedRandomAccessFile? is called a lot more before</technical_language>

Target:
protected static String extractTestXml(File xmlFile, String category, String definitionName) throws IOException, FileNotFoundException { StringBuilder xmlPart = new StringBuilder(); boolean started = false; try (BufferedRandomAccessFile raf = new BufferedRandomAccessFile(xmlFile, "r");) { String s = raf.readLine(); while (s != null) { if (s.equals("<Definition category=\"" + category + "\" name=\"" + definitionName + "\">")) { started = true; } if (started) { if (s.equals("</Definition>")) { break; } xmlPart.append(s); xmlPart.append('\n'); } s = raf.readLine(); } } return xmlPart.toString(); }
Source:
<code>private void sendLargeFile(AbstractJournalStorageManager.JournalContent content, SimpleString pageStore, final long id, SequentialFile file, long maxBytesToSend) throws Exception { if (!enabled) return; if (!file.isOpen()) { file.open(); } final int size = 1024 * 1024; long fileSize = file.size(); int flowControlSize = 10; int packetsSent = 0; FlushAction action = new FlushAction(); long offset = 0; RandomAccessFile raf; FileChannel fileChannel = null; try { raf = new RandomAccessFile(file.getJavaFile(), "r"); fileChannel = raf.getChannel(); while (true) { long chunkSize = Math.min(size, fileSize - offset); int toSend = (int) chunkSize; if (chunkSize > 0) { if (chunkSize >= maxBytesToSend) { toSend = (int) maxBytesToSend; maxBytesToSend = 0; } else { maxBytesToSend = maxBytesToSend - chunkSize; } } logger.debug("sending " + toSend + " bytes on file " + file.getFileName()); sendSyncFileMessage(new ReplicationSyncFileMessage(content, pageStore, id, raf, fileChannel, offset, toSend), offset + toSend == fileSize); packetsSent++; offset += toSend; if (packetsSent % flowControlSize == 0) { flushReplicationStream(action); } if (toSend == 0 || maxBytesToSend == 0) break; } flushReplicationStream(action); } catch (Exception e) { if (fileChannel != null) <START> fileChannel.close(); <END> throw e; } finally { if (file.isOpen()) file.close(); } }</code><technical_language>raf? mark expected packet netty able register a listener close deallocate (after a successful/failed write)</technical_language>

Target:
private void sendLargeFile(AbstractJournalStorageManager.JournalContent content, SimpleString pageStore, final long id, SequentialFile file, long maxBytesToSend) throws Exception { if (!enabled) return; if (!file.isOpen()) { file.open(); } final int size = 1024 * 1024; long fileSize = file.size(); int flowControlSize = 10; int packetsSent = 0; FlushAction action = new FlushAction(); long offset = 0; RandomAccessFile raf = null; FileChannel fileChannel = null; try { raf = new RandomAccessFile(file.getJavaFile(), "r"); fileChannel = raf.getChannel(); while (true) { long chunkSize = Math.min(size, fileSize - offset); int toSend = (int) chunkSize; if (chunkSize > 0) { if (chunkSize >= maxBytesToSend) { toSend = (int) maxBytesToSend; maxBytesToSend = 0; } else { maxBytesToSend = maxBytesToSend - chunkSize; } } logger.debug("sending " + toSend + " bytes on file " + file.getFileName()); sendSyncFileMessage(new ReplicationSyncFileMessage(content, pageStore, id, raf, fileChannel, offset, toSend), offset + toSend == fileSize); packetsSent++; offset += toSend; if (packetsSent % flowControlSize == 0) { flushReplicationStream(action); } if (toSend == 0 || maxBytesToSend == 0) break; } flushReplicationStream(action); } catch (Exception e) { if (raf != null) raf.close(); throw e; } finally { if (file.isOpen()) file.close(); } }
Source:
<code>public int[] getSceneValue(String token, DSID dSID, String dSUID, String name, Short sceneId) { int[] value = { -1, -1 }; if (checkRequiredDevice(dSID, dSUID, name)) { try { String response = transport.execute(SimpleRequestBuilder.buildNewRequest(InterfaceKeys.JSON) .addRequestClass(ClassKeys.DEVICE).addFunction(FunctionKeys.GET_SCENE_VALUE) .addParameter(ParameterKeys.SCENE_ID, convertShortToString(sceneId)) .addParameter(ParameterKeys.DSID, getDsidString(dSID)).addParameter(ParameterKeys.DSUID, dSUID) .addParameter(ParameterKeys.NAME, name).addParameter(ParameterKeys.TOKEN, token) <START> .buildRequestString(), 4000, 20000); <END> JsonObject responseObj = JSONResponseHandler.toJsonObject(response); if (JSONResponseHandler.checkResponse(responseObj)) { JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj); if (obj != null && obj.get("value") != null) { value[0] = obj.get("value").getAsInt(); if (obj.get("angle") != null) { value[1] = obj.get("angle").getAsInt(); } return value; } } } catch (Exception e) { logger.debug("An exception occurred", e); } } return value; }</code><technical_language>magic numbers again? :)</technical_language>

Target:
public int[] getSceneValue(String token, DSID dSID, String dSUID, String name, Short sceneId) { int[] value = { -1, -1 }; if (checkRequiredDevice(dSID, dSUID, name)) { String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.DEVICE) .addFunction(FunctionKeys.GET_SCENE_VALUE).addDefaultDeviceParameter(token, dSID, dSUID, name) .addParameter(ParameterKeys.SCENE_ID, SimpleRequestBuilder.objectToString(sceneId)) .buildRequestString(), Config.DEFAULT_CONNECTION_TIMEOUT, Config.HIGH_READ_TIMEOUT); JsonObject responseObj = JSONResponseHandler.toJsonObject(response); if (JSONResponseHandler.checkResponse(responseObj)) { JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj); if (obj != null && obj.get(JSONApiResponseKeysEnum.VALUE.getKey()) != null) { value[GeneralLibConstance.SCENE_ARRAY_INDEX_VALUE] = obj.get(JSONApiResponseKeysEnum.VALUE.getKey()) .getAsInt(); if (obj.get(JSONApiResponseKeysEnum.ANGLE.getKey()) != null) { value[GeneralLibConstance.SCENE_ARRAY_INDEX_ANGLE] = obj .get(JSONApiResponseKeysEnum.ANGLE.getKey()).getAsInt(); } return value; } } } return value; }
Source:
<code>public void stop() { if (System.getenv("ZEPPELIN_FORCE_STOP") != null) { if (isRunning()) { logger.info("Kill interpreter process"); try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { <START> logger.warn("ignore the exception when shutting down"); <END> } } } }</code><technical_language>log exception</technical_language>

Target:
public void stop() { if (System.getenv("ZEPPELIN_FORCE_STOP") != null) { if (isRunning()) { logger.info("Kill interpreter process"); try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { logger.warn("ignore the exception when shutting down interpreter process.", e); } } } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OCFile file = getFile(); Bundle args = getArguments(); if (file == null) <START> file = args.getParcelable(FileDisplayActivity.EXTRA_FILE); <END> if (mAccount == null) mAccount = args.getParcelable(FileDisplayActivity.EXTRA_ACCOUNT); if (savedInstanceState == null) { if (file == null) { throw new IllegalStateException("Instanced with a NULL OCFile"); } if (mAccount == null) { throw new IllegalStateException("Instanced with a NULL ownCloud Account"); } } else { file = savedInstanceState.getParcelable(EXTRA_FILE); mAccount = savedInstanceState.getParcelable(EXTRA_ACCOUNT); } setFile(file); setHasOptionsMenu(true); }</code><technical_language>prefer { } in one-liners</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OCFile file = getFile(); Bundle args = getArguments(); if (file == null) { file = args.getParcelable(FileDisplayActivity.EXTRA_FILE); } if (mAccount == null) { mAccount = args.getParcelable(FileDisplayActivity.EXTRA_ACCOUNT); } if (savedInstanceState == null) { if (file == null) { throw new IllegalStateException("Instanced with a NULL OCFile"); } if (mAccount == null) { throw new IllegalStateException("Instanced with a NULL ownCloud Account"); } } else { file = savedInstanceState.getParcelable(EXTRA_FILE); mAccount = savedInstanceState.getParcelable(EXTRA_ACCOUNT); } setFile(file); setHasOptionsMenu(true); }