auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void readPaint(String paint) { try { <START> String parts[] = paint.split(borderSeparator); <END> useGradient = parts[0].contains(gradientSeparator); if (useGradient) { String gradientParts[] = parts[0].split(gradientSeparator); color1 = Color.valueOf(gradientParts[0]); color2 = Color.valueOf(gradientParts[1]); x0 = Float.parseFloat(gradientParts[2]); y0 = Float.parseFloat(gradientParts[3]); float x1 = Float.parseFloat(gradientParts[4]); float y1 = Float.parseFloat(gradientParts[5]); gradientVector = new Vector2(x1 - x0, y1 - y0); gradientLength = gradientVector.len(); } else { color1 = Color.valueOf(parts[0]); } hasBorder = parts.length > 1; if (hasBorder) { borderColor = Color.valueOf(parts[1]); } } catch (Exception e) { hasBorder = false; Gdx.app.error("ShapeFactory", "Invalid paint " + paint, e); } }</code><technical_language>json (String) - > Object conversion done right here? prefer in a centralized (i.e. loader) place</technical_language>

Target:
private void readPaint(String paint) { try { String parts[] = paint.split(borderSeparator); useGradient = parts[0].contains(gradientSeparator); if (useGradient) { String gradientParts[] = parts[0].split(gradientSeparator); color1 = Color.valueOf(gradientParts[0]); color2 = Color.valueOf(gradientParts[1]); x0 = Float.parseFloat(gradientParts[2]); y0 = Float.parseFloat(gradientParts[3]); float x1 = Float.parseFloat(gradientParts[4]); float y1 = Float.parseFloat(gradientParts[5]); gradientVector = new Vector2(x1 - x0, y1 - y0); gradientLength = gradientVector.len(); } else { color1 = Color.valueOf(parts[0]); } hasBorder = parts.length > 1; if (hasBorder) { borderColor = Color.valueOf(parts[1]); } } catch (Exception e) { hasBorder = false; useGradient = false; color1 = Color.PINK; Gdx.app.error("ShapeFactory", "Invalid paint " + paint + ". Paint set to pink.", e); } }
Source:
<code>public void render(Node node) { if (node instanceof TaskListItemMarker) { <START> Map<String, String> attributes = context.extendAttributes(node, "input", Collections.<String, String>emptyMap()); <END> attributes.put("type", "checkbox"); attributes.put("disabled", ""); if (((TaskListItemMarker) node).isChecked()) { attributes.put("checked", ""); } html.tag("input", attributes); html.text(" "); renderChildren(node); } }</code><technical_language>Hmm, interesting. I expected this instead: Map<String, String> attributes = new LinkedHashMap<>(); attributes.put(...); ... html.tag("input", context.extendAttributes(node, "input", attributes); order, extensions AttributeProvider change/remove of attributes here, I is want. thought happen write this way</technical_language>

Target:
public void render(Node node) { if (node instanceof TaskListItemMarker) { Map<String, String> attributes = new LinkedHashMap<>(); attributes.put("type", "checkbox"); attributes.put("disabled", ""); if (((TaskListItemMarker) node).isChecked()) { attributes.put("checked", ""); } html.tag("input", context.extendAttributes(node, "input", attributes)); html.text(" "); renderChildren(node); } }
Source:
<code>private void handleInternalLink(PageTitle title) { if (!isAdded()) { return; } if (title.isSpecial()) { Utils.visitInExternalBrowser(getActivity(), Uri.parse(title.getMobileUri())); return; } if (referenceDialog != null && referenceDialog.isShowing()) { referenceDialog.dismiss(); } if (app.isProdRelease() || app.getLinkPreviewVersion() == 0) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); getPageActivity().displayNewPage(title, historyEntry); new LinkPreviewFunnel(app, title).logNavigate(); } else { LinkPreviewDialog dialog = LinkPreviewDialog.newInstance(title); <START> dialog.setOnNavigateListener(new LinkPreviewDialog.OnNavigateListener() { <END> @Override public void onNavigate(PageTitle title) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); ((PageActivity) getActivity()).displayNewPage(title, historyEntry); } }); dialog.show(getActivity().getSupportFragmentManager(), "link_preview_dialog"); } }</code><technical_language>feels this is identical in places. Is a default implementation (maybe HistoryEntry.SOURCE_LINK a construction parameter)</technical_language>

Target:
private void handleInternalLink(PageTitle title) { if (!isAdded()) { return; } if (title.isSpecial()) { Utils.visitInExternalBrowser(getActivity(), Uri.parse(title.getMobileUri())); return; } if (referenceDialog != null && referenceDialog.isShowing()) { referenceDialog.dismiss(); } if (app.isProdRelease() || app.getLinkPreviewVersion() == 0) { HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); getPageActivity().displayNewPage(title, historyEntry); new LinkPreviewFunnel(app, title).logNavigate(); } else { getPageActivity().showLinkPreview(title, HistoryEntry.SOURCE_INTERNAL_LINK); } }
Source:
<code>public int run() throws IOException { int b = in.read(); if (b != -1) { mOut.write(b); size++; return 1; } else { mOut.close(); LongObjectId loid = LongObjectId .fromRaw(mOut.getMessageDigest().digest()); Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new <START> CorruptMediaFile(mediaFile, <END> size, fsSize); } } else { FileUtils.mkdirs(mediaFile.getParent().toFile(), true); FileUtils.rename(tmpFile.toFile(), mediaFile.toFile()); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); out.close(); return -1; } }</code><technical_language>CorruptLongObjectException</technical_language>

Target:
public int run() throws IOException { int b = in.read(); if (b != -1) { dOut.write(b); size++; return 1; } else { dOut.close(); LongObjectId loid = LongObjectId .fromRaw(dOut.getMessageDigest().digest()); Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } } else { FileUtils.mkdirs(mediaFile.getParent().toFile(), true); FileUtils.rename(tmpFile.toFile(), mediaFile.toFile()); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); out.close(); return -1; } }
Source:
<code>public void process() { PerformanceMonitor.startActivity("rendering/copyImageToHMD"); <START> displayResolutionDependentFBOs.get(new ResourceUrn("engine:sceneFinal")).bindTexture(); <END> renderFinalStereoImage(worldRenderer.getCurrentRenderStage()); PerformanceMonitor.endActivity(); }</code><technical_language>usage of get() in - new ResourceUrn() - (optional) if state change SetInputTextureFromFBO in initialise() instead of .bindTexture() here</technical_language>

Target:
public void process() { PerformanceMonitor.startActivity("rendering/copyImageToHMD"); sceneFinalFbo.bindTexture(); renderFinalStereoImage(worldRenderer.getCurrentRenderStage()); PerformanceMonitor.endActivity(); }
Source:
<code>Collection<LocationProvider> getProviders() { <START> return this.providers; <END> }</code><technical_language>nit: 'this.' usages necessary, consistent style in rest of library code</technical_language>

Target:
Collection<LocationProvider> getProviders() { return providers; }
Source:
<code>public List<CorfuQueueRecord<E>> entryList(Long entriesAfter, int maxEntries) { if (maxEntries <= 0) { throw new IllegalArgumentException("entryList given negative maxEntries"); } if (maxEntries > MAX_INDEX_ENTRIES) { throw new IllegalArgumentException( "entryList can't return more than "+MAX_INDEX_ENTRIES+" entries" ); } long snapshotVersion; boolean startedNewTransaction = false; if (TransactionalContext.isInTransaction()) { snapshotVersion = TransactionalContext.getCurrentContext() .getSnapshotTimestamp().getSequence(); } else { runtime.getObjectsView().TXBuild().type(TransactionType.WRITE_AFTER_WRITE) .build() .begin(); snapshotVersion = TransactionalContext.getCurrentContext() .getSnapshotTimestamp().getSequence(); startedNewTransaction = true; } List<CorfuQueueRecord<E>> copy = new ArrayList<>( Math.min(corfuTable.size(), maxEntries) ); int index = 0; <START> for (Long entryId : corfuTable.keySet().stream().sorted().collect(Collectors.toList())) { <END> if (entryId <= entriesAfter) { continue; } if (++index >= maxEntries) { break; } long ordering = (snapshotVersion << MAX_BITS_FOR_INDEX) | index; CorfuQueueRecord<E> record = new CorfuQueueRecord<>( ordering, entryId, corfuTable.get(entryId) ); copy.add(record); } if (startedNewTransaction) { runtime.getObjectsView().TXEnd(); } return copy; }</code><technical_language>filter keys out collecting a list</technical_language>

Target:
public List<CorfuQueueRecord<E>> entryList(Long entriesAfter, int maxEntries) { if (maxEntries <= 0) { throw new IllegalArgumentException("entryList given negative maxEntries"); } if (maxEntries > MAX_INDEX_ENTRIES) { throw new IllegalArgumentException( "entryList can't return more than "+MAX_INDEX_ENTRIES+" entries" ); } long snapshotVersion; boolean startedNewTransaction = false; if (TransactionalContext.isInTransaction()) { snapshotVersion = TransactionalContext.getCurrentContext() .getSnapshotTimestamp().getSequence(); } else { runtime.getObjectsView().TXBuild().type(TransactionType.WRITE_AFTER_WRITE) .build() .begin(); snapshotVersion = TransactionalContext.getCurrentContext() .getSnapshotTimestamp().getSequence(); startedNewTransaction = true; } List<CorfuQueueRecord<E>> copy = new ArrayList<>( Math.min(corfuTable.size(), maxEntries) ); int index = 0; for (Long entryId : corfuTable.keySet().stream() .filter(e -> e > entriesAfter) .sorted().collect(Collectors.toList())) { if (++index >= maxEntries) { break; } long ordering = (snapshotVersion << MAX_BITS_FOR_INDEX) | index; CorfuQueueRecord<E> record = new CorfuQueueRecord<>( ordering, entryId, corfuTable.get(entryId) ); copy.add(record); } if (startedNewTransaction) { runtime.getObjectsView().TXEnd(); } return copy; }
Source:
<code>public Set<FormulaVariable> getFormulaVariablesInStudy(final Integer studyId, final Integer datasetId) { final Set<Integer> variableIds = new HashSet<>(); final Integer plotDatasetId = this.daoFactory.getDmsProjectDAO().getDatasetsByTypeForStudy(studyId, DatasetTypeEnum.PLOT_DATA.getId()).get(0).getProjectId(); final List<MeasurementVariable> measurementVariables = this.daoFactory.getDmsProjectDAO().getObservationSetVariables(Arrays.asList(plotDatasetId, datasetId), <START> Arrays <END> .asList(VariableType.TRAIT.getId(), VariableType.ENVIRONMENT_DETAIL.getId(), VariableType.STUDY_CONDITION.getId())); for (final MeasurementVariable measurementVariable : measurementVariables) { variableIds.add(measurementVariable.getTermId()); } return this.formulaService.getAllFormulaVariables(variableIds); }</code><technical_language>extract this constant multiple times in code: Arrays.asList(VariableType.TRAIT.getId(), VariableType.ENVIRONMENT_DETAIL.getId(), VariableType.STUDY_CONDITION.getId())</technical_language>

Target:
public Set<FormulaVariable> getFormulaVariablesInStudy(final Integer studyId, final Integer datasetId) { final Set<Integer> variableIds = new HashSet<>(); final Integer plotDatasetId = this.daoFactory.getDmsProjectDAO().getDatasetsByTypeForStudy(studyId, DatasetTypeEnum.PLOT_DATA.getId()).get(0).getProjectId(); final List<MeasurementVariable> measurementVariables = this.daoFactory.getDmsProjectDAO().getObservationSetVariables(Arrays.asList(plotDatasetId, datasetId), CALCULATED_VARIABLE_VARIABLE_TYPES); for (final MeasurementVariable measurementVariable : measurementVariables) { variableIds.add(measurementVariable.getTermId()); } return this.formulaService.getAllFormulaVariables(variableIds); }
Source:
<code>public UserMessageDto(UserMessageModel userMessageModel) { this.userMessageId = userMessageModel.getMessageId(); this.title = userMessageModel.getTitle(); <START> this.content = userMessageModel.getContent(); <END> this.read = userMessageModel.isRead(); this.createdTime = userMessageModel.getCreatedTime(); }</code><technical_language>if content == null content = title</technical_language>

Target:
public UserMessageDto(UserMessageModel userMessageModel) { this.userMessageId = userMessageModel.getMessageId(); this.title = userMessageModel.getTitle(); this.content = StringUtils.isEmpty(userMessageModel.getContent()) ? userMessageModel.getTitle() : userMessageModel.getContent(); this.read = userMessageModel.isRead(); this.createdTime = userMessageModel.getCreatedTime(); }
Source:
<code>public <T extends IAtsObject> Collection<T> getRelated(IAtsObject atsObject, RelationTypeSide relationType, DeletionFlag flag, Class<T> clazz) { List<T> results = new ArrayList<>(); Artifact useArt = getArtifact(atsObject); if <START> (atsObject.isInvalid()) <END> { return results; } if (useArt != null) { for (Artifact art : useArt.getRelatedArtifacts(relationType, flag)) { IAtsObject object = AtsObjects.getAtsObject(art, atsClient); if (object != null) { results.add((T) object); } } } return results; }</code><technical_language>this useArt? Is "useArt" atsObject is null</technical_language>

Target:
public <T extends IAtsObject> Collection<T> getRelated(IAtsObject atsObject, RelationTypeSide relationType, DeletionFlag flag, Class<T> clazz) { List<T> results = new ArrayList<>(); Artifact useArt = getArtifact(atsObject); if (atsObject == null || atsObject.isInvalid()) { return results; } if (useArt != null) { for (Artifact art : useArt.getRelatedArtifacts(relationType, flag)) { IAtsObject object = AtsObjects.getAtsObject(art, atsClient); if (object != null) { results.add((T) object); } } } return results; }
Source:
<code>protected void onInitExtras(Bundle extras) { super.onInitExtras(extras); mRepoOwner = extras.getString("owner"); mRepoName = extras.getString("repo"); mPullRequestNumber = extras.getInt("number"); mInitialCommentId = extras.getLong("initial_comment", -1); mInitialPage = extras.getInt("initial_page", -1); extras.remove("initial_comment"); <START> extras.remove("target_screen"); <END> }</code><technical_language>Oops, right</technical_language>

Target:
protected void onInitExtras(Bundle extras) { super.onInitExtras(extras); mRepoOwner = extras.getString("owner"); mRepoName = extras.getString("repo"); mPullRequestNumber = extras.getInt("number"); mInitialCommentId = extras.getLong("initial_comment", -1); mInitialPage = extras.getInt("initial_page", -1); extras.remove("initial_comment"); extras.remove("initial_page"); }
Source:
<code>private static void mkdirsOrThrow(File dir) throws IOException { <START> if (!dir.exists()) { <END> if (!dir.mkdirs()) { throw new IOException("Failed to create directory " + dir); } } }</code><technical_language>issue I put checks a single line (if (!dir.exists() && !dir.mkdirs()))</technical_language>

Target:
private static void mkdirsOrThrow(File dir) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Failed to create directory " + dir); } }
Source:
<code>private DBObject writeReplaceQuery(DBObject doc) { DBObject hidden=getHidden(doc,false); ObjectId top=null; if(hidden!=null) { List<ObjectId> list=(List<ObjectId>)hidden.get(DOCVER); if(list!=null&&!list.isEmpty()) top=list.get(0); } BasicDBObject query=new BasicDBObject("_id",doc.get("_id")); <START> query.append(DOCVER_FLD0,top); <END> return query; }</code><technical_language>docver array indexed default? (So is in memory: <LINK_0></technical_language>

Target:
private DBObject writeReplaceQuery(DBObject doc) { DBObject hidden=getHidden(doc,false); ObjectId top=null; if(hidden!=null) { List<ObjectId> list=(List<ObjectId>)hidden.get(DOCVER); if(list!=null&&!list.isEmpty()) top=list.get(0); } BasicDBObject query=new BasicDBObject("_id",doc.get("_id")); if(detectConcurrencyErrors) query.append(DOCVER_FLD0,top); return query; }
Source:
<code>public void test_ok() { <START> JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok1.js")); <END> JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok2.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok3.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok4.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok5.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok6.js")); }</code><technical_language>name files more meaningfully? I open find out :)</technical_language>

Target:
public void test_ok() { JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok_with_bitwise_operator.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok_outside_condition.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok_with_literal.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok_several_suspicious.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok_for_init.js")); JavaScriptCheckVerifier.verify(check, new File(DIR, "file_ok_for_no_condition.js")); }
Source:
<code>public Integer getGridSize() { Object objectValue = getValueForKey(MDS_DEFAULT_GRID_SIZE); Integer value = DEFAULT_GRID_SIZE; <START> if (objectValue != null && StringUtils.isNotBlank(objectValue.toString())) { <END> value = Integer.parseInt(objectValue.toString()); } return value; }</code><technical_language>do need this? setters parse integer</technical_language>

Target:
public Integer getGridSize() { if (gridSize == null) { return DEFAULT_GRID_SIZE; } return gridSize; }
Source:
<code>private static Collection<RestClientListener> listeners() { <START> ClassLoader threadContextClassLoader = AccessController.doPrivileged( <END> (PrivilegedAction<ClassLoader>)() -> Thread.currentThread().getContextClassLoader()); synchronized (REST_CLIENT_LISTENERS) { return REST_CLIENT_LISTENERS.computeIfAbsent(threadContextClassLoader, key -> { Collection<RestClientListener> listeners = new ArrayList<>(); for (RestClientListener listener : ServiceLoader.load(RestClientListener.class)) { listeners.add(listener); } return listeners; }); } }</code><technical_language>check if SecurityManager is present? if (System.getSecurityManager() == null) { // priviledged } else { // priviledged } of apps run SecurityManager, gain some efficiency here. do think</technical_language>

Target:
private static Collection<RestClientListener> listeners() { ClassLoader threadContextClassLoader; if (System.getSecurityManager() == null) { threadContextClassLoader = Thread.currentThread().getContextClassLoader(); } else { threadContextClassLoader = AccessController.doPrivileged( (PrivilegedAction<ClassLoader>)() -> Thread.currentThread().getContextClassLoader()); } synchronized (REST_CLIENT_LISTENERS) { return REST_CLIENT_LISTENERS.computeIfAbsent(threadContextClassLoader, key -> StreamSupport.stream(ServiceLoader.load(RestClientListener.class).spliterator(), false) .collect(Collectors.toList())); } }
Source:
<code>public void createRollbackTxTest() { FedoraTransaction tx = repository.startTransaction(); repository.createFolderObject(pid, model); <START> tx.cancel(); <END> }</code><technical_language>verify created folder exist rollback. check active transaction cleared</technical_language>

Target:
public void createRollbackTxTest() { FedoraTransaction tx = repository.startTransaction(); FolderObject obj = repository.createFolderObject(pid, model); tx.cancel(); assertNull(repository.getFolderObject(pid)); assertNull(obj.getUri()); assertFalse(FedoraTransaction.hasTxId()); assertFalse(FedoraTransaction.isStillAlive()); }
Source:
<code>public boolean evaluate(int threads, Statistics statistics) { OperationStats stats = statistics.getOperationsStats().get(on); if (stats == null) throw new IllegalStateException("No statistics for operation " + on); org.radargun.stats.representation.Percentile percentile = stats.getRepresentation(org.radargun.stats.representation.Percentile.class, value); <START> if (percentile == null) throw new IllegalStateException("Cannot determine mean from " + stats); <END> log.info("Response time is " + percentile.responseTimeMax + " ns " + PropertyHelper.toString(this)); if (below != null) return percentile.responseTimeMax < below; if (over != null) return percentile.responseTimeMax > over; throw new IllegalStateException(); }</code><technical_language>percentile</technical_language>

Target:
public boolean evaluate(int threads, Statistics statistics) { OperationStats stats = statistics.getOperationsStats().get(on); if (stats == null) throw new IllegalStateException("No statistics for operation " + on); org.radargun.stats.representation.Percentile percentile = stats.getRepresentation(org.radargun.stats.representation.Percentile.class, value); if (percentile == null) throw new IllegalStateException("Cannot determine percentile from " + stats); log.info("Response time is " + percentile.responseTimeMax + " ns " + PropertyHelper.toString(this)); if (below != null) return percentile.responseTimeMax < below; if (over != null) return percentile.responseTimeMax > over; throw new IllegalStateException(); }
Source:
<code>for (Change.Status s : Change.Status.values()) { ChangeStatusPredicate p = new ChangeStatusPredicate(s); PREDICATES.put(canonicalize(s), <START> new ChangeStatusPredicate(s)); <END> (s.isOpen() ? open : closed).add(p); }</code><technical_language>'p'</technical_language>

Target:
for (Change.Status s : Change.Status.values()) { ChangeStatusPredicate p = new ChangeStatusPredicate(s); PREDICATES.put(canonicalize(s), p); (s.isOpen() ? open : closed).add(p); }
Source:
<code>private boolean validateId( String fieldName, ModelProblemCollector problems, Severity severity, Version version, String id, String sourceHint, InputLocationTracker tracker ) { if ( !validateStringNotEmpty( fieldName, problems, severity, version, id, sourceHint, tracker ) ) { return false; <START> } <END> else { if ( !org.apache.commons.lang3.StringUtils.containsOnly( id, ID_CHARS ) ) { addViolation( problems, severity, version, fieldName, sourceHint, "with value '" + id + "' does not match a valid id pattern.", tracker ); return false; } return true; } }</code><technical_language>This message reflect issue anymore anymore</technical_language>

Target:
private boolean validateId( String fieldName, ModelProblemCollector problems, Severity severity, Version version, String id, String sourceHint, InputLocationTracker tracker ) { if ( !validateStringNotEmpty( fieldName, problems, severity, version, id, sourceHint, tracker ) ) { return false; } else { if ( !isValidId( id ) ) { addViolation( problems, severity, version, fieldName, sourceHint, "with value '" + id + "' does not match a valid id pattern.", tracker ); return false; } return true; } }
Source:
<code>private HashMap<UUID, Object> readMapFromJson() throws FileNotFoundException { Type mapType = new TypeToken<HashMap<UUID, Object>>() {}.getType(); <START> return new Gson().fromJson(new FileReader(deviceVariablesFile), mapType); <END> }</code><technical_language>this crashes this is a valid json file. project is unrecoverably broken for user delete file manually. (its in app private storage)</technical_language>

Target:
public HashMap<UUID, Object> readMapFromJson() { try { Type mapType = new TypeToken<HashMap<UUID, Object>>() {}.getType(); return new Gson().fromJson(new FileReader(deviceVariablesFile), mapType); } catch (FileNotFoundException e) { if (deviceVariablesFile.exists()) { Log.e(TAG, "Device Variable File corrupted!"); deviceVariablesFile.delete(); } return null; } }
Source:
<code>public void shouldUnStagePartialChangeInCompareEditor() throws Exception { resetRepositoryToCreateInitialTag(); changeFilesInProject(); launchSynchronization(HEAD, HEAD, true); setGitChangeSetPresentationModel(); getCompareEditorForFileInGitChangeSet(FILE1, true).bot(); Display.getDefault().syncExec(new Runnable() { public void run() { CommonUtils.runCommand("org.eclipse.compare.copyRightToLeft", null); } }); bot.activeEditor().save(); FileRepository repo = lookupRepository(repositoryFile); Status status = new Git(repo).status().call(); <START> assertThat(status.getModified().size(), is(1)); <END> assertThat(status.getModified().iterator().next(), is(PROJ1 + "/" + FOLDER + "/" + FILE2)); }</code><technical_language>I get a boxing warning</technical_language>

Target:
public void shouldUnStagePartialChangeInCompareEditor() throws Exception { resetRepositoryToCreateInitialTag(); changeFilesInProject(); launchSynchronization(HEAD, HEAD, true); setGitChangeSetPresentationModel(); getCompareEditorForFileInGitChangeSet(FILE1, true).bot(); Display.getDefault().syncExec(new Runnable() { public void run() { CommonUtils.runCommand("org.eclipse.compare.copyRightToLeft", null); } }); bot.activeEditor().save(); FileRepository repo = lookupRepository(repositoryFile); Status status = new Git(repo).status().call(); assertThat(Long.valueOf(status.getModified().size()), is(Long.valueOf(1))); assertThat(status.getModified().iterator().next(), is(PROJ1 + "/" + FOLDER + "/" + FILE2)); }
Source:
<code>public void registerProtofiles(@Parameter(name = "fileNames", description = "names of the protofiles") String[] names, @Parameter(name = "fileContents", description = "content of the files") String[] contents) throws Exception { if (names.length != contents.length) throw new MBeanException(new IllegalArgumentException("invalid parameter sizes")); for (int i = 0; i < names.length; i++) { clusterRegistry.put(REGISTRY_SCOPE, names[i], contents[i]); } <START> compile(); <END> }</code><technical_language>wondering other cluster nodes updated new files added? Also, existing (persistent contents of cluster registry) handled</technical_language>

Target:
public void registerProtofiles(@Parameter(name = "fileNames", description = "names of the protofiles") String[] names, @Parameter(name = "fileContents", description = "content of the files") String[] contents) throws Exception { if (names.length != contents.length) throw new MBeanException(new IllegalArgumentException("invalid parameter sizes")); FileDescriptorSource fileDescriptorSource = getFileDescriptorSource(); for (int i = 0; i < names.length; i++) { fileDescriptorSource.addProtoFile(names[i], contents[i]); } clusterRegistry.put(REGISTRY_SCOPE, REGISTRY_KEY, fileDescriptorSource); }
Source:
<code>void tick() { final Object[] observers = this.observers; if (observers == null) { return; } <START> if (counter.getAndIncrement() == 0) { <END> final int length = observers.length; final Observer<? super R> child = this.child; final AtomicLong requested = this.requested; do { while (true) { final Object[] vs = new Object[length]; boolean allHaveValues = true; for (int i = 0; i < length; i++) { RxRingBuffer buffer = ((InnerSubscriber) observers[i]).items; Object n = buffer.peek(); if (n == null) { allHaveValues = false; continue; } if (buffer.isCompleted(n)) { child.onCompleted(); childSubscription.unsubscribe(); return; } else { vs[i] = buffer.getValue(n); } } if (requested.get() > 0 && allHaveValues) { try { child.onNext(zipFunction.call(vs)); requested.decrementAndGet(); emitted++; } catch (Throwable e) { Exceptions.throwOrReport(e, child, vs); return; } for (Object obj : observers) { RxRingBuffer buffer = ((InnerSubscriber) obj).items; buffer.poll(); if (buffer.isCompleted(buffer.peek())) { child.onCompleted(); childSubscription.unsubscribe(); return; } } if (emitted > THRESHOLD) { for (Object obj : observers) { ((InnerSubscriber) obj).requestMore(emitted); } emitted = 0; } } else { break; } } } while (counter.decrementAndGet() > 0); } }</code><technical_language>counter read a local variable loop if moved Zip's class hierarchy</technical_language>

Target:
void tick() { final Object[] observers = this.observers; if (observers == null) { return; } if (getAndIncrement() == 0) { final int length = observers.length; final Observer<? super R> child = this.child; final AtomicLong requested = this.requested; do { while (true) { final Object[] vs = new Object[length]; boolean allHaveValues = true; for (int i = 0; i < length; i++) { RxRingBuffer buffer = ((InnerSubscriber) observers[i]).items; Object n = buffer.peek(); if (n == null) { allHaveValues = false; continue; } if (buffer.isCompleted(n)) { child.onCompleted(); childSubscription.unsubscribe(); return; } else { vs[i] = buffer.getValue(n); } } if (requested.get() > 0 && allHaveValues) { try { child.onNext(zipFunction.call(vs)); requested.decrementAndGet(); emitted++; } catch (Throwable e) { Exceptions.throwOrReport(e, child, vs); return; } for (Object obj : observers) { RxRingBuffer buffer = ((InnerSubscriber) obj).items; buffer.poll(); if (buffer.isCompleted(buffer.peek())) { child.onCompleted(); childSubscription.unsubscribe(); return; } } if (emitted > THRESHOLD) { for (Object obj : observers) { ((InnerSubscriber) obj).requestMore(emitted); } emitted = 0; } } else { break; } } } while (decrementAndGet() > 0); } }
Source:
<code>public void doWork() throws Exception { try ( Connection cx = maxwellConnectionPool.getConnection() ) { cx.setAutoCommit(false); <START> try { if (getLock(cx)) { compact(cx); } } finally { releaseLock(cx); } <END> } }</code><technical_language>I mysql locking, for releaseLock fail, connection error etc. - is lock auto-released connection dies? - explicitly shutdown connection error (and out of pool) ensure that</technical_language>

Target:
public void doWork() throws Exception { try ( Connection cx = maxwellConnectionPool.getConnection() ) { cx.setAutoCommit(false); try { if (getLock(cx)) { compact(cx); } } finally { cx.setAutoCommit(true); releaseLock(cx); } } }
Source:
<code>private boolean clearAll(CommandSender sender, Player player, Material material, int data, int maxCount, ResourceBundle resourceBundle) { int count = countAllItems(player.getInventory(), material, data, maxCount); if (maxCount == 0) { new LocalizedStringImpl("clear.count", resourceBundle).send( sender, player.getName(), count); return true; } if (count == 0) { new LocalizedStringImpl("clear.empty", resourceBundle).send( sender, player.getName()); return false; } if (material == null) { player.getInventory().clear(); } else { int remaining = maxCount; for (ItemStack stack : player.getInventory().getContents()) { if (stack.getType() == material && (data == -1 || data == stack.getData() .getData())) { if (maxCount == -1) { player.getInventory().remove(stack); } else { int oldAmount = stack.getAmount(); int removed = Math.min(oldAmount, remaining); stack.setAmount(oldAmount - removed); remaining -= removed; } } if (remaining == 0) { break; } } } <START> new LocalizedStringImpl("clear.done", resourceBundle).send( <END> sender, player.getName(), count); return true; }</code><technical_language>this changed singular form item is count == 1</technical_language>

Target:
private boolean clearAll(CommandSender sender, Player player, Material material, int data, int maxCount, ResourceBundle resourceBundle) { int count = countAllItems(player.getInventory(), material, data, maxCount); if (maxCount == 0) { new LocalizedStringImpl("clear.count", resourceBundle).send( sender, player.getName(), count); return true; } if (count == 0) { new LocalizedStringImpl("clear.empty", resourceBundle).send( sender, player.getName()); return false; } if (material == null) { player.getInventory().clear(); } else { int remaining = maxCount; for (ItemStack stack : player.getInventory().getContents()) { if (stack.getType() == material && (data == -1 || data == stack.getData() .getData())) { if (maxCount == -1) { player.getInventory().remove(stack); } else { int oldAmount = stack.getAmount(); int removed = Math.min(oldAmount, remaining); stack.setAmount(oldAmount - removed); remaining -= removed; } } if (remaining == 0) { break; } } } if (count == 1) { new LocalizedStringImpl("clear.done.singular", resourceBundle).send( sender, player.getName()); } else { new LocalizedStringImpl("clear.done", resourceBundle).send( sender, player.getName(), count); } return true; }
Source:
<code>protected void executeCommand() { Cluster cluster = getCluster(); boolean initSucceeded = true; <START> clusterCpuFlagsManager.updateClusterCpuFlags(); <END> initHostKdumpDetectionStatus(); getVds().setPowerManagementControlledByPolicy(true); vdsDynamicDao.updateVdsDynamicPowerManagementPolicyFlag( getVds().getId(), getVds().isPowerManagementControlledByPolicy()); if (getVds().getHighlyAvailableIsConfigured()) { haMaintenanceFailed = !hostedEngineHelper.updateHaLocalMaintenanceMode(getVds(), false); } if (cluster.supportsTrustedService()) { initSucceeded = initTrustedService(); } if (initSucceeded && cluster.supportsVirtService()) { initSucceeded = initVirtResources(); } if (initSucceeded && cluster.supportsGlusterService()) { initSucceeded = glusterCommandHelper.initGlusterHost(getVds()); } setSucceeded(initSucceeded); if (getSucceeded()) { addCustomValue("HostStatus", getVds().getStatus().toString()); auditLogDirector.log(this, AuditLogType.VDS_DETECTED); } }</code><technical_language>update CPU flags cluster host is, clusters. safe, please pass current updated host a parameter, in case flags saved in DB</technical_language>

Target:
protected void executeCommand() { Cluster cluster = getCluster(); boolean initSucceeded = true; vdsDynamicDao.updateCpuFlags(getVds().getId(), getVds().getCpuFlags()); clusterCpuFlagsManager.updateClusterCpuFlags(getCluster()); initHostKdumpDetectionStatus(); getVds().setPowerManagementControlledByPolicy(true); vdsDynamicDao.updateVdsDynamicPowerManagementPolicyFlag( getVds().getId(), getVds().isPowerManagementControlledByPolicy()); if (getVds().getHighlyAvailableIsConfigured()) { haMaintenanceFailed = !hostedEngineHelper.updateHaLocalMaintenanceMode(getVds(), false); } if (cluster.supportsTrustedService()) { initSucceeded = initTrustedService(); } if (initSucceeded && cluster.supportsVirtService()) { initSucceeded = initVirtResources(); } if (initSucceeded && cluster.supportsGlusterService()) { initSucceeded = glusterCommandHelper.initGlusterHost(getVds()); } setSucceeded(initSucceeded); if (getSucceeded()) { addCustomValue("HostStatus", getVds().getStatus().toString()); auditLogDirector.log(this, AuditLogType.VDS_DETECTED); } }
Source:
<code>public static <T> void assertCorrectPropertyPaths(Set<ConstraintViolation<T>> violations, String... propertyPaths) { List<String> propertyPathsOfViolations = new ArrayList<String>(); for ( ConstraintViolation<?> violation : violations ) { propertyPathsOfViolations.add( violation.getPropertyPath().toString() ); } assertEquals( propertyPathsOfViolations.size(), propertyPaths.length, "Wrong number of property paths." ); for ( String propertyPath : propertyPaths ) { <START> if ( !propertyPathsOfViolations.contains( propertyPath ) ) { <END> fail( propertyPath + " is not in the list of path instances contained in the actual constraint violations: " + propertyPathsOfViolations ); } } }</code><technical_language>Hum, risky solely base assertion string representation, spec mandate one. assertCorrectPropertyPaths() a more object-orientated representation of expected paths (we leave current for common case of plain non-indexed, non-keyed props). If agree, open a follow-up BVTCK issue for it</technical_language>

Target:
public static <T> void assertCorrectPropertyPaths(Set<ConstraintViolation<T>> violations, String... propertyPaths) { List<Path> propertyPathsOfViolations = new ArrayList<Path>(); for ( ConstraintViolation<?> violation : violations ) { propertyPathsOfViolations.add( violation.getPropertyPath() ); } assertEquals( propertyPathsOfViolations.size(), propertyPaths.length, "Wrong number of property paths." ); for ( String propertyPath : propertyPaths ) { Path expectedPath = PathImpl.createPathFromString( propertyPath ); boolean containsPath = false; for ( Path actualPath : propertyPathsOfViolations ) { if ( assertEqualPaths( expectedPath, actualPath ) ) { containsPath = true; break; } } if ( !containsPath ) { fail( expectedPath + " is not in the list of path instances contained in the actual constraint violations: " + propertyPathsOfViolations ); } } }
Source:
<code>private String getCheckerVersion() { String version = null; Properties p = new Properties(); String RLS_FILE = "/docs/developer/release/release.properties"; p.putAll(getProperties(getClass(), RLS_FILE)); String startTag = p.getProperty("checkers.ver.0"); String endTag = p.getProperty("checkers.ver.1"); String XML_FILE = "/docs/examples/MavenExample/pom.xml"; try { InputStream in = getClass().getResourceAsStream(XML_FILE); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null && version == null) { if (line.split(startTag).length > 1) { <START> version = line.split(startTag)[1].split(endTag)[0]; <END> } } } catch (IOException e) { System.out.println("IOException while reading version information: " + e.getMessage()); } return version; }</code><technical_language>this loop continue setting version? a return statement here</technical_language>

Target:
private String getCheckerVersion() { Properties gitProperties = getProperties(getClass(), "/git.properties"); String version = gitProperties.getProperty("git.build.version"); if (version != null) { return version; } throw new BugInCF("Could not find the version in git.properties"); }
Source:
<code>protected List getFieldOrder() { return Arrays.asList(new String[] { "dwStructSize", "lpszSourceUrlName", "lpszLocalFileName", "CacheEntryType", "dwUseCount", "dwHitRate", "dwSizeLow", "dwSizeHigh", "LastModifiedTime", "ExpireTime", "LastAccessTime", "LastSyncTime", "lpHeaderInfo", "dwHeaderInfoSize", "lpszFileExtension", "u", "additional" }); <START> } <END></code><technical_language>suppress warning need allocate _new String[]_ - java @Override protected List<String> getFieldOrder() { return Arrays.asList("field1", "field2", ...); }</technical_language>

Target:
protected List getFieldOrder() { return Arrays.asList("dwStructSize", "lpszSourceUrlName", "lpszLocalFileName", "CacheEntryType", "dwUseCount", "dwHitRate", "dwSizeLow", "dwSizeHigh", "LastModifiedTime", "ExpireTime", "LastAccessTime", "LastSyncTime", "lpHeaderInfo", "dwHeaderInfoSize", "lpszFileExtension", "u", "additional"); }
Source:
<code>public ConfigMemorySize getMemorySize(String path) { BigInteger size; try { size = BigInteger.valueOf(getLong(path)); } catch (ConfigException.WrongType e) { ConfigValue v = find(path, ConfigValueType.STRING); size = parseBytesAsBigInteger((String) v.unwrapped(), v.origin(), path); } <START> return ConfigMemorySize.ofBytes(size); <END> }</code><technical_language>great reduce cut-and-paste getMemorySize getBytes ... flip calls other, getBytes call getMemorySize.toBytes? toBytes need tweaked throw ConfigException throw bytes out of range</technical_language>

Target:
public ConfigMemorySize getMemorySize(String path) { return ConfigMemorySize.ofBytes(getBytesBigInteger(path)); }
Source:
<code>private Collection<Long> toList(TLongList values) { List<Long> result = Lists.newArrayListWithExpectedSize(values.size()); <START> for (int i = 0; i < values.size(); i++) { <END> result.add(values.get(i)); } return result; }</code><technical_language>replace for loop values.forEach(result::add);</technical_language>

Target:
private Collection<Long> toList(TLongList values) { List<Long> result = Lists.newArrayListWithExpectedSize(values.size()); values.forEach(result::add); return result; }
Source:
<code>protected List<CandidateCellForSweeping> computeNext() { if (endOfResults) { return endOfData(); } else { try (ConnectionSupplier conns = new ConnectionSupplier(connectionPool); ClosableIterator<AgnosticLightResultRow> iter = selectNextPage(conns)) { List<CandidateCellForSweeping> results = new ArrayList<>(); boolean noResults = true; cellTsPairsExaminedCurrentBatch = 0; while (iter.hasNext()) { noResults = false; AgnosticLightResultRow sqlRow = iter.next(); byte[] rowName = sqlRow.getBytes("row_name"); byte[] colName = sqlRow.getBytes("col_name"); <START> if (!Arrays.equals(currentRowName, rowName) || !Arrays.equals(currentColName, colName)) { <END> getCurrentCandidate().ifPresent(results::add); currentCellTimestamps.clear(); currentRowName = rowName; currentColName = colName; } Object[] timestamps = (Object[]) sqlRow.getArray("timestamps"); for (Object ts : timestamps) { currentCellTimestamps.add((Long) ts); } cellTsPairsExaminedCurrentBatch = sqlRow.getLong("cell_ts_number"); if (request.shouldCheckIfLatestValueIsEmpty()) { currentIsLatestValueEmpty = sqlRow.getBoolean("latest_val_empty"); } } if (noResults) { getCurrentCandidate().ifPresent(results::add); endOfResults = true; } else { computeNextStartPosition(); } cellTsPairsExaminedTotal += cellTsPairsExaminedCurrentBatch; return results; } } }</code><technical_language>(nit) this line more sense in De Morgan'd form !(sameRow sameCol) currently written</technical_language>

Target:
protected List<CandidateCellForSweeping> computeNext() { if (endOfResults) { return endOfData(); } else { try (ConnectionSupplier conns = new ConnectionSupplier(connectionPool); ClosableIterator<AgnosticLightResultRow> iter = selectNextPage(conns)) { List<CandidateCellForSweeping> results = new ArrayList<>(); boolean noResults = true; cellTsPairsExaminedCurrentBatch = 0; while (iter.hasNext()) { noResults = false; AgnosticLightResultRow sqlRow = iter.next(); byte[] rowName = sqlRow.getBytes("row_name"); byte[] colName = sqlRow.getBytes("col_name"); if (!isCurrentCell(rowName, colName)) { getCurrentCandidate().ifPresent(results::add); currentCellTimestamps.clear(); currentRowName = rowName; currentColName = colName; } Object[] timestamps = (Object[]) sqlRow.getArray("timestamps"); for (Object ts : timestamps) { currentCellTimestamps.add((Long) ts); } cellTsPairsExaminedCurrentBatch = sqlRow.getLong("max_row_number"); if (request.shouldCheckIfLatestValueIsEmpty()) { currentIsLatestValueEmpty = sqlRow.getBoolean("latest_val_empty"); } } if (noResults || cellTsPairsExaminedCurrentBatch < sqlRowLimit) { getCurrentCandidate().ifPresent(results::add); endOfResults = true; } else { computeNextStartPosition(); } cellTsPairsExaminedTotal += cellTsPairsExaminedCurrentBatch; return results; } } }
Source:
<code>private Promise<Boolean> validatePropertyIsNotEmpty(final List<Property> listProperty, final String errorMessage) { boolean isEmpty = false; for (Property property : listProperty) { if (property.getName() == null || property.getName().trim().isEmpty()) { isEmpty = true; } if (property.getValue() == null || property.getValue().trim().isEmpty()) { isEmpty = true; } } <START> boolean finalIsEmpty = isEmpty; <END> return promises.create((resolve, reject) -> { if (finalIsEmpty) { reject.onInvoke(errorMessage); } else { resolve.onInvoke(true); } }); }</code><technical_language>Is this assignment needed</technical_language>

Target:
Promise<Boolean> validatePropertyIsNotEmpty(final List<Property> listProperty, final String errorMessage) { return promises.create((resolve, reject) -> { if (isEmpty(listProperty)) { reject.onInvoke(errorMessage); } else { resolve.onInvoke(true); } }); }
Source:
<code>private void initializeMap() { WebSourceTileLayer tileSource = new WebSourceTileLayer( "openstreetmap", <START> MAP_TILE_SOURCE + "{z}/{x}/{y}.png", <END> true ); mapView.setDiskCacheEnabled(true); mapView.setTileSource(tileSource); mapView.setZoom(MAP_DEFAULT_ZOOM); mapView.setUserLocationEnabled(true); mapView.setUserLocationTrackingMode(UserLocationOverlay.TrackingMode.FOLLOW_BEARING); mapView.getUserLocationOverlay().runOnFirstFix(new Runnable() { @Override public void run() { currentLocation = mapView.getUserLocationOverlay().getLastFix(); makeUseOfNewLocation(currentLocation); fetchNearbyPages(); } }); mapView.setMapViewListener(new MapViewListener() { @Override public void onShowMarker(MapView mapView, Marker marker) { } @Override public void onHideMarker(MapView mapView, Marker marker) { } @Override public void onTapMarker(MapView mapView, Marker marker) { highlightMarker(marker); int index = adapter.getPosition((NearbyPage) marker.getRelatedObject()); if (index == -1) { return; } nearbyList.setSelection(index); } @Override public void onLongPressMarker(MapView mapView, Marker marker) { } @Override public void onTapMap(MapView mapView, ILatLng iLatLng) { } @Override public void onLongPressMap(MapView mapView, ILatLng iLatLng) { } }); mapView.addListener(new MapListener() { @Override public void onScroll(ScrollEvent scrollEvent) { fetchNearbyPages(); } @Override public void onZoom(ZoomEvent zoomEvent) { fetchNearbyPages(); } @Override public void onRotate(RotateEvent rotateEvent) { } }); }</code><technical_language>put "{z}/{x}/{y}.png" in MAP_TILE_SOURCE</technical_language>

Target:
private void initializeMap() { WebSourceTileLayer tileSource = new WebSourceTileLayer( "openstreetmap", getString(R.string.map_tile_source_url), true ); mapView.setDiskCacheEnabled(true); mapView.setTileSource(tileSource); mapView.setZoom(getResources().getInteger(R.integer.map_default_zoom)); mapView.setUserLocationEnabled(true); mapView.setUserLocationTrackingMode(UserLocationOverlay.TrackingMode.FOLLOW_BEARING); mapView.getUserLocationOverlay().runOnFirstFix(new Runnable() { @Override public void run() { currentLocation = mapView.getUserLocationOverlay().getLastFix(); makeUseOfNewLocation(currentLocation); fetchNearbyPages(); } }); mapView.setMapViewListener(new DefaultMapViewListener() { @Override public void onTapMarker(MapView mapView, Marker marker) { highlightMarker(marker); int index = adapter.getPosition((NearbyPage) marker.getRelatedObject()); if (index == -1) { return; } nearbyList.setSelection(index); } }); mapView.addListener(new MapListener() { @Override public void onScroll(ScrollEvent scrollEvent) { fetchNearbyPages(); } @Override public void onZoom(ZoomEvent zoomEvent) { fetchNearbyPages(); } @Override public void onRotate(RotateEvent rotateEvent) { } }); }
Source:
<code>public void testQueryClassExistence() { <START> List<VdcQueryType> missingQueries = new ArrayList<>(); <END> for (VdcQueryType vqt : VdcQueryType.values()) { if (vqt != VdcQueryType.Unknown) { if (CommandsFactory.getQueryClass(vqt.name()) == null) { missingQueries.add(vqt); } } } assertTrue("VdcQueryType contains the following values that does not correspond to an existing query class: " + missingQueries, missingQueries.isEmpty()); }</code><technical_language>Nit: A LinkedList more suited for this kind of usage</technical_language>

Target:
public void testQueryClassExistence() { List<VdcQueryType> missingQueries = new LinkedList<>(); for (VdcQueryType vqt : VdcQueryType.values()) { if (vqt != VdcQueryType.Unknown) { if (CommandsFactory.getQueryClass(vqt.name()) == null) { missingQueries.add(vqt); } } } assertTrue("VdcQueryType contains the following values that does not correspond to an existing query class: " + missingQueries, missingQueries.isEmpty()); }
Source:
<code>public ThingUID getThingUID(ServiceInfo service) { if (service != null) { String name = service.getName(); <START> if (Objects.equals(service.getType(), getServiceType()) && (name.matches(GATEWAY_NAME_REGEX_PATTERN))) { <END> return new ThingUID(GATEWAY_TYPE_UID, name.replaceAll("[^A-Za-z0-9_]", "")); } } return null; }</code><technical_language>mentioned previously, check for service type belong here. I created <LINK_0> instead</technical_language>

Target:
public ThingUID getThingUID(ServiceInfo service) { if (service != null) { Matcher m = GATEWAY_NAME_REGEX_PATTERN.matcher(service.getName()); if (m.find()) { return new ThingUID(GATEWAY_TYPE_UID, m.group(1).replaceAll("[^A-Za-z0-9_]", "")); } } return null; }