auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean existsUser(String username) { try { for (String serviceName : securityManager.listUserGroupServices()) { if (securityManager.loadUserGroupService(serviceName).getUserByUsername(username) != null) { return true; } } for (String roleServiceName : securityManager.listRoleServices()) { if (securityManager.loadRoleService(roleServiceName).getRolesForUser(username) != null && !securityManager.loadRoleService(roleServiceName).getRolesForUser(username).isEmpty()) { return true; <START> } <END> } } catch (IOException e) { logger.log(Level.WARNING, e.getMessage(), e); } return false; }</code><technical_language>I split user roles retrieve condition check, I more clear avoid retrieving times information, this: SortedSet<GeoServerRole> userRoles = securityManager.loadRoleService(roleServiceName).getRolesForUser(username); if (userRoles != null && !userRoles.isEmpty()) { return true; }</technical_language>

Target:
public boolean existsUser(String username) { try { for (String serviceName : securityManager.listUserGroupServices()) { if (securityManager.loadUserGroupService(serviceName).getUserByUsername(username) != null) { return true; } } for (String roleServiceName : securityManager.listRoleServices()) { SortedSet<GeoServerRole> userRoles = securityManager.loadRoleService(roleServiceName).getRolesForUser(username); if (userRoles != null && !userRoles.isEmpty()) { return true; } } } catch (IOException e) { logger.log(Level.WARNING, e.getMessage(), e); } return false; }
Source:
<code>public void verifyVideoWidth(int widthDesired) { waitForElementByElement(withInputField); <START> int width = Integer.parseInt(withInputField.getAttribute("value")); <END> Assertion.assertNumber( widthDesired, width, "video width is " + width + " should be " + widthDesired); PageObjectLogging.log("verifyVideoWidth", "video width verified", true); }</code><technical_language>widthInputField</technical_language>

Target:
public void verifyVideoWidth(int widthDesired) { waitForElementByElement(widthInputField); int width = Integer.parseInt(widthInputField.getAttribute("value")); Assertion.assertEquals( widthDesired, width); PageObjectLogging.log("verifyVideoWidth", "video width verified", true); }
Source:
<code>protected void render() { FormRenderingContext context = dynamicFormModelGenerator.getContextForModel(fieldCopy); if (context != null) { FormEditorRenderingContext renderingContext = new FormEditorRenderingContext(helper.getPath()); renderingContext.setRootForm(context.getRootForm()); <START> renderingContext.getAvailableForms().putAll(context.getAvailableForms()); <END> renderingContext.setModel(fieldCopy); doRender(helper, renderingContext); } else { propertiesService.call(new RemoteCallback<FormEditorRenderingContext>() { @Override public void callback(FormEditorRenderingContext renderingContext) { renderingContext.setModel(fieldCopy); renderingContext.setParentContext(helper.getCurrentRenderingContext()); doRender(helper, renderingContext); } }).getFieldPropertiesRenderingContext(fieldCopy, helper.getPath()); } }</code><technical_language>In this class, is a lot of logic in GWT compiled class, move MVP pattern, some of logic testable</technical_language>

Target:
protected void render() { FormRenderingContext context = dynamicFormModelGenerator.getContextForModel(fieldCopy); if (context != null) { FormEditorRenderingContext renderingContext = new FormEditorRenderingContext(helper.getPath()); renderingContext.setRootForm(context.getRootForm()); renderingContext.getAvailableForms().putAll(context.getAvailableForms()); renderingContext.setModel(fieldCopy); doRender(helper, renderingContext); } }
Source:
<code>public static SimpleFeature toFeature(JSONObject json, SimpleFeatureBuilder builder) throws JSONException { String type = json.getString(GeoJSON.TYPE); if (!GeoJSON.FEATURE.equals(type)) { throw new IllegalArgumentException("type was not " + GeoJSON.FEATURE); } if (builder == null) { builder = getBuilder(json); } builder.reset(); JSONObject geometry = json.optJSONObject(GeoJSON.GEOMETRY); if (geometry != null) { <START> builder.set("geom", toGeometry(geometry)); <END> } JSONObject properties = json.optJSONObject(GeoJSON.PROPERTIES); if (properties != null) { @SuppressWarnings("unchecked") Iterator<String> keys = properties.keys(); while (keys.hasNext()) { String name = keys.next(); Object value = properties.get(name); builder.set(name, value); } } String id = json.optString(GeoJSON.ID); return builder.buildFeature(id); }</code><technical_language>Add "geom" a constant is repeated multiple times code. builder.getDefaultGeometry() instead of "geom" here</technical_language>

Target:
public static SimpleFeature toFeature(JSONObject json, SimpleFeatureBuilder builder) throws JSONException { String type = json.getString(GeoJSON.TYPE); if (!GeoJSON.FEATURE.equals(type)) { throw new IllegalArgumentException("type was not " + GeoJSON.FEATURE); } if (builder == null) { builder = getBuilder(json); } builder.reset(); JSONObject geometry = json.optJSONObject(GeoJSON.GEOMETRY); if (geometry != null) { builder.set(GEOM_ATTRIBUTE, toGeometry(geometry)); } JSONObject properties = json.optJSONObject(GeoJSON.PROPERTIES); if (properties != null) { @SuppressWarnings("unchecked") Iterator<String> keys = properties.keys(); while (keys.hasNext()) { String name = keys.next(); Object value = properties.get(name); builder.set(name, value); } } String id = json.optString(GeoJSON.ID); return builder.buildFeature(id); }
Source:
<code>public void testGetValueAt() { final DetailAST node = tree.getFirstChild() .getNextSibling() .getNextSibling() .getNextSibling(); final ParseTreeTablePModel parseTree = new ParseTreeTablePModel(null); final Object treeModel = parseTree.getValueAt(node, 0); final String type = (String) parseTree.getValueAt(node, 1); final int line = (int) parseTree.getValueAt(node, 2); final int column = (int) parseTree.getValueAt(node, 3); final String text = (String) parseTree.getValueAt(node, 4); Assert.assertEquals("IDENT", type); Assert.assertEquals(4, line); Assert.assertEquals(6, column); Assert.assertEquals("InputJavadocAttributesAndMethods", text); Assert.assertNull(treeModel); try { <START> parseTree.getValueAt(node, 231); <END> Assert.fail("IllegalStateException expected"); } catch (IllegalStateException ex) { Assert.assertEquals("Unknown column", ex.getMessage()); } }</code><technical_language>231? 230 232 issue</technical_language>

Target:
public void testGetValueAt() { final DetailAST node = tree.getFirstChild() .getNextSibling() .getNextSibling() .getNextSibling(); Assert.assertNotNull("Expected a non-null identifier node here", node); Assert.assertEquals("Expected identifier token", TokenTypes.IDENT, node.getType()); final ParseTreeTablePModel parseTree = new ParseTreeTablePModel(null); final Object treeModel = parseTree.getValueAt(node, 0); final String type = (String) parseTree.getValueAt(node, 1); final int line = (int) parseTree.getValueAt(node, 2); final int column = (int) parseTree.getValueAt(node, 3); final String text = (String) parseTree.getValueAt(node, 4); Assert.assertEquals("Node should be an Identifier", "IDENT", type); Assert.assertEquals("Class identifier should start on line 4", 4, line); Assert.assertEquals("Class name should start from column 6", 6, column); Assert.assertEquals("Wrong class name", "InputJavadocAttributesAndMethods", text); Assert.assertNull("Root node should have null value", treeModel); try { parseTree.getValueAt(node, parseTree.getColumnCount()); Assert.fail("IllegalStateException expected"); } catch (IllegalStateException ex) { Assert.assertEquals("Unknown column", ex.getMessage()); } }
Source:
<code>public long getMaxPutLatency() { <START> return maxPutLatencyNanos; <END> }</code><technical_language>converted MS too</technical_language>

Target:
public long getMaxPutLatency() { return convertNanosToMillis(maxPutLatencyNanos); }
Source:
<code>public void withRPlumber(String userAction, final Command command) { withDependencies( "Plumber", userAction, new Dependency[] { <START> Dependency.cranPackage("plumber", "0.4.5") <END> }, true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); }</code><technical_language>Do expect 0.4.5 CRAN soon? If embed this package daily users plumber integration (ping for details, straightforward!)</technical_language>

Target:
public void withRPlumber(String userAction, final Command command) { withDependencies( "Plumber", userAction, new Dependency[] { Dependency.embeddedPackage("plumber") }, true, new CommandWithArg<Boolean>() { @Override public void execute(Boolean succeeded) { if (succeeded) command.execute(); } } ); }
Source:
<code>private void writeHelperInvocation(JavaClassName helperClassName, String parameterName, Name methodName) { javaBuffer.addImport(InvocationTargetException.class); String helperMethodName = "get" + javaNames.getJavaClassStyleName(methodName) + "Signature"; javaBuffer.addLine("try {"); javaBuffer.addLine("return (Response)(" + helperClassName.getSimpleName() + "." + helperMethodName + "(" + parameterName + ").invoke(this, " + parameterName + "));"); javaBuffer.addLine("}"); javaBuffer.addLine("catch(InvocationTargetException e) {"); javaBuffer.addLine("throw <START> (RuntimeException)e.getTargetException();"); <END> javaBuffer.addLine("}"); javaBuffer.addLine("catch(IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException e) {"); javaBuffer.addLine("throw new IllegalStateException(\"Failed to find or invoke API method. The failure is in auto-generated code and indicates a bug in the JAX-RS intrafaces generation process\", e);"); javaBuffer.addLine("}"); }</code><technical_language>Is this needed? if exception throws target a RuntimeException</technical_language>

Target:
private void writeHelperInvocation(JavaClassName helperClassName, String parameterName, Name methodName) { javaBuffer.addImport(InvocationTargetException.class); String helperMethodName = "get" + javaNames.getJavaClassStyleName(methodName) + "Signature"; javaBuffer.addLine("try {"); javaBuffer.addLine("return (Response)(" + helperClassName.getSimpleName() + "." + helperMethodName + "(" + parameterName + ").invoke(this, " + parameterName + "));"); javaBuffer.addLine("}"); javaBuffer.addLine("catch(InvocationTargetException e) {"); javaBuffer.addLine("throw (RuntimeException)e.getTargetException();"); javaBuffer.addLine("}"); javaBuffer.addLine("catch(IllegalAccessException | NoSuchMethodException | SecurityException e) {"); javaBuffer.addLine("throw new IllegalStateException(\"Failed to find or invoke API method. The failure is in auto-generated code and indicates a bug in the JAX-RS intrafaces generation process\", e);"); javaBuffer.addLine("}"); }
Source:
<code>public NodeMetadata apply(final ServerWithExternalIp serverWithExternalIp) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); Server server = serverWithExternalIp.server(); builder.ids(server.id()); builder.name(server.name()); <START> builder.hostname(serverWithExternalIp.server().description()); <END> if (server.datacenterId() != null) { builder.location(find(locations.get(), idEquals(nullToEmpty(server.datacenterId())))); } builder.group(nodeNamingConvention.groupInUniqueNameOrNull(server.name())); BaseImage baseImage = getBaseImage(server.sourceImageId()); builder.hardware(baseImageToHardware.apply(baseImage)); Image image = baseImageToImage.apply(baseImage); if (image != null) { builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); } if (server.state() != null) { builder.status(serverStateToNodeStatus.get(server.state())); } String privateAddress = null; if (server.networkInfo() != null && server.networkInfo().primaryNic() != null && server.networkInfo().primaryNic().privateIpv4() != null) { privateAddress = server.networkInfo().primaryNic().privateIpv4(); builder.privateAddresses(ImmutableSet.of(privateAddress)); } if (privateAddress != null && serverWithExternalIp.externalIp() != null) { builder.publicAddresses(ImmutableSet.of(serverWithExternalIp.externalIp())); } Credentials credentials = credentialStore.get("node#" + server.id()); if (credentials instanceof LoginCredentials) { builder.credentials(LoginCredentials.class.cast(credentials)); } return builder.build(); }</code><technical_language>Is this hostname? put if not</technical_language>

Target:
public NodeMetadata apply(final ServerWithExternalIp serverWithExternalIp) { NodeMetadataBuilder builder = new NodeMetadataBuilder(); Server server = serverWithExternalIp.server(); builder.ids(server.id()); builder.name(server.name()); builder.location(find(locations.get(), idEquals(nullToEmpty(server.datacenterId())))); builder.group(nodeNamingConvention.groupInUniqueNameOrNull(server.name())); builder.hardware(serverToHardware.apply(serverWithExternalIp.server())); builder.imageId(server.sourceImageId()); builder.operatingSystem(operatingSystemToOperatingSystem.apply(server.guest().operatingSystem())); builder.status(serverStateToNodeStatus.get(server.state())); Set<String> privateAddresses = new HashSet<String>(); if (server.networkInfo() != null) { if (server.networkInfo().primaryNic() != null && server.networkInfo().primaryNic().privateIpv4() != null) { privateAddresses.add(server.networkInfo().primaryNic().privateIpv4()); } if (!server.networkInfo().additionalNic().isEmpty()) { privateAddresses.addAll(Sets.newHashSet( Iterables.transform(server.networkInfo().additionalNic(), new Function<NIC, String>() { @Override public String apply(NIC nic) { return nic.privateIpv4(); } }))); } } builder.privateAddresses(privateAddresses); if (serverWithExternalIp.externalIp() != null) { builder.publicAddresses(ImmutableSet.of(serverWithExternalIp.externalIp())); } return builder.build(); }
Source:
<code><START> public LeadershipToken blockOnBecomingLeader() throws InterruptedException { <END> try { return batcher.apply(null).get(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(e); } }</code><technical_language>Cool, this _only_ batches blockOnBecomingLeader() operations</technical_language>

Target:
public LeadershipToken blockOnBecomingLeader() throws InterruptedException { try { return batcher.apply(null).get(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(cause); } }
Source:
<code>public T newInstance(Object... params) throws InvocationTargetException, IllegalAccessException { try { return constructor.newInstance(params); <START> } catch (InstantiationException e) { <END> throw new RuntimeException(e); } }</code><technical_language>Throwables.throwingOnlyUnchecked</technical_language>

Target:
T newInstance(Object... params) { return throwingOnlyUnchecked(() -> constructor.newInstance(params)); }
Source:
<code>private boolean isVmMigrationValid(Cluster cluster, VM candidateVm) { boolean canMove = schedulingManager.canSchedule(cluster, candidateVm, <START> Collections.emptyList(), Collections.emptyList(), <END> new ArrayList<>()); if (canMove) { log.debug("VM is a viable candidate for solving affinity group violation situation.", candidateVm.getId()); return true; } log.debug("VM is NOT a viable candidate for solving affinity group violation situation.", candidateVm.getId()); return false; }</code><technical_language>add current host (but current one) blacklist</technical_language>

Target:
private boolean isVmMigrationValid(Cluster cluster, VM candidateVm) { List<Guid> vdsBlackList = candidateVm.getRunOnVds() == null ? Collections.emptyList() : Arrays.asList(candidateVm.getRunOnVds()); boolean canMove = schedulingManager.canSchedule(cluster, candidateVm, vdsBlackList, Collections.emptyList(), new ArrayList<>()); if (canMove) { log.debug("VM is a viable candidate for solving affinity group violation situation.", candidateVm.getId()); return true; } log.debug("VM is NOT a viable candidate for solving affinity group violation situation.", candidateVm.getId()); return false; }
Source:
<code>public void test_valid_region_variant() throws IOException, SAXException { <START> JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=hudson.logging.Messages&language=de_DE_cloudBees").getJSONObject(); <END> Assert.assertEquals("ok", response.getString("status")); JSONObject data = response.getJSONObject("data"); Assert.assertEquals("Initialisiere Log-Rekorder", data.getString("LogRecorderManager.init")); }</code><technical_language>Ideally a test verifying separators combinations. e.g. en_US|cloudBeers</technical_language>

Target:
public void test_valid_region_variant() throws IOException, SAXException { JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=jenkins.i18n.Messages&language=en_AU_variant").getJSONObject(); Assert.assertEquals("ok", response.getString("status")); JSONObject data = response.getJSONObject("data"); Assert.assertEquals("value_au_variant", data.getString("Key")); }
Source:
<code>public static boolean isWellFormedUrl(final String input) { <START> UrlValidator validator = new UrlValidator(); <END> return validator.isValid(input); }</code><technical_language>UrlValidator a static member of this class created once? need created time this method is called</technical_language>

Target:
public static boolean isWellFormedUrl(final String input) { return urlValidator.isValid(input); }
Source:
<code><START> private Authentication createAuthentication() { <END> val principal = createPrincipal(); val attributes = new HashMap<String, Object>(); attributes.put("attribute", "value"); val mock = mock(Authentication.class); when(mock.getAttributes()).thenReturn(attributes); when(mock.getPrincipal()).thenReturn(principal); return mock; }</code><technical_language>remove, similar functionality in CoreAuthenticationTestUtils</technical_language>

Target:
private Authentication createAuthentication() { val attributes = CoreAuthenticationTestUtils.getAttributes(); attributes.put("attribute", "value"); return CoreAuthenticationTestUtils.getAuthentication("principal", attributes); }
Source:
<code>public void testPushForMasterWithApprovals() throws GitAPIException, IOException, RestApiException { PushOneCommit.Result r = pushTo("refs/for/master/%l=Code-Review"); r.assertOkStatus(); ChangeInfo ci = get(r.getChangeId()); LabelInfo cr = ci.labels.get("Code-Review"); assertThat(cr.all).hasSize(1); assertThat(cr.all.get(0).name).isEqualTo("Administrator"); <START> assertThat(cr.all.get(0).value.intValue()).isEqualTo(1); <END> PushOneCommit push = pushFactory.create(db, admin.getIdent(), PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to(git, "refs/for/master/%l=Code-Review+2"); ci = get(r.getChangeId()); cr = ci.labels.get("Code-Review"); assertThat(cr.all).hasSize(1); assertThat(cr.all.get(0).name).isEqualTo("Administrator"); assertThat(cr.all.get(0).value.intValue()).isEqualTo(2); }</code><technical_language>write this assertThat(cr.all.get(0).value).is(1);</technical_language>

Target:
public void testPushForMasterWithApprovals() throws GitAPIException, IOException, RestApiException { PushOneCommit.Result r = pushTo("refs/for/master/%l=Code-Review"); r.assertOkStatus(); ChangeInfo ci = get(r.getChangeId()); LabelInfo cr = ci.labels.get("Code-Review"); assertThat(cr.all).hasSize(1); assertThat(cr.all.get(0).name).isEqualTo("Administrator"); assertThat(cr.all.get(0).value.intValue()).is(1); PushOneCommit push = pushFactory.create(db, admin.getIdent(), PushOneCommit.SUBJECT, "b.txt", "anotherContent", r.getChangeId()); r = push.to(git, "refs/for/master/%l=Code-Review+2"); ci = get(r.getChangeId()); cr = ci.labels.get("Code-Review"); assertThat(cr.all).hasSize(1); assertThat(cr.all.get(0).name).isEqualTo("Administrator"); assertThat(cr.all.get(0).value.intValue()).is(2); }
Source:
<code>private boolean isException(String value) { <START> return value.length() == 4 || Integer.parseInt(value) < 8; <END> }</code><technical_language>This line triggers a java.lang.NumberFormatException for code: $a = 012_345;</technical_language>

Target:
private static boolean isException(String value) { return value.length() == 4 || Integer.parseInt(value) < 8; }
Source:
<code>public RunRuleActionHandler(final Action module, final RuleRegistry ruleRegistry) { super(module); final Configuration config = module.getConfiguration(); if (config == null) { throw new IllegalArgumentException("'Configuration' can not be null."); } <START> ruleUIDs = (List<String>) config.get(RULE_UIDS_KEY); <END> if (ruleUIDs == null) { throw new IllegalArgumentException("'ruleUIDs' property can not be null."); } if (config.get(CONSIDER_CONDITIONS_KEY) != null && config.get(CONSIDER_CONDITIONS_KEY) instanceof Boolean) { this.considerConditions = ((Boolean) config.get(CONSIDER_CONDITIONS_KEY)).booleanValue(); } this.ruleRegistry = ruleRegistry; }</code><technical_language>Tabs? formatter is working</technical_language>

Target:
public RunRuleActionHandler(final Action module, final RuleRegistry ruleRegistry) { super(module); final Configuration config = module.getConfiguration(); if (config == null) { throw new IllegalArgumentException("'Configuration' can not be null."); } ruleUIDs = (List<String>) config.get(RULE_UIDS_KEY); if (ruleUIDs == null) { throw new IllegalArgumentException("'ruleUIDs' property must not be null."); } if (config.get(CONSIDER_CONDITIONS_KEY) != null && config.get(CONSIDER_CONDITIONS_KEY) instanceof Boolean) { this.considerConditions = ((Boolean) config.get(CONSIDER_CONDITIONS_KEY)).booleanValue(); } this.ruleRegistry = ruleRegistry; }
Source:
<code>private void setupViews() { backgroundJobStartStop = findViewById(R.id.backgroundJobStartStop); backgroundJobStartStop.setOnClickListener(new View.OnClickListener() { @Override <START> public void onClick(View v) { <END> if (!backgroundTask.isStarted()) { backgroundTask.start(); } else { backgroundTask.stop(); } updateJobButton(); } }); }</code><technical_language>support Java 8 in examples, feel free lamdas</technical_language>

Target:
private void setupViews() { backgroundJobStartStop = findViewById(R.id.backgroundJobStartStop); backgroundJobStartStop.setOnClickListener(v -> { if (!backgroundTask.isStarted()) { backgroundTask.start(); } else { backgroundTask.stop(); } updateJobButton(); }); }
Source:
<code>public void close() { RuntimeException ex = null; try { factsDb.close(); } catch (Exception e) { <START> if (ex == null) { <END> ex = Throwables.propagate(e); } else { ex.addSuppressed(e); } } indexAndOffsets.clear(); aggBuffers.clear(); try { FileUtils.deleteDirectory(tmpDirLocation); } catch(IOException ioe) { if (ex == null) { ex = Throwables.propagate(ioe); } else { ex.addSuppressed(ioe); } } if (selectors != null) { selectors.clear(); } super.close(); if (ex != null) { throw ex; } }</code><technical_language>ex null</technical_language>

Target:
public void close() { RuntimeException ex = null; try { factsDb.close(); } catch (Exception e) { ex = Throwables.propagate(e); } indexAndOffsets.clear(); aggBuffers.clear(); try { FileUtils.deleteDirectory(tmpDirLocation); } catch(IOException ioe) { if (ex == null) { ex = Throwables.propagate(ioe); } else { ex.addSuppressed(ioe); } } if (selectors != null) { selectors.clear(); } super.close(); if (ex != null) { throw ex; } }
Source:
<code>public Optional<List<LockWatchEvent>> getFromVersion(long version) { <START> return getFromTo(version, nextSequence - 1); <END> }</code><technical_language>nit: call lastVersion() here</technical_language>

Target:
public Optional<List<LockWatchEvent>> getFromVersion(long version) { return getFromTo(version, lastVersion()); }
Source:
<code>public void close() { List<ViolationMessage> outputList = new ArrayList<>(this.msgBuffer.values().stream() .filter(msg -> !ignoredLineNumbers.contains(msg.getLineNumber())).collect(Collectors.toList())); Collections.sort(outputList); if (outputList.size() > 0) { String header = getHeader(inputFile, colorOutput, invertColorOutput); <START> if (colorOutput) { <END> AnsiConsole.out.println(Ansi.ansi().render(header)); } else { System.out.println(header); } } if (colorOutput) { for (ViolationMessage output : outputList) { output.setColorOutput(colorOutput); if (invertColorOutput) { output.invertColorOutput(); } output.setLineNumberWidth(String.valueOf(highestLineNumber).length()); output.setColumnNumberWidth(String.valueOf(highestColumnNumber).length()); AnsiConsole.out.println(Ansi.ansi().render(output.toString())); } } else { outputList.forEach(System.out::println); } this.msgBuffer.clear(); }</code><technical_language>This is a recurring pattern, a good time refactor this if statement a method</technical_language>

Target:
public void close() { List<ViolationMessage> outputList = new ArrayList<>(this.msgBuffer.values().stream() .filter(msg -> !ignoredLineNumbers.contains(msg.getLineNumber())).collect(Collectors.toList())); Collections.sort(outputList); if (outputList.size() > 0) { printColoredMessage(getHeader(inputFile, colorSettings)); } if (colorSettings.colorOutput) { for (ViolationMessage output : outputList) { output.setColorSettings(colorSettings); output.setLineNumberWidth(String.valueOf(highestLineNumber).length()); output.setColumnNumberWidth(String.valueOf(highestColumnNumber).length()); AnsiConsole.out.println(Ansi.ansi().render(output.toString())); } } else { outputList.forEach(System.out::println); } this.msgBuffer.clear(); }
Source:
<code>ConstructDate assign( Field field, AnyValue value ) { switch ( field ) { case year: year = assignment( field, year, value ); return this; case quarter: case dayOfQuarter: return new QuarterDate( year, date ).assign( field, value ); case month: case day: return new CalendarDate( year, date ).assign( field, value ); case week: case dayOfWeek: return new WeekDate( year, date ).assign( field, value ); case ordinalDay: return new OrdinalDate( year, date ).assign( field, value ); case date: case datetime: date = assignment( field, date, value ); return this; default: <START> throw new UnsupportedTemporalUnitException( "Not a date field: " + field ); <END> } }</code><technical_language>concern above</technical_language>

Target:
ConstructDate assign( Field field, AnyValue value ) { switch ( field ) { case year: year = assignment( field, year, value ); return this; case quarter: case dayOfQuarter: return new QuarterDate( year, date ).assign( field, value ); case month: case day: return new CalendarDate( year, date ).assign( field, value ); case week: case dayOfWeek: return new WeekDate( year, date ).assign( field, value ); case ordinalDay: return new OrdinalDate( year, date ).assign( field, value ); case date: case datetime: date = assignment( field, date, value ); return this; default: throw new IllegalStateException( "Not a date field: " + field ); } }
Source:
<code>public void setGlusterNetwork(ClusterNetworkModel model, boolean value) { if (!isMultiCluster()) { if (value) { if (getGlusterNetwork() != null) { getGlusterNetwork().setGlusterNetwork(false); } glusterNetwork = model; } else { <START> getManagementNetwork().setGlusterNetwork(true); <END> } } model.setGlusterNetwork(value); }</code><technical_language>update glusterNetwork member well</technical_language>

Target:
public void setGlusterNetwork(ClusterNetworkModel model, boolean value) { if (!isMultiCluster()) { if (value) { if (getGlusterNetwork() != null) { getGlusterNetwork().setGlusterNetwork(false); } glusterNetwork = model; } } model.setGlusterNetwork(value); }
Source:
<code><START> public <END> void setSellOrders(HashMap<String, ArrayList<Order>> sellOrders) { this.sellOrders = sellOrders; }</code><technical_language>this method changed private</technical_language>

Target:
private void setSellOrders(HashMap<String, ArrayList<Order>> sellOrders) { this.sellOrders = sellOrders; }
Source:
<code>public static IThenable.ThenOnFulfilledCallbackFn<List<String>, Object> getListObjectThenOnFulfilledCallbackFn(List<String> simpleDataTypes, ListBoxValues dataTypeListBoxValues) { return serverDataTypes -> { List<String> mergedList = new ArrayList<>(simpleDataTypes); <START> for (String type : serverDataTypes) { <END> String displayType = createDataTypeDisplayName(type); getMapDataTypeNamesToDisplayNames().put( displayType, type ); mergedList.add(displayType); } dataTypeListBoxValues.addValues(mergedList); return null; }; }</code><technical_language>here, Streams result more readable</technical_language>

Target:
static IThenable.ThenOnFulfilledCallbackFn<List<String>, Object> getListObjectThenOnFulfilledCallbackFn(List<String> simpleDataTypes, ListBoxValues dataTypeListBoxValues) { return serverDataTypes -> { List<String> mergedList = new ArrayList<>(simpleDataTypes); for (String type : serverDataTypes) { String displayType = createDataTypeDisplayName(type); getMapDataTypeNamesToDisplayNames().put( displayType, type ); mergedList.add(displayType); } dataTypeListBoxValues.addValues(mergedList); return null; }; }
Source:
<code><START> public Boolean isPartial() <END> { return isPartial; }</code><technical_language>return a boolean primitive (lowercase b) a boolean object (uppercase B)</technical_language>

Target:
public boolean isPartial() { return isPartial; }
Source:
<code>public CloudProvisioningRequest(Label label, int workloadToProvision, <START> Collection<? extends Actionable> queue) { <END> this.label = label; this.workloadToProvision = workloadToProvision; this.queue = new ArrayList<Actionable>(queue); }</code><technical_language>package-private I think, expected caller is NodeProvisioner, point of factoring out a request class is able add more parameters later</technical_language>

Target:
CloudProvisioningRequest(Label label, int workloadToProvision, Collection<? extends Actionable> queue) { this.label = label; this.workloadToProvision = workloadToProvision; this.queue = new ArrayList<Actionable>(queue); }
Source:
<code>public static ObjectMapper withDefaultModules(ObjectMapper mapper) { return mapper .registerModule(new GuavaModule()) <START> .registerModule(new Jdk8Module().configureAbsentsAsNulls(true)) <END> .registerModule(new AfterburnerModule()) .registerModule(new JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .disable(DeserializationFeature.WRAP_EXCEPTIONS) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES); }</code><technical_language>for this code, arguments: 1. This code remoting Jackson version independent. some internal projects run 2.9. leaving in is nice version independence. 2. OTOH Jackson 2.7+ now, want remoting leverage that</technical_language>

Target:
public static ObjectMapper withDefaultModules(ObjectMapper mapper) { return mapper .registerModule(new GuavaModule()) .registerModule(new ShimJdk7Module()) .registerModule(new Jdk8Module().configureAbsentsAsNulls(true)) .registerModule(new AfterburnerModule()) .registerModule(new JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .disable(DeserializationFeature.WRAP_EXCEPTIONS) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES); }
Source:
<code>public void testRefAltAssignmentInRenormalization() { Variant variant = new Variant("1", 1, 1, "", "T"); variant.renormalize(1, 2, "A", "AT"); assertEquals("A", variant.getReference()); assertEquals("AT", variant.getAlternate()); <START> variant = new Variant("1", 1, 1, "T", ""); <END> variant.renormalize(1, 2, "AT", "A"); assertEquals("AT", variant.getReference()); assertEquals("A", variant.getAlternate()); }</code><technical_language>I is enough for test assign check once</technical_language>

Target:
public void testRefAltAssignmentInRenormalization() { Variant variant = new Variant("1", 1, 1, "", "T"); variant.renormalize(1, 2, "A", "AT"); assertEquals("A", variant.getReference()); assertEquals("AT", variant.getAlternate()); }
Source:
<code>public ServerSocket socket() throws IOException { final String port = this.map.get("port"); if (port == null) { throw new IllegalArgumentException("--port must be specified"); } final ServerSocket socket; if (port.matches("\\d+")) { socket = new ServerSocket(Integer.parseInt(port)); } else { final File file = new File(port); if (file.exists()) { final Reader reader = new InputStreamReader( new FileInputStream(file), StandardCharsets.UTF_8 ); try { final char[] chars = new char[8]; if (reader.read(chars) < 0) { throw new HttpException( <START> HttpURLConnection.HTTP_BAD_REQUEST, <END> "The end of the stream has been reached" ); } socket = new ServerSocket( Integer.parseInt(new String(chars)) ); } finally { reader.close(); } } else { socket = new ServerSocket(0); final Writer writer = new OutputStreamWriter( new FileOutputStream(file), StandardCharsets.UTF_8 ); try { writer.append(Integer.toString(socket.getLocalPort())); } finally { writer.close(); } } } return socket; }</code><technical_language>@sebing IOException</technical_language>

Target:
public ServerSocket socket() throws IOException { final String port = this.map.get("port"); if (port == null) { throw new IllegalArgumentException("--port must be specified"); } final ServerSocket socket; if (port.matches("\\d+")) { socket = new ServerSocket(Integer.parseInt(port)); } else { final File file = new File(port); if (file.exists()) { final Reader reader = new InputStreamReader( new FileInputStream(file) ); try { final char[] chars = new char[8]; reader.read(chars); socket = new ServerSocket( Integer.parseInt(new String(chars)) ); } finally { reader.close(); } } else { socket = new ServerSocket(0); final Writer writer = new OutputStreamWriter( new FileOutputStream(file) ); try { writer.append(Integer.toString(socket.getLocalPort())); } finally { writer.close(); } } } return socket; }
Source:
<code>public void setResourcesDir(File newResourcesDir) { <START> this.resourcesDir <END> = newResourcesDir; }</code><technical_language>purpose of naming "new..." is avoid "this...", remove it</technical_language>

Target:
public void setResourcesDir(File newResourcesDir) { resourcesDir = newResourcesDir; }
Source:
<code>public static Calendar ChangeTimezone(Calendar instant, String timezone) { <START> if (Arrays.asList(TimeZone.getAvailableIDs()).contains(timezone)) <END> return instant.setTimeZone(TimeZone.getTimeZone(timezone)); else throw new YailRuntimeError("Your given timezone is not a valid timezone."); }</code><technical_language>wondering if sense cache this time this method is called constructed time calls ChangeTimezone</technical_language>

Target:
public static Calendar ChangeTimezone(Calendar instant, String timezone) { if (timezone == null) throw new YailRuntimeError("No timezones available.", "Runtime Error"); if (timezones.contains(timezone)) { instant.setTimeZone(TimeZone.getTimeZone(timezone)); } else { for (String tz : timezones) { if (tz.equalsIgnoreCase(timezone)) return ChangeTimezone(instant, tz); } throw new YailRuntimeError("Your given timezone is not a valid timezone.", "Sorry to be so picky"); } return instant; }
Source:
<code>void sendMailToWithNotificationAndPersonsAndAdministrator() { when(mailProperties.getAdministrator()).thenReturn("admin@firma.test"); setupMockServletRequest(); final Person hans = new Person(); hans.setEmail("hans@firma.test"); when(personService.getPersonsWithNotificationType(NOTIFICATION_USER)).thenReturn(List.of(hans)); final Person franz = new Person(); franz.setEmail("franz@firma.test"); final String subjectMessageKey = "subject.overtime.created"; final String templateName = "overtime_office"; final Mail mail = Mail.builder() <START> .withRecipient(true) <END> .withRecipient(List.of(franz), true) .withRecipient(NOTIFICATION_USER) .withSubject(subjectMessageKey) .withTemplate(templateName, new HashMap<>()) .build(); sut.send(mail); verify(mailSenderService).sendEmail(eq("no-reply@firma.test"), eq(singletonList("hans@firma.test")), eq("subject"), eq("emailBody")); verify(mailSenderService).sendEmail(eq("no-reply@firma.test"), eq(singletonList("franz@firma.test")), eq("subject"), eq("emailBody")); verify(mailSenderService).sendEmail(eq("no-reply@firma.test"), eq(singletonList("admin@firma.test")), eq("subject"), eq("emailBody")); }</code><technical_language>IntelliJ's tooltips hard recognize true means here. rename method withTechnicalRecipient() (without Parameter). I miss some advantage of overloading here</technical_language>

Target:
void sendMailToWithNotificationAndPersonsAndAdministrator() { when(mailProperties.getAdministrator()).thenReturn("admin@firma.test"); setupMockServletRequest(); final Person hans = new Person(); hans.setEmail("hans@firma.test"); when(personService.getPersonsWithNotificationType(NOTIFICATION_USER)).thenReturn(List.of(hans)); final Person franz = new Person(); franz.setEmail("franz@firma.test"); final String subjectMessageKey = "subject.overtime.created"; final String templateName = "overtime_office"; final Mail mail = Mail.builder() .withTechnicalRecipient(true) .withRecipient(List.of(franz)) .withRecipient(NOTIFICATION_USER) .withSubject(subjectMessageKey) .withTemplate(templateName, new HashMap<>()) .build(); sut.send(mail); verify(mailSenderService).sendEmail(eq("no-reply@firma.test"), eq(singletonList("hans@firma.test")), eq("subject"), eq("emailBody")); verify(mailSenderService).sendEmail(eq("no-reply@firma.test"), eq(singletonList("franz@firma.test")), eq("subject"), eq("emailBody")); verify(mailSenderService).sendEmail(eq("no-reply@firma.test"), eq(singletonList("admin@firma.test")), eq("subject"), eq("emailBody")); }
Source:
<code>String getCulpritsOfEmailList(AbstractProject upstreamProject, AbstractBuild<?, ?> currentBuild, TaskListener listener) throws AddressException, UnsupportedEncodingException { AbstractBuild<?,?> upstreamBuild = currentBuild.getUpstreamRelationshipBuild(upstreamProject); AbstractBuild<?,?> previousBuild = currentBuild.getPreviousBuild(); AbstractBuild<?,?> previousBuildUpstreamBuild = previousBuild!=null ? previousBuild.getUpstreamRelationshipBuild(upstreamProject) : null; if(previousBuild==null && upstreamBuild==null) { listener.getLogger().println("Unable to compute the changesets in "+ upstreamProject +". Is the fingerprint configured?"); return null; } if(previousBuild==null || upstreamBuild==null || previousBuildUpstreamBuild==null) { listener.getLogger().println("Unable to compute the changesets in "+ upstreamProject); return null; } AbstractBuild<?,?> b=previousBuildUpstreamBuild; StringBuilder culpritEmails = new StringBuilder(); do { b = b.getNextBuild(); <START> if (b != null) { <END> String userEmails = getUserEmailList(listener, b.getCulprits()); if (culpritEmails.length() > 0) { culpritEmails.append(","); } culpritEmails.append(userEmails); } } while ( b != upstreamBuild && b != null ); return culpritEmails.toString(); }</code><technical_language>Is this check needed</technical_language>

Target:
String getCulpritsOfEmailList(AbstractProject upstreamProject, AbstractBuild<?, ?> currentBuild, TaskListener listener) throws AddressException, UnsupportedEncodingException { AbstractBuild<?,?> upstreamBuild = currentBuild.getUpstreamRelationshipBuild(upstreamProject); AbstractBuild<?,?> previousBuild = currentBuild.getPreviousBuild(); AbstractBuild<?,?> previousBuildUpstreamBuild = previousBuild!=null ? previousBuild.getUpstreamRelationshipBuild(upstreamProject) : null; if(previousBuild==null && upstreamBuild==null && previousBuildUpstreamBuild==null) { listener.getLogger().println("Unable to compute the changesets in "+ upstreamProject +". Is the fingerprint configured?"); return null; } if(previousBuild==null || upstreamBuild==null || previousBuildUpstreamBuild==null) { listener.getLogger().println("Unable to compute the changesets in "+ upstreamProject); return null; } AbstractBuild<?,?> b=previousBuildUpstreamBuild; StringBuilder culpritEmails = new StringBuilder(); do { b = b.getNextBuild(); if (b != null) { String userEmails = getUserEmailList(listener, b.getCulprits()); if (culpritEmails.length() > 0) { culpritEmails.append(","); } culpritEmails.append(userEmails); } } while ( b != upstreamBuild && b != null ); return culpritEmails.toString(); }
Source:
<code>protected Iterable<List<Object>> computeNext() { while (client.isRunning()) { checkInterruption(); QueryStatusInfo results = client.currentStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); Iterable<List<Object>> data = client.currentData().getData(); try { client.advance(); } catch (RuntimeException e) { checkInterruption(); <START> throw e; <END> } if (data != null) { return data; } } verify(client.isFinished()); QueryStatusInfo results = client.finalStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); if (results.getError() != null) { throw new RuntimeException(resultsException(results)); } return endOfData(); }</code><technical_language>e lost if checkInterruption throws. This interruption exception, potentially interesting. Add suppressed</technical_language>

Target:
protected Iterable<List<Object>> computeNext() { while (client.isRunning()) { checkInterruption(null); QueryStatusInfo results = client.currentStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); Iterable<List<Object>> data = client.currentData().getData(); try { client.advance(); } catch (RuntimeException e) { checkInterruption(e); throw e; } if (data != null) { return data; } } verify(client.isFinished()); QueryStatusInfo results = client.finalStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); if (results.getError() != null) { throw new RuntimeException(resultsException(results)); } return endOfData(); }
Source:
<code>public List<Variable> getEnv() { List<Variable> variables = new ArrayList<>(); Set<String> keys = new HashSet<>(); variables.add( Variable .newBuilder() <START> .setName("INHERIT_ENV_VARS") <END> .setValue(Joiner.on(" ").join(inheritVariables)) .build() ); taskInfo .getExecutor() .getCommand() .getEnvironment() .getVariablesList() .forEach( v -> { if (!keys.contains(v.getName())) { variables.add(v); keys.add(v.getName()); } } ); return variables; }</code><technical_language>If loop these, need another variable. this end setting extra variable unused. add list instead another getter loop in template functions avoid duplication/unused vars</technical_language>

Target:
public List<Variable> getEnv() { List<Variable> variables = new ArrayList<>(); Set<String> keys = new HashSet<>(); taskInfo .getExecutor() .getCommand() .getEnvironment() .getVariablesList() .forEach( v -> { if (!keys.contains(v.getName())) { variables.add(v); keys.add(v.getName()); } } ); return variables; }
Source:
<code>public OperatorFactory createRemoteSource(Session session, int operatorId, PlanNodeId planNodeId, List<Type> types) { Iterator<Page> pagesIterator = null; if (rowInputs.containsKey(planNodeId)) { Iterator<PrestoSparkRow> rowsIterator = rowInputs.get(planNodeId); pagesIterator = transformRowsToPages(rowsIterator, types); } if (pageInputs.containsKey(planNodeId)) { <START> Iterator<Page> iterator = transform(transform(pageInputs.get(planNodeId), PrestoSparkUtils::toSerializedPage), pagesSerde::deserialize); <END> if (pagesIterator == null) { pagesIterator = iterator; } else { pagesIterator = concat(pagesIterator, iterator); } } checkState(pagesIterator != null, "input is missing for plan node: %s", planNodeId); return new SparkRemoteSourceOperatorFactory( operatorId, planNodeId, pagesIterator); }</code><technical_language>nit: avoid nested transform is inline operation lambda: java Iterator<Page> iterator = transform( pageInputs.get(planNodeId), prestoSparkSerializedPage -> pagesSerde.deserialize(toSerializedPage(prestoSparkSerializedPage)) ); I want nested transform, I strong opinion :)</technical_language>

Target:
public OperatorFactory createRemoteSource(Session session, int operatorId, PlanNodeId planNodeId, List<Type> types) { Iterator<PrestoSparkRow> shuffleInput = shuffleInputs.get(planNodeId); Iterator<PrestoSparkSerializedPage> broadcastInput = broadcastInputs.get(planNodeId); checkArgument(shuffleInput != null || broadcastInput != null, "input not found for plan node with id %s", planNodeId); checkArgument(shuffleInput == null || broadcastInput == null, "single remote source cannot accept both, broadcast and shuffle inputs"); if (broadcastInput != null) { return new SparkRemoteSourceOperatorFactory( operatorId, planNodeId, transform(broadcastInput, sparkSerializedPage -> pagesSerde.deserialize(toSerializedPage(sparkSerializedPage)))); } return new SparkRemoteSourceOperatorFactory( operatorId, planNodeId, transformRowsToPages(shuffleInput, types)); }
Source:
<code>public void remove() { <START> throw new UnsupportedOperationException("Not implemented yet"); <END> }</code><technical_language>Instead of "Not implemented yet", I suggest "Iterator is read-only"</technical_language>

Target:
public void remove() { throw new UnsupportedOperationException("Iterator is read-only"); }
Source:
<code>private void gcDeletedSnapshot(String name) { final Snapshot.Root deleted; <START> namesystem.readLock(); <END> try { deleted = namesystem.getSnapshotManager().chooseDeletedSnapshot(); } finally { namesystem.readUnlock(); } if (deleted == null) { LOG.trace("{}: no snapshots are marked as deleted.", name); return; } final String snapshotRoot = deleted.getRootFullPathName(); final String snapshotName = deleted.getLocalName(); LOG.info("{}: delete snapshot from {}", name, snapshotName, snapshotRoot); try { namesystem.gcDeletedSnapshot(snapshotRoot, snapshotName); } catch (Throwable e) { LOG.warn("Failed to gcDeletedSnapshot " + deleted.getFullPathName(), e); } }</code><technical_language>Lets add assert this is snapshot in snapshottable dir</technical_language>

Target:
private void gcDeletedSnapshot(String name) { final Snapshot.Root deleted; namesystem.readLock(); try { deleted = namesystem.getSnapshotManager().chooseDeletedSnapshot(); } catch (Throwable e) { LOG.error("Failed to chooseDeletedSnapshot", e); throw e; } finally { namesystem.readUnlock(); } if (deleted == null) { LOG.trace("{}: no snapshots are marked as deleted.", name); return; } final String snapshotRoot = deleted.getRootFullPathName(); final String snapshotName = deleted.getLocalName(); LOG.info("{}: delete snapshot from {}", name, snapshotName, snapshotRoot); try { namesystem.gcDeletedSnapshot(snapshotRoot, snapshotName); } catch (Throwable e) { LOG.error("Failed to gcDeletedSnapshot " + deleted.getFullPathName(), e); } }