auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void patchReplacePasswordWithToken() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withPassword(password) .build(); String newPassword = "newpassword"; context.restoreAuthSystemState(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/password", newPassword); ops.add(replaceOperation); String patchBody = getPatchContent(ops); accountService.sendRegistrationInfo(context, ePerson.getEmail()); String tokenForEPerson = registrationDataService.findByEmail(context, ePerson.getEmail()).getToken(); String token = getAuthToken(admin.getEmail(), password); PasswordHash oldPassword = ePersonService.getPasswordHash(ePerson); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON) .param("token", tokenForEPerson)) .andExpect(status().isOk()); PasswordHash newPasswordHash = ePersonService.getPasswordHash(ePerson); assertFalse(oldPassword.equals(newPasswordHash)); <START> assertTrue(registrationDataService.findByEmail(context, ePerson.getEmail()) == null); context.turnOffAuthorisationSystem(); registrationDataService.deleteByToken(context, tokenForEPerson); context.restoreAuthSystemState(); <END> }</code><technical_language>misunderstanding something, if registration data *is null*, token deleted already? do need deleteByToken() here</technical_language>

Target:
public void patchReplacePasswordWithToken() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .withPassword(password) .build(); String newPassword = "newpassword"; context.restoreAuthSystemState(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/password", newPassword); ops.add(replaceOperation); String patchBody = getPatchContent(ops); accountService.sendRegistrationInfo(context, ePerson.getEmail()); String tokenForEPerson = registrationDataService.findByEmail(context, ePerson.getEmail()).getToken(); PasswordHash oldPassword = ePersonService.getPasswordHash(ePerson); getClient().perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON) .param("token", tokenForEPerson)) .andExpect(status().isOk()); PasswordHash newPasswordHash = ePersonService.getPasswordHash(ePerson); assertNotEquals(oldPassword, newPasswordHash); assertTrue(registrationDataService.findByEmail(context, ePerson.getEmail()) == null); assertNull(registrationDataService.findByToken(context, tokenForEPerson)); }
Source:
<code><START> public static String[] splitKeyword(String keyword) { <END> Pattern p = Pattern.compile(String.format("([^\\%s\\%s]+)(\\%s|\\%s)([^\\%s\\%s]*)", EXCLUSIVE_DELIMITER, NONEXCLUSIVE_DELIMITER, EXCLUSIVE_DELIMITER, NONEXCLUSIVE_DELIMITER, EXCLUSIVE_DELIMITER, NONEXCLUSIVE_DELIMITER)); Matcher m = p.matcher(keyword); if (m.find()) return new String[] {m.group(1), m.group(2), m.group(3)}; return new String[] {"", "", keyword}; }</code><technical_language>a unit tests for this method. (and test) behaves for corner cases. e.g. multiple delimiters, starting a delimiter</technical_language>

Target:
private static String[] splitKeyword(String keyword) { Pattern p = Pattern.compile(GROUP_PATTERN); Matcher m = p.matcher(keyword); if (!m.find()) return new String[] {"", "", keyword}; return new String[] {m.group(1), m.group(2), m.group(3)}; }
Source:
<code>public void testCallbackQueryFailureHandling() { final AsyncResult<QueryResult> res = new AsyncResult<>(); this.influxDB.query(new Query("SHOW SERRIES"), res.resultConsumer, res.errorConsumer); <START> Assertions.assertThrows(InfluxDBException.class, res::result, <END> "Malformed query should throw InfluxDBException"); }</code><technical_language>is test expected Exception message</technical_language>

Target:
public void testCallbackQueryFailureHandling() throws Throwable { final AsyncResult<QueryResult> res = new AsyncResult<>(); this.influxDB.query(new Query("SHOW SERRIES"), res.resultConsumer, res.errorConsumer); try{ res.result(); Assertions.fail("Malformed query should throw InfluxDBException"); } catch (InfluxDBException e){ Pattern errorPattern = Pattern.compile("Bad Request.*error parsing query: found SERRIES, expected.*", Pattern.DOTALL); Assertions.assertTrue(errorPattern.matcher(e.getMessage()).matches(), "Error string \"" + e.getMessage() + "\" does not match error pattern"); } }
Source:
<code>public void assertSimilarity( final BufferedImage actualImage, final double maxDistance) throws IOException { if (this.generateExpectedImages) { ImageIO.write(actualImage, "png", this.expectedPath); return; <START> } <END> final File actualOutput = new File(this.expectedPath.getParentFile(), (this.expectedPath.getName().contains("expected") ? this.expectedPath.getName().replace("expected", "actual") : "actual-" + this.expectedPath.getName()) .replace(".tiff", ".png")); if (!this.expectedPath.exists()) { ImageIO.write(actualImage, "png", expectedPath); throw new AssertionError("The expected file was missing and has been generated: " + actualOutput.getAbsolutePath()); } final double distance = calcDistance(actualImage); if (distance > maxDistance) { ImageIO.write(actualImage, "png", actualOutput); throw new AssertionError(String.format("similarity difference between images is: %s which is " + "greater than the max distance of %s%n" + "actual=%s%n" + "expected=%s", distance, maxDistance, actualOutput.getAbsolutePath(), this.expectedPath.getAbsolutePath())); } }</code><technical_language>remove</technical_language>

Target:
public void assertSimilarity( final BufferedImage actualImage, final double maxDistance) throws IOException { final File actualOutput = getRelatedFile("actual"); if (!this.expectedPath.exists()) { ImageIO.write(actualImage, "png", expectedPath); throw new AssertionError("The expected file was missing and has been generated: " + actualOutput.getAbsolutePath()); } final double distance = calcDistance(actualImage); if (distance > maxDistance) { ImageIO.write(actualImage, "png", actualOutput); throw new AssertionError(String.format("similarity difference between images is: %s which is " + "greater than the max distance of %s%n" + "actual=%s%n" + "expected=%s", distance, maxDistance, actualOutput.getAbsolutePath(), this.expectedPath.getAbsolutePath())); } }
Source:
<code>private void showDaysOfMonth() { int row = 0; int column = 0; for(int i = 1; i < 32; i++) { if(i%7 == 1 && i != 1) { row++; column = 0; } daysOfMonth.setWidget(row, column, new Label(Integer.toString(i))); daysOfMonth.getCellFormatter().getElement(row, column).addClassName("normalFlexTableCell"); clickedMap.put(i, false); column++; } <START> Label widget = new Label("Last Day"); END> daysOfMonth.setWidget(row, column, widget); daysOfMonth.getFlexCellFormatter().setColSpan(row, column, 4); clickedMap.put(32, false); wrapperPanel.add(daysOfMonth); }</code><technical_language>localize "Last Day"</technical_language>

Target:
private void showDaysOfMonth() { int row = 0; int column = 0; for (int i = 1; i < LAST_DAY; i++) { if (i % DAYS_IN_WEEK == 1 && i != 1) { row++; column = 0; } daysOfMonth.setWidget(row, column, new Label(Integer.toString(i))); daysOfMonth.getCellFormatter().getElement(row, column).addClassName("normalFlexTableCell"); clickedMap.put(i, false); column++; } Label widget = new Label(constants.lastDay()); daysOfMonth.setWidget(row, column, widget); daysOfMonth.getFlexCellFormatter().setColSpan(row, column, 4); clickedMap.put(LAST_DAY, false); wrapperPanel.add(daysOfMonth); }
Source:
<code>public void eval(Object rowKey) throws IOException { <START> Result result = table.get(readHelper.createGet(rowKey)); <END> if (!result.isEmpty()) { collect(serde.convertToRow(result)); } }</code><technical_language>Do HBaseReadWriteHelper. legacy type. add a new method createGet in HbaseSerDe</technical_language>

Target:
public void eval(Object rowKey) throws IOException { Get get = serde.createGet(rowKey); if (get != null) { Result result = table.get(get); if (!result.isEmpty()) { collect(serde.convertToRow(result)); } } }
Source:
<code>public void calculate() { zoombarHeight = calculate(ZoomBarView.ZOOM_BAR_FACTOR, getHeight()); <START> sidebarWidth = calculate(SideBarView.SIDEBAR_FACTOR, getWidth()); <END> }</code><technical_language>ZOOM_BAR instead of ZOOMBAR SIDE_BAR instead of SIDEBAR</technical_language>

Target:
public void calculate() { zoombarHeight = calculate(ZoomBarView.ZOOMBAR_FACTOR, getHeight()); sidebarWidth = calculate(SideBarView.SIDEBAR_FACTOR, getWidth()); }
Source:
<code>private Map<T, Double> normalize() { if (isNormalised) return normalised; Map<T, Double> temp = createMapDataStructure(); double sum = 0; for (Entry<T, Double> entry : map.entrySet()) { <START> final Double p = entry.getValue(); <END> if (p != null) { sum += p; } } for (Entry<T, Double> entry : temp.entrySet()) { final T t = entry.getKey(); final Double p = entry.getValue(); if (p != null) { temp.put(t, p / sum); } } normalised = temp; isNormalised = true; return temp; }</code><technical_language>sense final. if necessary otherwise. This nicer java streams</technical_language>

Target:
private Map<T, Double> normalize() { if (isNormalised) return normalised; Map<T, Double> temp = createMapDataStructure(); double sum = 0; for (Entry<T, Double> entry : map.entrySet()) { Double p = entry.getValue(); if (p != null) { sum += p; } } for (Entry<T, Double> entry : temp.entrySet()) { T t = entry.getKey(); Double p = entry.getValue(); if (p != null) { temp.put(t, p / sum); } } normalised = temp; isNormalised = true; return temp; }
Source:
<code>private void parseGenotype(String genotype) { String[] alleles = genotypePattern.split(genotype, -1); this.code = alleles.length > 1 ? AllelesCode.ALLELES_OK : AllelesCode.HAPLOID; this.allelesIdx = new int[alleles.length]; for (int i = 0; i < alleles.length; i++) { String allele = alleles[i]; if (allele.equals(".") || allele.equals("-1")) { this.code = AllelesCode.ALLELES_MISSING; this.allelesIdx[i] = -1; } else { <START> if (StringUtils.isNumeric(allele)) { END> this.allelesIdx[i] = Integer.parseInt(allele); } else { if (allele.equalsIgnoreCase(reference)) { this.allelesIdx[i] = 0; } else if (allele.equalsIgnoreCase(alternate)) { this.allelesIdx[i] = 1; } else { if (allele.isEmpty()) { System.out.println("Empty allele: REF=" + reference + ",ALT=" + alternate); } this.allelesIdx[i] = 2; } } if (allelesIdx[i] > 1) { this.code = AllelesCode.MULTIPLE_ALTERNATES; } } } }</code><technical_language>replaced Guava's method [Ints#tryParse(String)](<LINK_0> doing: java if (Ints.tryParse(allele) != null) { ... }</technical_language>

Target:
private void parseGenotype(String genotype) { String[] alleles = genotypePattern.split(genotype, -1); this.code = alleles.length > 1 ? AllelesCode.ALLELES_OK : AllelesCode.HAPLOID; this.allelesIdx = new int[alleles.length]; for (int i = 0; i < alleles.length; i++) { String allele = alleles[i]; if (allele.equals(".") || allele.equals("-1")) { this.code = AllelesCode.ALLELES_MISSING; this.allelesIdx[i] = -1; } else { Integer alleleParsed = Ints.tryParse(allele); if (alleleParsed != null) { this.allelesIdx[i] = alleleParsed; } else { if (allele.equalsIgnoreCase(reference)) { this.allelesIdx[i] = 0; } else if (allele.equalsIgnoreCase(alternate)) { this.allelesIdx[i] = 1; } else { if (allele.isEmpty()) { logger.error("Empty allele: REF=" + reference + ",ALT=" + alternate); } this.allelesIdx[i] = 2; } } if (allelesIdx[i] > 1) { this.code = AllelesCode.MULTIPLE_ALTERNATES; } } } }
Source:
<code>@Override public String toString() { return new StringBuilder().append(type) .append(" Affected object: ") .append(objectName) .append(" Timestamp: ") .append(df.format(timestamp)) .append(" User: ") .append(user) .append(" Additional information: ") .append(extraInfo) <START> .toString(); <END> }</code><technical_language>I put quotes fields logged, e.g. "object name" in case object name contains weird characters spaces whatnot</technical_language>

Target:
@Override public String toString() { return new StringBuilder().append(type) .append(" Affected object: \"") .append(objectName) .append("\" Timestamp: \"") .append(df.format(timestamp)) .append("\" User: \"") .append(user) .append("\" Additional information: \"") .append(extraInfo) .append("\"") .toString(); }
Source:
<code>public RqChunk(final Request req) { super( <START> new RqOf( <END> req::head, () -> RqChunk.cap(req) ) ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
public RqChunk(final Request req) { super( new RequestOf( req::head, () -> RqChunk.cap(req) ) ); }
Source:
<code>public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; <START> if (skip < pos) <END> skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; pos = (int) (skip + offset); return skip; } }</code><technical_language>skip > n</technical_language>

Target:
public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; if (skip > n) skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; pos = (int) (skip + offset); return skip; } }
Source:
<code>public void testSnippetContent() throws GitLabApiException { Snippet snippet = createSnippet( <START> new Snippet("Snippet 1", "Snippet.java", "System.out.println(\"\");")); <END> SnippetsApi api = gitLabApi.getSnippetApi(); String snippetContent = api.getSnippetContent(snippet.getId()); assertEquals("System.out.println(\"\");", snippetContent); deleteSnippet(snippet); }</code><technical_language>Create a constant hold content instead of literals: final String CONTENT = "System.out.println(\"\");";</technical_language>

Target:
public void testSnippetContent() throws GitLabApiException { Snippet snippet = createSnippet( new Snippet(TEST_SNIPPET_TITLE_1, TEST_SNIPPET_FILE_NAME_1, TEST_SNIPPET_CONTENT_1)); SnippetsApi api = gitLabApi.getSnippetApi(); String snippetContent = api.getSnippetContent(snippet.getId()); assertEquals(TEST_SNIPPET_CONTENT_1, snippetContent); deleteSnippet(snippet); }
Source:
<code>private boolean removeVmsInPool() { List<VM> vmsInPool = DbFacade.getInstance().getVmDao().getAllForVmPool(getVmPoolId()); VdcReturnValueBase result; for (VM vm : vmsInPool) { <START> if (!vm.isDown()) { <END> return false; } result = runInternalActionWithTasksContext( VdcActionType.RemoveVmFromPool, new RemoveVmFromPoolParameters(vm.getId())); if (!result.getSucceeded()) { return false; } result = runInternalAction( VdcActionType.RemoveVm, withRootCommandInfo(new RemoveVmParameters(vm.getId(), false), getActionType()), createRemoveVmStepContext(vm.getName())); if (!result.getSucceeded()) { return false; } } return true; }</code><technical_language>need lock VMs users able run stopping of pool removal</technical_language>

Target:
private boolean removeVmsInPool() { VdcReturnValueBase result; for (VM vm : getVmsInPool()) { RemoveVmFromPoolParameters removeVmFromPoolParameters = new RemoveVmFromPoolParameters(vm.getId()); removeVmFromPoolParameters.setTransactionScopeOption(TransactionScopeOption.Suppress); result = runInternalActionWithTasksContext( VdcActionType.RemoveVmFromPool, removeVmFromPoolParameters); if (!result.getSucceeded()) { return false; } result = runInternalAction( VdcActionType.RemoveVm, withRootCommandInfo(new RemoveVmParameters(vm.getId(), false), getActionType()), createRemoveVmStepContext(vm)); if (!result.getSucceeded()) { return false; } } return true; }
Source:
<code>public void run() { Job job = new Job(ifJobName) { @Override protected IStatus run(IProgressMonitor monitor) { TimeGraphControl ctrl = getTimeGraphViewer().getTimeGraphControl(); ITimeGraphEntry traceEntry = ctrl.getSelectedTrace(); long ts = ctrl.getTimeDataProvider().getSelectionBegin(); ITmfTimestamp ts2 = TmfTraceManager.getInstance().getCurrentTraceContext().getSelectionRange().getStartTime(); <START> ITimeEvent selectedState = Utils.findEvent(traceEntry, ts, 0); <END> if (selectedState == null) { return Status.OK_STATUS; } ITimeGraphEntry entry = selectedState.getEntry(); if (!(entry instanceof ControlFlowEntry)) { return Status.OK_STATUS; } ControlFlowEntry cfEntry = (ControlFlowEntry) entry; int tid = cfEntry.getThreadId(); ITmfTrace trace = cfEntry.getTrace(); ITmfContext ctx = trace.seekEvent(ts2); long rank = ctx.getRank(); ctx.dispose(); Predicate<@NonNull ITmfEvent> predicate = event -> { Integer eventTid = KernelTidAspect.INSTANCE.resolve(event); return (eventTid != null && eventTid.intValue() == tid); }; ITmfEvent event = (ifDirection ? TmfTraceUtils.getNextEventMatching(cfEntry.getTrace(), rank, predicate, monitor) : TmfTraceUtils.getPreviousEventMatching(cfEntry.getTrace(), rank, predicate, monitor)); if (event != null) { TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, event.getTimestamp())); } return Status.OK_STATUS; } }; job.setRule(fSearchActionMutexRule); job.schedule(); }</code><technical_language>selected state's entry is viewer's getSelection(). viewer's getSelectionBegin() stored in TmfTraceManager. If a difference synchronization happened yet, in case, viewer's time</technical_language>

Target:
public void run() { Job job = new Job(ifJobName) { @Override protected IStatus run(IProgressMonitor monitor) { TimeGraphControl ctrl = getTimeGraphViewer().getTimeGraphControl(); ITimeGraphEntry traceEntry = ctrl.getSelectedTrace(); long ts = getTimeGraphViewer().getSelectionBegin(); ITimeEvent selectedState = Utils.findEvent(traceEntry, ts, 0); if (selectedState == null) { return Status.OK_STATUS; } ITimeGraphEntry entry = selectedState.getEntry(); if (!(entry instanceof ControlFlowEntry)) { return Status.OK_STATUS; } ControlFlowEntry cfEntry = (ControlFlowEntry) entry; int tid = cfEntry.getThreadId(); ITmfTrace trace = cfEntry.getTrace(); ITmfContext ctx = trace.seekEvent(TmfTimestamp.fromNanos(ts)); long rank = ctx.getRank(); ctx.dispose(); Predicate<@NonNull ITmfEvent> predicate = event -> { Integer eventTid = KernelTidAspect.INSTANCE.resolve(event); return (eventTid != null && eventTid.intValue() == tid); }; ITmfEvent event = (ifDirection ? TmfTraceUtils.getNextEventMatching(cfEntry.getTrace(), rank, predicate, monitor) : TmfTraceUtils.getPreviousEventMatching(cfEntry.getTrace(), rank, predicate, monitor)); if (event != null) { TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, event.getTimestamp())); } return Status.OK_STATUS; } }; job.setRule(fSearchActionMutexRule); job.schedule(); }
Source:
<code>public static <A> Show<A> showS(final F<A, String> f) { <START> return new Show<A>(a -> fromString(f.f(a))); <END> }</code><technical_language>Again, static constructor. In this case Show.show(F<A, Stream<Character>>)</technical_language>

Target:
public static <A> Show<A> showS(final F<A, String> f) { return show(a -> fromString(f.f(a))); }
Source:
<code>public KeyframeRequester(int mediaSenderSSRC) { super(FIR_RETRY_INTERVAL_MS); this.mediaSenderSSRC = mediaSenderSSRC; <START> this.sequenceNumber = new AtomicInteger(0); <END> this.remainingRetries = 0; }</code><technical_language>a moot point here, I admit. easier read if initialize sequenceNumber final get initialized a constructor argument</technical_language>

Target:
public KeyframeRequester(int mediaSenderSSRC) { super(FIR_RETRY_INTERVAL_MS); this.mediaSenderSSRC = mediaSenderSSRC; this.remainingRetries = 0; }
Source:
<code>public void testSetTtlTimeProvider() throws Exception { AbstractStreamOperatorTestHarness<Integer> result; AbstractStreamOperator operator = new AbstractStreamOperator<Integer>() {}; result = new AbstractStreamOperatorTestHarness<>( operator, 1, 1, 0); result.config.setStateKeySerializer(IntSerializer.INSTANCE); long expectedTimeStamp = 42; result.setTtlTimeProvider(() -> expectedTimeStamp); result.initializeState(new OperatorSubtaskState()); result.open(); Assert.assertEquals(expectedTimeStamp, <START> ((AbstractKeyedStateBackend<?>) operator.getKeyedStateBackend()).getTtlTimeProvider().currentTimestamp()); <END> }</code><technical_language>I avoid exposing getTtlTimeProvider in AbstractKeyedStateBackend, annotate VisibleForTesting, visible for users. working of custom TtlTimeProvider tested e.g. creating TTL states checking expire custom timestamp. this tested other tests rely this injection of custom TtlTimeProvider</technical_language>

Target:
public void testSetTtlTimeProvider() throws Exception { AbstractStreamOperator<Integer> operator = new AbstractStreamOperator<Integer>() {}; try (AbstractStreamOperatorTestHarness<Integer> result = new AbstractStreamOperatorTestHarness<>( operator, 1, 1, 0)) { result.config.setStateKeySerializer(IntSerializer.INSTANCE); Time timeToLive = Time.hours(1); result.initializeState(new OperatorSubtaskState()); result.open(); ValueStateDescriptor<Integer> stateDescriptor = new ValueStateDescriptor<>("test", IntSerializer.INSTANCE); stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(timeToLive).build()); KeyedStateBackend<Integer> keyedStateBackend = operator.getKeyedStateBackend(); ValueState<Integer> state = keyedStateBackend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, stateDescriptor); int expectedValue = 42; keyedStateBackend.setCurrentKey(1); result.setStateTtlProcessingTime(0L); state.update(expectedValue); Assert.assertEquals(expectedValue, (int) state.value()); result.setStateTtlProcessingTime(timeToLive.toMilliseconds() + 1); Assert.assertNull(state.value()); } }
Source:
<code>private void setNumericTimestamp(Timestamp value, Calendar cal) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(isNull(), "setNumericTimestamp called when already set"); } if (value != null) { if( cal == null) { <START> cal = localCal.get(); <END> } setValue(computeEncodedDate(value, cal), computeEncodedTime(value, cal), value.getNanos()); } }</code><technical_language>is a thread local created for purpose is in other locations in SQLTimestamp. suggestion cal = SQLDate.GREGORIAN_CALENDAR.get();</technical_language>

Target:
private void setNumericTimestamp(Timestamp value, Calendar cal) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(isNull(), "setNumericTimestamp called when already set"); } if (value != null) { if( cal == null) { cal = SQLDate.GREGORIAN_CALENDAR.get(); } setValue(computeEncodedDate(value, cal), computeEncodedTime(value, cal), value.getNanos()); } }
Source:
<code>public void addFences(List<Fence> newFences) throws Throwable { if (sourceImmutablePolicy == null) { <START> throw new Throwable("Source Policy is null cannot add fences"); <END> } ArrayList<Fence> fences = new ArrayList<>(); if (sourceImmutablePolicy.getFences() != null) { fences.addAll(sourceImmutablePolicy.getFences()); } fences.addAll(newFences); if (sourceImmutablePolicy instanceof MethodAmountPolicy) { sourceImmutablePolicy = new MethodAmountPolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), fences, ((MethodAmountPolicy) sourceImmutablePolicy).getAmount()); } else if (sourceImmutablePolicy instanceof FactorsPolicy) { FactorsPolicy factorsPolicy = (FactorsPolicy) sourceImmutablePolicy; sourceImmutablePolicy = new FactorsPolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), fences, factorsPolicy.isInherenceRequired(), factorsPolicy.isKnowledgeRequired(), factorsPolicy.isPossessionRequired()); } else if (sourceImmutablePolicy instanceof ConditionalGeoFencePolicy) { sourceImmutablePolicy = new ConditionalGeoFencePolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), fences, ((ConditionalGeoFencePolicy) sourceImmutablePolicy).getInPolicy(), ((ConditionalGeoFencePolicy) sourceImmutablePolicy).getOutPolicy()); } else { throw new Throwable("Source Policy is of unknown type"); } }</code><technical_language>Source Policy is null add fences</technical_language>

Target:
public void addFences(List<Fence> newFences) throws Throwable { if (sourceImmutablePolicy == null) { throw new Throwable("Source Policy is null and cannot add fences"); } ArrayList<Fence> fences = new ArrayList<>(); if (sourceImmutablePolicy.getFences() != null) { fences.addAll(sourceImmutablePolicy.getFences()); } fences.addAll(newFences); if (sourceImmutablePolicy instanceof MethodAmountPolicy) { sourceImmutablePolicy = new MethodAmountPolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), fences, ((MethodAmountPolicy) sourceImmutablePolicy).getAmount()); } else if (sourceImmutablePolicy instanceof FactorsPolicy) { FactorsPolicy factorsPolicy = (FactorsPolicy) sourceImmutablePolicy; sourceImmutablePolicy = new FactorsPolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), fences, factorsPolicy.isInherenceRequired(), factorsPolicy.isKnowledgeRequired(), factorsPolicy.isPossessionRequired()); } else if (sourceImmutablePolicy instanceof ConditionalGeoFencePolicy) { sourceImmutablePolicy = new ConditionalGeoFencePolicy(sourceImmutablePolicy.getDenyRootedJailbroken(), sourceImmutablePolicy.getDenyEmulatorSimulator(), fences, ((ConditionalGeoFencePolicy) sourceImmutablePolicy).getInside(), ((ConditionalGeoFencePolicy) sourceImmutablePolicy).getOutside()); } else { throw new Throwable("Source Policy is of unknown type"); } }
Source:
<code>private List<Long> getMutatedGenes() { List<Long> mutatedGenes = new ArrayList<Long>(); config.getChromosomeLength(); for (int i = 0; i < config.getChromosomeLength(); i++) { mutatedGenes.add(selectGene(i)); } <START> <END> return mutatedGenes; }</code><technical_language>Brace style for lines 143 146 for 187: unnecessary local variable</technical_language>

Target:
private List<Long> getMutatedGenes() { List<Long> mutatedGenes = new ArrayList<Long>(); config.getChromosomeLength(); for (int i = 0; i < config.getChromosomeLength(); i++) mutatedGenes.add(selectGene(i)); return mutatedGenes; }
Source:
<code>public synchronized void stateChanged(TaskStatus newStatus) { long currentUserMemory = newStatus.getMemoryReservation().toBytes(); long currentSystemMemory = newStatus.getSystemMemoryReservation().toBytes(); long deltaUserMemoryInBytes = currentUserMemory - previousUserMemory; long deltaSystemMemoryInBytes = currentSystemMemory - previousSystemMemory; previousUserMemory = currentUserMemory; previousSystemMemory = currentSystemMemory; <START> stateMachine.updateMemoryUsage(deltaUserMemoryInBytes, deltaSystemMemoryInBytes); <END> }</code><technical_language>existing code unnecessarily roundabout. simplified. Here, absolute number, turn delta. In QueryStateMachine.updateMemoryUsage, takes delta, converts absolute value</technical_language>

Target:
public synchronized void stateChanged(TaskStatus newStatus) { long currentUserMemory = newStatus.getMemoryReservation().toBytes(); long currentSystemMemory = newStatus.getSystemMemoryReservation().toBytes(); stateMachine.updateMemoryUsage(currentUserMemory, currentSystemMemory); }
Source:
<code>public void verifyFollowedArticle(String articleName){ waitForElementByXPath(" <START> PageObjectLogging.log("verifyFollowedArticle", articleName + "is visible on followed list", true, driver); <END> }</code><technical_language>sure, screenshot here? verifying method</technical_language>

Target:
public void verifyFollowedArticle(String articleName) { waitForElementByXPath(" PageObjectLogging.log("verifyFollowedArticle", articleName + "is visible on followed list", true); }
Source:
<code>public PrimeVaccinationScheduleDto createOrUpdateWithDto(PrimeVaccinationScheduleDto dto, Boolean ignoreLimitation) { VisitBookingDetails primeDetails = visitBookingDetailsDataService.findById(dto.getVisitBookingDetailsId()); VisitBookingDetails screeningDetails = getScreeningDetails(primeDetails); if (primeDetails == null || screeningDetails == null) { throw new IllegalArgumentException("Cannot save, because details for Visit not found"); } Clinic clinic = primeDetails.getClinic(); if (clinic != null && !ignoreLimitation) { checkNumberOfPatients(dto, clinic); } if (!dto.getIgnoreDateLimitation()) { <START> validateDate(dto); <END> } return new PrimeVaccinationScheduleDto(updateVisitWithDto(primeDetails, screeningDetails, dto)); }</code><technical_language>validateDate check if date is null if is in done checkNumberOfPatients</technical_language>

Target:
public PrimeVaccinationScheduleDto createOrUpdateWithDto(PrimeVaccinationScheduleDto dto, Boolean ignoreLimitation) { VisitBookingDetails primeDetails = visitBookingDetailsDataService.findById(dto.getVisitBookingDetailsId()); VisitBookingDetails screeningDetails = getScreeningDetails(primeDetails); if (primeDetails == null || screeningDetails == null) { throw new IllegalArgumentException("Cannot save, because details for Visit not found"); } Clinic clinic = primeDetails.getClinic(); validateDate(dto); if (clinic != null && !ignoreLimitation) { checkNumberOfPatients(dto, clinic); } return new PrimeVaccinationScheduleDto(updateVisitWithDto(primeDetails, screeningDetails, dto)); }
Source:
<code><START> private void checkNotOverlappingRules(Rule first, Rule second) { <END> BinaryComparisonOperator fFirst = (BinaryComparisonOperator) first.getFilter(); BinaryComparisonOperator fSecond; if (second.getFilter() instanceof And) fSecond = (BinaryComparisonOperator) ((And) second.getFilter()).getChildren().get(0); else fSecond = (BinaryComparisonOperator) second.getFilter(); assertTrue(fFirst.getExpression2().equals(fSecond.getExpression2())); assertFalse(fSecond instanceof PropertyIsGreaterThanOrEqualTo); }</code><technical_language>Name suggests a general overlap test, in fact pretty specific test in rule filter. Suggestion for a approach: SimpleFeatureType ft = (SimpleFeatureType)= getCatalog().getFeatureTypeByName("ClassificationPoints2").getFeatureType(); SimpleFeature feature = DataUtilities.create(ft, "=1|2.0|POINT(4 2.5)"); assertTrue(first.getFilter().evaluate(feature)); assertFalse(second.getFilter().evaluate(feature));</technical_language>

Target:
private void checkNotOverlappingRules(Rule first, Rule second) throws IOException { SimpleFeatureType ft = (SimpleFeatureType) getCatalog().getFeatureTypeByName("ClassificationPoints2").getFeatureType(); SimpleFeature feature = DataUtilities.createFeature(ft, "=1|2.0|POINT(4 2.5)"); assertTrue(first.getFilter().evaluate(feature)); assertFalse(second.getFilter().evaluate(feature)); }
Source:
<code>public DataSourceDto(DataSource dataSource, DataFeed dataFeed) { dataSourceId = dataSource.getId(); dataSourceName = dataSource.getName(); description = dataSource.getDescription(); <START> tagIds = getTagIds(dataSource.getTags()); <END> tags = getTagNames(dataSource.getTags()); timestamp = dataSource.getTimestamp(); type = dataSource.getType(); typeConfig = dataSource.getTypeConfig(); if (dataFeed != null) { dataFeedName = dataFeed.getName(); parserId = dataFeed.getParserId(); dataFeedType = dataFeed.getType(); } }</code><technical_language>remove tagIds DTO tags ? leads confusion if tagIds present, tags effect</technical_language>

Target:
public DataSourceDto(DataSource dataSource, DataFeed dataFeed) { dataSourceId = dataSource.getId(); dataSourceName = dataSource.getName(); description = dataSource.getDescription(); tags = getTagNames(dataSource.getTags()); timestamp = dataSource.getTimestamp(); type = dataSource.getType(); typeConfig = dataSource.getTypeConfig(); if (dataFeed != null) { dataFeedName = dataFeed.getName(); parserId = dataFeed.getParserId(); dataFeedType = dataFeed.getType(); } }
Source:
<code><START> public T signalNext(T element) throws InterruptedException { <END> sendNext(element); return element; }</code><technical_language>Public</technical_language>

Target:
private T signalNext(T element) throws InterruptedException { sendNext(element); return element; }
Source:
<code>private static void createDirectoryIfNonExistent(String fileDirectory) throws IOException { File directory = new File(fileDirectory); boolean directoryExists = directory.exists() && directory.isDirectory(); if (!directoryExists) { if (directory.mkdirs()) { logger.info("Directory created: " + directory.toString()); } else { logger.error("Could not create file directory"); <START> throw new IOException(); <END> } } }</code><technical_language>put error message IOException well</technical_language>

Target:
private static void createDirectoryIfNonExistent(String fileDirectory) throws IOException { File directory = new File(fileDirectory); boolean isDirectoryExists = directory.exists() && directory.isDirectory(); if (isDirectoryExists) { return; } boolean isMkdirsSuccessful = directory.mkdirs(); if (isMkdirsSuccessful) { logger.info("Directory created: " + directory.toString()); return; } logger.error("Could not create file directory"); throw new IOException("Could not create file directory"); }
Source:
<code><START> private ClusterSetup(Builder builder) throws IOException, InvalidRoutingDataException { <END> switch (builder._realmMode) { case MULTI_REALM: _zkClient = new FederatedZkClient(builder._realmAwareZkConnectionConfig, builder._realmAwareZkClientConfig); break; case SINGLE_REALM: _zkClient = SharedZkClientFactory.getInstance() .buildZkClient(builder._realmAwareZkConnectionConfig.createZkConnectionConfig(), builder._realmAwareZkClientConfig.createHelixZkClientConfig()); break; default: throw new HelixException("Invalid RealmMode given: " + builder._realmMode); } _admin = new ZKHelixAdmin(_zkClient); _usesExternalZkClient = false; }</code><technical_language>mentioned, do need checked exception signature? If yes, is consideration thrown checked exceptions</technical_language>

Target:
private ClusterSetup(Builder builder) { switch (builder._realmMode) { case MULTI_REALM: try { _zkClient = new FederatedZkClient(builder._realmAwareZkConnectionConfig, builder._realmAwareZkClientConfig.setZkSerializer(new ZNRecordSerializer())); break; } catch (IOException | InvalidRoutingDataException | IllegalStateException e) { throw new HelixException("Failed to create ClusterSetup!", e); } case SINGLE_REALM: _zkClient = SharedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(builder._zkAddress), builder._realmAwareZkClientConfig.createHelixZkClientConfig() .setZkSerializer(new ZNRecordSerializer())); break; default: throw new HelixException("Invalid RealmMode given: " + builder._realmMode); } _admin = new ZKHelixAdmin(_zkClient); _usesExternalZkClient = false; }
Source:
<code>public void before(){ browser.navigate().refresh(); Graphene.goTo(DataSourcesMetricsPage.class); <START> browser.manage().window().maximize(); <END> Console.withBrowser(browser).waitUntilLoaded(); }</code><technical_language>consider org.jboss.hal.testsuite.util.Console.maximizeWindow() instead</technical_language>

Target:
public void before(){ browser.navigate().refresh(); Graphene.goTo(DataSourcesMetricsPage.class); Console.withBrowser(browser).maximizeWindow().waitUntilLoaded(); }
Source:
<code><START> public CaffeineCache(final Cache<NamedKey, byte[]> cache, CaffeineCacheConfig config) <END> { this.cache = cache; this.config = config; }</code><technical_language>this private</technical_language>

Target:
private CaffeineCache(final Cache<NamedKey, byte[]> cache, CaffeineCacheConfig config) { this.cache = cache; this.config = config; }
Source:
<code><START> private BlobReadOptions getUndeletedBlobReadOptions(IndexValue value, StoreKey key, <END> ConcurrentSkipListMap<Offset, IndexSegment> indexSegments) throws StoreException { IndexValue putValue = findKey(key, new FileSpan(getStartOffset(indexSegments), value.getOffset()), EnumSet.of(IndexEntryType.PUT), indexSegments); if (putValue != null) { return new BlobReadOptions(log, putValue.getOffset(), new MessageInfo(key, putValue.getSize(), false, value.isFlagSet(IndexValue.Flags.Ttl_Update_Index), true, value.getExpiresAtMs(), null, putValue.getAccountId(), putValue.getContainerId(), putValue.getOperationTimeInMs(), value.getLifeVersion())); } else { throw new StoreException("Did not find PUT index entry for key [" + key + "] when there is an undelete entry", StoreErrorCodes.ID_Not_Found); } }</code><technical_language>getDeletedBlobReadOptions is complicated</technical_language>

Target:
private BlobReadOptions getUndeletedBlobReadOptions(IndexValue value, StoreKey key, ConcurrentSkipListMap<Offset, IndexSegment> indexSegments) throws StoreException { IndexValue putValue = findKey(key, new FileSpan(getStartOffset(indexSegments), value.getOffset()), EnumSet.of(IndexEntryType.PUT), indexSegments); if (putValue != null) { return new BlobReadOptions(log, putValue.getOffset(), new MessageInfo(key, putValue.getSize(), false, value.isTTLUpdate(), true, value.getExpiresAtMs(), null, putValue.getAccountId(), putValue.getContainerId(), putValue.getOperationTimeInMs(), value.getLifeVersion())); } else { throw new StoreException("Did not find PUT index entry for key [" + key + "] when there is an undelete entry", StoreErrorCodes.ID_Not_Found); } }
Source:
<code>private void pauseTopicManagerPartitions(Collection<TopicPartition> topicManagerPartitions) { if (null == topicManagerPartitions || topicManagerPartitions.isEmpty()) { return; } <START> _consumer.pause(topicManagerPartitions); <END> for (TopicPartition tp : topicManagerPartitions) { _autoPausedSourcePartitions.put(tp, new PausedSourcePartitionMetadata(() -> _topicManager.shouldUnPausePartition(tp), PausedSourcePartitionMetadata.Reason.TOPIC_NOT_CREATED)); } _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }</code><technical_language>Currently, time a partition needs paused, add autoPausedSourcePartitions set add task taskUpdates. Then, automatically care of pausePartitions() in pre-poll hook. I suggest letting normal flow care of pause avoid calling consumer.pause() here</technical_language>

Target:
private void pauseTopicManagerPartitions(Collection<TopicPartition> topicManagerPartitions) { if (null == topicManagerPartitions || topicManagerPartitions.isEmpty()) { return; } _consumer.pause(topicManagerPartitions); for (TopicPartition tp : topicManagerPartitions) { _autoPausedSourcePartitions.put(tp, new PausedSourcePartitionMetadata(() -> _topicManager.shouldResumePartition(tp), PausedSourcePartitionMetadata.Reason.TOPIC_NOT_CREATED)); } }
Source:
<code>private void importProjects(final Set<File> dotProjectFiles) { WorkspaceJob job = new WorkspaceJob( UIText.ImportChangedProjectsCommand_ImportingChangedProjects) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { for (File f : dotProjectFiles) { <START> if (monitor.isCanceled()) { <END> return Status.CANCEL_STATUS; } String ap = f.getAbsolutePath(); importProject(ap); } return Status.OK_STATUS; } }; job.schedule(); }</code><technical_language>braces</technical_language>

Target:
private void importProjects(final Set<File> dotProjectFiles) { WorkspaceJob job = new WorkspaceJob( UIText.ImportChangedProjectsCommand_ImportingChangedProjects) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { for (File f : dotProjectFiles) { if (monitor.isCanceled()) return Status.CANCEL_STATUS; String ap = f.getAbsolutePath(); importProject(ap); } return Status.OK_STATUS; } }; job.schedule(); }
Source:
<code>public List<String> getListCasesHavingArtifactInstancesKnownBad(CorrelationAttributeInstance.Type aType, String value) throws EamDbException, CorrelationAttributeNormalizationException { <START> String normalizeValuedd = CorrelationAttributeNormalizer.normalize(aType, value); <END> Connection conn = connect(); Collection<String> caseNames = new LinkedHashSet<>(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; String tableName = EamDbUtil.correlationTypeToInstanceTableName(aType); String sql = "SELECT DISTINCT case_name FROM " + tableName + " INNER JOIN cases ON " + tableName + ".case_id=cases.id WHERE " + tableName + ".value=? AND " + tableName + ".known_status=?"; try { preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, normalizeValuedd); preparedStatement.setByte(2, TskData.FileKnown.BAD.getFileKnownValue()); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { caseNames.add(resultSet.getString("case_name")); } } catch (SQLException ex) { throw new EamDbException("Error getting notable artifact instances.", ex); } finally { EamDbUtil.closeStatement(preparedStatement); EamDbUtil.closeResultSet(resultSet); EamDbUtil.closeConnection(conn); } return caseNames.stream().collect(Collectors.toList()); }</code><technical_language>Is a typo in this name</technical_language>

Target:
public List<String> getListCasesHavingArtifactInstancesKnownBad(CorrelationAttributeInstance.Type aType, String value) throws EamDbException, CorrelationAttributeNormalizationException { String normalizedValue = CorrelationAttributeNormalizer.normalize(aType, value); Connection conn = connect(); Collection<String> caseNames = new LinkedHashSet<>(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; String tableName = EamDbUtil.correlationTypeToInstanceTableName(aType); String sql = "SELECT DISTINCT case_name FROM " + tableName + " INNER JOIN cases ON " + tableName + ".case_id=cases.id WHERE " + tableName + ".value=? AND " + tableName + ".known_status=?"; try { preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1, normalizedValue); preparedStatement.setByte(2, TskData.FileKnown.BAD.getFileKnownValue()); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { caseNames.add(resultSet.getString("case_name")); } } catch (SQLException ex) { throw new EamDbException("Error getting notable artifact instances.", ex); } finally { EamDbUtil.closeStatement(preparedStatement); EamDbUtil.closeResultSet(resultSet); EamDbUtil.closeConnection(conn); } return caseNames.stream().collect(Collectors.toList()); }
Source:
<code>public void onInit() { <START> this.createdAt = Timer.nanos(); <END> }</code><technical_language>name is confusing. I call this startNanos. I read createdAt; I impression is some kind of epoch time</technical_language>

Target:
public void onInit() { this.startNanos = Timer.nanos(); }
Source:
<code>public MesosCloud(String nativeLibraryPath, String master, String description, String frameworkName, int slaveCpus, int slaveMem, int maxExecutors, int executorCpus, int executorMem, int idleTerminationMinutes) throws NumberFormatException { super("MesosCloud"); this.nativeLibraryPath = nativeLibraryPath; this.master = master; this.description = description; <START> if (StringUtils.isNotBlank(frameworkName)) { <END> this.frameworkName = frameworkName; } else { this.frameworkName = DEFAULT_FRAMEWORK_NAME; } this.slaveCpus = slaveCpus; this.slaveMem = slaveMem; this.maxExecutors = maxExecutors; this.executorCpus = executorCpus; this.executorMem = executorMem; this.idleTerminationMinutes = idleTerminationMinutes; restartMesos(); }</code><technical_language>a ternary operator for conciseness</technical_language>

Target:
public MesosCloud(String nativeLibraryPath, String master, String description, String frameworkName, int slaveCpus, int slaveMem, int maxExecutors, int executorCpus, int executorMem, int idleTerminationMinutes) throws NumberFormatException { super("MesosCloud"); this.nativeLibraryPath = nativeLibraryPath; this.master = master; this.description = description; this.frameworkName = StringUtils.isNotBlank(frameworkName) ? frameworkName : DEFAULT_FRAMEWORK_NAME; this.slaveCpus = slaveCpus; this.slaveMem = slaveMem; this.maxExecutors = maxExecutors; this.executorCpus = executorCpus; this.executorMem = executorMem; this.idleTerminationMinutes = idleTerminationMinutes; restartMesos(); }
Source:
<code>private void loadNews() { Platform.runLater(() -> { <START> newsWebView.getEngine().load("<LINK_0>"); <END> onLoadingStop(); }); }</code><technical_language>do hardcoded urls. load FafApiProperties class declare in application.yml add remote preferences give a bit more flexibility settled</technical_language>

Target:
private void loadNews() { Platform.runLater(() -> { Website website = clientProperties.getWebsite(); newsWebView.getEngine().load(website.getNewsHubUrl()); }); }
Source:
<code>public void zoomToFit(List<LatLong> coords) { final BaiduMap map = getBaiduMap(); if (map == null) return; if (!coords.isEmpty()) { final List<LatLng> points = new ArrayList<LatLng>(); for (LatLong coord : coords) points.add(CoordToLatLang(coord)); final LatLngBounds bounds = getBounds(points); final Activity activity = getActivity(); if(activity == null) return; final View rootView = ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0); if(rootView == null) return; final int height = rootView.getHeight(); final int width = rootView.getWidth(); Log.d(TAG, String.format(Locale.US, "Screen W %d, H %d", width, height)); if(height > 0 && width > 0) { <START> MapStatusUpdate animation = MapStatusUpdateFactory.newLatLngBounds(bounds, width, height); END> map.animateMapStatus(animation); } } }</code><technical_language>@droneboost in Google map implementation, 100 is amount of padding in pixels. too. right, stored a constant give a indication use</technical_language>

Target:
public void zoomToFit(List<LatLong> coords) { final BaiduMap map = getBaiduMap(); if (map == null) return; if (!coords.isEmpty()) { final List<LatLng> points = new ArrayList<LatLng>(); for (LatLong coord : coords) points.add(CoordToLatLng(coord)); final LatLngBounds bounds = getBounds(points); final Activity activity = getActivity(); if (activity == null) return; final View rootView = ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0); if (rootView == null) return; final int height = rootView.getHeight(); final int width = rootView.getWidth(); Log.d(TAG, String.format(Locale.US, "Screen W %d, H %d", width, height)); if (height > 0 && width > 0) { MapStatusUpdate animation = MapStatusUpdateFactory.newLatLngBounds(bounds, width, height); map.animateMapStatus(animation); } } }