auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ListenableFuture<Void> updateProgress( @NonNull final Context context, @NonNull final UUID id, @NonNull final Data data) { final SettableFuture<Void> future = SettableFuture.create(); mTaskExecutor.executeOnBackgroundThread(new Runnable() { @Override public void run() { String workSpecId = id.toString(); Logger.get().info(TAG, String.format("Updating progress for %s (%s)", id, data)); mWorkDatabase.beginTransaction(); try { State state = mWorkDatabase.workSpecDao().getState(workSpecId); if (state != null && !state.isFinished()) { WorkProgress progress = new WorkProgress(workSpecId, data); mWorkDatabase.workProgressDao().insert(progress); } else { Logger.get().warning(TAG, String.format( <START> "Ignoring setProgress(...). WorkSpec (%s) has finished " + "execution.", <END> workSpecId)); } future.set(null); mWorkDatabase.setTransactionSuccessful(); } catch (Throwable throwable) { Logger.get().error(TAG, "Error updating Worker progress", throwable); future.setException(throwable); } finally { mWorkDatabase.endTransaction(); } } }); return future; }</code><technical_language>Update error message. state null</technical_language>

Target:
public ListenableFuture<Void> updateProgress( @NonNull final Context context, @NonNull final UUID id, @NonNull final Data data) { final SettableFuture<Void> future = SettableFuture.create(); mTaskExecutor.executeOnBackgroundThread(new Runnable() { @Override public void run() { String workSpecId = id.toString(); Logger.get().info(TAG, String.format("Updating progress for %s (%s)", id, data)); mWorkDatabase.beginTransaction(); try { State state = mWorkDatabase.workSpecDao().getState(workSpecId); if (state == null) { Logger.get().warning(TAG, String.format( "Ignoring setProgress(...). WorkSpec (%s) does not exist.", workSpecId)); } else if (state.isFinished()) { Logger.get().warning(TAG, String.format( "Ignoring setProgress(...). WorkSpec (%s) has finished " + "execution.", workSpecId)); } else { WorkProgress progress = new WorkProgress(workSpecId, data); mWorkDatabase.workProgressDao().insert(progress); } future.set(null); mWorkDatabase.setTransactionSuccessful(); } catch (Throwable throwable) { Logger.get().error(TAG, "Error updating Worker progress", throwable); future.setException(throwable); } finally { mWorkDatabase.endTransaction(); } } }); return future; }
Source:
<code>public void applyPlacement(final KVector offset) { if (layoutDirection.isHorizontal()) { applyHorizontalPlacement(offset); <START> <END> } else { applyVerticalPlacement(offset); } }</code><technical_language>Superfluous blank line :)</technical_language>

Target:
public void applyPlacement(final KVector offset) { if (layoutDirection.isHorizontal()) { applyPlacementForHorizontalLayout(offset); } else { applyPlacementVerticalForVerticalLayout(offset); } }
Source:
<code>private static void createMainGoloFile(File intoDir, String projectName) { final File mainGoloFile = new File(intoDir, "main.golo"); PrintWriter writer; try { writer = new PrintWriter(mainGoloFile, "UTF-8"); writer.println("module " + projectName); writer.println(""); writer.println("function main = |args| {"); writer.println(" println(\"Hello " + projectName + "!\")"); writer.println("}"); writer.close(); <START> } catch (FileNotFoundException e) { <END> System.err.println(e.getMessage()); } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } }</code><technical_language>..or propagate exceptions instead of swallowing them</technical_language>

Target:
private static void createMainGoloFile(File intoDir, String projectName) throws FileNotFoundException, UnsupportedEncodingException { File mainGoloFile = new File(intoDir, "main.golo"); PrintWriter writer = new PrintWriter(mainGoloFile, "UTF-8"); writer.println("module " + projectName); writer.println(""); writer.println("function main = |args| {"); writer.println(" println(\"Hello " + projectName + "!\")"); writer.println("}"); writer.close(); }
Source:
<code>public void start() { if (!started) { <START> Thread connectThread = new Thread(); <END> connectThread.setName("DubboZkclientConnector"); connectThread.setDaemon(true); connectThread.start(); try { client = completableFuture.get(timeout, TimeUnit.MILLISECONDS); } catch (Throwable t) { logger.error("Timeout! zookeeper server can not be connected in : " + timeout + "ms!", t); } started = true; } else { logger.warn("Zkclient has already been started!"); } }</code><technical_language>I Thread connectThread = new Thread(); is longer needed here, started ZkClient in async thread invoking CompletableFuture.supplyAsync</technical_language>

Target:
public void start() { if (!started) { try { client = completableFuture.get(timeout, TimeUnit.MILLISECONDS); } catch (Throwable t) { logger.error("Timeout! zookeeper server can not be connected in : " + timeout + "ms!", t); completableFuture.whenComplete(this::makeClientReady); } started = true; } else { logger.warn("Zkclient has already been started!"); } }
Source:
<code>public void testInjectionOfOperatorName() throws Exception { final LocalMode lma = LocalMode.newInstance(); StreamingApplication testApp = new StreamingApplication() { @Override public void populateDAG(DAG dag, Configuration conf) { MockInputOperator input = dag.addOperator("input", new MockInputOperator()); <START> GenericNodeTest.GenericOperator output = dag.addOperator("output", new GenericNodeTest.GenericOperator()); <END> dag.addStream("stream", input.output, output.ip1); } }; lma.prepareDAG(testApp, new Configuration()); LocalMode.Controller lc = lma.getController(); lc.runAsync(); long startTime = System.currentTimeMillis(); while (!foundOperatorName && System.currentTimeMillis() - startTime < 2000) { Thread.sleep(100); } Assert.assertTrue("operator name found", foundOperatorName); lc.shutdown(); }</code><technical_language>Critical catch. nice job @gauravgopi123</technical_language>

Target:
public void testInjectionOfOperatorName() throws Exception { final LocalMode lma = LocalMode.newInstance(); StreamingApplication testApp = new StreamingApplication() { @Override public void populateDAG(DAG dag, Configuration conf) { dag.addOperator("input", new MockInputOperator()); } }; lma.prepareDAG(testApp, new Configuration()); LocalMode.Controller lc = lma.getController(); lc.runAsync(); long startTime = System.currentTimeMillis(); while (operatorName == null && System.currentTimeMillis() - startTime < 2000) { Thread.sleep(100); } Assert.assertEquals("operator name", "input", operatorName); lc.shutdown(); }
Source:
<code><START> private void rebuildQuarks(final int nbAttributes, Boolean value) { <END> fQuarksAdded.ensureCapacity(nbAttributes); while (fQuarksAdded.size() < nbAttributes) { fQuarksAdded.add(value); } }</code><technical_language>clarify this a bit. Rebuild quarks? boolean represent</technical_language>

Target:
private void rebuildQuarks(final int nbAttributes, Boolean value) { fAddedQuarks.ensureCapacity(nbAttributes); while (fAddedQuarks.size() < nbAttributes) { fAddedQuarks.add(value); } }
Source:
<code>public AMQPMessage setAddress(SimpleString address) { this.address = address; <START> setProtonAddress(address.toString()); <END> return this; }</code><technical_language>is outer setAddress method used? AMQP Properties section is part of immutable bare message in general setting 'to' address in creating section if present. Exception cases protocol conversion, explicit a side effect unintended here</technical_language>

Target:
public AMQPMessage setAddress(SimpleString address) { this.address = address; createExtraProperties().putSimpleStringProperty(ADDRESS_PROPERTY, address); return this; }
Source:
<code>private void approve(RevisionResource rsrc, ChangeUpdate update, IdentifiedUser caller, Timestamp timestamp) throws OrmException { PatchSet.Id psId = rsrc.getPatchSet().getId(); List<PatchSetApproval> approvals = Lists.newArrayList( approvalsUtil.byPatchSet(dbProvider.get(), rsrc.getNotes(), psId)); PatchSetApproval submit = ApprovalsUtil.getSubmitter(psId, approvals); if (submit == null || submit.getAccountId() != caller.getAccountId()) { submit = new PatchSetApproval( new PatchSetApproval.Key( rsrc.getPatchSet().getId(), caller.getAccountId(), LabelId.SUBMIT), (short) 1, TimeUtil.nowTs()); approvals.add(submit); } submit.setValue((short) 1); submit.setGranted(timestamp); approvals = labelNormalizer.normalize(rsrc.getControl(), approvals); update.putApproval(submit.getLabel(), submit.getValue()); <START> update.submit(approvals); <END> dbProvider.get().patchSetApprovals().upsert(approvals); }</code><technical_language>I stamping submit record accepted submit rule, existing approvals</technical_language>

Target:
private BatchMetaDataUpdate approve(RevisionResource rsrc, ChangeUpdate update, IdentifiedUser caller, Timestamp timestamp) throws OrmException { PatchSet.Id psId = rsrc.getPatchSet().getId(); List<PatchSetApproval> approvals = approvalsUtil.byPatchSet(dbProvider.get(), rsrc.getNotes(), psId); Map<PatchSetApproval.Key, PatchSetApproval> byKey = Maps.newHashMapWithExpectedSize(approvals.size()); for (PatchSetApproval psa : approvals) { if (!byKey.containsKey(psa.getKey())) { byKey.put(psa.getKey(), psa); } } PatchSetApproval submit = ApprovalsUtil.getSubmitter(psId, byKey.values()); if (submit == null || submit.getAccountId() != caller.getAccountId()) { submit = new PatchSetApproval( new PatchSetApproval.Key( rsrc.getPatchSet().getId(), caller.getAccountId(), LabelId.SUBMIT), (short) 1, TimeUtil.nowTs()); byKey.put(submit.getKey(), submit); } submit.setValue((short) 1); submit.setGranted(timestamp); approvals = labelNormalizer.normalize(rsrc.getControl(), byKey.values()); update.putApproval(submit.getLabel(), submit.getValue()); dbProvider.get().patchSetApprovals().upsert(approvals); try { return saveToBatch(rsrc, update, approvals, timestamp); } catch (IOException e) { throw new OrmException(e); } }
Source:
<code>public void bundleChanged(BundleEvent event) { Bundle bundle = event.getBundle(); <START> String loggerName = (bundle != null) ? LOGGER_BUNDLE_EVENT + "." + bundle.getSymbolicName() : LOGGER_BUNDLE_EVENT; END> if (logReaderServiceFactory.isLoggable(bundle, loggerName, LogService.LOG_INFO)) { LoggerImpl logger = (LoggerImpl) systemBundleLog.getLogger(loggerName); int eventType = event.getType(); logger.log(bundle, event, null, LogService.LOG_INFO, getBundleEventTypeName(eventType), null, null); } }</code><technical_language>symbolic name null also. I add: String bsn = bundle == null ? null : bundle.getSymbolicName(); String loggerName = bsn == null ? LOGGER_BUNDLE_EVENT : LOGGER_BUNDLE_EVENT + "." bsn;</technical_language>

Target:
public void bundleChanged(BundleEvent event) { Bundle bundle = event.getBundle(); String bsn = (bundle == null) ? null : bundle.getSymbolicName(); String loggerName = (bsn == null) ? LOGGER_BUNDLE_EVENT : LOGGER_BUNDLE_EVENT + "." + bsn; if (logReaderServiceFactory.isLoggable(bundle, loggerName, LogService.LOG_INFO)) { LoggerImpl logger = (LoggerImpl) systemBundleLog.getLogger(loggerName); int eventType = event.getType(); logger.log(bundle, event, null, LogService.LOG_INFO, getBundleEventTypeName(eventType), null, null); } }
Source:
<code>public void createEcKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { getKeyClient(httpClient, serviceVersion); <START> createEcKeyRunner((expected) -> assertKeyEquals(expected, client.createEcKey(expected))); <END> }</code><technical_language>do for clients. suggestion createEcKeyRunner((expected) -> StepVerifier.create(client.createEcKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete());</technical_language>

Target:
public void createEcKey(HttpClient httpClient, KeyServiceVersion serviceVersion) { getKeyClient(httpClient, serviceVersion); createEcKeyRunner((expected) -> StepVerifier.create(client.createEcKey(expected)) .assertNext(response -> assertKeyEquals(expected, response)) .verifyComplete()); }
Source:
<code>public void acknowledgeAlert(@NonNull Alert alert, @NonNull Callback<List<String>> callback) { <START> alert.setId(alert.getId()); <END> savePipe(BackendPipes.Names.ALERT_ACKNOWLEDGE, alert, callback, Alert.class); }</code><technical_language>This sounds suspiciously wrong</technical_language>

Target:
public void acknowledgeAlert(@NonNull Alert alert, @NonNull Callback<List<String>> callback) { savePipe(BackendPipes.Names.ALERT_ACKNOWLEDGE, alert, callback); }
Source:
<code>public List<File> getExtensionsDirectories() { String path = getProperty("ENGINE_EXTENSION_PATH"); if (path == null) { <START> log.warn("No extension configurations directories were provided"); <END> return Collections.emptyList(); } List<File> results = new ArrayList<File>(); for (String currentPath : path.split(":")) { if (StringUtils.isNotBlank(currentPath)) { results.add(new File(currentPath)); } } return results; }</code><technical_language>need of warning is caller this infrastructure component</technical_language>

Target:
public List<File> getExtensionsDirectories() { String path = getProperty("ENGINE_EXTENSION_PATH"); if (path == null) { return Collections.emptyList(); } List<File> results = new ArrayList<File>(); for (String currentPath : path.split(":")) { if (StringUtils.isNotBlank(currentPath)) { results.add(new File(currentPath)); } } return results; }
Source:
<code>protected void execute(Job job, JobParameters jobParameters) <START> throws JobExecutionAlreadyRunningException, JobRestartException, <END> JobInstanceAlreadyCompleteException, JobParametersInvalidException { JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.taskJobExplorer).getNextJobParameters(job).toJobParameters(); JobExecution execution = this.taskJobLauncher.run(job, nextParameters); if (this.taskApplicationEventPublisher != null) { this.taskApplicationEventPublisher.publishEvent(new JobExecutionEvent(execution)); } this.jobExecutionList.add(execution); if (execution.getExitStatus().getExitCode().equals(ExitStatus.FAILED.getExitCode())) { throwJobFailedException(Collections.singletonList(execution)); } }</code><technical_language>Wrong status. validating batch status...not exit code</technical_language>

Target:
protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { String jobName = job.getName(); JobParameters parameters = jobParameters; boolean jobInstanceExists = this.taskJobRepository.isJobInstanceExists(jobName, parameters); if (jobInstanceExists) { JobExecution lastJobExecution = this.taskJobRepository .getLastJobExecution(jobName, jobParameters); if (lastJobExecution != null && isStoppedOrFailed(lastJobExecution) && job.isRestartable()) { JobParameters previousParameters = lastJobExecution.getJobParameters(); JobParameters previousIdentifyingParameters = removeNonIdentifying( previousParameters); parameters = merge(previousIdentifyingParameters, jobParameters); } } else { JobParametersIncrementer incrementer = job.getJobParametersIncrementer(); if (incrementer != null) { JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.taskJobExplorer).getNextJobParameters(job).toJobParameters(); parameters = merge(nextParameters, jobParameters); } } JobExecution execution = this.taskJobLauncher.run(job, parameters); if (this.taskApplicationEventPublisher != null) { this.taskApplicationEventPublisher.publishEvent(new JobExecutionEvent(execution)); } this.jobExecutionList.add(execution); if (execution.getStatus().equals(BatchStatus.FAILED)) { throwJobFailedException(Collections.singletonList(execution)); } }
Source:
<code>private static Optional<Expression> searchForBadCsrfSettingInDictionary(DictionaryLiteral dict) { return dict.elements().stream() <START> .filter(KeyValuePair.class::isInstance) <END> .map(KeyValuePair.class::cast) .filter(kvp -> checkedCast(StringLiteral.class, kvp.key()) .filter(strLit -> "csrf".equals(strLit.trimmedQuotesValue())) .isPresent()) .findFirst() .filter(kvp -> Expressions.isFalsy(kvp.value())) .map(KeyValuePair::value); }</code><technical_language>I rely Kind</technical_language>

Target:
private static Optional<Expression> searchForBadCsrfSettingInDictionary(DictionaryLiteral dict) { return dict.elements().stream() .filter(e -> e.is(Tree.Kind.KEY_VALUE_PAIR)) .map(KeyValuePair.class::cast) .filter(kvp -> Optional.ofNullable(kvp.key()) .filter(s -> s.is(Tree.Kind.STRING_LITERAL) && "csrf".equals(((StringLiteral) s).trimmedQuotesValue())) .isPresent()) .findFirst() .filter(kvp -> Expressions.isFalsy(kvp.value())) .map(KeyValuePair::value); }
Source:
<code>public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { <START> if (segments.contains((Object) segmentId)) { <END> finishedSegments.add((Integer) segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }</code><technical_language>implement in IntSet methods avoid this casts (un)boxing</technical_language>

Target:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains(segmentId)) { finishedSegments.add(segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }
Source:
<code>public Class< ? > getType() { <START> Class<?> clazz; <END> if (this.parameterType instanceof Class) { clazz = (Class) this.parameterType; } else if (this.parameterType instanceof ParameterizedType) { clazz = (Class) ((ParameterizedType) this.parameterType).getRawType(); } else { clazz = String.class; } return clazz; }</code><technical_language>ReflectionUtils#getTypeClass(Type), I forgotten this method</technical_language>

Target:
public Class<?> getType() { Class<?> type = ReflectionUtils.getTypeClass(this.parameterType); if (type == null) { type = String.class; } return type; }
Source:
<code>public JsonArrayBuilder handleDirectory(DataverseRequest dataverseRequest, File dir, ImportUtil.ImportType importType, PrintWriter validationLog, PrintWriter cleanupLog, Boolean createDV) throws ImportException{ JsonArrayBuilder status = Json.createArrayBuilder(); Dataverse owner = dataverseService.findByAlias(dir.getName()); if (owner == null ) { if (createDV) { System.out.println("creating new dataverse: " + dir.getName()); owner = importService.createDataverse(dir.getName(), dataverseRequest); } else { throw new ImportException("Can't find dataverse with identifier='" + dir.getName() + "'"); } } for (File file : dir.listFiles()) { <START> if(null!=file) <END> { if (!file.isHidden()) { try { JsonObjectBuilder fileStatus = importService.handleFile(dataverseRequest, owner, file, importType, validationLog, cleanupLog); status.add(fileStatus); } catch (ImportException | IOException e) { status.add(Json.createObjectBuilder().add("importStatus", "Exception importing " + file.getName() + ", message = " + e.getMessage())); } } } } return status; }</code><technical_language>huh</technical_language>

Target:
public JsonArrayBuilder handleDirectory(DataverseRequest dataverseRequest, File dir, ImportUtil.ImportType importType, PrintWriter validationLog, PrintWriter cleanupLog, Boolean createDV) throws ImportException{ JsonArrayBuilder status = Json.createArrayBuilder(); Dataverse owner = dataverseService.findByAlias(dir.getName()); if (owner == null ) { if (createDV) { System.out.println("creating new dataverse: " + dir.getName()); owner = importService.createDataverse(dir.getName(), dataverseRequest); } else { throw new ImportException("Can't find dataverse with identifier='" + dir.getName() + "'"); } } for (File file : dir.listFiles()) { if (!file.isHidden()) { try { JsonObjectBuilder fileStatus = importService.handleFile(dataverseRequest, owner, file, importType, validationLog, cleanupLog); status.add(fileStatus); } catch (ImportException | IOException e) { status.add(Json.createObjectBuilder().add("importStatus", "Exception importing " + file.getName() + ", message = " + e.getMessage())); } } } return status; }
Source:
<code>public static Group findByName(Context context, String name) throws SQLException { String query = "select * from epersongroup e " + "LEFT JOIN metadatavalue m on (m.resource_id = e.eperson_group_id and m.resource_type_id = ? and m.metadata_field_id = ?) " + "where "; <START> if("oracle".equals(ConfigurationManager.getProperty("db.name"))) { <END> query += " dbms_lob.substr(m.text_value) = ?"; }else{ query += " m.text_value = ?"; } TableRow row = DatabaseManager.querySingle(context, query, Constants.GROUP, MetadataField.findByElement(context, MetadataSchema.find(context, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), name ); if (row == null) { return null; } else { Group fromCache = (Group) context.fromCache(Group.class, row .getIntColumn("eperson_group_id")); if (fromCache != null) { return fromCache; } else { return new Group(context, row); } } }</code><technical_language>DatabaseManager.isOracle()</technical_language>

Target:
public static Group findByName(Context context, String name) throws SQLException { String query = "select * from epersongroup e " + "LEFT JOIN metadatavalue m on (m.resource_id = e.eperson_group_id and m.resource_type_id = ? and m.metadata_field_id = ?) " + "where "; if(DatabaseManager.isOracle()) { query += " dbms_lob.substr(m.text_value) = ?"; }else{ query += " m.text_value = ?"; } TableRow row = DatabaseManager.querySingle(context, query, Constants.GROUP, MetadataField.findByElement(context, MetadataSchema.find(context, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), name ); if (row == null) { return null; } else { Group fromCache = (Group) context.fromCache(Group.class, row .getIntColumn("eperson_group_id")); if (fromCache != null) { return fromCache; } else { return new Group(context, row); } } }
Source:
<code>private static Optional<OsFamily> findInStandardFamilies(final String osFamily) { return tryFind(asList(OsFamily.values()), new Predicate<OsFamily>() { @Override public boolean apply(OsFamily input) { <START> if (osFamily != null) { <END> return osFamily.toLowerCase().contains(input.value().toLowerCase()); } else { return false; } } }); }</code><technical_language>osFamily is input parameter of function. need do redundant check in iteration. Remove this return absent beginning if input parameter is null. for other function</technical_language>

Target:
private static Optional<OsFamily> findInStandardFamilies(final String osFamily) { if (osFamily == null) { return Optional.absent(); } return tryFind(asList(OsFamily.values()), new Predicate<OsFamily>() { @Override public boolean apply(OsFamily input) { return osFamily.toLowerCase().contains(input.value().toLowerCase()); } }); }
Source:
<code>public List<Brick> getReversedCheckedBrickList() { <START> List<Brick> reverseCheckedList = new ArrayList<>(); <END> for (int counter = checkedBricks.size() - 1; counter >= 0; counter--) { reverseCheckedList.add(checkedBricks.get(counter)); } return reverseCheckedList; }</code><technical_language>liner for this method: return Lists.reverse(checkedBricks);</technical_language>

Target:
public List<Brick> getReversedCheckedBrickList() { return Lists.reverse(checkedBricks); }
Source:
<code>private static Geocache parseCache(final JSONObject response) { final Geocache cache = new Geocache(); cache.setReliableLatLon(true); try { cache.setGeocode("EC" + response.getString("cache_id")); cache.setName(response.getString("title")); cache.setCoords(new Geopoint(response.getString("lat"), response.getString("lon"))); cache.setType(getCacheType(response.getString("type"))); cache.setDifficulty((float) response.getDouble("difficulty")); cache.setTerrain((float) response.getDouble("terrain")); cache.setFound(response.getInt("found") == 1 ? true : false); DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_CACHE)); <START> } catch (final JSONException e) { <END> Log.e("ECApi.parseCache", e); } return cache; }</code><technical_language>I this much, return a partially defined cache if is a JSONException while decoding a field. means filled fields get depend order of setters above, is ugly. exception propagate</technical_language>

Target:
private static Geocache parseCache(final JSONObject response) { final Geocache cache = new Geocache(); cache.setReliableLatLon(true); try { cache.setGeocode("EC" + response.getString("cache_id")); cache.setName(response.getString("title")); cache.setCoords(new Geopoint(response.getString("lat"), response.getString("lon"))); cache.setType(getCacheType(response.getString("type"))); cache.setDifficulty((float) response.getDouble("difficulty")); cache.setTerrain((float) response.getDouble("terrain")); cache.setFound(response.getInt("found") == 1 ? true : false); DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_CACHE)); } catch (final JSONException e) { Log.e("ECApi.parseCache", e); return null; } return cache; }
Source:
<code>public VoidResult setStarred(final String reviewId, final boolean starred, IProgressMonitor monitor) throws GerritException { final Change.Id id = new Change.Id(id(reviewId)); final ToggleStarRequest req = new ToggleStarRequest(); <START> req.toggle(new Change.Id(id(reviewId)), starred); <END> if (isVersion28OrLater(monitor)) { final String uri = "/a/accounts/self/starred.changes/" + id.get(); return execute(monitor, new Operation<VoidResult>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { if (starred) { executePutRestRequest(uri, req, ToggleStarRequest.class, new ErrorHandler() { @Override public void handleError(HttpMethodBase method) throws GerritException { throw new GerritException(method.getStatusLine().getReasonPhrase()); } }, monitor); } else { executeDeleteRestRequest(uri, req, ToggleStarRequest.class, new ErrorHandler() { @Override public void handleError(HttpMethodBase method) throws GerritException { throw new GerritException(method.getStatusLine().getReasonPhrase()); } }, monitor); } } }); } else { return execute(monitor, new Operation<VoidResult>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { getChangeListService(monitor).toggleStars(req, this); } }); } }</code><technical_language>a Change.Id, above</technical_language>

Target:
public VoidResult setStarred(final String reviewId, final boolean starred, IProgressMonitor monitor) throws GerritException { final Change.Id id = new Change.Id(id(reviewId)); final ToggleStarRequest req = new ToggleStarRequest(); req.toggle(id, starred); if (isVersion28OrLater(monitor)) { final String uri = "/a/accounts/self/starred.changes/" + id.get(); return execute(monitor, new Operation<VoidResult>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { if (starred) { executePutRestRequest(uri, req, ToggleStarRequest.class, handleErrorHandler(), monitor); } else { executeDeleteRestRequest(uri, req, ToggleStarRequest.class, handleErrorHandler(), monitor); } } }); } else { return execute(monitor, new Operation<VoidResult>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { getChangeListService(monitor).toggleStars(req, this); } }); } }
Source:
<code>public void updateConditionFromPart() { Mounted mounted = getMounted(); if (mounted != null) { mounted.setHit(false); mounted.setDestroyed(false); mounted.setRepairable(true); getUnit().repairSystem(CriticalSlot.TYPE_EQUIPMENT, equipmentNum); <START> mounted.setShotsLeft(getFullShots() - shotsNeeded/getNumTroopers()); <END> } }</code><technical_language>suggestion mounted.setShotsLeft(getFullShots() - (shotsNeeded / getNumTroopers()));</technical_language>

Target:
public void updateConditionFromPart() { Mounted mounted = getMounted(); if (mounted != null) { mounted.setHit(false); mounted.setDestroyed(false); mounted.setRepairable(true); getUnit().repairSystem(CriticalSlot.TYPE_EQUIPMENT, equipmentNum); mounted.setShotsLeft(getFullShots() - (shotsNeeded / getNumTroopers())); } }
Source:
<code>public GISModel trainModel(ObjectStream<Event> eventStream, int iterations, int cutoff) throws IOException { DataIndexer indexer=new OnePassDataIndexer(); <START> Map<String, String> params=new HashMap<String, String>(); <END> params.put(GIS.ITERATIONS_PARAM, Integer.toString(iterations)); params.put(GIS.CUTOFF_PARAM, Integer.toString(cutoff)); indexer.init(params, new HashMap<String, String>()); return trainModel(iterations, indexer, cutoff); }</code><technical_language>need types RHS</technical_language>

Target:
public GISModel trainModel(ObjectStream<Event> eventStream, int iterations, int cutoff) throws IOException { DataIndexer indexer = new OnePassDataIndexer(); Map<String, String> params = new HashMap<>(); params.put(GIS.ITERATIONS_PARAM, Integer.toString(iterations)); params.put(GIS.CUTOFF_PARAM, Integer.toString(cutoff)); indexer.init(params, new HashMap<>()); return trainModel(iterations, indexer, cutoff); }
Source:
<code>public boolean checkStopScanCondition(String interfaceName) { boolean stopScan = false; <START> if (scanners.containsKey(interfaceName) <END> && scanners.get(interfaceName).stream().mapToInt(e -> e.isScanning() ? 1 : 0).sum() == 1) { stopScan = true; } return stopScan; }</code><technical_language>this simplified checkStartScanCondition</technical_language>

Target:
public boolean checkStopScanCondition(String interfaceName) { boolean stopScan = false; if (scanners.containsKey(interfaceName) && getScannersCount(interfaceName) == 1) { stopScan = true; } return stopScan; }
Source:
<code>void processItem(final String agent) { try { <START> if (masterModel.isHostUp(agent)) { <END> return; } final AgentInfo agentInfo = masterModel.getAgentInfo(agent); if (agentInfo == null) { return; } final long downSince = agentInfo.getStartTime() + agentInfo.getUptime(); final long downDurationMillis = clock.now().getMillis() - downSince; if (downDurationMillis >= timeoutMillis) { try { log.info("Reaping dead agent '{}' (DOWN for hours)", agent, DurationFormatUtils.formatDurationHMS(downDurationMillis)); masterModel.deregisterHost(agent); } catch (Exception e) { log.warn("Failed to reap agent '{}'", agent, e); } } } catch (Exception e) { log.warn("Failed to determine if agent '{}' should be reaped", agent, e); } }</code><technical_language>change this logic all? AFAICT this is before, adds a new method do it</technical_language>

Target:
void processItem(final String agent) { try { final HostStatus hostStatus = masterModel.getHostStatus(agent); if (hostStatus == null || hostStatus.getStatus() != HostStatus.Status.DOWN) { return; } final AgentInfo agentInfo = hostStatus.getAgentInfo(); if (agentInfo == null) { return; } final long downSince = agentInfo.getStartTime() + agentInfo.getUptime(); final long downDurationMillis = clock.now().getMillis() - downSince; if (downDurationMillis >= timeoutMillis) { try { log.info("Reaping dead agent '{}' (DOWN for hours)", agent, DurationFormatUtils.formatDurationHMS(downDurationMillis)); masterModel.deregisterHost(agent); } catch (Exception e) { log.warn("Failed to reap agent '{}'", agent, e); } } } catch (Exception e) { log.warn("Failed to determine if agent '{}' should be reaped", agent, e); } }
Source:
<code>public EnumActionResult onProcessRightClick(PlayerInteractionManager interactionManager, EntityPlayer player, net.minecraft.world.World worldIn, @Nullable ItemStack stack, EnumHand hand) { EnumActionResult actionResult = interactionManager.processRightClick(this.player, worldIn, stack, hand); <START> if (!SpongeCommonEventFactory.playerInteractItemChanged) { <END> final PhaseTracker phaseTracker = PhaseTracker.getInstance(); final PhaseData peek = phaseTracker.getCurrentPhaseData(); final ItemStack itemStack = ItemStackUtil.toNative(((PacketContext<?>) peek.context).getItemUsed()); if (!ItemStack.areItemStacksEqual(itemStack, player.getHeldItem(hand)) && SpongeCommonEventFactory.interactBlockRightClickEventCancelled) { PacketPhaseUtil.handlePlayerSlotRestore((EntityPlayerMP) player, itemStack, hand); } } SpongeCommonEventFactory.playerInteractItemChanged = false; SpongeCommonEventFactory.interactBlockRightClickEventCancelled = false; return actionResult; }</code><technical_language>Is some phase context flag flipped instead of checking a static variable? While I do want standardize interact events, I do want some of legacy style static variable nonsense of dodo</technical_language>

Target:
public EnumActionResult onProcessRightClick(PlayerInteractionManager interactionManager, EntityPlayer player, net.minecraft.world.World worldIn, @Nullable ItemStack stack, EnumHand hand) { EnumActionResult actionResult = interactionManager.processRightClick(this.player, worldIn, stack, hand); final PhaseData peek = PhaseTracker.getInstance().getCurrentPhaseData(); if (!((PacketContext<?>) peek.context).getInteractItemChanged()) { final ItemStack itemStack = ItemStackUtil.toNative(((PacketContext<?>) peek.context).getItemUsed()); if (!ItemStack.areItemStacksEqual(itemStack, player.getHeldItem(hand)) && SpongeCommonEventFactory.interactBlockRightClickEventCancelled) { PacketPhaseUtil.handlePlayerSlotRestore((EntityPlayerMP) player, itemStack, hand); } } ((PacketContext<?>) peek.context).interactItemChanged(false); SpongeCommonEventFactory.interactBlockRightClickEventCancelled = false; return actionResult; }
Source:
<code>protected int getMaxRampStage() { <START> return 4; <END> }</code><technical_language>ditto. Please avoid hardcoded numbers</technical_language>

Target:
protected int getMaxRampStage() { return MAX_RAMP_STAGE; }
Source:
<code>public void shouldFindUrlsInAreaPingElements() { SpiderHtmlParser htmlParser = new SpiderHtmlParser(new SpiderParam()); TestSpiderParserListener listener = createTestSpiderParserListener(); htmlParser.addSpiderParserListener(listener); <START> HttpMessage messageHtmlResponse = createMessageWith("AElementsWithPingSpiderHtmlParser.html"); <END> Source source = createSource(messageHtmlResponse); boolean completelyParsed = htmlParser.parseResource(messageHtmlResponse, source, BASE_DEPTH); assertThat(completelyParsed, is(equalTo(false))); assertThat(listener.getNumberOfUrlsFound(), is(equalTo(23))); assertThat( listener.getUrlsFound(), contains( "<LINK_6>", "<LINK_0>", "<LINK_2>", "<LINK_9>", "<LINK_1>", "<LINK_13>", "<LINK_12>", "<LINK_4>", "<LINK_8>", "<LINK_8>/ping", "ftp://a.example.com/", "<LINK_16>", "<LINK_7>", "<LINK_11>", "<LINK_14>", "<LINK_5>", "<LINK_3>", "<LINK_10>", "<LINK_15>", "<LINK_17>", "<LINK_10>", "<LINK_15>", "<LINK_17>")); }</code><technical_language>File name updated</technical_language>

Target:
public void shouldFindUrlsInAreaPingElements() { SpiderHtmlParser htmlParser = new SpiderHtmlParser(new SpiderParam()); TestSpiderParserListener listener = createTestSpiderParserListener(); htmlParser.addSpiderParserListener(listener); HttpMessage messageHtmlResponse = createMessageWith("AreaElementsWithPingSpiderHtmlParser.html"); Source source = createSource(messageHtmlResponse); boolean completelyParsed = htmlParser.parseResource(messageHtmlResponse, source, BASE_DEPTH); assertThat(completelyParsed, is(equalTo(false))); assertThat(listener.getNumberOfUrlsFound(), is(equalTo(23))); assertThat( listener.getUrlsFound(), contains( "<LINK_6>", "<LINK_0>", "<LINK_2>", "<LINK_9>", "<LINK_1>", "<LINK_13>", "<LINK_12>", "<LINK_4>", "<LINK_8>", "<LINK_8>/ping", "ftp://a.example.com/", "<LINK_16>", "<LINK_7>", "<LINK_11>", "<LINK_14>", "<LINK_5>", "<LINK_3>", "<LINK_10>", "<LINK_15>", "<LINK_17>", "<LINK_10>", "<LINK_15>", "<LINK_17>")); }
Source:
<code>public static void closeConnection(Connection dbConnection) { if (dbConnection != null) { try { <START> if (dbConnection != null && !dbConnection.isClosed()) { <END> dbConnection.close(); } } catch (SQLRecoverableException ex) { handleSQLRecoverableException(dbConnection, ex); } catch (SQLException e) { log.error("Database error. Could not close statement. Continuing with others. - " + e.getMessage(), e); } } }</code><technical_language>fix indentation issues, in couple of places</technical_language>

Target:
public static void closeConnection(Connection dbConnection) { close(dbConnection); }
Source:
<code>DebuggerInfo getInfo() throws DebuggerException; void disconnect() throws DebuggerException; void start(StartAction action) throws DebuggerException; <START> void suspend() throws DebuggerException; <END> void addBreakpoint(Breakpoint breakpoint) throws DebuggerException; void deleteBreakpoint(Location location) throws DebuggerException; void deleteAllBreakpoints() throws DebuggerException; List<Breakpoint> getAllBreakpoints() throws DebuggerException; SimpleValue getValue(VariablePath variablePath) throws DebuggerException; void setValue(Variable variable) throws DebuggerException; String evaluate(String expression) throws DebuggerException; void stepOver(StepOverAction action) throws DebuggerException; void stepInto(StepIntoAction action) throws DebuggerException; void stepOut(StepOutAction action) throws DebuggerException; void resume(ResumeAction action) throws DebuggerException; StackFrameDump dumpStackFrame() throws DebuggerException; interface DebuggerCallback { void onEvent(DebuggerEvent event); }</code><technical_language>Add default behavior instead of throwing exception in implementation</technical_language>

Target:
DebuggerInfo getInfo() throws DebuggerException; void disconnect() throws DebuggerException; void start(StartAction action) throws DebuggerException; default void suspend() throws DebuggerException { throw new DebuggerException("Unsupported operation for current debugger implementation."); }
Source:
<code>public synchronized CompletableFuture<RaftRole> start() { if (raft.getCluster().getActiveMemberStates().isEmpty()) { log.debug("Single member cluster. Transitioning directly to leader."); <START> raft.transition(RaftServer.Role.LEADER); <END> return CompletableFuture.completedFuture(this); } return super.start().thenRun(this::startElection).thenApply(v -> this); }</code><technical_language>new term vote persisted transitioning leader, i.e raft.setTerm(raft.getTerm() + 1); raft.setLastVotedFor(raft.getCluster().getMember().memberId()); this raft is in invalid state, is test currently failing this branch</technical_language>

Target:
public synchronized CompletableFuture<RaftRole> start() { if (raft.getCluster().getActiveMemberStates().isEmpty()) { log.debug("Single member cluster. Transitioning directly to leader."); raft.setTerm(raft.getTerm() + 1); raft.setLastVotedFor(raft.getCluster().getMember().memberId()); raft.transition(RaftServer.Role.LEADER); return CompletableFuture.completedFuture(this); } return super.start().thenRun(this::startElection).thenApply(v -> this); }
Source:
<code>public void subscribe(Subscriber<? super KeyValueEntry<K, V>> subscriber) { subscribers.add(subscriber); createContinuousQueryFlowable(); flowable.subscribe(subscriber); <START> flowable.doOnError(e -> { <END> log.error(e); continuousQuery.removeContinuousQueryListener(continuousQueryListener); }).doOnCancel(() -> continuousQuery.removeContinuousQueryListener(continuousQueryListener)); }</code><technical_language>do need add error cancel handles time? done create flowable</technical_language>

Target:
public void subscribe(Subscriber<? super KeyValueEntry<K, V>> subscriber) { createContinuousQueryFlowable(); flowable.subscribe(subscriber); }
Source:
<code>private void rebuildMetadata(final Map<HostInfo, Set<TopicPartition>> activePartitionHostMap, final Map<HostInfo, Set<TopicPartition>> standbyPartitionHostMap) { allMetadata.clear(); if (activePartitionHostMap.isEmpty() && standbyPartitionHostMap.isEmpty()) { return; } final Map<String, List<String>> storeToSourceTopics = builder.stateStoreNameToSourceTopics(); Stream.concat(activePartitionHostMap.keySet().stream(), standbyPartitionHostMap.keySet().stream()) .distinct() <START> .forEach(key -> { <END> final Set<TopicPartition> activePartitionsOnHost = new HashSet<>(); final Set<String> activeStoresOnHost = new HashSet<>(); if (activePartitionHostMap.containsKey(key)) { activePartitionsOnHost.addAll(activePartitionHostMap.get(key)); activeStoresOnHost.addAll(getStoresOnHost(storeToSourceTopics, activePartitionsOnHost)); } activeStoresOnHost.addAll(globalStores); final Set<TopicPartition> standbyPartitionsOnHost = new HashSet<>(); final Set<String> standbyStoresOnHost = new HashSet<>(); if (standbyPartitionHostMap.containsKey(key)) { standbyPartitionsOnHost.addAll(standbyPartitionHostMap.get(key)); standbyStoresOnHost.addAll(getStoresOnHost(storeToSourceTopics, standbyPartitionsOnHost)); } final StreamsMetadata metadata = new StreamsMetadata(key, activeStoresOnHost, activePartitionsOnHost, standbyStoresOnHost, standbyPartitionsOnHost); allMetadata.add(metadata); if (key.equals(thisHost)) { myMetadata = metadata; } }); }</code><technical_language>hostInfo a clearer name</technical_language>

Target:
private void rebuildMetadata(final Map<HostInfo, Set<TopicPartition>> activePartitionHostMap, final Map<HostInfo, Set<TopicPartition>> standbyPartitionHostMap) { allMetadata.clear(); if (activePartitionHostMap.isEmpty() && standbyPartitionHostMap.isEmpty()) { return; } final Map<String, List<String>> storeToSourceTopics = builder.stateStoreNameToSourceTopics(); Stream.concat(activePartitionHostMap.keySet().stream(), standbyPartitionHostMap.keySet().stream()) .distinct() .forEach(hostInfo -> { final Set<TopicPartition> activePartitionsOnHost = new HashSet<>(); final Set<String> activeStoresOnHost = new HashSet<>(); if (activePartitionHostMap.containsKey(hostInfo)) { activePartitionsOnHost.addAll(activePartitionHostMap.get(hostInfo)); activeStoresOnHost.addAll(getStoresOnHost(storeToSourceTopics, activePartitionsOnHost)); } activeStoresOnHost.addAll(globalStores); final Set<TopicPartition> standbyPartitionsOnHost = new HashSet<>(); final Set<String> standbyStoresOnHost = new HashSet<>(); if (standbyPartitionHostMap.containsKey(hostInfo)) { standbyPartitionsOnHost.addAll(standbyPartitionHostMap.get(hostInfo)); standbyStoresOnHost.addAll(getStoresOnHost(storeToSourceTopics, standbyPartitionsOnHost)); } final StreamsMetadata metadata = new StreamsMetadata(hostInfo, activeStoresOnHost, activePartitionsOnHost, standbyStoresOnHost, standbyPartitionsOnHost); allMetadata.add(metadata); if (hostInfo.equals(thisHost)) { localMetadata = metadata; } }); }
Source:
<code>public Map<String, TransportConfiguration> getConnectors() { <START> return Collections.unmodifiableMap(connectors); <END> }</code><technical_language>relation this change WFLY-19339</technical_language>

Target:
public Map<String, TransportConfiguration> getConnectors() { return connectors; }
Source:
<code>for (RelDataType operandType: operandTypes) { int operandPrecision = operandType.getPrecision(); amount = (long) operandPrecision + amount; if (!hasPrecisionNotSpecifiedOperand <START> && operandPrecision == RelDataType.PRECISION_NOT_SPECIFIED) { <END> hasPrecisionNotSpecifiedOperand = true; } }</code><technical_language>break iteration when: 1) encountering PRECISION_NOT_SPECIFIED, 2) amount large max precision</technical_language>

Target:
for (RelDataType operandType: operandTypes) { int operandPrecision = operandType.getPrecision(); amount = (long) operandPrecision + amount; if (operandPrecision == RelDataType.PRECISION_NOT_SPECIFIED) { hasPrecisionNotSpecifiedOperand = true; break; } if (amount > typeSystem.getMaxPrecision(SqlTypeName.VARCHAR)) { precisionOverflow = true; break; } }
Source:
<code><START> public String getAppiumServerPort(String host) throws Exception { <END> JSONArray hostMachineObject = CapabilityManager.getInstance().getHostMachineObject(); List<Object> objects = hostMachineObject.toList(); Object o = objects.stream().filter(object -> ((HashMap) object).get("machineIP") .toString().equalsIgnoreCase(host) && ((HashMap) object).get("port") != null) .findFirst().orElse(null); if (o != null) { return ((HashMap) o).get("port").toString(); } return null; }</code><technical_language>Code repetition.. code present in getAppiumServerPath. Extract function</technical_language>

Target:
public String getAppiumServerPort(String host) throws Exception { return appiumServerProp(host,"appiumPort"); }
Source:
<code>protected void processFiltered(File file, FileText fileText) { if (getHeaderLines().size() > fileText.getLines().size()) { log(1, MSG_MISSING); } else { for (int i = 0; i < getHeaderLines().size(); i++) { <START> if (!isMatch(i, fileText.getLines().get(i))) { <END> log(i + 1, MSG_MISMATCH, getHeaderLines().get(i)); break; } } } }</code><technical_language>calling getLines in a loop bad. creating new instances loop. Please a temporary variable entering loop. temporary variable for previous call getLines a lines</technical_language>

Target:
protected void processFiltered(File file, FileText fileText) { final List<String> lines = fileText.getLines(); if (getHeaderLines().size() > lines.size()) { log(1, MSG_MISSING); } else { for (int i = 0; i < getHeaderLines().size(); i++) { if (!isMatch(i, lines.get(i))) { log(i + 1, MSG_MISMATCH, getHeaderLines().get(i)); break; } } } }
Source:
<code>public IFluidTankProperties[] getTankProperties() { <START> if(parent.get() != null) { <END> IFluidTankProperties[] iFluidTankPropertiesArray = parent.get().getTankProperties(); if(iFluidTankPropertiesArray.length > 0) { IFluidTankProperties fluidTankProperties = parent.get().getTankProperties()[0]; return new IFluidTankProperties[]{new FluidTankProperties(fluidTankProperties.getContents(), fluidTankProperties.getCapacity(), true, false)}; } } return EmptyFluidHandler.EMPTY_TANK_PROPERTIES_ARRAY; }</code><technical_language>hasParent</technical_language>

Target:
public IFluidTankProperties[] getTankProperties() { if(hasParent()) { IFluidTankProperties[] iFluidTankPropertiesArray = parent.get().getTankProperties(); if(iFluidTankPropertiesArray.length > 0) { IFluidTankProperties fluidTankProperties = parent.get().getTankProperties()[0]; return new IFluidTankProperties[]{new FluidTankProperties(fluidTankProperties.getContents(), fluidTankProperties.getCapacity(), true, false)}; } } return EmptyFluidHandler.EMPTY_TANK_PROPERTIES_ARRAY; }
Source:
<code>public ParametersBuilder add(int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { <START> nanosecond = 0; <END> } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, 1970, 1, 1 ); }</code><technical_language>if condition be: if ( !isNanosecondPrecisionSupported() )</technical_language>

Target:
public ParametersBuilder add(int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, 1970, 1, 1 ); }