auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void createDEAStandaloneGratuityPostingRule(StandaloneInstallmentBean bean, DegreeCurricularPlan degreeCurricularPlan) { check(AcademicPredicates.MANAGE_PAYMENTS); DegreeCurricularPlanServiceAgreementTemplate dcpSAT = degreeCurricularPlan.getServiceAgreementTemplate(); if (dcpSAT != null) { YearMonthDay startDate = bean.getStartDate(); LocalDate startLocalDate = new LocalDate(startDate.getYear(), startDate.getMonthOfYear(), startDate.getDayOfMonth()); BigDecimal ectsForYear = bean.getEctsForYear(); BigDecimal gratuityFactor = bean.getGratuityFactor(); BigDecimal ectsFactor = bean.getEctsFactor(); new StandaloneEnrolmentGratuityPR(startLocalDate.toDateTimeAtStartOfDay(), null, dcpSAT, ectsForYear, gratuityFactor, ectsFactor); } else { <START> throw new DomainException(""); <END> } }</code><technical_language>is this a TODO error message exception</technical_language>

Target:
public static void createDEAStandaloneGratuityPostingRule(StandaloneInstallmentBean bean, DegreeCurricularPlan degreeCurricularPlan) { check(AcademicPredicates.MANAGE_PAYMENTS); DegreeCurricularPlanServiceAgreementTemplate dcpSAT = degreeCurricularPlan.getServiceAgreementTemplate(); if (dcpSAT != null) { YearMonthDay startDate = bean.getStartDate(); LocalDate startLocalDate = new LocalDate(startDate.getYear(), startDate.getMonthOfYear(), startDate.getDayOfMonth()); BigDecimal ectsForYear = bean.getEctsForYear(); BigDecimal gratuityFactor = bean.getGratuityFactor(); BigDecimal ectsFactor = bean.getEctsFactor(); new StandaloneEnrolmentGratuityPR(startLocalDate.toDateTimeAtStartOfDay(), null, dcpSAT, ectsForYear, gratuityFactor, ectsFactor); } else { throw new DomainException("StandaloneEnrolmentGratuityPR.DegreeCurricularPlanServiceAgreementTemplate.cannot.be.null"); } }
Source:
<code>ClusterContext(Set<AssignableReplica> replicaSet, int instanceCount, Map<String, ResourceAssignment> baselineAssignment, Map<String, ResourceAssignment> bestPossibleAssignment) { int totalReplicas = 0; int totalTopStateReplicas = 0; for (Map.Entry<String, List<AssignableReplica>> entry : replicaSet.stream() .collect(Collectors.groupingBy(AssignableReplica::getResourceName)) .entrySet()) { int replicas = entry.getValue().size(); totalReplicas += replicas; int replicaCnt = Math.max(1, estimateAvgReplicaCount(replicas, instanceCount)); _estimatedMaxPartitionByResource.put(entry.getKey(), replicaCnt); totalTopStateReplicas += entry.getValue().stream().filter(AssignableReplica::isReplicaTopState).count(); } _estimatedMaxPartitionCount = estimateAvgReplicaCount(totalReplicas, instanceCount); _estimatedMaxTopStateCount = estimateAvgReplicaCount(totalTopStateReplicas, instanceCount); <START> _baselineAssignment = baselineAssignment.isEmpty() ? Collections.emptyMap() : baselineAssignment; <END> _bestPossibleAssignment = bestPossibleAssignment.isEmpty() ? Collections.emptyMap() : baselineAssignment; }</code><technical_language>nit: (baselineAssignment == null || baselineAssignment.isEmpty()) ...</technical_language>

Target:
ClusterContext(Set<AssignableReplica> replicaSet, int instanceCount, Map<String, ResourceAssignment> baselineAssignment, Map<String, ResourceAssignment> bestPossibleAssignment) { int totalReplicas = 0; int totalTopStateReplicas = 0; for (Map.Entry<String, List<AssignableReplica>> entry : replicaSet.stream() .collect(Collectors.groupingBy(AssignableReplica::getResourceName)) .entrySet()) { int replicas = entry.getValue().size(); totalReplicas += replicas; int replicaCnt = Math.max(1, estimateAvgReplicaCount(replicas, instanceCount)); _estimatedMaxPartitionByResource.put(entry.getKey(), replicaCnt); totalTopStateReplicas += entry.getValue().stream().filter(AssignableReplica::isReplicaTopState).count(); } _estimatedMaxPartitionCount = estimateAvgReplicaCount(totalReplicas, instanceCount); _estimatedMaxTopStateCount = estimateAvgReplicaCount(totalTopStateReplicas, instanceCount); _baselineAssignment = baselineAssignment; _bestPossibleAssignment = bestPossibleAssignment; }
Source:
<code>private static ImmutableMap<String, FxIndex> loadFromCsv() { List<ResourceLocator> resources = ResourceConfig.orderedResources("FxIndexData.csv"); Map<String, FxIndex> map = new HashMap<>(); for (ResourceLocator resource : resources) { try { CsvFile csv = CsvFile.of(resource.getCharSource(), true); for (int i = 0; i < csv.rowCount(); i++) { FxIndex parsed = parseFxIndex(csv, i); map.put(parsed.getName(), parsed); } } catch (RuntimeException ex) { <START> log.severe("Error processing resource as FX Index CSV file: " + resource + ex.getMessage()); <END> return ImmutableMap.of(); } } return ImmutableMap.copyOf(map); }</code><technical_language>This produce odd error message. log.log(Level.SEVERE, "..." + resource, ex);</technical_language>

Target:
private static ImmutableMap<String, FxIndex> loadFromCsv() { List<ResourceLocator> resources = ResourceConfig.orderedResources("FxIndexData.csv"); Map<String, FxIndex> map = new HashMap<>(); for (ResourceLocator resource : resources) { try { CsvFile csv = CsvFile.of(resource.getCharSource(), true); for (int i = 0; i < csv.rowCount(); i++) { FxIndex parsed = parseFxIndex(csv, i); map.put(parsed.getName(), parsed); } } catch (RuntimeException ex) { log.log(Level.SEVERE, "Error processing resource as FX Index CSV file: " + resource, ex); return ImmutableMap.of(); } } return ImmutableMap.copyOf(map); }
Source:
<code>public void testNullACL() throws Exception { File tmpDir = ClientBase.createTmpDir(); ClientBase.setupTestEnv(); ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000); final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]); ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1); f.startup(zks); ZooKeeper zk = ClientBase.createZKClient(HOSTPORT); try { try { <START> zk.create("/foo", "foo".getBytes(), null, CreateMode.PERSISTENT); <END> Assert.fail("Expected InvalidACLException for null ACL parameter"); } catch (InvalidACLException e) { } catch (Exception e) { LOG.error("Error in testNullACL", e); Assert.fail("Expected InvalidACLException for null ACL parameter"); } try { zk.create("/foo", "foo".getBytes(), null, CreateMode.PERSISTENT, null); Assert.fail("Expected InvalidACLException for null ACL parameter"); } catch (InvalidACLException e) { } catch (Exception e) { LOG.error("Error in testNullACL", e); Assert.fail("Expected InvalidACLException for null ACL parameter"); } try { zk.setACL("/foo", null, 0); Assert.fail("Expected InvalidACLException for null ACL parameter"); } catch (InvalidACLException e) { } catch (Exception e) { LOG.error("Error in testNullACL", e); Assert.fail("Expected InvalidACLException for null ACL parameter"); } } finally { zk.close(); f.shutdown(); zks.shutdown(); Assert.assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT)); } }</code><technical_language>tests consolidated a single try block avoid duplicate boilerplate code</technical_language>

Target:
public void testNullACL() throws Exception { File tmpDir = ClientBase.createTmpDir(); ClientBase.setupTestEnv(); ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000); final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]); ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1); f.startup(zks); ZooKeeper zk = ClientBase.createZKClient(HOSTPORT); try { try { zk.create("/foo", "foo".getBytes(), null, CreateMode.PERSISTENT); Assert.fail("Expected InvalidACLException for null ACL parameter"); } catch (InvalidACLException e) { } try { zk.create("/foo", "foo".getBytes(), null, CreateMode.PERSISTENT, null); Assert.fail("Expected InvalidACLException for null ACL parameter"); } catch (InvalidACLException e) { } try { zk.setACL("/foo", null, 0); Assert.fail("Expected InvalidACLException for null ACL parameter"); } catch (InvalidACLException e) { } } finally { zk.close(); f.shutdown(); zks.shutdown(); Assert.assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT)); } }
Source:
<code>public void testChunkingSizeAndTime() throws IOException { final String testId = "testChunkingSizeAndTime"; final int recordCount = 25; final int deferredWriteDelay = 500; final IMonitoringController controller = this.createController(testId, deferredWriteDelay); for (int recordIndex = 0; recordIndex < recordCount; recordIndex++) { final OperationExecutionRecord record = new OperationExecutionRecord("op()", "SESS-ID", 0, recordIndex, recordIndex, "host", recordIndex, 1); controller.newMonitoringRecord(record); } <START> LockSupport.parkNanos(2 * deferredWriteDelay * 1000000L); <END> controller.terminateMonitoring(); final byte[] data = TestRawDataStorage.getInstance().getData(testId); final List<String> lines = TestChunkingCollector.linesFromData(data); final int numberOfLines = lines.size(); Assert.assertEquals(recordCount + 1, numberOfLines); }</code><technical_language>Please append time unit variable name, e.g., deferredWriteDelayInMs</technical_language>

Target:
public void testChunkingSizeAndTime() throws IOException { final String testId = "testChunkingSizeAndTime"; final int recordCount = 25; final int deferredWriteDelayInMs = 500; final IMonitoringController controller = this.createController(testId, deferredWriteDelayInMs); for (int recordIndex = 0; recordIndex < recordCount; recordIndex++) { final OperationExecutionRecord record = new OperationExecutionRecord("op()", "SESS-ID", 0, recordIndex, recordIndex, "host", recordIndex, 1); controller.newMonitoringRecord(record); } LockSupport.parkNanos(2 * deferredWriteDelayInMs * 1000000L); controller.terminateMonitoring(); final byte[] data = TestRawDataStorage.getInstance().getData(testId); final List<String> lines = TestChunkingCollector.linesFromData(data); final int numberOfLines = lines.size(); Assert.assertEquals(recordCount + 1, numberOfLines); }
Source:
<code>public static File getSelectedFile(String extension, String description, DialogType type, boolean fixExtension) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extension); chooser.setFileFilter(filter); String currentDirectory = (String) ApplicationSettings.Setting.USER_LASTDIR.getValue(); if(currentDirectory != null && currentDirectory.length() > 0) { chooser.setCurrentDirectory(new File(currentDirectory)); } int returnVal = 0; switch (type) { case SAVE: <START> chooser.setDialogTitle("Save As"); <END> returnVal = chooser.showSaveDialog(null); break; case SAVEAS: chooser.setDialogTitle("Save As"); returnVal = chooser.showSaveDialog(null); break; case OPEN: returnVal = chooser.showOpenDialog(null); break; case PDF: returnVal = chooser.showDialog(null, "Generate PDF"); break; default: break; } if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.exists() && type == DialogType.OPEN) { JOptionPane.showMessageDialog(null, "File doesn't exist", "Item not found", JOptionPane.ERROR_MESSAGE); } else { String filePath = file.getAbsolutePath(); if (fixExtension && !filePath.endsWith("." + extension)) { file = new File(filePath + "." + extension); } ApplicationSettings.Setting.USER_LASTDIR.setValue(file.getAbsolutePath()); ApplicationSettings.INSTANCE.save(); return file; } } return null; }</code><technical_language>do set title "Save as" for SAVE SAVEAS case</technical_language>

Target:
public static File getSelectedFile(String extension, String description, DialogType type, boolean fixExtension) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extension); chooser.setFileFilter(filter); String currentDirectory = (String) ApplicationSettings.Setting.USER_LASTDIR.getValue(); if(currentDirectory != null && currentDirectory.length() > 0) { chooser.setCurrentDirectory(new File(currentDirectory)); } int returnVal = 0; switch (type) { case SAVE: case SAVEAS: chooser.setDialogTitle("Save As"); returnVal = chooser.showSaveDialog(null); break; case OPEN: returnVal = chooser.showOpenDialog(null); break; case PDF: returnVal = chooser.showDialog(null, "Generate PDF"); break; default: break; } if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); if (!file.exists() && type == DialogType.OPEN) { JOptionPane.showMessageDialog(null, "File doesn't exist", "Item not found", JOptionPane.ERROR_MESSAGE); } else { String filePath = file.getAbsolutePath(); if (fixExtension && !filePath.endsWith("." + extension)) { file = new File(filePath + "." + extension); } ApplicationSettings.Setting.USER_LASTDIR.setValue(file.getAbsolutePath()); ApplicationSettings.INSTANCE.save(); return file; } } return null; }
Source:
<code><START> private Optional<List<String>> parseResults(String[] lines) { <END> List<String> result = new ArrayList<>(); for (String line : lines) { Matcher matcher = TEST.matcher(line); if (matcher.matches()) { result.add(matcher.group("name")); } } return Optional.of(result); }</code><technical_language>Optional if return Optional.absent(): return empty list</technical_language>

Target:
private List<String> parseResults(String[] lines) { List<String> result = new ArrayList<>(); for (String line : lines) { Matcher matcher = TEST.matcher(line); if (matcher.matches()) { result.add(matcher.group("name")); } } return result; }
Source:
<code>public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) <START> .last() <END> .publishOn(scheduler); }</code><technical_language>I if this is correct operator, if multiple instants? .single() throw exception if more element</technical_language>

Target:
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); }
Source:
<code>public static Process execute(String exportUnixFile, String initUnixFile) { Process p = null; try { File file = new File(exportUnixFile); if(!exportUnixFile.equals("")) p = Runtime.getRuntime().exec( "/bin/bash -c 'source "+exportUnixFile+"'"); file = new File(initUnixFile); p = Runtime.getRuntime().exec( "/bin/bash "+initUnixFile+""); p.waitFor(); } catch (Exception ex) { ex.printStackTrace(); <START> System.exit(-1); <END> p = null; } return null; }</code><technical_language>if exception is thrown? monitor finishes execution? This is a dangerous behavior in opinion</technical_language>

Target:
public static Process execute(String exportUnixFile, String initUnixFile) { Process p = null; try { if (!exportUnixFile.equals("")) p = Runtime.getRuntime().exec( "/bin/bash -c 'source " + exportUnixFile + "'"); p = Runtime.getRuntime().exec("/bin/bash " + initUnixFile + ""); p.waitFor(); } catch (Exception ex) { ex.printStackTrace(); p = null; } return null; }
Source:
<code>public static void create(IResource resource, GradleBuild gradleBuild, String message, Throwable exception, int lineNumber) throws CoreException { IMarker marker = resource.createMarker(GradleErrorMarker.ID); if (lineNumber >= 0) { marker.setAttribute(IMarker.LINE_NUMBER, lineNumber); } marker.setAttribute(IMarker.MESSAGE, collectErrorMessages(exception)); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); <START> marker.setAttribute(IMarker.LOCATION, "Gradle build script"); <END> marker.setAttribute(ATTRIBUTE_ROOT_DIR, gradleBuild.getBuildConfig().getRootProjectDirectory().getAbsolutePath()); if (exception != null) { marker.setAttribute(GradleErrorMarker.ATTRIBUTE_STACKTRACE, collectStacktrace(exception)); } }</code><technical_language>necessarily a build script - if resource is a file</technical_language>

Target:
public static void create(IResource resource, GradleBuild gradleBuild, String message, Throwable exception, int lineNumber) throws CoreException { IMarker marker = resource.createMarker(GradleErrorMarker.ID); if (lineNumber >= 0) { marker.setAttribute(IMarker.LINE_NUMBER, lineNumber); } marker.setAttribute(IMarker.MESSAGE, collectErrorMessages(exception)); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(ATTRIBUTE_ROOT_DIR, gradleBuild.getBuildConfig().getRootProjectDirectory().getAbsolutePath()); if (exception != null) { marker.setAttribute(GradleErrorMarker.ATTRIBUTE_STACKTRACE, collectStacktrace(exception)); } }
Source:
<code>protected InputStream openObjectStream(URI object) throws IOException { URLConnection urlConnection = object.toURL().openConnection(); <START> if (!"".equals(httpAuthenticationUsername) && !"".equals(httpAuthenticationPassword)) { <END> String userPass = httpAuthenticationUsername + ":" + httpAuthenticationPassword; String basicAuthString = "Basic " + Base64.getEncoder().encodeToString(StringUtils.toUtf8(userPass)); urlConnection.setRequestProperty("Authorization", basicAuthString); } return urlConnection.getInputStream(); }</code><technical_language>Please add this another method openObjectStream(URI object, long start) too</technical_language>

Target:
protected InputStream openObjectStream(URI object) throws IOException { return openObjectStream(object, 0); }
Source:
<code>protected void authenticateUser() { <START> userType = gateKeeper.getCurrentUser(); <END> }</code><technical_language>store a boolean shouldSkipVerification instead</technical_language>

Target:
protected void authenticateUser() { }
Source:
<code>private int getRowForTheDay(int date) { int row = date / DAYS_IN_WEEK; <START> return date % 7 == 0 ? row - 1 : row; <END> }</code><technical_language>DAYS_IN_WEEK</technical_language>

Target:
private int getRowForTheDay(int date) { int row = date / DAYS_IN_WEEK; return date % DAYS_IN_WEEK == 0 ? row - 1 : row; }
Source:
<code>public int hashCode() { int result = rowParts != null ? rowParts.hashCode() : 0; <START> result = 31 * result + numberOfComponentsHashed; <END> return result; }</code><technical_language>I maintain backcompat is safer if relied hashCode definition</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (numberOfComponentsHashed == 1 ? 1231 : 1237); result = prime * result + ((rowParts == null) ? 0 : rowParts.hashCode()); if (numberOfComponentsHashed > 1) { result = prime * result + numberOfComponentsHashed; } return result; }
Source:
<code>private void setLayoutRestrictions(boolean <START> <END> allowScrollThumb, boolean allowAlphaJump, boolean bias) { Resources res = mPagedListView.getContext().getResources(); ImageView upButton = mPagedListView.findViewById(androidx.car.test.R.id.page_up); ImageView downButton = mPagedListView.findViewById(androidx.car.test.R.id.page_down); Button alphaJump = mPagedListView.findViewById(androidx.car.test.R.id.alpha_jump); View scrollThumb = mPagedListView.findViewById(androidx.car.test.R.id.scrollbar_thumb); View scrollBarView = mPagedListView.findViewById(androidx.car.test.R.id.paged_scroll_view); ViewGroup.LayoutParams params = scrollBarView.getLayoutParams(); int seperateMargin = res.getDimensionPixelSize(androidx.car.R.dimen.car_padding_4); int restrictedHeight = mPagedListView.getPaddingTop() + upButton.getHeight() + downButton.getHeight() + mPagedListView.getPaddingBottom() + seperateMargin; if (allowScrollThumb) { restrictedHeight += scrollThumb.getHeight() + seperateMargin; } if (allowAlphaJump) { restrictedHeight += alphaJump.getHeight() + seperateMargin; } if (bias) { restrictedHeight += -1; } params.height = restrictedHeight; try { mActivityRule.runOnUiThread(() -> { scrollBarView.setLayoutParams(params); }); } catch (Throwable throwable) { throwable.printStackTrace(); throw new RuntimeException(throwable); } }</code><technical_language>extra space</technical_language>

Target:
private void setLayoutRestrictions(boolean allowScrollThumb, boolean allowAlphaJump, boolean bias) { ImageView upButton = mPagedListView.findViewById(androidx.car.test.R.id.page_up); ImageView downButton = mPagedListView.findViewById(androidx.car.test.R.id.page_down); Button alphaJump = mPagedListView.findViewById(androidx.car.test.R.id.alpha_jump); View scrollThumb = mPagedListView.findViewById(androidx.car.test.R.id.scrollbar_thumb); View scrollBarView = mPagedListView.findViewById(androidx.car.test.R.id.paged_scroll_view); ViewGroup.LayoutParams params = scrollBarView.getLayoutParams(); int seperateMargin = mPagedListView.getContext().getResources() .getDimensionPixelSize(androidx.car.R.dimen.car_padding_4); int restrictedHeight = mPagedListView.getPaddingTop() + upButton.getHeight() + downButton.getHeight() + mPagedListView.getPaddingBottom() + seperateMargin; if (allowScrollThumb) { restrictedHeight += scrollThumb.getHeight() + seperateMargin; } if (allowAlphaJump) { restrictedHeight += alphaJump.getHeight() + seperateMargin; } if (bias) { restrictedHeight += -1; } params.height = restrictedHeight; try { mActivityRule.runOnUiThread(() -> { scrollBarView.requestLayout(); }); } catch (Throwable throwable) { throwable.printStackTrace(); throw new RuntimeException(throwable); } }
Source:
<code>@Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { lock.lock(); try { long timeoutNanos = unit.toNanos(timeout); while (queue.isEmpty() && timeoutNanos > 0) { timeoutNanos = nonEmpty.awaitNanos(timeoutNanos); } E peek = queue.peek(); if (peek == null) { throw new NoSuchElementException(); } queue.remove(); return peek; } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); <START> return null; <END> } finally { lock.unlock(); } }</code><technical_language>throws</technical_language>

Target:
@Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { lock.lock(); try { long timeoutNanos = unit.toNanos(timeout); while (queue.isEmpty() && timeoutNanos > 0) { timeoutNanos = nonEmpty.awaitNanos(timeoutNanos); } E peek = queue.peek(); if (peek == null) { throw new NoSuchElementException(); } queue.remove(); return peek; } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
<code>protected void initSelectedType() { final VmInterfaceType defaultNicType = getDeafultNicTypeByProfile(); <START> getNicType().setItems(supportedVnicTypes, defaultNicType); <END> }</code><technical_language>Please update items if time, I mean- 'getItems()' is null. Otherwise, update selection</technical_language>

Target:
protected void initSelectedType() { final VmInterfaceType defaultNicType = getDeafultNicTypeByProfile(); final Collection<VmInterfaceType> vnicTypes = supportedVnicTypes == null ? new ArrayList<VmInterfaceType>() : supportedVnicTypes; if (getNicType().getItems() != vnicTypes) { getNicType().setItems(vnicTypes, defaultNicType); } else { getNicType().setSelectedItem(defaultNicType); } }
Source:
<code>private void doSlice(ObjectReader or, Slice s) throws IOException { dw = new DeltaWindow(block.config, block.dc, or, block.pm, block.list, s.beginIndex, s.endIndex); dw.search(); <START> dw = null; <END> }</code><technical_language>a note: 1) steal work currently processing worker 2) other stealing threads exit if notice is work remaining ( period switching threads) If sychronize access delta worker slices, check item in slices list first, delta worker if is empty</technical_language>

Target:
private void doSlice(ObjectReader or, Slice s) throws IOException { DeltaWindow w = new DeltaWindow(block.config, block.dc, or, block.pm, block.list, s.beginIndex, s.endIndex); synchronized (this) { dw = w; } w.search(); synchronized (this) { dw = null; } }
Source:
<code>protected void after() { logger.debug("S3 proxy is stopping"); try { <START> s3Proxy.stop(); <END> } catch (Exception e) { throw new RuntimeException("Unable to stop S3 proxy", e); } logger.debug("S3 proxy has stopped"); }</code><technical_language>clean BlobStore via: java BlobStore blobStore = blobStoreContext.getBlobStore(); for (StorageMetadata metadata : blobStore.list()) { blobStore.deleteContainer(metadata.getName()); } blobStoreContext.close();</technical_language>

Target:
protected void after() { logger.debug("S3 proxy is stopping"); try { s3Proxy.stop(); BlobStore blobStore = blobStoreContext.getBlobStore(); for (StorageMetadata metadata : blobStore.list()) { blobStore.deleteContainer(metadata.getName()); } blobStoreContext.close(); } catch (Exception e) { throw new RuntimeException("Unable to stop S3 proxy", e); } FileUtils.deleteQuietly(blobStoreLocation); logger.debug("S3 proxy has stopped"); }
Source:
<code>public String getResponseContinuation() { <START> return this.inner.getContinuation(); <END> }</code><technical_language>OK add a getContinuation method QueryIterable, if useful for you. consistent, please QueryIterable's existing getResponseHeaders() method apply this change other getters of FeedResponse. getActivityId(), getSessionToken() etc. definition references this.responseHeaders completely removed. public String getResponseContinuation() { return FeedResponse.getValueOrNull( this.inner.getResponseHeaders(), HttpConstants.HttpHeaders.CONTINUATION); } private static String getValueOrNull(Map<String, String> map, String key) { if (map != null) { return map.get(key); } return null; }</technical_language>

Target:
public String getResponseContinuation() { return FeedResponse.getValueOrNull(this.inner.getResponseHeaders(), HttpConstants.HttpHeaders.CONTINUATION); }
Source:
<code>public static @Nullable ResourceLocation guessName(@Nullable Object input) { if (input instanceof IForgeRegistryEntry) { return ((IForgeRegistryEntry) input).getRegistryName(); } else if (input instanceof ItemStack) { <START> return getNameFromOutput((ItemStack) input); END> } else if (input instanceof String) { return new ResourceLocation("ore", (String) input); } else if (input instanceof IRailcraftObjectContainer) { IRailcraftObjectContainer<?> container = Code.cast(input); return container.getRegistryName(); } return null; }</code><technical_language>This incomplete? other optional input types? generate non-unique names. I correct solution is merge functions. Find a resource location, pass MultiSet unique counter generate a unique one</technical_language>

Target:
public static @Nullable ResourceLocation guessName(@Nullable Object input) { if (input instanceof IForgeRegistryEntry) { return getNameFromOutput(Objects.requireNonNull(((IForgeRegistryEntry) input).getRegistryName())); } else if (input instanceof ItemStack) { return getNameFromOutput((ItemStack) input); } else if (input instanceof String) { return getNameFromOutput(new ResourceLocation("ore", (String) input)); } else if (input instanceof IRailcraftObjectContainer) { IRailcraftObjectContainer<?> container = Code.cast(input); return getNameFromOutput(container.getRegistryName()); } return null; }
Source:
<code>public boolean execute() { Gson gsonParser = Utils.getTeammatesGson(); ArrayList<StudentEnrollDetails> enrollmentList = gsonParser .fromJson(enrollmentDetails, new TypeToken<ArrayList<StudentEnrollDetails>>(){} .getType()); log.info("Adjusting submissions for feedback session :" + sessionName + "in course : " + courseId); FeedbackSessionAttributes feedbackSession = FeedbackSessionsLogic.inst() .getFeedbackSession(sessionName, courseId); StudentsLogic stLogic = StudentsLogic.inst(); String errorString = "Error encountered while adjusting feedback session responses " + "of %s in course : %s : %s\n%s"; if(feedbackSession != null) { List<FeedbackResponseAttributes> allResponses = FeedbackResponsesLogic.inst() .getFeedbackResponsesForSession(feedbackSession.feedbackSessionName, feedbackSession.courseId); for (FeedbackResponseAttributes response : allResponses) { try { stLogic.adjustFeedbackResponseForEnrollments(enrollmentList, response); } catch (Exception e) { <START> log.severe(String.format(errorString, sessionName, courseId, e.getMessage(), e.getStackTrace().toString())); <END> return false; } } return true; } else { log.severe(String.format(errorString, sessionName, courseId, "feedback session is null", "")); return false; } }</code><technical_language>I remember a utility method extracts stack trace a string</technical_language>

Target:
public boolean execute() { Gson gsonParser = Utils.getTeammatesGson(); ArrayList<StudentEnrollDetails> enrollmentList = gsonParser .fromJson(enrollmentDetails, new TypeToken<ArrayList<StudentEnrollDetails>>(){} .getType()); log.info("Adjusting submissions for feedback session :" + sessionName + "in course : " + courseId); FeedbackSessionAttributes feedbackSession = FeedbackSessionsLogic.inst() .getFeedbackSession(sessionName, courseId); StudentsLogic stLogic = StudentsLogic.inst(); String errorString = "Error encountered while adjusting feedback session responses " + "of %s in course : %s : %s\n%s"; if(feedbackSession != null) { List<FeedbackResponseAttributes> allResponses = FeedbackResponsesLogic.inst() .getFeedbackResponsesForSession(feedbackSession.feedbackSessionName, feedbackSession.courseId); for (FeedbackResponseAttributes response : allResponses) { try { stLogic.adjustFeedbackResponseForEnrollments(enrollmentList, response); } catch (Exception e) { log.severe(String.format(errorString, sessionName, courseId, e.getMessage(), ActivityLogEntry.generateServletActionFailureLogMessage(request, e))); return false; } } return true; } else { log.severe(String.format(errorString, sessionName, courseId, "feedback session is null", "")); return false; } }
Source:
<code>private void generateTarFile() throws IOException { File folder = new File(backupTempDirPath); File[] srcFiles = folder.listFiles(); if (srcFiles == null) { log.debug("no backup file found under directory {}", backupTempDirPath); return; } try (FileOutputStream fileOutput = new FileOutputStream(filePath); TarArchiveOutputStream tarOutput = new TarArchiveOutputStream(fileOutput)) { for (File srcFile : srcFiles) { <START> addToTarFile(srcFile, tarOutput); <END> } } catch (IOException e) { log.error("failed to generate a backup tar file {}", filePath); throw e; } log.debug("backup tar file is generated at {}", filePath); }</code><technical_language>do want preserve file delete original in TAR? is this done in cleanup</technical_language>

Target:
private void generateTarFile() throws IOException { File folder = new File(backupTempDirPath); File[] srcFiles = folder.listFiles(); if (srcFiles == null) { log.debug("no backup file found under directory {}", backupTempDirPath); return; } try (FileOutputStream fileOutput = new FileOutputStream(filePath); TarArchiveOutputStream tarOutput = new TarArchiveOutputStream(fileOutput)) { for (File srcFile : srcFiles) { addToTarFile(srcFile, tarOutput); } } catch (IOException e) { log.error("failed to generate a backup tar file {}", filePath); throw e; } log.info("backup tar file is generated at {}", filePath); }
Source:
<code>public static Queue queueMapToQueue(Map<String, Object> map) { String name = (String) map.get("name"); boolean durable = (Boolean) map.get("durable"); <START> boolean exclusive = false; END> boolean autoDelete = (Boolean) map.get("auto_delete"); @SuppressWarnings("unchecked") Map<String, Object> arguments = (Map<String, Object>) map.get("arguments"); map.remove("name"); map.remove("durable"); map.remove("auto_delete"); map.remove("arguments"); return new Queue(name, durable, exclusive, autoDelete, arguments, map); }</code><technical_language>exclusive_consumer_tag</technical_language>

Target:
public static Queue queueMapToQueue(Map<String, Object> map) { String name = (String) map.get("name"); boolean durable = (Boolean) map.get("durable"); boolean exclusive = map.get("owner_pid_details") != null; boolean autoDelete = (Boolean) map.get("auto_delete"); @SuppressWarnings("unchecked") Map<String, Object> arguments = (Map<String, Object>) map.get("arguments"); map.remove("name"); map.remove("durable"); map.remove("auto_delete"); map.remove("arguments"); return new Queue(name, durable, exclusive, autoDelete, arguments, map); }
Source:
<code>public boolean isAssignableTo(Type other) { if ( equals( other ) ) { return true; } <START> TypeMirror typeMirrotToMatch = isWildCardExtendsBound() ? getTypeBound().typeMirror : typeMirror; <END> TypeMirror otherTypeMirrotToMatch = other.isWildCardSuperBound() ? other.getTypeBound().typeMirror : other.typeMirror; return typeUtils.isAssignable( typeMirrotToMatch, otherTypeMirrotToMatch ); }</code><technical_language>is a type in variable typeMirrotToMatch, typeMirrorToMatch for otherTypeMirrotToMatch, otherTypeMirrorToMatch</technical_language>

Target:
public boolean isAssignableTo(Type other) { if ( equals( other ) ) { return true; } TypeMirror typeMirrorToMatch = isWildCardExtendsBound() ? getTypeBound().typeMirror : typeMirror; return typeUtils.isAssignable( typeMirrorToMatch, other.typeMirror ); }
Source:
<code><START> public void setNewCommand(UICommand newCommand) { <END> this.newCommand = newCommand; }</code><technical_language>This other setters public, private</technical_language>

Target:
private void setNewCommand(UICommand newCommand) { this.newCommand = newCommand; }
Source:
<code>private void writeNullToLeaves(GroupColumnIO group) { IntArrayList nullCache = groupNullCache.get(group); if (nullCache == null || nullCache.isEmpty()) return; int parentDefinitionLevel = group.getParent().getDefinitionLevel(); for (ColumnWriter leafWriter : groupToLeafWriter.get(group)) { <START> for (int repetitionLevel : groupNullCache.get(group)) { <END> leafWriter.writeNull(repetitionLevel, parentDefinitionLevel); } } nullCache.clear(); }</code><technical_language>call groupNullCache.get(group) leafWriter group is constant, stored in nullCache, this be: int parentDefinitionLevel = group.getParent().getDefinitionLevel(); for (ColumnWriter leafWriter : groupToLeafWriter.get(group)) { for (int repetitionLevel : nullCache) { leafWriter.writeNull(repetitionLevel, parentDefinitionLevel); } }</technical_language>

Target:
private void writeNullToLeaves(GroupColumnIO group) { IntArrayList nullCache = groupNullCache.get(group); if (nullCache == null || nullCache.isEmpty()) return; int parentDefinitionLevel = group.getParent().getDefinitionLevel(); for (ColumnWriter leafWriter : groupToLeafWriter.get(group)) { for (IntIterator iter = nullCache.iterator(); iter.hasNext();) { int repetitionLevel = iter.nextInt(); leafWriter.writeNull(repetitionLevel, parentDefinitionLevel); } } nullCache.clear(); }
Source:
<code>public PollerFlux<OperationResult, List<FormPage>> beginRecognizeContent(RecognizeOptions recognizeOptions) { <START> if (recognizeOptions.getFormUrl() != null) { <END> return beginRecognizeContentFromUrl(recognizeOptions); } Flux<ByteBuffer> buffer = getByteBufferFlux(recognizeOptions.getForm(), recognizeOptions.getFormData()); return new PollerFlux<>( recognizeOptions.getPollInterval(), contentStreamActivationOperation(buffer, recognizeOptions.getLength(), recognizeOptions.getFormContentType()), extractContentPollOperation(), (activationResponse, context) -> monoError(logger, new RuntimeException("Cancellation is not supported")), fetchExtractContentResult()); }</code><technical_language>Add a null check for recognizeOptions it</technical_language>

Target:
public PollerFlux<OperationResult, List<FormPage>> beginRecognizeContent(RecognizeOptions recognizeOptions) { try { Objects.requireNonNull(recognizeOptions, "'recognizeOptions' is required and cannot be null."); if (recognizeOptions.getFormUrl() != null) { return beginRecognizeContentFromUrl(recognizeOptions); } Flux<ByteBuffer> buffer = getByteBufferFlux(recognizeOptions.getForm(), recognizeOptions.getFormData()); return new PollerFlux<>( recognizeOptions.getPollInterval(), contentStreamActivationOperation(buffer, recognizeOptions.getLength(), recognizeOptions.getFormContentType()), extractContentPollOperation(), (activationResponse, context) -> monoError(logger, new RuntimeException("Cancellation is not supported")), fetchExtractContentResult()); } catch (RuntimeException ex) { return PollerFlux.error(ex); } }
Source:
<code>public Map<List<Object>, Integer> processMessage(Message<?> message) { if (this.routingSlip == null) { synchronized (this) { if (this.routingSlip == null) { List<Object> routingSlipValues = new ArrayList<Object>(this.routingSlipPath.size()); for (Object path : this.routingSlipPath) { if (path instanceof String) { String entry = (String) path; if (this.beanFactory.containsBean(entry)) { Object bean = this.beanFactory.getBean(entry); Assert.state(bean instanceof MessageChannel || bean instanceof RoutingSlipRouteStrategy, "The RoutingSlip can contain only bean names of MessageChannel or " + "RoutingSlipRouteStrategy: " + bean); routingSlipValues.add(entry); } else { ExpressionEvaluatingRoutingSlipRouteStrategy strategy = new ExpressionEvaluatingRoutingSlipRouteStrategy(entry); strategy.setIntegrationEvaluationContext(this.evaluationContext); routingSlipValues.add(strategy); } } else { <START> routingSlipValues.add(path); <END> } } this.routingSlip = Collections.singletonMap(Collections.unmodifiableList(routingSlipValues), 0); } } } return this.routingSlip; }</code><technical_language>validate a MessageChannel RSRS if a String</technical_language>

Target:
public Map<List<Object>, Integer> processMessage(Message<?> message) { if (this.routingSlip == null) { synchronized (this) { if (this.routingSlip == null) { List<Object> routingSlipValues = new ArrayList<Object>(this.routingSlipPath.size()); for (Object path : this.routingSlipPath) { if (path instanceof String) { String entry = (String) path; if (this.beanFactory.containsBean(entry)) { Object bean = this.beanFactory.getBean(entry); if (!(bean instanceof MessageChannel || bean instanceof RoutingSlipRouteStrategy)) { throw new IllegalArgumentException("The RoutingSlip can contain " + "only bean names of MessageChannel or RoutingSlipRouteStrategy: " + bean); } routingSlipValues.add(entry); } else { ExpressionEvaluatingRoutingSlipRouteStrategy strategy = new ExpressionEvaluatingRoutingSlipRouteStrategy(entry); strategy.setIntegrationEvaluationContext(this.evaluationContext); routingSlipValues.add(strategy); } } else { routingSlipValues.add(path); } } this.routingSlip = Collections.singletonMap(Collections.unmodifiableList(routingSlipValues), 0); } } } return this.routingSlip; }
Source:
<code>public Map<String, Set<DatastreamTask>> assign(List<DatastreamGroup> datastreams, List<String> instances, Map<String, Set<DatastreamTask>> currentAssignment) { LOG.info(String.format("Trying to assign datastreams {%s} to instances {%s} and the current assignment is {%s}", datastreams, instances, currentAssignment)); Map<String, Set<DatastreamTask>> assignment = new HashMap<>(); for (String instance : instances) { assignment.put(instance, new HashSet<>()); currentAssignment.computeIfAbsent(instance, (x) -> new HashSet<>()); } int instancePos = 0; for (DatastreamGroup dg : datastreams) { int numTask = Math.min(getMaxTasks(dg), instances.size()); <START> for (int taskPos=0; taskPos <numTask; taskPos++) { <END> String instance = instances.get(instancePos); DatastreamTask foundDatastreamTask = currentAssignment.get(instance).stream() .filter(x -> x.getTaskPrefix().equals(dg.getTaskPrefix())) .findFirst() .orElse(new DatastreamTaskImpl(dg.getDatastreams())); assignment.get(instance).add(foundDatastreamTask); instancePos = (instancePos + 1) % instances.size(); } } LOG.info(String.format("New assignment is {%s}", assignment)); return assignment; }</code><technical_language>nit: add space = <</technical_language>

Target:
public Map<String, Set<DatastreamTask>> assign(List<DatastreamGroup> datastreams, List<String> instances, Map<String, Set<DatastreamTask>> currentAssignment) { LOG.info(String.format("Trying to assign datastreams {%s} to instances {%s} and the current assignment is {%s}", datastreams, instances, currentAssignment)); Map<String, Set<DatastreamTask>> assignment = new HashMap<>(); for (String instance : instances) { assignment.put(instance, new HashSet<>()); currentAssignment.computeIfAbsent(instance, (x) -> new HashSet<>()); } int instancePos = 0; for (DatastreamGroup dg : datastreams) { int numTask = getNumTasks(dg, instances.size()); for (int taskPos = 0; taskPos < numTask; taskPos++) { String instance = instances.get(instancePos); DatastreamTask foundDatastreamTask = currentAssignment.get(instance) .stream() .filter(x -> x.getTaskPrefix().equals(dg.getTaskPrefix())) .findFirst() .orElse(new DatastreamTaskImpl(dg.getDatastreams())); assignment.get(instance).add(foundDatastreamTask); instancePos = (instancePos + 1) % instances.size(); } } LOG.info(String.format("New assignment is {%s}", assignment)); return assignment; }
Source:
<code>public void close() { synchronized (documentStores) { DocumentStore ds = documentStores.get(location); if (ds != null) { <START> System.out.println("removing "+location); <END> ((DatabaseImpl)database).close(); ((IndexManagerImpl)query).close(); documentStores.remove(location); } } eventBus.post(new DatabaseClosed(databaseName)); }</code><technical_language>This a formal log removed</technical_language>

Target:
public void close() { synchronized (documentStores) { DocumentStore ds = documentStores.remove(location); if (ds != null) { ((DatabaseImpl)database).close(); ((IndexManagerImpl)query).close(); } else { throw new IllegalStateException("DocumentStore "+location+" already closed"); } } eventBus.post(new DatabaseClosed(databaseName)); }
Source:
<code>public void updateInstructorByGoogleId(String googleId, InstructorAttributes instructor) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull("Supplied parameter was null", instructor); coursesLogic.verifyCourseIsPresent(instructor.courseId); <START> verifyIsInstructorOfCourse(googleId, instructor.courseId); <END> InstructorAttributes instructorToUpdate = getInstructorForGoogleId(instructor.courseId, googleId); instructorToUpdate.name = instructor.name; instructorToUpdate.email = instructor.email; instructorsDb.updateInstructorByGoogleId(instructorToUpdate); }</code><technical_language>Similarly, rename this verifyIsGoogleIdOfInstructorOfCourse, match other method</technical_language>

Target:
public void updateInstructorByGoogleId(String googleId, InstructorAttributes instructor) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull("Supplied parameter was null", instructor); coursesLogic.verifyCourseIsPresent(instructor.courseId); verifyIsGoogleIdOfInstructorOfCourse(googleId, instructor.courseId); InstructorAttributes instructorToUpdate = getInstructorForGoogleId(instructor.courseId, googleId); instructorToUpdate.name = instructor.name; instructorToUpdate.email = instructor.email; instructorsDb.updateInstructorByGoogleId(instructorToUpdate); }
Source:
<code>public ModelAndView getUsersGroup(HttpServletRequest request, HttpServletResponse response) { IPerson person = personManager.getPerson(request); Set<Entity> groups = Collections.EMPTY_SET; if (person != null) { groups = groupService.getGroupsForMember(person.getUserName()); } <START> <END> return new ModelAndView("json", "groups", groups); }</code><technical_language>is guest user handled? want check return getUserName() is blank</technical_language>

Target:
public ModelAndView getUsersGroup(HttpServletRequest request, HttpServletResponse response) { IPerson person = personManager.getPerson(request); Set<Entity> groups = Collections.EMPTY_SET; if (person != null) { String username = person.getUserName(); if (username != null) { groups = groupService.getGroupsForMember(username); } } return new ModelAndView("json", "groups", groups); }
Source:
<code>public void getCache() throws IOException { RestResponse r = adminSession.get("/config/server/caches/accounts"); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); <START> CacheInfo result = newGson().fromJson(r.getReader(), new TypeToken<CacheInfo>() {}.getType()); <END> assertEquals("accounts", result.name); assertNull(result.type); assertEquals(1, result.entries.mem.longValue()); assertNotNull(result.averageGet); assertTrue(result.averageGet.endsWith("s")); assertNull(result.entries.disk); assertNull(result.entries.space); assertTrue(result.hitRatio.mem >= 0); assertTrue(result.hitRatio.mem <= 100); assertNull(result.hitRatio.disk); userSession.get("/config/server/version").consume(); r = adminSession.get("/config/server/caches/accounts"); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); result = newGson().fromJson(r.getReader(), new TypeToken<CacheInfo>() {}.getType()); assertEquals(2, result.entries.mem.longValue()); }</code><technical_language>done with: CacheInfo result = newGson().fromJson(r.getReader(), CacheInfo.class); in other places in this follow change</technical_language>

Target:
public void getCache() throws IOException { RestResponse r = adminSession.get("/config/server/caches/accounts"); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); CacheInfo result = newGson().fromJson(r.getReader(), CacheInfo.class); assertEquals("accounts", result.name); assertNull(result.type); assertEquals(1, result.entries.mem.longValue()); assertNotNull(result.averageGet); assertTrue(result.averageGet.endsWith("s")); assertNull(result.entries.disk); assertNull(result.entries.space); assertTrue(result.hitRatio.mem >= 0); assertTrue(result.hitRatio.mem <= 100); assertNull(result.hitRatio.disk); userSession.get("/config/server/version").consume(); r = adminSession.get("/config/server/caches/accounts"); assertEquals(HttpStatus.SC_OK, r.getStatusCode()); result = newGson().fromJson(r.getReader(), CacheInfo.class); assertEquals(2, result.entries.mem.longValue()); }
Source:
<code>public static Controller[] availableControllers() { try { @SuppressWarnings("unchecked") final Constructor<ControllerEnvironment> constructor = (Constructor<ControllerEnvironment>) Class.forName("net.java.games.input.DefaultControllerEnvironment").getDeclaredConstructors()[0]; constructor.setAccessible(true); return constructor.newInstance().getControllers(); } catch (final InvocationTargetException | ClassNotFoundException <START> | IllegalAccessException | InstantiationException e) { <END> Log.error("Unable to scan for joysticks"); return null; } }</code><technical_language>nitpick for multiline. single file list in cases need breakline java } catch (final InvocationTargetException | ClassNotFoundException | IllegalAccessException | InstantiationException e ) {</technical_language>

Target:
static Controller[] availableControllers() { try { @SuppressWarnings("unchecked") final Constructor<ControllerEnvironment> constructor = (Constructor<ControllerEnvironment>) Class.forName("net.java.games.input.DefaultControllerEnvironment").getDeclaredConstructors()[0]; constructor.setAccessible(true); return constructor.newInstance().getControllers(); } catch (final InvocationTargetException | ClassNotFoundException | IllegalAccessException | InstantiationException e ) { Log.error("Unable to scan for joysticks"); return new Controller[]{}; } }
Source:
<code>public void testFooPing() { <START> Logger logger = Logger.getLogger(JMXMethodExecutor.class.getName()); <END> Level originalLevel = logger.getLevel(); logger.setLevel(Level.OFF); new Weld().initialize(); logger.setLevel(originalLevel); }</code><technical_language>logging "client" side. need setup log level there, @BeforeClass @AfterClass? I move this code AbstractShutdownHookTest.deploy() method work</technical_language>

Target:
public void testFooPing() { new Weld().initialize(); }