auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testOnStartCommandStartReplicationCommandsQueuedConsecutiveDuplicatesRemoved() { PeriodicReplicationService service = new TestReplicationService(mMockContext); Intent startIntent = new Intent(mMockContext, TestReplicationService.class); startIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService.COMMAND_START_REPLICATION); Intent stopIntent = new Intent(mMockContext, TestReplicationService.class); stopIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService .COMMAND_STOP_REPLICATION); service.setReplicationPolicyManager(mMockReplicationPolicyManager); service.onCreate(); final CountDownLatch latch = new CountDownLatch(2); service.setOperationStartedListener(new PeriodicReplicationService .OperationStartedListener() { @Override public void operationStarted(int operationId) { if (latch.getCount() == 2 && operationId == PeriodicReplicationService .COMMAND_START_REPLICATION) { <START> latch.countDown(); <END> } else if (latch.getCount() == 1 && operationId == PeriodicReplicationService .COMMAND_STOP_REPLICATION) { latch.countDown(); } } }); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(stopIntent, 0, 0); service.setReplicators(mMockReplicators); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }</code><technical_language>previous case, is worth checking ordering too</technical_language>

Target:
public void testOnStartCommandStartReplicationCommandsQueuedConsecutiveDuplicatesRemoved() { PeriodicReplicationService service = new TestReplicationService(mMockContext); Intent startIntent = new Intent(mMockContext, TestReplicationService.class); startIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService.COMMAND_START_REPLICATION); Intent stopIntent = new Intent(mMockContext, TestReplicationService.class); stopIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService .COMMAND_STOP_REPLICATION); service.setReplicationPolicyManager(mMockReplicationPolicyManager); service.onCreate(); final CountDownLatch latch = new CountDownLatch(2); service.setOperationStartedListener(new PeriodicReplicationService .OperationStartedListener() { @Override public void operationStarted(int operationId) { if (latch.getCount() == 2 && operationId == PeriodicReplicationService .COMMAND_START_REPLICATION) { latch.countDown(); } else if (latch.getCount() == 1 && operationId == PeriodicReplicationService .COMMAND_STOP_REPLICATION) { latch.countDown(); } else { fail("Unexpected command or commands received in incorrect order"); } } }); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(stopIntent, 0, 0); service.setReplicators(mMockReplicators); try { assertTrue("The countdown should reach zero", latch.await(DEFAULT_WAIT_SECONDS, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } }
Source:
<code>public void testCanAttachToPackageMultipleNodes() { <START> ClassNode node1 = new ClassNode(); <END> InterfaceNode node2 = new InterfaceNode(); PackageNode node3 = new PackageNode(); aDiagram.addRootNode(node1); aDiagram.addRootNode(node2); aDiagram.addRootNode(node3); assertTrue(aBuilder.canAttachToPackage(Arrays.asList(node1, node2))); }</code><technical_language>initialized in a setUp method @BeforeEach</technical_language>

Target:
public void testCanAttachToPackageMultipleNodes() { ClassNode child1 = new ClassNode(); InterfaceNode child2 = new InterfaceNode(); PackageNode parent = new PackageNode(); aDiagram.addRootNode(child1); aDiagram.addRootNode(child2); aDiagram.addRootNode(parent); assertTrue(aBuilder.canAttachToPackage(Arrays.asList(child1, child2))); }
Source:
<code>private static int calculateBinaryShiftCost(State state) { <START> if (state.binaryShiftByteCount > 62) { <END> return 21; } else if (state.binaryShiftByteCount > 31) { return 20; } else if (state.binaryShiftByteCount > 0) { return 10; } else { return 0; } }</code><technical_language>Nit: 2-space indent here. I dispense "else" statements write: if (...) { return ...; } if (...) { return ...; }</technical_language>

Target:
private static int calculateBinaryShiftCost(State state) { if (state.binaryShiftByteCount > 62) { return 21; } if (state.binaryShiftByteCount > 31) { return 20; } if (state.binaryShiftByteCount > 0) { return 10; } return 0; }
Source:
<code>public List<ValueReference> getAllPossibleValues(final Variable variable) { List<ValueReference> possibleValues = this.getCachedValues(false, variable); if (possibleValues.isEmpty()) { DataType dataType = variable.getScale().getDataType(); <START> if (TermId.BREEDING_METHOD_CODE.getId() == variable.getId() || TermId.BREEDING_METHOD_VARIATE_CODE.getId() == variable.getId()) { <END> dataType = DataType.BREEDING_METHOD; } switch (dataType) { case BREEDING_METHOD: possibleValues .add(new ValueReference(0, AppConstants.PLEASE_CHOOSE.getString(), AppConstants.PLEASE_CHOOSE.getString())); final List<ValueReference> allBreedingMethods = this.getAllBreedingMethods(true, this.contextUtil.getCurrentProgramUUID()); possibleValues.addAll(allBreedingMethods); this.possibleValuesCache.addPossibleValuesByDataType(DataType.BREEDING_METHOD, allBreedingMethods); break; case LOCATION: possibleValues = this.getAllLocations(true); this.possibleValuesCache.addLocations(true, possibleValues); break; case PERSON: possibleValues = this.convertPersonsToValueReferences(this.fieldbookMiddlewareService.getAllPersonsOrderedByLocalCentral()); this.possibleValuesCache.addPossibleValuesByDataType(DataType.PERSON, possibleValues); break; case CATEGORICAL_VARIABLE: for (final TermSummary value : variable.getScale().getCategories()) { possibleValues.add(new ValueReference(value)); } this.possibleValuesCache.addPossibleValues(variable.getId(), possibleValues); break; default: break; } } return possibleValues; }</code><technical_language>I checked _cvterm_relationship_ table in maize database. - BM_CODE_VTE cvterm 8252 - scale BMETH_CODE cvterm 6015 (cvterm_relationship table) - Scale BMETH_CODE data type 1120 = Character (cvterm_relationship table) I is, instead of 1120, if set data type = 1136 (Breeding Method) wouln't eliminate this hack in code? applies for original hack done in <LINK_0> for STUDY_BM_CODE</technical_language>

Target:
public List<ValueReference> getAllPossibleValues(final Variable variable) { return this.getAllPosibleValues(variable, true, true); }
Source:
<code>public Map<String, Object> execute(Map<String, Object> context) { for (String uid : ruleUIDs) { if (ruleRegistry != null) { ruleRegistry.runNow(uid, considerConditions); } else { <START> logger.warn("Action is not applyed to because RuleRegistry is not available.", uid); <END> } } return null; }</code><technical_language>typo: applied</technical_language>

Target:
public Map<String, Object> execute(Map<String, Object> context) { for (String uid : ruleUIDs) { if (ruleRegistry != null) { ruleRegistry.runNow(uid, considerConditions); } else { logger.warn("Action is not applied to because RuleRegistry is not available.", uid); } } return null; }
Source:
<code>public void populateCachedValues(Collection<?> objects, Map<Long, String> preComputedValueMap) { for (Object element : objects) { Artifact artifactCursor = getArtifactFromElement(element); if (artifactCursor != null) { <START> Long artId = artifactCursor.getId(); <END> if (!artIdToName.containsKey(artId)) { if (artifactCursor.isDeleted()) { artIdToName.put(artId, "deleted"); } else { StringBuilder builder = new StringBuilder(20); Artifact root = OseeSystemArtifacts.getDefaultHierarchyRootArtifact(artifactCursor.getBranch()); String error = Strings.emptyString(); while (!artifactCursor.equals(root)) { Artifact parent = null; try { parent = artifactCursor.getParent(); } catch (OseeCoreException ex) { error = "Hierarchy Index unavailable: " + ex.getLocalizedMessage(); break; } if (parent == null) { error = "not connected to root"; break; } builder.insert(0, getPosition(artifactCursor) + "."); artifactCursor = parent; } if (error.isEmpty()) { if (builder.length() > 0) { artIdToName.put(artId, builder.substring(0, builder.length() - 1)); } else { artIdToName.put(artId, "no parent"); } } else { artIdToName.put(artId, error); } } } } } parentToChildrenCache.clear(); }</code><technical_language>need artIdToName map, preComputedValueMap. need override getText method below</technical_language>

Target:
public void populateCachedValues(Collection<?> objects, Map<Long, String> preComputedValueMap) { for (Object element : objects) { Artifact artifactCursor = getArtifactFromElement(element); if (artifactCursor != null) { Long artId = artifactCursor.getId(); if (!preComputedValueMap.containsKey(artId)) { if (artifactCursor.isDeleted()) { preComputedValueMap.put(artId, "deleted"); } else { StringBuilder builder = new StringBuilder(20); String error = Strings.emptyString(); while (!artifactCursor.equals(CoreArtifactTokens.DefaultHierarchyRoot)) { Artifact parent = null; try { parent = artifactCursor.getParent(); } catch (OseeCoreException ex) { error = "Hierarchy Index unavailable: " + ex.getLocalizedMessage(); break; } if (parent == null) { error = "not connected to root"; break; } builder.insert(0, getPosition(artifactCursor) + "."); artifactCursor = parent; } if (error.isEmpty()) { if (builder.length() > 0) { preComputedValueMap.put(artId, builder.substring(0, builder.length() - 1)); } else { preComputedValueMap.put(artId, "no parent"); } } else { preComputedValueMap.put(artId, error); } } } } } parentToChildrenCache.clear(); }
Source:
<code>private int writeString(PutRecordRequest putRecordRequest, Object data) { putRecordRequest.setData(ByteBuffer.wrap(Bytes.toBytes((String) data))); <START> kinesisClient.putRecord(putRecordRequest); <END> return 1; }</code><technical_language>if this fails? return a 1 record written</technical_language>

Target:
private int writeString(PutRecordRequest putRecordRequest, Object data) { putRecordRequest.setData(ByteBuffer.wrap(Bytes.toBytes((String) data))); return putRecord(putRecordRequest); }
Source:
<code>public Collection<Replay> getLocalReplays() { Collection<Replay> replayInfos = new ArrayList<>(); String replayFileGlob = clientProperties.getReplay().getReplayFileGlob(); Path replaysDirectory = preferencesService.getReplaysDirectory(); if (Files.notExists(replaysDirectory)) { noCatch(() -> createDirectories(replaysDirectory)); } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replaysDirectory, replayFileGlob)) { for (Path replayFile : directoryStream) { try { LocalReplayInfo replayInfo = replayFileReader.parseMetaData(replayFile); FeaturedMod featuredMod = modService.getFeaturedMod(replayInfo.getFeaturedMod()).getNow(FeaturedMod.UNKNOWN); mapService.findByMapFolderName(replayInfo.getMapname()) .thenAccept(mapBean -> { if (!mapBean.isPresent()) { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("mapNotFound", replayInfo.getMapname()), WARN )); return; } replayInfos.add(new Replay(replayInfo, replayFile, featuredMod, mapBean.get())); }); } catch (Exception e) { <START> logger.warn(MessageFormat.format("Could not read replay file {0}", replayFile), e); <END> moveCorruptedReplayFile(replayFile); } } } return replayInfos; }</code><technical_language>logger supports both, string replacement exceptions stack traces; logger.warn("Could read replay file '{}'", replayFile, e);</technical_language>

Target:
public Collection<Replay> getLocalReplays() { Collection<Replay> replayInfos = new ArrayList<>(); String replayFileGlob = clientProperties.getReplay().getReplayFileGlob(); Path replaysDirectory = preferencesService.getReplaysDirectory(); if (Files.notExists(replaysDirectory)) { noCatch(() -> createDirectories(replaysDirectory)); } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replaysDirectory, replayFileGlob)) { for (Path replayFile : directoryStream) { try { LocalReplayInfo replayInfo = replayFileReader.parseMetaData(replayFile); FeaturedMod featuredMod = modService.getFeaturedMod(replayInfo.getFeaturedMod()).getNow(FeaturedMod.UNKNOWN); mapService.findByMapFolderName(replayInfo.getMapname()) .thenAccept(mapBean -> { if (!mapBean.isPresent()) { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("mapNotFound", replayInfo.getMapname()), WARN )); return; } replayInfos.add(new Replay(replayInfo, replayFile, featuredMod, mapBean.get())); }); } catch (Exception e) { logger.warn("Could not read replay file '{}'", replayFile, e); moveCorruptedReplayFile(replayFile); } } } return replayInfos; }
Source:
<code>public void noLocalBinaryTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message, never()).setHeader(eq(CdrBinaryPath), anyString()); <START> verify(message, never()).setHeader(eq(CdrBinaryId), anyString()); <END> }</code><technical_language>If this class set CdrBinaryId, need test for</technical_language>

Target:
public void noLocalBinaryTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message, never()).setHeader(eq(CdrBinaryPath), anyString()); }
Source:
<code>public JobFutureTask(final JobManager jobManager, final RunMonitor runMonitor, final JobInput input, final CallableChain<RESULT> callableChain, final Callable<RESULT> callable) { super(() -> callableChain.call(callable) ); m_jobManager = jobManager; m_runMonitor = runMonitor; m_input = input; m_executionSemaphore = ExecutionSemaphore.get(input); m_callableChain = callableChain; m_completionPromise = new CompletionPromise<>(this, jobManager.getExecutor()); m_expirationDate = (input.getExpirationTimeMillis() != JobInput.EXPIRE_NEVER ? System.currentTimeMillis() + input.getExpirationTimeMillis() : null); m_executionHints.addAll(input.getExecutionHints()); m_jobManager.interceptCallableChain(m_callableChain, this, m_runMonitor, m_input); <START> addRunMonitorCancelledCallableInterceptor(m_callableChain, <END> m_runMonitor); m_callableChain.addLast(() -> { changeState(JobState.RUNNING); return null; }); m_trigger = createQuartzTrigger(input); m_calendar = (input.getExecutionTrigger() == null ? null : input.getExecutionTrigger().getCalendar()); m_firstFireTime = computeFirstFireTime(m_trigger); m_singleExecution = computeSingleExecuting(m_trigger, m_firstFireTime); m_delayedExecution = (input.getExecutionTrigger() == null ? false : computeDelayedExecuting(m_firstFireTime, m_input.getExecutionTrigger().getNow())); m_jobManager.registerFuture(this); m_runMonitor.registerCancellable(this); }</code><technical_language>is this done in extra method while next is done inline? In general overridable method call in a constructor is considered bad practice</technical_language>

Target:
public JobFutureTask(final JobManager jobManager, final RunMonitor runMonitor, final JobInput input, final CallableChain<RESULT> callableChain, final Callable<RESULT> callable) { super(() -> callableChain.call(callable) ); m_jobManager = jobManager; m_runMonitor = runMonitor; m_input = input; m_executionSemaphore = ExecutionSemaphore.get(input); m_callableChain = callableChain; m_completionPromise = new CompletionPromise<>(this, jobManager.getExecutor()); m_expirationDate = (input.getExpirationTimeMillis() != JobInput.EXPIRE_NEVER ? System.currentTimeMillis() + input.getExpirationTimeMillis() : null); m_executionHints.addAll(input.getExecutionHints()); m_jobManager.interceptCallableChain(m_callableChain, this, m_runMonitor, m_input); m_callableChain.addLast(new ICallableInterceptor<RESULT>() { @Override public RESULT intercept(Chain<RESULT> chain) throws Exception { return null; } @Override public boolean isEnabled() { return m_runMonitor.isCancelled(); } }); m_callableChain.addLast(() -> { changeState(JobState.RUNNING); return null; }); m_trigger = createQuartzTrigger(input); m_calendar = (input.getExecutionTrigger() == null ? null : input.getExecutionTrigger().getCalendar()); m_firstFireTime = computeFirstFireTime(m_trigger); m_singleExecution = computeSingleExecuting(m_trigger, m_firstFireTime); m_delayedExecution = (input.getExecutionTrigger() == null ? false : computeDelayedExecuting(m_firstFireTime, m_input.getExecutionTrigger().getNow())); m_jobManager.registerFuture(this); m_runMonitor.registerCancellable(this); }
Source:
<code>public static String formatAbbrev(final Context context, final Date date) { if (date == null) { return ""; } GregorianCalendar now = new GregorianCalendar(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); <START> cal.add(GregorianCalendar.DAY_OF_MONTH, 10); <END> boolean withinLastYear = now.get(Calendar.YEAR) == cal.get(Calendar.YEAR); int format = android.text.format.DateUtils.FORMAT_ABBREV_ALL; if (withinLastYear) { format |= android.text.format.DateUtils.FORMAT_NO_YEAR; } return android.text.format.DateUtils.formatDateTime(context, date.getTime(), format); }</code><technical_language>this line removed, then</technical_language>

Target:
public static String formatAbbrev(final Context context, final Date date) { if (date == null) { return ""; } GregorianCalendar now = new GregorianCalendar(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); boolean withinLastYear = now.get(Calendar.YEAR) == cal.get(Calendar.YEAR); int format = android.text.format.DateUtils.FORMAT_ABBREV_ALL; if (withinLastYear) { format |= android.text.format.DateUtils.FORMAT_NO_YEAR; } return android.text.format.DateUtils.formatDateTime(context, date.getTime(), format); }
Source:
<code>public void afterTest(Method method) { Robolectric.flushBackgroundThreadScheduler(); <START> assertTrue(asyncTestsPassed); <END> }</code><technical_language>This ends bubbling end "the failure", worth retaining (I more one, good one) of exceptions this point pass assertion failure. output confusing, I think</technical_language>

Target:
public void afterTest(Method method) { Robolectric.flushBackgroundThreadScheduler(); if (!asyncExceptions.isEmpty()) { for(Throwable throwable: asyncExceptions) { throwable.printStackTrace(); fail("Test failed due to " + asyncExceptions.size() + " threads crashing off the main thread. See error log for more details"); } } }
Source:
<code>public boolean isSubtypeOf(TypeValue other) { if (this == other) { return true; } if (!(other instanceof TupleTypeValue)) { return false; } TupleTypeValue oTuple = (TupleTypeValue) other; if (!(getSize() != oTuple.getSize())) { return false; } for (int i = 0; i < getSize(); ++i) { TypeValue myType = entry(i).getType(); TypeValue otherType = oTuple.entry(i).getType(); <START> if (!(myType.isSubtypeOf(otherType) || otherType.isSubtypeOf(myType))) { <END> return false; } } return true; }</code><technical_language>a tuple qualify a subtype of another if members supertype of other</technical_language>

Target:
public boolean isSubtypeOf(TypeValue other) { if (this == other) { return true; } if (!(other instanceof TupleTypeValue)) { return false; } TupleTypeValue oTuple = (TupleTypeValue) other; if (!(getSize() != oTuple.getSize())) { return false; } for (int i = 0; i < getSize(); ++i) { TypeValue myType = entry(i).getType(); TypeValue otherType = oTuple.entry(i).getType(); if (!myType.isSubtypeOf(otherType)) { return false; } } return true; }
Source:
<code>PlanNodeStatsEstimate calculateJoinComplementStats( Optional<Expression> filter, List<JoinNode.EquiJoinClause> criteria, PlanNodeStatsEstimate leftStats, PlanNodeStatsEstimate rightStats, TypeProvider types) { <START> if (leftStats.getOutputRowCount() == 0 || rightStats.getOutputRowCount() == 0) { <END> return leftStats; } if (criteria.isEmpty()) { if (filter.isPresent()) { return PlanNodeStatsEstimate.unknown(); } return normalizer.normalize(leftStats.mapOutputRowCount(rowCount -> 0.0), types); } int numberOfFilterClauses = filter.map(expression -> extractConjuncts(expression).size()).orElse(0); return criteria.stream() .map(drivingClause -> calculateJoinComplementStats(leftStats, rightStats, drivingClause, criteria.size() - 1 + numberOfFilterClauses)) .filter(estimate -> !estimate.isOutputRowCountUnknown()) .max(comparingDouble(PlanNodeStatsEstimate::getOutputRowCount)) .map(estimate -> normalizer.normalize(estimate, types)) .orElse(PlanNodeStatsEstimate.unknown()); }</code><technical_language>a test for that? Especially in of TestTpc*Stats classes</technical_language>

Target:
PlanNodeStatsEstimate calculateJoinComplementStats( Optional<Expression> filter, List<JoinNode.EquiJoinClause> criteria, PlanNodeStatsEstimate leftStats, PlanNodeStatsEstimate rightStats, TypeProvider types) { if (rightStats.getOutputRowCount() == 0) { return leftStats; } if (criteria.isEmpty()) { if (filter.isPresent()) { return PlanNodeStatsEstimate.unknown(); } return normalizer.normalize(leftStats.mapOutputRowCount(rowCount -> 0.0), types); } int numberOfFilterClauses = filter.map(expression -> extractConjuncts(expression).size()).orElse(0); return criteria.stream() .map(drivingClause -> calculateJoinComplementStats(leftStats, rightStats, drivingClause, criteria.size() - 1 + numberOfFilterClauses)) .filter(estimate -> !estimate.isOutputRowCountUnknown()) .max(comparingDouble(PlanNodeStatsEstimate::getOutputRowCount)) .map(estimate -> normalizer.normalize(estimate, types)) .orElse(PlanNodeStatsEstimate.unknown()); }
Source:
<code>public boolean validateSettings() { <START> try { <END> DateTimeFormatter.ofPattern(markTimeStampFormatProperty.getValue()); } catch (IllegalArgumentException exception) { DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showErrorDialogAndWait(Localization.lang("Invalid date format"), Localization.lang("The chosen date format for new entries is not valid"))); return false; } return true; }</code><technical_language>[mvvmfx.validation library](<LINK_0> provides a nice approach validation, advantages (e.g. direct user feedback). is in a other dialogs if want a done</technical_language>

Target:
public boolean validateSettings() { ValidationStatus status = markTimeStampFormatValidationStatus(); if (!status.isValid()) { dialogService.showErrorDialogAndWait(status.getHighestMessage().get().getMessage()); return false; } return true; }
Source:
<code>public static boolean isSunJDK() { <START> return JAVA_VM_VENDOR.toUpperCase().contains("sun") <END> || JAVA_VM_VENDOR.toUpperCase().contains("oracle"); }</code><technical_language>toLowerCase</technical_language>

Target:
public static boolean isSunJDK() { return JAVA_VM_VENDOR.toLowerCase().contains("sun") || JAVA_VM_VENDOR.toLowerCase().contains("oracle"); }
Source:
<code><START> public Callsite getCallsite(String eventName) { <END> return callsitesByName.get(eventName).getFirst(); }</code><technical_language>Interesting! I this in public API needed. getCallsiteCandidates().getFirst() already, more verbose..</technical_language>

Target:
public CTFCallsite getCallsite(String eventName) { return callsitesByName.get(eventName).getFirst(); }
Source:
<code>public void blockPorts(final Range<Integer> blockedRange) { checkNotNull(blockedRange); <START> synchronized (reservedPorts) { <END> this.blockedPortRanges.add(blockedRange); } }</code><technical_language>more readable mark relevant methods synchronized arbitrary member for locking</technical_language>

Target:
public synchronized void blockPorts(final Range<Integer> blockedRange) { checkNotNull(blockedRange); this.blockedPortRanges.add(blockedRange); }
Source:
<code><START> public AutoCompletionCandidates doAutoCompleteApplication(@QueryParameter final String value, @AncestorInPath AbstractProject project) { <END> String resolvedApplicationName = expandValue(value, project); final AutoCompletionCandidates applicationCadidates = new AutoCompletionCandidates(); final String applicationName = DeployitServerFactory.getNameFromId(resolvedApplicationName); DeployitNotifier deployitNotifier = RepositoryUtils.retrieveDeployitNotifierFromProject(project); if (deployitNotifier != null) { Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(deployitNotifier.credential, overridingcredential, project); if (null != deployitServer) { List<String> applicationSuggestions = deployitServer.search(DeployitDescriptorRegistry.UDM_APPLICATION, applicationName + "%"); for (String applicationSuggestion : applicationSuggestions) { applicationCadidates.add(applicationSuggestion); } } } return applicationCadidates; }</code><technical_language>permission check @RequirePOST</technical_language>

Target:
public AutoCompletionCandidates doAutoCompleteApplication(@QueryParameter final String value, @AncestorInPath AbstractProject project) { project.checkPermission(Jenkins.ADMINISTER); String resolvedApplicationName = expandValue(value, project); final AutoCompletionCandidates applicationCadidates = new AutoCompletionCandidates(); final String applicationName = DeployitServerFactory.getNameFromId(resolvedApplicationName); DeployitNotifier deployitNotifier = RepositoryUtils.retrieveDeployitNotifierFromProject(project); if (deployitNotifier != null) { Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(deployitNotifier.credential, overridingcredential, project); if (null != deployitServer) { List<String> applicationSuggestions = deployitServer.search(DeployitDescriptorRegistry.UDM_APPLICATION, applicationName + "%"); for (String applicationSuggestion : applicationSuggestions) { applicationCadidates.add(applicationSuggestion); } } } return applicationCadidates; }
Source:
<code>void testMergeSegments() throws InterruptedException { tokenStore.initializeTokenSegments(testSubject.getName(), 2); testSubject.start(); while (testSubject.processingStatus().isEmpty()) { Thread.sleep(10); } <START> assertTrue(testSubject.mergeSegment(0).join(), "Expected merge to succeed"); <END> waitForProcessingStatus(0, EventTrackerStatus::isMerging); waitForSegmentStart(0); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(1); waitForProcessingNotInStatus(0, EventTrackerStatus::isMerging); }</code><technical_language>Nit: a named variable for 0 called segmentId. I here, face a magic number I think</technical_language>

Target:
void testMergeSegments() throws InterruptedException { tokenStore.initializeTokenSegments(testSubject.getName(), 2); testSubject.start(); while (testSubject.processingStatus().isEmpty()) { Thread.sleep(10); } int segmentId = 0; assertTrue(testSubject.mergeSegment(segmentId).join(), "Expected merge to succeed"); waitForProcessingStatus(segmentId, EventTrackerStatus::isMerging); waitForSegmentStart(segmentId); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(1); waitForProcessingNotInStatus(segmentId, EventTrackerStatus::isMerging); }
Source:
<code>public void createPluginSettings(PluginSettings newPluginSettings, Username currentUser, LocalizedOperationResult result) { final String pluginId = newPluginSettings.getPluginId(); <START> if (hasPermission(currentUser, result) && checkPluginLoaded(pluginId, result) && checkPluginSupportsPluginSettings(pluginId, result)) { <END> final String keyToLockOn = keyToLockOn(newPluginSettings.getPluginId()); synchronized (keyToLockOn) { final Plugin plugin = pluginDao.findPlugin(newPluginSettings.getPluginId()); if (plugin instanceof NullPlugin) { updatePluginSettingsAndNotifyPluginSettingsChangeListeners(result, newPluginSettings); } else { result.unprocessableEntity(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", String.format("The plugin settings for plugin[%s] is already exist. In order to update the plugin settings refer the <LINK_0>", newPluginSettings.getPluginId(), CurrentGoCDVersion.getInstance().goVersion()))); } } } }</code><technical_language>check for authorization controller level itself</technical_language>

Target:
public void createPluginSettings(PluginSettings newPluginSettings, Username currentUser, LocalizedOperationResult result) { final String keyToLockOn = keyToLockOn(newPluginSettings.getPluginId()); synchronized (keyToLockOn) { if (hasPermission(currentUser, result)) { final Plugin plugin = pluginDao.findPlugin(newPluginSettings.getPluginId()); if (plugin instanceof NullPlugin) { updatePluginSettingsAndNotifyPluginSettingsChangeListeners(result, newPluginSettings); } else { result.unprocessableEntity(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", String.format("Plugin settings for the plugin `%s` already exist. In order to update the plugin settings refer the <LINK_0>", newPluginSettings.getPluginId(), CurrentGoCDVersion.getInstance().goVersion()))); } } } }
Source:
<code>public void testCreateReadDelete() { CommentManager commentManager = new CommentManagerImpl(CommentServiceHelper.getCommentService().getConfig()); DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACL acl = acp.getOrCreateACL(ACL.LOCAL_ACL); acl.add(new ACE(USERNAME, SecurityConstants.READ, true)); doc.setACP(acp, true); try (CloseableCoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH, COMMENT_CONTENT); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH)); <START> <END> commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }</code><technical_language>for calls</technical_language>

Target:
public void testCreateReadDelete() { DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); DocumentModel folder = session.createDocumentModel("/", "folder", "Folder"); session.createDocument(folder); DocumentModel doc = session.createDocumentModel("/folder/", "TestFile", "File"); doc = session.createDocument(doc); ACP acp = doc.getACP(); ACL acl = acp.getOrCreateACL(ACL.LOCAL_ACL); acl.add(new ACE(USERNAME, SecurityConstants.READ, true)); doc.setACP(acp, true); try (CloseableCoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); Comment comment = new CommentImpl(); comment.setAuthor(session.getPrincipal().getName()); comment.setText(COMMENT_CONTENT); comment.setParentId(userDoc.getId()); commentManager.createComment(session, comment); List<DocumentModel> dml = session.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<Comment> comments = commentManager.getComments(userSession, userDoc.getId()); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getText()); commentManager.deleteComment(userSession, comments.get(0).getId()); comments = commentManager.getComments(userSession, userDoc.getId()); assertEquals(0, comments.size()); } }
Source:
<code>private void validateAddress(String address) throws BindingConfigParseException { String lowerCaseAddress = address.toLowerCase(); <START> if ( !lowerCaseAddress.matches("[a-p]([1-9]|1[0-6])") ) { <END> throw new BindingConfigParseException("The specified address '" + address + "' is not a valid X10 address."); } }</code><technical_language>please extract Regex a static Pattern this Pattern</technical_language>

Target:
private void validateAddress(String address) throws BindingConfigParseException { Matcher matcher = X10_ADDRESS_PATTERN.matcher(address.toLowerCase()); if ( !matcher.matches() ) { throw new BindingConfigParseException("The specified address '" + address + "' is not a valid X10 address."); } }
Source:
<code>public void createRegistryDatabase() throws ConfigurationException { String databaseType = null; File scripFile = null; try { databaseType = DatabaseCreator.getDatabaseType(this.dataSource.getConnection()); String scripPath = getDbScriptLocation(databaseType); scripFile = new File(scripPath); } catch (Exception e) { <START> log.error("Unexpected error occurred while connecting to the database."); <END> throw new ConfigurationException("Unexpected error occurred while connecting to" + " the database.", e); } if(scripFile.canRead()){ try { super.createRegistryDatabase(); } catch (Exception e) { log.error("Unexpected error occurred while creating the database tables."); throw new ConfigurationException("Unexpected error occurred while creating the" + " database tables.", e); } } else { log.error("Unexpected error occurred while reading db script : " + scripFile); throw new ConfigurationException("Unexpected error occurred while reading db script"); } }</code><technical_language>if logging this eror please pass exception too</technical_language>

Target:
public void createRegistryDatabase() throws ConfigurationException { String databaseType; File scripFile; try { databaseType = DatabaseCreator.getDatabaseType(this.dataSource.getConnection()); String scripPath = getDbScriptLocation(databaseType); scripFile = new File(scripPath); } catch (Exception e) { log.error("Unexpected error occurred while connecting to the database.", e); throw new ConfigurationException("Unexpected error occurred while connecting to" + " the database.", e); } if (scripFile.canRead()) { try { super.createRegistryDatabase(); } catch (Exception e) { log.error("Unexpected error occurred while creating the database tables.", e); throw new ConfigurationException("Unexpected error occurred while creating the" + " database tables.", e); } } else { log.error("Unexpected error occurred while reading db script : " + scripFile); throw new ConfigurationException("Unexpected error occurred while reading db script"); } }
Source:
<code>public void typeRamAmount(String machineName, String ramAmount) { moveCursorToEditButton(machineName); clickOnRamField(machineName); seleniumWebDriverHelper.setValue(getRamAmountTextFieldLocator(machineName), ""); <START> if (ramAmount.isEmpty()) { <END> return; } for (int i = 0; i < ramAmount.length(); i++) { seleniumWebDriverHelper.waitAndSendKeysTo( getRamAmountTextFieldLocator(machineName), valueOf(ramAmount.charAt(i))); } seleniumWebDriverHelper.waitValueEqualsTo(getRamAmountTextFieldLocator(machineName), ramAmount); }</code><technical_language>sense check start of method return fast possible</technical_language>

Target:
public void typeRamAmount(String machineName, String ramAmount) { final String emptyValue = ""; seleniumWebDriverHelper.setValue(getRamAmountTextFieldLocator(machineName), emptyValue); if (ramAmount.isEmpty()) { return; } for (int i = 0; i < ramAmount.length(); i++) { seleniumWebDriverHelper.waitAndSendKeysTo( getRamAmountTextFieldLocator(machineName), valueOf(ramAmount.charAt(i))); } seleniumWebDriverHelper.waitValueEqualsTo(getRamAmountTextFieldLocator(machineName), ramAmount); }
Source:
<code>private KeyStore initializeKeyStore(final String keyStoreLocation, final String keyStorePassword, final String keyStoreType) throws WebClientException { InputStream stream = null; try { final KeyStore keyStore = KeyStore.getInstance(keyStoreType.toUpperCase()); stream = new FileInputStream(this.keyStoreLocation); keyStore.load(stream, keyStorePassword.toCharArray()); return keyStore; } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new WebClientException("Error initializing KeyStore", e); } finally { if (stream != null) { try { stream.close(); } catch (final IOException e) { <START> throw new WebClientException("Error closing stream after initializing KeyStore", e); <END> } } } }</code><technical_language>@bvdzwet a more elegant approach a try-with-resource statement. finally block is longer needed</technical_language>

Target:
private KeyStore initializeKeyStore(final String keyStoreLocation, final String keyStorePassword, final String keyStoreType) throws WebClientException { try (InputStream stream = new FileInputStream(keyStoreLocation)) { final KeyStore ks = KeyStore.getInstance(keyStoreType.toUpperCase()); ks.load(stream, keyStorePassword.toCharArray()); return ks; } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new WebClientException("Error initializing KeyStore", e); } }
Source:
<code>protected CascadingTypeParameter getCascadingMetaData() { <START> Map<TypeVariable<?>, CascadingTypeParameter> typeParametersCascadingMetaData = new HashMap<>(); <END> for ( ContainerElementConstraintMappingContextImpl typeArgumentContext : containerElementContexts.values() ) { CascadingTypeParameter cascadingTypeParameter = typeArgumentContext.getCascadingTypeParameter(); if ( cascadingTypeParameter != null ) { typeParametersCascadingMetaData.put( cascadingTypeParameter.getTypeParameter(), cascadingTypeParameter ); } } boolean isArray = TypeHelper.isArray( configuredType ); CascadingTypeParameter cascadingMetaData = isArray ? CascadingTypeParameter.arrayElement( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ) : CascadingTypeParameter.annotatedObject( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ); return cascadingMetaData; }</code><technical_language>size 3 4 perhaps</technical_language>

Target:
protected CascadingTypeParameter getCascadingMetaData() { Map<TypeVariable<?>, CascadingTypeParameter> typeParametersCascadingMetaData = containerElementContexts.values().stream() .filter( c -> c.getCascadingTypeParameter() != null ) .collect( Collectors.toMap( c -> c.getCascadingTypeParameter().getTypeParameter(), c -> c.getCascadingTypeParameter() ) ); for ( ContainerElementConstraintMappingContextImpl typeArgumentContext : containerElementContexts.values() ) { CascadingTypeParameter cascadingTypeParameter = typeArgumentContext.getCascadingTypeParameter(); if ( cascadingTypeParameter != null ) { typeParametersCascadingMetaData.put( cascadingTypeParameter.getTypeParameter(), cascadingTypeParameter ); } } boolean isArray = TypeHelper.isArray( configuredType ); CascadingTypeParameter cascadingMetaData = isArray ? CascadingTypeParameter.arrayElement( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ) : CascadingTypeParameter.annotatedObject( configuredType, isCascading, typeParametersCascadingMetaData, groupConversions ); return cascadingMetaData; }
Source:
<code>public void putAndPersistAdditionalInformation(String key, String value) { String valueToUpdate = this.additionalInformation.get(key); if (valueToUpdate == null || (valueToUpdate != null && !valueToUpdate.equals(value))) { this.additionalInformation.put(key, value); this.descriptor.getAdditionalInformation().put(key, value); this.monitoring.nodeSourceEvent(new RMNodeSourceEvent(RMEventType.NODESOURCE_UPDATED, this.administrator.getName(), this.name, this.getDescription(), this.additionalInformation, this.administrator.getName(), this.getStatus().toString())); <START> persistAdditionalInformation(); <END> } }</code><technical_language>persist called sending event</technical_language>

Target:
public void putAndPersistAdditionalInformation(String key, String value) { String valueToUpdate = this.additionalInformation.get(key); if (valueToUpdate == null || (valueToUpdate != null && !valueToUpdate.equals(value))) { this.additionalInformation.put(key, value); this.descriptor.getAdditionalInformation().put(key, value); persistAdditionalInformation(); this.monitoring.nodeSourceEvent(new RMNodeSourceEvent(RMEventType.NODESOURCE_UPDATED, this.administrator.getName(), this.name, this.getDescription(), this.additionalInformation, this.administrator.getName(), this.getStatus().toString())); } }
Source:
<code>public String getStringValue() { <START> return null; <END> }</code><technical_language>is throw exception in #7486</technical_language>

Target:
public String getStringValue() { throw createUnsupportedOperationException(); }
Source:
<code>public void visitNode(AstNode node) { if (isUsingDjangoModel) { AstNode attributeRef = node.getFirstChild(PythonGrammar.ATTRIBUTE_REF); if (attributeRef != null) { <START> String functionName = attributeRef.getLastChild(PythonGrammar.NAME).getTokenValue(); <END> if (functionName.equals("raw") || functionName.equals("extra")) { addIssue(node, MESSAGE); } } } if (isUsingDjangoDBConnection || isUsingDjangoDBConnections) { AstNode attributeRef = node.getFirstChild(PythonGrammar.ATTRIBUTE_REF); if (attributeRef != null && attributeRef.getLastChild(PythonGrammar.NAME).getTokenValue().equals("execute")) { addIssue(node, MESSAGE); } } super.visitNode(node); }</code><technical_language>getLastChild(KIND) nullable? I add a null check for safety</technical_language>

Target:
public void visitNode(AstNode node) { AstNode attributeRef = node.getFirstChild(PythonGrammar.ATTRIBUTE_REF); if (attributeRef != null) { String functionName = attributeRef.getLastChild(PythonGrammar.NAME).getTokenValue(); if (isSQLQueryFromDjangoModel(functionName) || isSQLQueryFromDjangoDBConnection(functionName)) { addIssue(node, MESSAGE); } } super.visitNode(node); }
Source:
<code><START> private RpcOptions determineRpcOptionsForBackupReplication(RpcManager rpc, boolean isSync, Collection<Address> recipients) { <END> RpcOptions options; if (isSync) { if (recipients == null) { options = rpc.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS).build(); } else { options = rpc.getDefaultRpcOptions(true); } } else { options = rpc.getDefaultRpcOptions(false); } return options; }</code><technical_language>below, defaultSyncOptions defaultAsyncOptions instead of rpc.getDefaultRpcOptions(true); rpc.getDefaultRpcOptions(false);</technical_language>

Target:
private RpcOptions determineRpcOptionsForBackupReplication(RpcManager rpc, boolean isSync, Collection<Address> recipients) { if (isSync) { return recipients == null ? rpc.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS).build() : defaultSyncOptions; } else { return defaultAsyncOptions; } }
Source:
<code>public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( <START> new SimpleModule("DruidLookupModule") <END> { @Override public void setupModule(SetupContext context) { context.registerSubtypes(MapLookupExtractorFactory.class); } } ); }</code><technical_language>suggest new SimpleModule("DruidLookupModule").registerSubtypes</technical_language>

Target:
public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( new SimpleModule("DruidLookupModule").registerSubtypes(MapLookupExtractorFactory.class) ); }
Source:
<code>public void updated(Dictionary<String, ?> config) throws ConfigurationException { for (String device : connectorThreads.keySet()) { logger.debug("Close previous message listener for device '" + device + "'"); final AnelConnectorThread connectorThread = connectorThreads.get(device); connectorThread.setInterrupted(); } for (String device : connectorThreads.keySet()) { final AnelConnectorThread connectorThread = connectorThreads.get(device); try { connectorThread.join(); } catch (InterruptedException e) { logger.info("Previous message listener closing interrupted for device '" + device + "'", e); } } connectorThreads.clear(); <START> refreshInterval = 0; <END> try { refreshInterval = AnelConfigReader.readConfig(config, connectorThreads, bindingFacade); logger.debug("Anel configuration read with refresh interval " + refreshInterval + "ms and " + connectorThreads.size() + " devices."); } catch (ConfigurationException e) { logger.error("Could not read configuration for Anel binding: " + e.getMessage()); return; } catch (Exception e) { logger.error("Could not read configuration for Anel binding", e); return; } setProperlyConfigured(true); for (String device : connectorThreads.keySet()) { final AnelConnectorThread connectorThread = connectorThreads.get(device); logger.debug("Starting message listener for device: " + connectorThread); connectorThread.start(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { } for (AnelConnectorThread connectorThread : connectorThreads.values()) { connectorThread.requestRefresh(); } } }).start(); }</code><technical_language>extract this a new method "disconnectAll()" in "deactivate() (see above)"</technical_language>

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { disconnectAll(); connectorThreads.clear(); refreshInterval = 0; try { refreshInterval = AnelConfigReader.readConfig(config, connectorThreads, bindingFacade); logger.debug("Anel configuration read with refresh interval " + refreshInterval + "ms and " + connectorThreads.size() + " devices."); } catch (ConfigurationException e) { logger.error("Could not read configuration for Anel binding: " + e.getMessage()); return; } catch (Exception e) { logger.error("Could not read configuration for Anel binding", e); return; } setProperlyConfigured(true); for (String device : connectorThreads.keySet()) { final AnelConnectorThread connectorThread = connectorThreads.get(device); logger.debug("Starting message listener for device: " + connectorThread); connectorThread.start(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(THREAD_INITIALIZATION_DELAY); } catch (InterruptedException e) { } refreshAll(); } }).start(); }