auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void release() { if (state == State.RELEASED) { return; } state = State.RELEASED; try { container.release(deployment, instance); } finally { try { instanceManager.poolInstance(new ThreadContext(deployment, null), instance); } catch (OpenEJBException e) { <START> e.printStackTrace(); <END> } instance = null; } }</code><technical_language>logging instead</technical_language>

Target:
public void release() { if (state == State.RELEASED) { return; } state = State.RELEASED; try { container.release(deployment, instance); } finally { if (instance != null) { try { instanceManager.poolInstance(new ThreadContext(deployment, null), instance); } catch (OpenEJBException e) { LOGGER.error("Unable to add instance back to the pool", e); } } instance = null; } }
Source:
<code>protected boolean perform() { try { getParameters().setStartTime(new Date()); destinationHostLock = new EngineLock(hostLocking.getSetupNetworksLock(getDestinationVdsId())); <START> lockManager.acquireLockWait(destinationHostLock); <END> if (unplugPassthroughNics() && connectLunDisks(getDestinationVdsId()) && migrateVm()) { ExecutionHandler.setAsyncJob(getExecutionContext(), true); return true; } runningFailed(); return false; } catch (Exception e) { runningFailed(); throw e; } }</code><technical_language>If I understand correctly, purpose of patch is fix a specific problem - failure of migration of 'refreshCaps' failure a lock. is enough a waiting lock ActivateDeactivateVmIntefaceCommand calling refresh, instead of locking host for migration period. pass 'lockProperties.withScope(Scope.Execution).withWait(true)' 'lockProperties' of parameters pass 'RefreshHost' (the 'RefreshHost' pass 'RefreshCaps')</technical_language>

Target:
protected boolean perform() { try { getParameters().setStartTime(new Date()); if (unplugPassthroughNics() && connectLunDisks(getDestinationVdsId()) && migrateVm()) { ExecutionHandler.setAsyncJob(getExecutionContext(), true); return true; } runningFailed(); return false; } catch (Exception e) { runningFailed(); throw e; } }
Source:
<code>public CreatorBuilder url(String url) throws CardBuilderException { <START> boolean isValid = v.optional(v.notNullOrEmpty(url), "App store URL cannot be blank."); <END> if (isValid) { try { this.url = new URL(url); } catch (MalformedURLException e) { v.required(v.fail(), "Could not parse URL from url string."); } } return this; }</code><technical_language>warning string is incorrect</technical_language>

Target:
public CreatorBuilder url(String url) throws CardBuilderException { boolean isValid = v.optional(v.notNullOrEmpty(url), "Creator URL cannot be blank."); if (isValid) { try { this.url = new URL(url); } catch (MalformedURLException e) { v.required(v.fail(), "Could not parse URL from url string."); } } return this; }
Source:
<code>public void storeCommand() throws PersistenceException { cql = addUserConstraintToCql(user, cql); Function<List<Map<String, Object>>, Integer> listFunction = results -> { int count = 0; for (int i = 0; i < results.size(); i++) { Map<String, Object> curStore = PersistentItem.stripSuffixes(results.get(i)); console.println("Result {" + i + "}:"); if (headerSet.isEmpty()) { headerSet.addAll(curStore.keySet()); } for (String curKey : headerSet) { console.println(curKey + ":"); console.println("\t" + curStore.get(curKey).toString()); count++; } } return count; }; <START> long totalCount = getResults(listFunction); <END> console.println(""); console.println("Results found: " + totalCount + "\n"); }</code><technical_language>this command print +100k lines if a lot of items large items in persistent store? a default limit of lines print 10 a command option increase it</technical_language>

Target:
public void storeCommand() throws PersistenceException { cql = addUserConstraintToCql(user, cql); Function<List<Map<String, Object>>, Integer> noOp = results -> { return results.size(); }; long totalCount = getResults(noOp); if (totalCount > 100) { console.println("Results found: " + totalCount + "\n"); console.println("Narrow the search criteria below 100 results to print"); return; } Function<List<Map<String, Object>>, Integer> listFunction = results -> { for (int i = 0; i < results.size(); i++) { Map<String, Object> curStore = PersistentItem.stripSuffixes(results.get(i)); console.println("Result {" + i + "}:"); if (headerSet.isEmpty()) { headerSet.addAll(curStore.keySet()); } for (String curKey : headerSet) { console.println(curKey + ":"); console.println("\t" + curStore.get(curKey).toString()); } } return results.size(); }; totalCount = getResults(listFunction); console.println(""); console.println("Results found: " + totalCount + "\n"); }
Source:
<code>private void enableThing(Console console, ThingUID thingUID, boolean isEnabled) { if (thingRegistry.get(thingUID) == null) { <START> console.println("unknwon thing for thingUID '" + thingUID.getAsString() + "'."); <END> return; } thingManager.setEnabled(thingUID, isEnabled); String command = isEnabled ? "enabled" : "disabled"; console.println(thingUID.getAsString() + " successfully " + command + "."); }</code><technical_language>Typo: unknwon unknown</technical_language>

Target:
private void enableThing(Console console, ThingUID thingUID, boolean isEnabled) { if (thingRegistry.get(thingUID) == null) { console.println("unknown thing for thingUID '" + thingUID.getAsString() + "'."); return; } thingManager.setEnabled(thingUID, isEnabled); String command = isEnabled ? "enabled" : "disabled"; console.println(thingUID.getAsString() + " successfully " + command + "."); }
Source:
<code>public GlusterTaskInfoReturnForXmlRpc glusterVolumeRemoveBricksStart(String volumeName, String[] brickList, int replicaCount, Boolean forceRemove) { RequestBuilder rBuilder; <START> if(forceRemove) { <END> rBuilder = new RequestBuilder("GlusterVolume.removeBrickForce"); } else { rBuilder = new RequestBuilder("GlusterVolume.removeBrickStart"); } JsonRpcRequest request = rBuilder.withParameter("volumeName", volumeName) .withParameter("brickList", new ArrayList<String>(Arrays.asList(brickList))) .withParameter("replicaCount", replicaCount) .build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new GlusterTaskInfoReturnForXmlRpc(response); }</code><technical_language>String commandName = null; if (forceRemove) { commandName = "GlusterVolume.removeBrickForce"; else { commandName = "GlusterVolume.removeBrickStart"; } JsonRpcRequest request = new RequestBuilder(commandName).with</technical_language>

Target:
public GlusterTaskInfoReturnForXmlRpc glusterVolumeRemoveBricksStart(String volumeName, String[] brickList, int replicaCount, Boolean forceRemove) { String command = "GlusterVolume.removeBrickStart"; if(forceRemove) { command = "GlusterVolume.removeBrickForce"; } JsonRpcRequest request = new RequestBuilder(command).withParameter("volumeName", volumeName) .withParameter("brickList", new ArrayList<String>(Arrays.asList(brickList))) .withParameter("replicaCount", replicaCount) .build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new GlusterTaskInfoReturnForXmlRpc(response); }
Source:
<code>public String copyResourceStep(String filePath) { final Resource res = resource(filePath); try (InputStream in = res.asInputStream()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (OutputStream gz = new GZIPOutputStream(out)) { IOUtils.copy(in, gz); } <START> return String.format("sh '''base64 --decode << ENDOFFILE | gunzip > %1$s \n%2$s\nENDOFFILE'''\n", <END> res.getName(), new String(Base64.encodeBase64Chunked(out.toByteArray()))); } catch (IOException e) { throw new AssertionError(e); } }</code><technical_language>This duplicate Job#copyResource does</technical_language>

Target:
public String copyResourceStep(String filePath) { final Resource res = resource(filePath); return String.format("sh '''%s'''%n", copyResourceShell(res, res.getName())); }
Source:
<code>public void onReceive(Object message) { <START> if (message instanceof Object[]) { <END> Object messageAsArray = (Object[]) message; if (!(messageAsArray[0] instanceof Config)) { unhandled(message); } Object[] newMessage = new Object[] {messageAsArray[0], messageAsArray[1], getSender()}; boolean taskSent = false; for (ActorRef actorRef : this.pool.keySet()) { if (this.pool.get(actorRef)) { taskSent = true; actorRef.tell(newMessage, getSelf()); this.pool.put(actorRef, Boolean.FALSE); break; } } if (!taskSent) this.pool.keySet().iterator().next().tell(message, getSender()); } else if (message instanceof Message) { switch ((Message) message) { case AVAILABLE: this.pool.put(getSender(), Boolean.TRUE); break; default: unhandled(message); } } else unhandled(message); }</code><technical_language>Object[]</technical_language>

Target:
public void onReceive(Object message) { if (message instanceof ConfigActor) { boolean taskSent = false; ((ConfigActor)message).setClient(getSender()); for (ActorRef actorRef : this.pool.keySet()) { if (this.pool.get(actorRef)) { taskSent = true; actorRef.tell(message, getSelf()); this.pool.put(actorRef, Boolean.FALSE); break; } } if (!taskSent) this.pool.keySet().iterator().next().tell(message, getSender()); } else if (message instanceof Message) { switch ((Message) message) { case AVAILABLE: this.pool.put(getSender(), Boolean.TRUE); break; default: unhandled(message); } } else unhandled(message); }
Source:
<code>OracleConnection unwrapConnection( Connection cx ) throws SQLException { if (cx == null) { return null; } if ( cx instanceof OracleConnection ) { return (OracleConnection) cx; } try { Connection testCon = cx; do { UnWrapper unwrapper = uwMap.get(testCon.getClass()); if (unwrapper == null) { unwrapper = DataSourceFinder.getUnWrapper(testCon); if (unwrapper == null) { unwrapper = UNWRAPPER_NOT_FOUND; } uwMap.put(testCon.getClass(), unwrapper); } if (unwrapper == UNWRAPPER_NOT_FOUND) { break; } testCon = unwrapper.unwrap(testCon); if (testCon instanceof OracleConnection) { return (OracleConnection) testCon; } <START> } while (testCon != null); <END> if (cx instanceof Wrapper) { try { Wrapper w = cx; if (w.isWrapperFor(OracleConnection.class)) { return w.unwrap(OracleConnection.class); } } catch (Throwable t) { LOGGER.log(Level.FINER, "Failed to unwrap connection using java 6 facilities", t); } } } catch(IOException e) { throw (SQLException) new SQLException( "Could not obtain native oracle connection.").initCause(e); } throw new SQLException( "Could not obtain native oracle connection for " + cx.getClass()); }</code><technical_language>worried this one, if stumble a badly written un-wrapper (one in some case returns connection given) get out of loop. want guard</technical_language>

Target:
OracleConnection unwrapConnection( Connection cx ) throws SQLException { if (cx == null) { return null; } if ( cx instanceof OracleConnection ) { return (OracleConnection) cx; } try { Connection testCon = cx; Connection toUnwrap; do { UnWrapper unwrapper = uwMap.get(testCon.getClass()); if (unwrapper == null) { unwrapper = DataSourceFinder.getUnWrapper(testCon); if (unwrapper == null) { unwrapper = UNWRAPPER_NOT_FOUND; } uwMap.put(testCon.getClass(), unwrapper); } if (unwrapper == UNWRAPPER_NOT_FOUND) { break; } toUnwrap = testCon; testCon = unwrapper.unwrap(testCon); if (testCon instanceof OracleConnection) { return (OracleConnection) testCon; } } while (testCon != null && testCon != toUnwrap); if (cx instanceof Wrapper) { try { Wrapper w = cx; if (w.isWrapperFor(OracleConnection.class)) { return w.unwrap(OracleConnection.class); } } catch (Throwable t) { LOGGER.log(Level.FINER, "Failed to unwrap connection using java 6 facilities", t); } } } catch(IOException e) { throw (SQLException) new SQLException( "Could not obtain native oracle connection.").initCause(e); } throw new SQLException( "Could not obtain native oracle connection for " + cx.getClass()); }
Source:
<code>private void processListing(CertifiedProductDetailsDTO cp) { try { LOGGER.info("Retrieving listing information for (" + cp.getId() + ") " + cp.getChplProductNumber()); CertifiedProductSearchDetails listing = certifiedProductDetailsManager.getCertifiedProductDetails(cp.getId()); <START> if (curesUpdateService.isCuresUpdate(listing)) { <END> LOGGER.info("************************** Updating " + cp.getId() + " as Cures Updated **************************"); updateListingAsCuresUpdated(listing); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }</code><technical_language>This job needs add a line of "cures update = false" cures_update_event table for listings meet curesUpdate requirement, "cures update = true" currently _shouldn't_ add activity for listings "cures update = false" though; for set true</technical_language>

Target:
private void processListing(CertifiedProductDetailsDTO cp) { try { LOGGER.info("Retrieving listing information for (" + cp.getId() + ") " + cp.getChplProductNumber()); CertifiedProductSearchDetails listing = certifiedProductDetailsManager.getCertifiedProductDetails(cp.getId()); if (isListingActive(listing) && curesUpdateService.isCuresUpdate(listing)) { LOGGER.info("************************** Updating " + cp.getId() + " as Cures Updated **************************"); updateListingAsCuresUpdated(listing); } else { updateListingAsNotCuresUpdated(listing); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }
Source:
<code>private void lockImageInDb() { final DiskImage diskImage = getDiskImage(); TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); <START> diskImage.setImageStatus(ImageStatus.LOCKED); <END> ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); getCompensationContext().stateChanged(); return null; }); }</code><technical_language>needed, next statement handles in DB, do care if status changed in instance</technical_language>

Target:
private void lockImageInDb() { final DiskImage diskImage = getDiskImage(); TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); getCompensationContext().stateChanged(); return null; }); }
Source:
<code>public GetObjectResult call() throws Exception { try { final Ds3ClientHelpers helpers = getClientHelpers(); final Path filePath = Paths.get(prefix, objectName); LOG.info("Output path: " + filePath.toString()); <START> final Ds3Object ds3Obj = new Ds3Object(objectName.replace("\\", "/")); <END> if (sync && SyncUtils.FileExists(filePath)) { final Iterable<Contents> objects = helpers.listObjects(bucketName); for (final Contents obj : objects){ if (ds3Obj.getName().equals(obj.getKey())) { if (SyncUtils.NeedToSync(filePath, obj, false)) { LOG.info("Syncing new version of " + objectName); Transfer(helpers, ds3Obj); return new GetObjectResult("SUCCESS: Finished syncing object."); } else { LOG.info("No need to sync " + objectName); return new GetObjectResult("SUCCESS: No need to sync " + objectName); } } } } Transfer(helpers, ds3Obj); return new GetObjectResult("SUCCESS: Finished downloading object. The object was written to: " + filePath); } catch(final FailedRequestException e) { if(e.getStatusCode() == 500) { LOG.info(e.getMessage()); if (LOG.isInfoEnabled()) { e.printStackTrace(); } throw new CommandException( "Error: Cannot communicate with the remote DS3 appliance.", e); } else if(e.getStatusCode() == 404) { if (LOG.isInfoEnabled()) { e.printStackTrace(); } throw new CommandException( "Error: " + e.getMessage(), e); } else { if (LOG.isInfoEnabled()) { e.printStackTrace(); } throw new CommandException( "Error: Encountered an unknown error of ("+ e.getStatusCode() +") while accessing the remote DS3 appliance.", e); } } }</code><technical_language>This split out 1) a function get specific file interested 2) perform transfer</technical_language>

Target:
public GetObjectResult call() throws Exception { try { final Ds3ClientHelpers helpers = getClientHelpers(); final Path filePath = Paths.get(prefix, objectName); LOG.info("Output path: " + filePath.toString()); final Ds3Object ds3Obj = new Ds3Object(objectName.replace("\\", "/")); if (sync && Utils.fileExists(filePath)) { if (SyncUtils.needToSync(helpers, bucketName, filePath, ds3Obj.getName(), false)) { Transfer(helpers, ds3Obj); return new GetObjectResult("SUCCESS: Finished syncing object."); } else { return new GetObjectResult("SUCCESS: No need to sync " + objectName); } } Transfer(helpers, ds3Obj); return new GetObjectResult("SUCCESS: Finished downloading object. The object was written to: " + filePath); } catch(final FailedRequestException e) { if(e.getStatusCode() == 500) { LOG.info(e.getMessage()); if (LOG.isInfoEnabled()) { e.printStackTrace(); } throw new CommandException( "Error: Cannot communicate with the remote DS3 appliance.", e); } else if(e.getStatusCode() == 404) { if (LOG.isInfoEnabled()) { e.printStackTrace(); } throw new CommandException( "Error: " + e.getMessage(), e); } else { if (LOG.isInfoEnabled()) { e.printStackTrace(); } throw new CommandException( "Error: Encountered an unknown error of ("+ e.getStatusCode() +") while accessing the remote DS3 appliance.", e); } } }
Source:
<code>public void close() throws Exception <START> { <END> statisticsAggregation.close(); }</code><technical_language>yield (return). Operator do a ton of work single call, a query "unkillable"</technical_language>

Target:
public void close() throws Exception { statisticsAggregationOperator.close(); }
Source:
<code>public static @CheckForNull Fingerprint load(@NonNull byte[] md5sum) throws IOException { long start=0; if(logger.isLoggable(Level.FINE)) start = System.currentTimeMillis(); Fingerprint loaded = FingerprintStorage.get().load(md5sum); initFacets(loaded); if(logger.isLoggable(Level.FINE)) logger.fine("Loading fingerprint took "+(System.currentTimeMillis()-start)+"ms"); <START> return loaded; <END> }</code><technical_language>a good public API. need here? moved storage</technical_language>

Target:
static @CheckForNull Fingerprint load(@NonNull byte[] md5sum) throws IOException { return load(Util.toHexString(md5sum)); }
Source:
<code>private RowExpression inlineReferences(RowExpression expression, Assignments assignments, TypeProvider types) { if (isExpression(expression)) { <START> return castToRowExpression(inlineReferences(castToExpression(expression), assignments, types)); <END> } Function<VariableReferenceExpression, RowExpression> mapping = variable -> { if (assignments.get(variable) == null) { return variable; } return assignments.get(variable); }; return RowExpressionVariableInliner.inlineVariables(mapping, expression); }</code><technical_language>inline inlineReferences for Expression here? easier reason logic function</technical_language>

Target:
private RowExpression inlineReferences(RowExpression expression, Assignments assignments, TypeProvider types) { if (isExpression(expression)) { Function<VariableReferenceExpression, Expression> mapping = variable -> { if (assignments.get(variable) == null) { return new SymbolReference(variable.getName()); } return castToExpression(assignments.get(variable)); }; return castToRowExpression(ExpressionVariableInliner.inlineVariables(mapping, castToExpression(expression), types)); } return RowExpressionVariableInliner.inlineVariables(variable -> assignments.getMap().getOrDefault(variable, variable), expression); }
Source:
<code>protected Integer addToFacts( AggregatorFactory[] metrics, boolean deserializeComplexMetrics, boolean reportParseExceptions, InputRow row, AtomicInteger numEntries, TimeAndDims key, ThreadLocal<InputRow> rowContainer, Supplier<InputRow> rowSupplier ) throws IndexSizeExceededException { final Integer priorIndex = facts.get(key); Aggregator[] aggs; if (null != priorIndex) { aggs = concurrentGet(priorIndex); doAggregate(aggs, rowContainer, row, reportParseExceptions); } else { aggs = new Aggregator[metrics.length]; rowContainer.set(row); for (int i = 0; i < metrics.length; i++) { final AggregatorFactory agg = metrics[i]; aggs[i] = agg.factorize( selectors.get(agg.getName()) ); <START> aggs[i].aggregate(); <END> } rowContainer.set(null); final Integer rowIndex = indexIncrement.getAndIncrement(); concurrentSet(rowIndex, aggs); if (numEntries.get() >= maxRowCount && !facts.containsKey(key)) { throw new IndexSizeExceededException("Maximum number of rows [%d] reached", maxRowCount); } final Integer prev = facts.putIfAbsent(key, rowIndex); if (null == prev) { numEntries.incrementAndGet(); } else { aggs = concurrentGet(prev); doAggregate(aggs, rowContainer, row, reportParseExceptions); concurrentRemove(rowIndex); } } return numEntries.get(); }</code><technical_language>doAggregate proper exception handling for parseExceptions, handle also. call doAggregate(...) new aggs array instead</technical_language>

Target:
protected Integer addToFacts( AggregatorFactory[] metrics, boolean deserializeComplexMetrics, boolean reportParseExceptions, InputRow row, AtomicInteger numEntries, TimeAndDims key, ThreadLocal<InputRow> rowContainer, Supplier<InputRow> rowSupplier ) throws IndexSizeExceededException { final Integer priorIndex = facts.get(key); Aggregator[] aggs; if (null != priorIndex) { aggs = concurrentGet(priorIndex); doAggregate(aggs, rowContainer, row, reportParseExceptions); } else { aggs = new Aggregator[metrics.length]; factorizeAggs(metrics, aggs, rowContainer, row); doAggregate(aggs, rowContainer, row, reportParseExceptions); final Integer rowIndex = indexIncrement.getAndIncrement(); concurrentSet(rowIndex, aggs); if (numEntries.get() >= maxRowCount && !facts.containsKey(key)) { throw new IndexSizeExceededException("Maximum number of rows [%d] reached", maxRowCount); } final Integer prev = facts.putIfAbsent(key, rowIndex); if (null == prev) { numEntries.incrementAndGet(); } else { aggs = concurrentGet(prev); doAggregate(aggs, rowContainer, row, reportParseExceptions); concurrentRemove(rowIndex); } } return numEntries.get(); }
Source:
<code>@Override protected AbstractBinder getAuthBinder() { <START> final Set<Class<? extends Principal>> principalClassSet = new HashSet<>(); <END> principalClassSet.add(JsonPrincipal.class); principalClassSet.add(NullPrincipal.class); return new PolymorphicAuthValueFactoryProvider.Binder<Principal>(principalClassSet); }</code><technical_language>I ImmutableSet.of(JsonPrincipal.class, NullPrincipal.class) more terse</technical_language>

Target:
@Override protected AbstractBinder getAuthBinder() { return new PolymorphicAuthValueFactoryProvider.Binder<>( ImmutableSet.of(JsonPrincipal.class, NullPrincipal.class)); }
Source:
<code>public static Future<Boolean> tryUpdateAsync(final String transactionId) throws IOException { Future<Boolean> future = null; if (transactionExecutorMap.containsKey(transactionId)) { ExecutorService transactionUpdateExecutor = transactionExecutorMap.get(transactionId); future = transactionUpdateExecutor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Boolean result = false; try { if (transactionExecutorMap.containsKey(transactionId) && transactionMap.containsKey(transactionId)) { Transaction read = transactionMap.get(transactionId); synchronized (read) { Path transactionPath = path(transactionId); if (transactionPath != null && Files.exists(transactionPath)) { final Path json = transactionPath.resolve(JSON); try (OutputStream output = Files.newOutputStream(json)) { objectMapper().writeValue(output, read); } } result = true; } } else { } } catch (IOException exception) { <START> error(exception, "").log(); <END> } return result; } }); } return future; }</code><technical_language>Consider adding a context message error</technical_language>

Target:
public static Future<Boolean> tryUpdateAsync(final String transactionId) throws IOException { Future<Boolean> future = null; if (transactionExecutorMap.containsKey(transactionId)) { ExecutorService transactionUpdateExecutor = transactionExecutorMap.get(transactionId); future = transactionUpdateExecutor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Boolean result = false; try { if (transactionExecutorMap.containsKey(transactionId) && transactionMap.containsKey(transactionId)) { Transaction read = transactionMap.get(transactionId); synchronized (read) { Path transactionPath = path(transactionId); if (transactionPath != null && Files.exists(transactionPath)) { final Path json = transactionPath.resolve(JSON); try (OutputStream output = Files.newOutputStream(json)) { objectMapper().writeValue(output, read); } } result = true; } } else { } } catch (IOException exception) { logBuilder().error(exception, "tryUpdateAsync: unexpected error encountered"); } return result; } }); } return future; }
Source:
<code>private void findStartEngineUrl(String newLine) { if (newLine.contains("info page of Axon.ivy Engine") && !engineStarted.get()) { String url = StringUtils.substringBetween(newLine, "http://", "/"); <START> url = "http://" + url + "/"; <END> url += evaluateDefaultContext(url); context.log.info("Axon.ivy Engine runs on : " + url); context.properties.setMavenProperty(Property.TEST_ENGINE_URL, url); engineStarted.set(true); } }</code><technical_language>line ..</technical_language>

Target:
private void findStartEngineUrl(String newLine) { if (newLine.contains("info page of Axon.ivy Engine") && !engineStarted.get()) { String url = "http://" + StringUtils.substringBetween(newLine, "http://", "/") + "/"; url += evaluateDefaultContext(url); context.log.info("Axon.ivy Engine runs on : " + url); context.properties.setMavenProperty(Property.TEST_ENGINE_URL, url); engineStarted.set(true); } }
Source:
<code>GHAppCreateTokenBuilder(GitHub root, String apiUrlTail, Map<String, GHPermissionType> permissions) { this.root = root; this.apiUrlTail = apiUrlTail; <START> this.builder = root.retrieve().method("POST"); <END> withPermissions(builder, permissions); }</code><technical_language>root.retrieve() setting method create() method</technical_language>

Target:
GHAppCreateTokenBuilder(GitHub root, String apiUrlTail, Map<String, GHPermissionType> permissions) { this.root = root; this.apiUrlTail = apiUrlTail; this.builder = root.createRequest(); withPermissions(builder, permissions); }
Source:
<code>public static CsvIterator of(CharSource source, boolean headerRow, char separator) { ArgChecker.notNull(source, "source"); return Unchecked.wrap(() -> { BufferedReader reader = source.openBufferedStream(); if (!headerRow) { return new CsvIterator(reader, separator, ImmutableList.of(), ImmutableMap.of()); } <START> String line = reader.readLine(); <END> if (line == null) { throw new IllegalArgumentException("Could not read header row from empty CSV file"); } ImmutableList<String> headers = CsvFile.parseLine(line, separator); return new CsvIterator(reader, separator, headers, CsvFile.buildSearchHeaders(headers)); }); }</code><technical_language>If this line if-block throws exception reader closed</technical_language>

Target:
public static CsvIterator of(CharSource source, boolean headerRow, char separator) { ArgChecker.notNull(source, "source"); @SuppressWarnings("resource") BufferedReader reader = Unchecked.wrap(() -> source.openBufferedStream()); try { if (!headerRow) { return new CsvIterator(reader, separator, ImmutableList.of(), ImmutableMap.of()); } String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Could not read header row from empty CSV file"); } ImmutableList<String> headers = CsvFile.parseLine(line, separator); return new CsvIterator(reader, separator, headers, CsvFile.buildSearchHeaders(headers)); } catch (RuntimeException ex) { try { reader.close(); } catch (IOException ex2) { ex.addSuppressed(ex2); } throw ex; } catch (IOException ex) { try { reader.close(); } catch (IOException ex2) { ex.addSuppressed(ex2); } throw new UncheckedIOException(ex); } }
Source:
<code>public Object compute(Map<String, Object> combinedAggregators) { Object retVal = combinedAggregators.get(fieldName); <START> if (retVal == null) { <END> throw new ISE("Mismatch! Agg[%s] was not specified!", fieldName); } return retVal; }</code><technical_language>figure this out earlier. add a verifyFields(Set<String>) method postAggs verify fields wants recursively do for other PostAggs have</technical_language>

Target:
public Object compute(Map<String, Object> combinedAggregators) { return combinedAggregators.get(fieldName); }
Source:
<code>public void init() { try { final String filtersDirectoryString = APILocator.getFileAssetAPI().getRealAssetsRootPath() + File.separator + "server" + File.separator + "publishing-filters" + File.separator; final File basePath = new File(filtersDirectoryString); if (!basePath.exists()) { basePath.mkdir(); final String systemFiltersDirectory = "com" + File.separator + "dotcms" + File.separator + "publishing-filters" + File.separator; final String systemFiltersPathString = Thread.currentThread() .getContextClassLoader().getResource(systemFiltersDirectory).getPath(); final File systemFilters = new File(systemFiltersPathString); Files.list(systemFilters.toPath()).forEach(filter -> { try { Files.copy(filter, Paths.get(filtersDirectoryString + filter.getFileName())); } catch (IOException e) { Logger.error(this, e.getMessage(), e); } }); <START> Logger.debug(PushPublishFiltersInitializer.class, " dotcms filters files copied"); <END> } Logger.info(PushPublishFiltersInitializer.class, " ymlFiles are set under: " + filtersDirectoryString); Files.list(basePath.toPath()).forEach(this::loadFilter); } catch (IOException e) { Logger.error(this, e.getMessage(), e); } }</code><technical_language>supplier version Logger.debug(PushPublishFiltersInitializer.class, ()-> " dotcms filters files copied");</technical_language>

Target:
public void init() { try { final String filtersDirectoryString = APILocator.getFileAssetAPI().getRealAssetsRootPath() + File.separator + "server" + File.separator + "publishing-filters" + File.separator; final File basePath = new File(filtersDirectoryString); if (!basePath.exists()) { basePath.mkdir(); final String systemFiltersDirectory = "com" + File.separator + "dotcms" + File.separator + "publishing-filters" + File.separator; final String systemFiltersPathString = Thread.currentThread() .getContextClassLoader().getResource(systemFiltersDirectory).getPath(); final File systemFilters = new File(systemFiltersPathString); Files.list(systemFilters.toPath()).forEach(filter -> { try { Files.copy(filter, Paths.get(filtersDirectoryString + filter.getFileName())); } catch (IOException e) { Logger.error(this, e.getMessage(), e); } }); Logger.debug(PushPublishFiltersInitializer.class, ()->" dotcms filters files copied"); } Logger.info(PushPublishFiltersInitializer.class, " ymlFiles are set under: " + filtersDirectoryString); Files.list(basePath.toPath()).forEach(this::loadFilter); } catch (IOException e) { Logger.error(this, e.getMessage(), e); } }
Source:
<code>public InputStream getInputStream() { inputStream = provider.getInputStream(); <START> if (inputStream != null) { <END> inputStream = new FilterInputStream(inputStream) { @Override public int read(byte[] b, int off, int len) throws IOException { int bytes = super.read(b, off, len); byte[] payload = new byte[bytes]; System.arraycopy(b, off, payload, 0, bytes); if (logToStderr) { System.err.println(id + " to LSP4E:" + new String(payload)); } if (logToFile) { log("\n" + id + " to LSP4E:" + new String(payload)); } return bytes; } }; } return inputStream; }</code><technical_language>2 lines, instantiate a new FilterInputStream this method is asked. Instead, generated filtered inputstream stored a field returned if existing</technical_language>

Target:
public InputStream getInputStream() { if (inputStream != null) { return inputStream; } if (provider.getInputStream() != null) { inputStream = new FilterInputStream(provider.getInputStream()) { @Override public int read(byte[] b, int off, int len) throws IOException { int bytes = super.read(b, off, len); byte[] payload = new byte[bytes]; System.arraycopy(b, off, payload, 0, bytes); if (logToStderr) { System.err.println(id + " to LSP4E:" + new String(payload)); } if (logToFile) { log("\n" + id + " to LSP4E:" + new String(payload)); } return bytes; } }; } return inputStream; }
Source:
<code>public void assumeNotNullThrowsException() { try { <START> Object[] objects = {1, 2, null}; <END> assumeNotNull(objects); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { } }</code><technical_language>Please put this line of "try" block</technical_language>

Target:
public void assumeNotNullThrowsException() { Object[] objects = {1, 2, null}; assumeNotNull(objects); }
Source:
<code>public TotalItem(final String measureIdentifier, final Total total, final String attributeIdentifier) { <START> this(measureIdentifier, notNull(total.toString(), "total"), attributeIdentifier); <END> }</code><technical_language>if total == null</technical_language>

Target:
public TotalItem(final String measureIdentifier, final Total total, final String attributeIdentifier) { this(measureIdentifier, notNull(total, "total").toString(), attributeIdentifier); }
Source:
<code>public void channelLinked(ChannelUID channelUID) { <START> onLightStateChanged(null, getHueBridgeHandler().getLightById(lightId)); <END> }</code><technical_language>getHueBridgeHandler() potentially return null, it</technical_language>

Target:
public void channelLinked(ChannelUID channelUID) { HueBridgeHandler handler = getHueBridgeHandler(); if (handler != null) { onLightStateChanged(null, handler.getLightById(lightId)); } }
Source:
<code>GroupType(Repetition repetition, String name, OriginalType originalType, List<Type> fields, ID id) { super(name, repetition, originalType, id); <START> if (fields.size() == 0) { <END> throw new InvalidSchemaException("A group type can not be empty. Parquet does not support empty group without leaves. Empty group: " + name); } this.fields = fields; this.indexByName = new HashMap<String, Integer>(); for (int i = 0; i < fields.size(); i++) { indexByName.put(fields.get(i).getName(), i); } }</code><technical_language>isEmpty()</technical_language>

Target:
GroupType(Repetition repetition, String name, OriginalType originalType, List<Type> fields, ID id) { super(name, repetition, originalType, id); if (fields.isEmpty()) { throw new InvalidSchemaException("A group type can not be empty. Parquet does not support empty group without leaves. Empty group: " + name); } this.fields = fields; this.indexByName = new HashMap<String, Integer>(); for (int i = 0; i < fields.size(); i++) { indexByName.put(fields.get(i).getName(), i); } }
Source:
<code>public static String toECLRecord(FieldDef field) throws Exception { if (field.getFieldType() != FieldType.RECORD) { throw new Exception("Invalid record structure. Root object must of type Record"); } HashMap<String, String> recordDefinitionMap = new HashMap<String, String>(); String rootRecordName = getEClTypeDefinition(field, recordDefinitionMap); <START> String rootDefinition = recordDefinitionMap.get(rootRecordName); <END> recordDefinitionMap.remove(rootRecordName); rootDefinition = rootDefinition.replace(rootRecordName, "RD"); String definition = ""; for (HashMap.Entry<String, String> entry : recordDefinitionMap.entrySet()) { definition += "\n\n" + entry.getKey() + " := " + entry.getValue(); } definition += "\n\n" + rootDefinition; int numRecordDefinitions = 1; for (HashMap.Entry<String, String> entry : recordDefinitionMap.entrySet()) { definition = definition.replace(entry.getKey(), "RD" + numRecordDefinitions); numRecordDefinitions++; } return definition; }</code><technical_language>minor, trailing whitespaces removed. Eclipse, do a find "( )+\R" replaceALL "\R"</technical_language>

Target:
public static String toECLRecord(FieldDef field) throws Exception { if (field.getFieldType() != FieldType.RECORD) { throw new Exception("Invalid record structure. Root object must of type Record"); } HashMap<String, String> recordDefinitionMap = new HashMap<String, String>(); String rootRecordName = getEClTypeDefinition(field, recordDefinitionMap); String rootDefinition = recordDefinitionMap.get(rootRecordName); recordDefinitionMap.remove(rootRecordName); rootDefinition = rootDefinition.replace(rootRecordName, "RD"); StringBuilder sb = new StringBuilder(8192); for (HashMap.Entry<String, String> entry : recordDefinitionMap.entrySet()) { sb.append("\n\n"); sb.append(entry.getKey()); sb.append(" := "); sb.append(entry.getValue()); } sb.append("\n\n"); sb.append(rootDefinition); String definition = sb.toString(); int numRecordDefinitions = 1; for (HashMap.Entry<String, String> entry : recordDefinitionMap.entrySet()) { definition = definition.replace(entry.getKey(), "RD" + numRecordDefinitions); numRecordDefinitions++; } return definition; }
Source:
<code>private File makeJunction(File baseDir, File pointToDir) throws Exception { File junc = new File(baseDir, "testJunction"); Process p = Runtime.getRuntime().exec("cmd.exe /C \"mklink /J " + junc.getPath() + " " + pointToDir.getPath() + "\""); <START> p.waitFor(); <END> return junc; }</code><technical_language>check return code is zero - skip test if (Asume...)</technical_language>

Target:
private File makeJunction(File baseDir, File pointToDir) throws Exception { File junc = new File(baseDir, "test Junction"); String cmd = "mklink /J \"" + junc.getPath() + "\" \"" + pointToDir.getPath() + "\""; ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", cmd); pb.inheritIO(); Process p = pb.start(); assertEquals("Running mklink failed (cmd=" + cmd + ")", 0, p.waitFor()); return junc; }
Source:
<code>public void testPathFilterBucketedPartitionedTable() throws Exception { <START> final List<Column> partitionColumns = new ArrayList(); <END> partitionColumns.add(new Column(TEST_PARTITION_COLUMN_NAME, HIVE_INT, Optional.empty())); final Table partitionedTable = getTable(partitionColumns); final BackgroundHiveSplitLoader backgroundHiveSplitLoader = getBackgroundHiveSplitLoader(getFiles(), getPathTupleDomain(returnedPath), getBuckets(MAX_BUCKETS), partitionedTable); final HiveSplitSource hiveSplitSource = new HiveSplitSource(1, backgroundHiveSplitLoader, mockExecutor); backgroundHiveSplitLoader.start(hiveSplitSource); assertEquals(1, hiveSplitSource.getOutstandingSplitCount()); final List<ConnectorSplit> connectorSplits = hiveSplitSource.getNextBatch(1).get(); assertEquals(1, connectorSplits.size()); final HiveSplit connectorSplit = (HiveSplit) connectorSplits.get(0); assertEquals(returnedPath.toString(), connectorSplit.getPath()); }</code><technical_language>ImmutableList.of()</technical_language>

Target:
public void testPathFilterBucketedPartitionedTable() throws Exception { BackgroundHiveSplitLoader backgroundHiveSplitLoader = backgroundHiveSplitLoader( TEST_FILES, RETURNED_PATH_DOMAIN, ImmutableList.of(), PARTITIONED_TABLE, Optional.of( new HiveBucketHandle( getRegularColumnHandles(TEST_CONNECTOR_ID, PARTITIONED_TABLE), BUCKET_COUNT))); HiveSplitSource hiveSplitSource = hiveSplitSource(backgroundHiveSplitLoader); backgroundHiveSplitLoader.start(hiveSplitSource); assertEquals(1, hiveSplitSource.getOutstandingSplitCount()); List<ConnectorSplit> connectorSplits = hiveSplitSource.getNextBatch(1).get(); assertEquals(1, connectorSplits.size()); assertEquals(RETURNED_PATH.toString(), ((HiveSplit) connectorSplits.get(0)).getPath()); }
Source:
<code>public void validDiscoveryResultIfWithoutBaseUrl() throws ValidationException { <START> <END> RemoteDevice fsInternetRadioDeviceWithoutUrl = createDefaultFSInternetRadioDevice(null); final DiscoveryResult result = discoveryParticipant.createResult(fsInternetRadioDeviceWithoutUrl); assertThat("A result with wrong thingUID was created for a FSInternetRadio device without base URL", result.getThingUID(), is(new ThingUID(DEFAULT_RADIO_THING_UID))); assertThat("A result with wrong thingTypeUID was created for a FSInternetRadio device without base URL", result.getThingTypeUID(), is(FSInternetRadioBindingConstants.THING_TYPE_RADIO)); assertThat("A result with wrong manifacturer was created for a FSInternetRadio device without base URL", result.getProperties().get(FSInternetRadioBindingConstants.PROPERTY_MANUFACTURER), is(DEFAULT_RADIO_MANIFACTURER)); assertThat("A result with wrong model number was created for a FSInternetRadio device without base URL", result.getProperties().get(FSInternetRadioBindingConstants.PROPERTY_MODEL), is(DEFAULT_RADIO_MODEL_NUMBER)); }</code><technical_language>empty line</technical_language>

Target:
public void validDiscoveryResultIfWithoutBaseUrl() throws ValidationException { RemoteDevice fsInternetRadioDeviceWithoutUrl = createDefaultFSInternetRadioDevice(null); final DiscoveryResult result = discoveryParticipant.createResult(fsInternetRadioDeviceWithoutUrl); assertEquals(new ThingUID(DEFAULT_RADIO_THING_UID), result.getThingUID()); assertEquals(FSInternetRadioBindingConstants.THING_TYPE_RADIO, result.getThingTypeUID()); assertEquals(DEFAULT_RADIO_MANIFACTURER, result.getProperties().get(FSInternetRadioBindingConstants.PROPERTY_MANUFACTURER)); assertEquals(DEFAULT_RADIO_MODEL_NUMBER, result.getProperties().get(FSInternetRadioBindingConstants.PROPERTY_MODEL)); }
Source:
<code>public static String getWebHost(final IServer server) throws ExecutionException { final String serverType = server.getServerType().getId(); <START> final Object adapter = server.loadAdapter(ServerDelegate.class, null); <END> if (serverType.equals(OPENSHIFT_SERVER_TYPE)) { if(adapter instanceof IExtendedPropertiesProvider) { final IExtendedPropertiesProvider propertiesProvider = (IExtendedPropertiesProvider) adapter; try { final URL welcomePageURL = new URL(propertiesProvider.getExtendedProperties().getWelcomePageUrl()); return welcomePageURL.getHost(); } catch (MalformedURLException | GetWelcomePageURLException e) { throw new ExecutionException("Failed to retrieve the hostname for the selected server", e ); } } } return server.getHost(); }</code><technical_language>adapter loading done if block</technical_language>

Target:
public static String getWebHost(final IServer server) throws CoreException { return server.getHost(); }
Source:
<code>public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return map.compute(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { <START> return nullSafeValueHolder(remappingFunction.apply(k, vValueHolder.value())); <END> } }); }</code><technical_language>I wrong vValueHoder a null, if mapping for key</technical_language>

Target:
public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return map.compute(key, new BiFunction<K, ValueHolder<V>, ValueHolder<V>>() { @Override public ValueHolder<V> apply(final K k, final ValueHolder<V> vValueHolder) { return nullSafeValueHolder(remappingFunction.apply(k, vValueHolder == null ? null : vValueHolder.value())); } }); }
Source:
<code>public void sentNotification() { final String message = "Subject \n message body"; final String topic = "Test Topic"; final String sub = "Test Subject"; final String body = "Test Body"; final AmazonSNS aws = Mockito.mock(AmazonSNS.class); final SNSClient client = Mockito.mock(SNSClient.class); final PublishResult result = Mockito.mock(PublishResult.class); final PublishRequest request = Mockito .mock(PublishRequest.class); Mockito.doReturn(request).when(request) .withTopicArn(topic); Mockito.doReturn(request).when(request) .withMessage(body); Mockito.doReturn(request).when(request).withSubject(sub); Mockito.doReturn(aws).when(client).get(); Mockito.doReturn(result).when(aws).publish(request); new SNS(topic, client).announce(message); MatcherAssert.assertThat( result, Matchers.equalTo(aws.publish(request)) ); <START> MatcherAssert.assertThat( <END> request, Matchers.equalTo(request.withTopicArn(topic)) ); MatcherAssert.assertThat( request, Matchers.equalTo(request.withMessage(body)) ); MatcherAssert.assertThat( request, Matchers.equalTo(request.withSubject(sub)) ); Mockito.verify(aws, Mockito.atLeast(1)).publish(request); }</code><technical_language>do need assertions?</technical_language>

Target:
public void sentNotification() { final String message = "Subject \n message body"; final String topic = "Test Topic"; final AmazonSNS aws = Mockito.mock(AmazonSNS.class); final SNSClient client = Mockito.mock(SNSClient.class); final PublishResult result = Mockito.mock(PublishResult.class); final PublishRequest request = Mockito .mock(PublishRequest.class); Mockito.doReturn(aws).when(client).get(); Mockito.doReturn(result).when(aws).publish(request); new SNS(topic, client).announce(message); MatcherAssert.assertThat( aws.publish(request) , Matchers.equalTo(result) ); Mockito.verify(aws); }
Source:
<code>public void thePlatformShouldBufferAnUpdateDeviceCdmaSettingsResponseMessage( final Map<String, String> responseParameters) { final String deviceIdentification = (String) ScenarioContext.current() .get(PlatformKeys.KEY_DEVICE_IDENTIFICATION); final String correlationUid = (String) ScenarioContext.current().get(PlatformKeys.KEY_CORRELATION_UID); final OsgpResultType expectedResult = Enum.valueOf(OsgpResultType.class, responseParameters.get(PlatformKeys.KEY_RESULT)); LOGGER.info("THEN: Buffer UpdateCdmaSettingsResponse [correlationUid={}, deviceIdentification={}, result={}]", correlationUid, deviceIdentification, expectedResult); final UpdateDeviceCdmaSettingsAsyncRequest request = new UpdateDeviceCdmaSettingsAsyncRequest(); request.setDeviceId(deviceIdentification); request.setCorrelationUid(correlationUid); Wait.until(() -> { UpdateDeviceCdmaSettingsResponse response = null; try { response = this.client.getUpdateDeviceCdmaSettingsResponse(request); } catch (final Exception e) { } <START> assertNotNull(response); <END> assertEquals(expectedResult, response.getResult()); }); }</code><technical_language>include assert statements in try clause? add Assert.fail() in exception handler</technical_language>

Target:
public void thePlatformShouldBufferAnUpdateDeviceCdmaSettingsResponseMessage( final Map<String, String> responseParameters) { final String deviceIdentification = (String) ScenarioContext.current() .get(PlatformKeys.KEY_DEVICE_IDENTIFICATION); final String correlationUid = (String) ScenarioContext.current().get(PlatformKeys.KEY_CORRELATION_UID); final OsgpResultType expectedResult = Enum.valueOf(OsgpResultType.class, responseParameters.get(PlatformKeys.KEY_RESULT)); LOGGER.info("THEN: Buffer UpdateCdmaSettingsResponse [correlationUid={}, deviceIdentification={}, result={}]", correlationUid, deviceIdentification, expectedResult); final UpdateDeviceCdmaSettingsAsyncRequest request = new UpdateDeviceCdmaSettingsAsyncRequest(); request.setDeviceId(deviceIdentification); request.setCorrelationUid(correlationUid); Wait.until(() -> { UpdateDeviceCdmaSettingsResponse response = null; try { response = this.client.getUpdateDeviceCdmaSettingsResponse(request); } catch (WebServiceSecurityException | InterruptedException e) { } assertNotNull(response); assertEquals(expectedResult, response.getResult()); }); }
Source:
<code><START> public H getSectionHeader() { <END> if (isSectionHeader) return sectionHeader; return null; }</code><technical_language>getHeaderData getItem data need check for anything. need return is set in constructor. methods final well</technical_language>

Target:
public final H getSectionHeader() { return headerData; }
Source:
<code>private void cancelUpload(MediaModel oneUpload) { if (oneUpload != null) { SiteModel site = mSiteStore.getSiteByLocalId(oneUpload.getLocalSiteId()); if (site != null) { <START> dispatchCancelAction(oneUpload, mSiteStore.getSiteByLocalId(oneUpload.getLocalSiteId())); <END> } else { AppLog.i(AppLog.T.MEDIA, "Unexpected state, site is null. Skipping cancellation of " + "this request - MediaUploadService."); } } }</code><technical_language>reuse site here</technical_language>

Target:
private void cancelUpload(MediaModel oneUpload) { if (oneUpload != null) { SiteModel site = mSiteStore.getSiteByLocalId(oneUpload.getLocalSiteId()); if (site != null) { dispatchCancelAction(oneUpload, site); } else { AppLog.i(AppLog.T.MEDIA, "Unexpected state, site is null. Skipping cancellation of " + "this request - MediaUploadService."); } } }