auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String updateQuantity(HttpServletRequest request, HttpServletResponse response, Model model, OrderItemRequestDTO itemRequest) throws IOException, UpdateCartException, PricingException, RemoveFromCartException { Order cart = CartState.getCart(); cart = orderService.updateItemQuantity(cart.getId(), itemRequest, true); cart = orderService.save(cart, false); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<>(); <START> extraData.put("productId", itemRequest.getProductId()); <END> extraData.put("cartItemCount", cart.getItemCount()); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return getCartView(); } else { return getCartPageRedirect(); } }</code><technical_language>This is right, set skuId based itemRequest anyway</technical_language>

Target:
public String updateQuantity(HttpServletRequest request, HttpServletResponse response, Model model, OrderItemRequestDTO itemRequest) throws IOException, UpdateCartException, PricingException, RemoveFromCartException { Order cart = CartState.getCart(); cart = orderService.updateItemQuantity(cart.getId(), itemRequest, true); cart = orderService.save(cart, false); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<>(); extraData.put("skuId", itemRequest.getSkuId()); extraData.put("productId", itemRequest.getProductId()); extraData.put("cartItemCount", cart.getItemCount()); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return getCartView(); } else { return getCartPageRedirect(); } }
Source:
<code>public void createIndexOverOneField() { String indexName = im.ensureIndexed(Arrays.<Object>asList("name"), "basic"); assertThat(indexName, is(notNullValue())); <START> assertThat(indexName, is("basic")); <END> Map<String, Object> indexes = im.listIndexes(); assertThat(indexes, hasKey("basic")); @SuppressWarnings("unchecked") Map<String, Object> index = (Map<String, Object>) indexes.get("basic"); @SuppressWarnings("unchecked") List<String> fields = (List<String>) index.get("fields"); assertThat(fields, containsInAnyOrder("_id", "_rev", "name")); }</code><technical_language>I need here</technical_language>

Target:
public void createIndexOverOneField() { String indexName = im.ensureIndexed(Arrays.<Object>asList("name"), "basic"); assertThat(indexName, is("basic")); Map<String, Object> indexes = im.listIndexes(); assertThat(indexes, hasKey("basic")); @SuppressWarnings("unchecked") Map<String, Object> index = (Map<String, Object>) indexes.get("basic"); @SuppressWarnings("unchecked") List<String> fields = (List<String>) index.get("fields"); assertThat(fields, containsInAnyOrder("_id", "_rev", "name")); }
Source:
<code>public void deleteCourseGroup(CourseGroup course) { try { <START> solrServer.deleteById(new Integer(course.getMuid()).toString()); <END> } catch (SolrServerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>declared string in schema need convert int</technical_language>

Target:
public void deleteCourseGroup(CourseGroup course) { try { solrServer.deleteById(new Integer(course.getMuid()).toString()); } catch (SolrServerException e) { log.error(e.getLocalizedMessage() + " whilst processing course [" + course.getCourseId() + ":" + course.getTitle() +"]", e); } catch (IOException e) { log.error(e.getLocalizedMessage() + " whilst processing course [" + course.getCourseId() + ":" + course.getTitle() +"]", e); } }
Source:
<code>public void service(org.zkoss.zk.au.AuRequest request, boolean everError) { final String cmd = request.getCommand(); if (cmd.equals(Events.ON_CHECK)) { CheckEvent evt = CheckEvent.getCheckEvent(request); if ("tristate".equals(getMold())) { Boolean state = evt.getState(); if (state == null) { _indeterminate = true; _checked = false; } else if (state) { _indeterminate = false; _checked = true; } else { _indeterminate = false; _checked = false; <START> } <END> } else { _checked = evt.isChecked(); _indeterminate = false; } Events.postEvent(evt); } else super.service(request, everError); }</code><technical_language>_indeterminate = state == null; _checked = state != null && state;</technical_language>

Target:
public void service(org.zkoss.zk.au.AuRequest request, boolean everError) { final String cmd = request.getCommand(); if (cmd.equals(Events.ON_CHECK)) { CheckEvent evt = CheckEvent.getCheckEvent(request); if ("tristate".equals(getMold())) { Boolean state = evt.getState(); _checked = (state != null) && state; _indeterminate = state == null; } else { _checked = evt.isChecked(); _indeterminate = false; } Events.postEvent(evt); } else super.service(request, everError); }
Source:
<code><START> public static HashMap<String, String> createJMSListeningParameterMap(String destinationName, String <END> connectionFactory, String destinationType, String jmsMode) { HashMap<String, String> jmsDestinationListeningParameters = new HashMap<>(); jmsDestinationListeningParameters.put(JMSConstants.DESTINATION_PARAM_NAME, destinationName); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_JNDI_PARAM_NAME, connectionFactory); jmsDestinationListeningParameters .put(JMSConstants.NAMING_FACTORY_INITIAL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_FACTORY_INITIAL); jmsDestinationListeningParameters.put(JMSConstants.PROVIDER_URL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_PROVIDER_URL); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_TYPE_PARAM_NAME, destinationType); jmsDestinationListeningParameters.put(JMSConstants.SESSION_ACK_MODE_PARAM_NAME, jmsMode); return jmsDestinationListeningParameters; }</code><technical_language>Return type a Map instead of a HashMap practice in API method signature</technical_language>

Target:
public static Map<String, String> createJMSListeningParameterMap(String destinationName, String connectionFactory, String destinationType, String jmsMode) { HashMap<String, String> jmsDestinationListeningParameters = new HashMap<>(); jmsDestinationListeningParameters.put(JMSConstants.DESTINATION_PARAM_NAME, destinationName); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_JNDI_PARAM_NAME, connectionFactory); jmsDestinationListeningParameters .put(JMSConstants.NAMING_FACTORY_INITIAL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_FACTORY_INITIAL); jmsDestinationListeningParameters.put(JMSConstants.PROVIDER_URL_PARAM_NAME, JMSTestConstants.ACTIVEMQ_PROVIDER_URL); jmsDestinationListeningParameters .put(JMSConstants.CONNECTION_FACTORY_TYPE_PARAM_NAME, destinationType); jmsDestinationListeningParameters.put(JMSConstants.SESSION_ACK_MODE_PARAM_NAME, jmsMode); return jmsDestinationListeningParameters; }
Source:
<code>public void post(final String text) throws IOException { this.origin.post(text); for (final Friend friend : this.bout.friends().iterate()) { <START> if (friend.email().isEmpty() || this.self == friend.alias()) { <END> continue; } this.email(friend, text); } }</code><technical_language>@ndbroadbent .equals here</technical_language>

Target:
public void post(final String text) throws IOException { this.origin.post(text); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || this.self.equals(friend.alias())) { continue; } this.email(friend, text); } }
Source:
<code>protected void refresh(InterpreterContext context) { context.out().clear(); try { context.out.write("%table("); context.out.write("type=ts,threshold=" + tsWindowThreshold); context.out.write(",columns="); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldNames()[i]; context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write(":"); } } context.out.write(")\n"); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldNames()[i]; context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write("\t"); } } context.out.write("\n"); materializedTable.sort((r1, r2) -> { String f1 = r1.getField(0).toString(); String f2 = r2.getField(0).toString(); return f1.compareTo(f2); }); <START> <END> if (materializedTable.size() != 0) { long maxTimestamp = ((java.sql.Timestamp) materializedTable.get(materializedTable.size() - 1) .getField(0)).getTime(); materializedTable = materializedTable.stream() .filter(row -> ((java.sql.Timestamp) row.getField(0)).getTime() > maxTimestamp - tsWindowThreshold) .collect(Collectors.toList()); LOGGER.debug("*****************Row size: " + materializedTable.size()); for (Row row : materializedTable) { for (int i = 0; i < row.getArity(); ++i) { Object field = row.getField(i); context.out.write(field.toString()); if (i != (row.getArity() - 1)) { context.out.write("\t"); } } LOGGER.debug("Row:" + row); context.out.write("\n"); } } context.out.flush(); } catch (IOException e) { e.printStackTrace(); LOGGER.error("Fail to refresh data", e); } }</code><technical_language>remove</technical_language>

Target:
protected void refresh(InterpreterContext context) { context.out().clear(); try { context.out.write("%table\n"); for (int i = 0; i < schema.getFieldCount(); ++i) { String field = schema.getFieldNames()[i]; context.out.write(field); if (i != (schema.getFieldCount() - 1)) { context.out.write("\t"); } } context.out.write("\n"); materializedTable.sort((r1, r2) -> { String f1 = r1.getField(0).toString(); String f2 = r2.getField(0).toString(); return f1.compareTo(f2); }); if (materializedTable.size() != 0) { long maxTimestamp = ((java.sql.Timestamp) materializedTable.get(materializedTable.size() - 1) .getField(0)).getTime(); materializedTable = materializedTable.stream() .filter(row -> ((java.sql.Timestamp) row.getField(0)).getTime() > maxTimestamp - tsWindowThreshold) .collect(Collectors.toList()); for (Row row : materializedTable) { for (int i = 0; i < row.getArity(); ++i) { Object field = row.getField(i); context.out.write(field.toString()); if (i != (row.getArity() - 1)) { context.out.write("\t"); } } context.out.write("\n"); } } context.out.flush(); } catch (IOException e) { LOGGER.error("Fail to refresh data", e); } }
Source:
<code>public void write(final InputStream input, final long size) throws IOException { <START> if (size == 0) { <END> throw new IllegalArgumentException( "the document size should be greater 0" ); } final Ocket ocket = this.ocket(); if (ocket.exists() && ocket.meta().getUserMetaDataOf(AwsDoc.HEADER) != null) { throw new IllegalStateException("you can't write to this doc"); } final ObjectMetadata meta = new ObjectMetadata(); if (size > 0) { meta.setContentLength(size); } ocket.write(input, meta); Logger.info(this, "%d bytes saved to %s", size, ocket.key()); }</code><technical_language>@dmzaytsev Maybe, a decorator SafeDoc check size avoid code duplication</technical_language>

Target:
public void write(final InputStream input, final long size) throws IOException { final Ocket ocket = this.ocket(); if (ocket.exists() && ocket.meta().getUserMetaDataOf(AwsDoc.HEADER) != null) { throw new IllegalStateException("you can't write to this doc"); } final ObjectMetadata meta = new ObjectMetadata(); if (size > 0) { meta.setContentLength(size); } ocket.write(input, meta); Logger.info(this, "%d bytes saved to %s", size, ocket.key()); }
Source:
<code><START> SubresourceParameter(String value) { <END> super("t", value); }</code><technical_language>constructor public</technical_language>

Target:
public SubresourceParameter(String value) { super("t", value); }
Source:
<code>private static boolean isRepoQualifier(Qualifier q) { switch (q.getType()) { case REPO: return true; default: return false; <START> } <END> }</code><technical_language>a return q.getType() == REPO do</technical_language>

Target:
private static boolean isRepoQualifier(Qualifier q) { return q.getType() == QualifierType.REPO; }
Source:
<code>public boolean isDirty() { <START> return StreamSupport.stream( instanceSelector.flatMap( IndexAccessor::isDirty ).spliterator(), false ) <END> .anyMatch( Boolean::booleanValue ); }</code><technical_language>Iterables.stream( instanceSelector.flatMap( IndexAccessor::isDirty ) ).anyMatch( Boolean::booleanValue )</technical_language>

Target:
public boolean isDirty() { return Iterables.stream( instanceSelector.transform( IndexAccessor::isDirty ) ).anyMatch( Boolean::booleanValue ); }
Source:
<code>public static int <START> intUnnecessaryShiftMasking(int <END> value, int shift) { return value << (shift & 31); }</code><technical_language>want prevent inlining of methods too</technical_language>

Target:
public static int $noinline$intUnnecessaryShiftMasking(int value, int shift) { if (doThrow) { throw new Error(); } return value << (shift & 31); }
Source:
<code>private static Double assignDoubleValueWithNullProtection(XmlRpcStruct input, String name) { Double doubleValue = AssignDoubleValue(input, name); <START> return (doubleValue == null ? new Double(0.0) : doubleValue); <END> }</code><technical_language>Double.valueOf(0.0)</technical_language>

Target:
private static Double assignDoubleValueWithNullProtection(XmlRpcStruct input, String name) { Double doubleValue = AssignDoubleValue(input, name); return (doubleValue == null ? Double.valueOf(0.0) : doubleValue); }
Source:
<code>public List<ToolLocationNodeProperty> getNodeProperties(){ <START> return nodeProperties; <END> }</code><technical_language>return emptyList if nodeProperties is null ? please set @Nonnull annotation if case</technical_language>

Target:
public List<ToolLocationNodeProperty> getNodeProperties(){ if (nodeProperties == null) { return Collections.emptyList(); } return nodeProperties; }
Source:
<code><START> default void addResources(Object kbuilder, Collection<ResourceWithConfiguration> resources, ResourceType type) throws Exception { <END> for (ResourceWithConfiguration rd : resources) { rd.getBeforeAdd().accept(kbuilder); addResource(kbuilder, rd.getResource(), type, rd.getResourceConfigutation()); rd.getAfterAdd().accept(kbuilder); } }</code><technical_language>I assume is suitable interface/class instead of Object</technical_language>

Target:
default void addResources(Object kbuilder, Collection<ResourceWithConfiguration> resources, ResourceType type) throws Exception { for (ResourceWithConfiguration rd : resources) { rd.getBeforeAdd().accept(kbuilder); addResource(kbuilder, rd.getResource(), type, rd.getResourceConfiguration()); rd.getAfterAdd().accept(kbuilder); } }
Source:
<code>private static void addHostBondDevices(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Object> bonds = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.NETWORK_BONDINGS); if (bonds != null) { for (Entry<String, Object> entry : bonds.entrySet()) { VdsNetworkInterface iface = new Bond(); updateCommonInterfaceData(iface, vds, entry); iface.setBonded(true); <START> Map<String, Object> bond = (Map<String, Object>) entry.getValue(); <END> if (bond != null) { iface.setMacAddress((String) bond.get("hwaddr")); if (bond.get("slaves") != null) { addBondDeviceToHost(vds, iface, (Object[]) bond.get("slaves")); } Map<String, Object> config = (Map<String, Object>) bond.get("cfg"); if (config != null && config.get("BONDING_OPTS") != null) { iface.setBondOptions(config.get("BONDING_OPTS").toString()); } } } } }</code><technical_language>I this is code, fix in this patch(or following), problem is in newly created method below. rename this. I understanding of this, 'bond' in 'iface' variable, I named bond. This is (probably) bondParameters</technical_language>

Target:
private static void addHostBondDevices(VDS vds, Map<String, Object> xmlRpcStruct) { Map<String, Map<String, Object>> bonds = (Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_BONDINGS); if (bonds != null) { for (Entry<String, Map<String, Object>> entry : bonds.entrySet()) { VdsNetworkInterface iface = new Bond(); updateCommonInterfaceData(iface, vds, entry); iface.setBonded(true); Map<String, Object> bond = entry.getValue(); if (bond != null) { iface.setMacAddress((String) bond.get("hwaddr")); if (bond.get("slaves") != null) { addBondDeviceToHost(vds, iface, (Object[]) bond.get("slaves")); } Map<String, Object> config = (Map<String, Object>) bond.get("cfg"); if (config != null && config.get("BONDING_OPTS") != null) { iface.setBondOptions(config.get("BONDING_OPTS").toString()); } } } } }
Source:
<code><START> protected int <END> getFontStyle(String fontStyleExpression, EAttribute eAttribute, FontData defaultFontData, StyledText text) { int fontStyle = defaultFontData.getStyle(); if (fontStyleExpression != null && !fontStyleExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); String fontStyleValue = eval.get(eAttribute, fontStyleExpression, String.class); fontStyle = getFontStyle(fontStyleValue, fontStyle, text); } return fontStyle; }</code><technical_language>useful, this method of AbstractEEFLifecycleManager</technical_language>

Target:
private int getFontStyle(String fontStyleExpression, EAttribute eAttribute, FontData defaultFontData, StyledText text) { int fontStyle = defaultFontData.getStyle(); if (fontStyleExpression != null && !fontStyleExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); String fontStyleValue = eval.get(eAttribute, fontStyleExpression, String.class); fontStyle = getFontStyle(fontStyleValue, fontStyle, text); } return fontStyle; }
Source:
<code>public void testValidTextFile() { MappingFile mf = getMappingFile("nm-output-example"); assertNotNull("global symbol file", mf); assertTrue(mf.getPid() < 0); mf = getMappingFile("symbol-123.map"); assertNotNull("Symbol file with pid", mf); assertEquals(123, mf.getPid()); Path nmOutput = Paths.get("..", "..", "tmf", "org.eclipse.tracecompass.tmf.core.tests", "testfiles", "callstack" , "symbol-123.map"); assertTrue(Files.exists(nmOutput)); String filePath = nmOutput.toFile().getAbsolutePath(); assertNotNull(filePath); mf = MappingFile.create(filePath, false, 2); assertNotNull("Symbol file for different pid", mf); assertEquals(2, mf.getPid()); <START> <END> }</code><technical_language>Please remove extra space</technical_language>

Target:
public void testValidTextFile() { IMappingFile mf = getMappingFile("nm-output-example"); assertNotNull("global symbol file", mf); assertTrue(mf.getPid() < 0); mf = getMappingFile("symbol-123.map"); assertNotNull("Symbol file with pid", mf); assertEquals(123, mf.getPid()); Path nmOutput = Paths.get("..", "..", "tmf", "org.eclipse.tracecompass.tmf.core.tests", "testfiles", "callstack" , "symbol-123.map"); assertTrue(Files.exists(nmOutput)); String filePath = nmOutput.toFile().getAbsolutePath(); assertNotNull(filePath); mf = IMappingFile.create(filePath, false, 2); assertNotNull("Symbol file for different pid", mf); assertEquals(2, mf.getPid()); }
Source:
<code>public void testVerifyInvalidToken() { <START> Header header = new Header("X-Auth-Token", "invalid"); <END> given(). header(header). when(). post("/token/verify"). then(). statusCode(HttpStatus.SC_UNAUTHORIZED); }</code><technical_language>I personally stored this header key in a private final in this class. magic strings. for invalid header</technical_language>

Target:
public void testVerifyInvalidToken() { Header header = new Header(AUTH_HEADER, "invalid"); given(). header(header). when(). post("/token/verify"). then(). statusCode(HttpStatus.SC_UNAUTHORIZED); }
Source:
<code>private static <T extends DocumentResult> void validateDocumentResult(boolean showStatistics, DocumentResultCollection<T> expectedResults, DocumentResultCollection<T> actualResults, BiConsumer<T, T> additionalAssertions) { final Map<String, T> expected = expectedResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); final Map<String, T> actual = actualResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); assertEquals(expected.size(), actual.size()); if (showStatistics) { validateBatchStatistics(expectedResults.getStatistics(), actualResults.getStatistics()); } expected.forEach((key, expectedValue) -> { T actualValue = actual.get(key); <START> assertTrue(actual.containsKey(key)); <END> assertNotNull(actualValue); if (showStatistics) { validateDocumentStatistics(expectedValue.getStatistics(), actualValue.getStatistics()); } if (expectedValue.getError() == null) { assertNull(actualValue.getError()); } else { assertNotNull(actualValue.getError()); assertEquals(expectedValue.getError().getCode(), actualValue.getError().getCode()); validateErrorDocument(expectedValue.getError(), actualValue.getError()); } additionalAssertions.accept(expectedValue, actualValue); }); }</code><technical_language>This needed. If key exist, returned null</technical_language>

Target:
private static <T extends DocumentResult> void validateDocumentResult(boolean showStatistics, DocumentResultCollection<T> expectedResults, DocumentResultCollection<T> actualResults, BiConsumer<T, T> additionalAssertions) { final Map<String, T> expected = expectedResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); final Map<String, T> actual = actualResults.stream().collect(Collectors.toMap(r -> r.getId(), r -> r)); assertEquals(expected.size(), actual.size()); if (showStatistics) { validateBatchStatistics(expectedResults.getStatistics(), actualResults.getStatistics()); } expected.forEach((key, expectedValue) -> { T actualValue = actual.get(key); assertNotNull(actualValue); if (showStatistics) { validateDocumentStatistics(expectedValue.getStatistics(), actualValue.getStatistics()); } if (expectedValue.getError() == null) { assertNull(actualValue.getError()); } else { assertNotNull(actualValue.getError()); assertEquals(expectedValue.getError().getCode(), actualValue.getError().getCode()); validateErrorDocument(expectedValue.getError(), actualValue.getError()); } additionalAssertions.accept(expectedValue, actualValue); }); }
Source:
<code>private void handleSingle(DoorsTableRow current, RowType rt) { switch (rt) { case SINGLE: stack.pop(); stack.push(current); break; case MULTI_START: stack.peek().setRowType(RowType.MULTI_START); current.setRowType(RowType.MULTI_MID); stack.push(current); break; case MULTI_MID: case MULTI_END: break; case FIRST_ROW: <START> break; <END> } }</code><technical_language>default</technical_language>

Target:
private void handleSingle(DoorsTableRow current, RowType rt) { switch (rt) { case SINGLE: stack.pop(); stack.push(current); break; case MULTI_START: stack.peek().setRowType(RowType.MULTI_START); current.setRowType(RowType.MULTI_MID); stack.push(current); break; case MULTI_MID: case MULTI_END: break; case FIRST_ROW: break; default: throw new OseeStateException("Unhandled enumeration", current); } }
Source:
<code>void initLocalServer(int hostId, boolean clearLocalDataDirectories) throws IOException { CommandLine cmdln = (templateCmdLine.makeCopy()); cmdln.startCommand(StartAction.INITIALIZE); cmdln.setJavaProperty(clusterHostIdProperty, String.valueOf(hostId)); if (this.m_additionalProcessEnv != null) { for (String name : this.m_additionalProcessEnv.keySet()) { cmdln.setJavaProperty(name, this.m_additionalProcessEnv.get(name)); } } if (clearLocalDataDirectories) { cmdln.setForceVoltdbCreate(true); } else { cmdln.setForceVoltdbCreate(false); } ServerThread th = new ServerThread(cmdln); File root = VoltFile.getServerSpecificRoot(String.valueOf(hostId), clearLocalDataDirectories); <START> cmdln.voltdbRoot(root + "/voltdbroot"); <END> th.start(); try { th.join(); VoltDB.resetInstance(); String hostIdStr = cmdln.getJavaProperty(clusterHostIdProperty); m_hostRoots.put(hostIdStr, cmdln.voltdbRoot().getAbsolutePath()); } catch (Exception ex) { ex.printStackTrace(); } }</code><technical_language>voltdbRoot accessors smarter account for '/voltdbroot'</technical_language>

Target:
void initLocalServer(int hostId, boolean clearLocalDataDirectories) throws IOException { CommandLine cmdln = (templateCmdLine.makeCopy()); cmdln.startCommand(StartAction.INITIALIZE); cmdln.setJavaProperty(clusterHostIdProperty, String.valueOf(hostId)); if (this.m_additionalProcessEnv != null) { for (String name : this.m_additionalProcessEnv.keySet()) { cmdln.setJavaProperty(name, this.m_additionalProcessEnv.get(name)); } } if (clearLocalDataDirectories) { cmdln.setForceVoltdbCreate(true); } else { cmdln.setForceVoltdbCreate(false); } ServerThread th = new ServerThread(cmdln); File root = VoltFile.getServerSpecificRoot(String.valueOf(hostId), clearLocalDataDirectories); cmdln.voltdbRoot(root + "/voltdbroot"); try { th.initialize(); } catch (VoltDB.SimulatedExitException expected) { } catch (Exception ex) { log.error("Failed to initialize cluster process:" + ex.getMessage(), ex); assert (false); } String hostIdStr = cmdln.getJavaProperty(clusterHostIdProperty); m_hostRoots.put(hostIdStr, cmdln.voltdbRoot().getAbsolutePath()); }
Source:
<code>private int getChildrenPos(int elementStartPos) { <START> if (getChildrenLenght(elementStartPos) == 0) { <END> return -1; } else { return elementStartPos + HEADER_LENGTH + getValueLength(elementStartPos); } }</code><technical_language>suggestion if (getChildrenLength(elementStartPos) == 0) {</technical_language>

Target:
private int getChildrenPos(int elementStartPos) { if (getChildrenLength(elementStartPos) == 0) { return -1; } else { return elementStartPos + HEADER_LENGTH + getValueLength(elementStartPos); } }
Source:
<code><START> @Override public <END> void handleFailure() { }</code><technical_language>In separate line</technical_language>

Target:
public void handleFailure() { }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; if (httpRequest.getHeader(ORIGIN) == null) { chain.doFilter(request, response); return; } String requestOrigin = null; Enumeration<String> originHeaders = httpRequest.getHeaders(ORIGIN); if (originHeaders != null && originHeaders.hasMoreElements()) { String originHeaderValue = originHeaders.nextElement(); if (originHeaderValue != null && !originHeaderValue.equals("null")) { requestOrigin = originHeaderValue.split(",")[0]; } <START> } <END> if (allowAnyOrigin || OriginValidation.isAllowedOrigin(requestOrigin, allowedOrigins)) { httpResponse.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigin); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_METHODS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_METHODS); httpResponse.addHeader(ACCESS_CONTROL_MAX_AGE, (72 * 60 * 60) + ""); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS); if (!isPreflightRequest((HttpServletRequest) request)) { chain.doFilter(request, response); } } else { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); httpResponse.setContentLength(0); return; } }</code><technical_language>simplify this to: java //NOT a CORS request String originHeader = httpRequest.getHeader(ORIGIN); if (originHeader == null) { chain.doFilter(request, response); return; } String requestOrigin = originHeader.split(",")[0];</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; String requestOrigin = httpRequest.getHeader(ORIGIN); if (requestOrigin == null) { chain.doFilter(request, response); return; } if (allowAnyOrigin || OriginValidation.isAllowedOrigin(requestOrigin, allowedOrigins)) { httpResponse.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigin); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_METHODS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_METHODS); httpResponse.addHeader(ACCESS_CONTROL_MAX_AGE, (72 * 60 * 60) + ""); httpResponse.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS); if (!isPreflightRequest((HttpServletRequest) request)) { chain.doFilter(request, response); } } else { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); httpResponse.setContentLength(0); return; } }
Source:
<code>public ConstraintMatch deserialize(JsonParser parser, DeserializationContext context) throws IOException { try { JsonNode tree = parser.getCodec().readTree(parser); String constraintPackage = tree.get("constraintPackage").asText(); String constraintName = tree.get("constraintName").asText(); Score<?> score = DeserializationUtils.deserializePolymorphicProperty(context, tree, "score"); List<Object> justificationList = new ArrayList<>(); tree.get("justificationList").forEach((t) -> { try { justificationList.add(DeserializationUtils.deserializePolymorphicProperty(context, t, "justification")); } catch (Exception e) { throw new IllegalStateException(e); } }); return new ConstraintMatch(constraintPackage, constraintName, justificationList, score); <START> } catch (ClassNotFoundException e) { <END> throw new IllegalStateException("Cannot find class " + e.getClass().getName(), e); } }</code><technical_language>try catch wide</technical_language>

Target:
public ConstraintMatch deserialize(JsonParser parser, DeserializationContext context) throws IOException { JsonNode tree = parser.getCodec().readTree(parser); String constraintPackage = tree.get("constraintPackage").asText(); String constraintName = tree.get("constraintName").asText(); Score<?> score = DeserializationUtils.deserializePolymorphicProperty(parser, context, tree, "score"); List<Object> justificationList = new ArrayList<>(); for (JsonNode t : tree.get("justificationList")) { justificationList.add(DeserializationUtils.deserializePolymorphicProperty(parser, context, t, "justification")); } return new ConstraintMatch(constraintPackage, constraintName, justificationList, score); }
Source:
<code>protected boolean accepts(final HttpServletRequest request) { if (!super.accepts(request)) { log.debug("Not accepting request because it is not coming from the dispatcher."); return false; } <START> try (ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(AUTH_INFO)) { <END> PathInfo pathInfo = new PathInfo(request.getRequestURI()); Resource reqResource = resourceResolver.getResource(pathInfo.getResourcePath()); if (reqResource != null) { Resource childResource = reqResource.getChild(JcrConstants.JCR_CONTENT); if (childResource != null) { return verifyResourceType(childResource); } } } catch (LoginException e) { log.error("Could not get resource resolver", e); } return false; }</code><technical_language>Is a service user required here? request require enough security context able derive Resource type anyhow? this simply be: return resourceTypes.stream().filter(rt -> { if(slingRequest.getResource().isResourceType(rt)) { return true; } else if (slingRequest.getResource().getChild("jcr:content") != null) { return slingRequest.getResource().getChild("jcr:content").isResourceType(rt); } ).anyMatch();</technical_language>

Target:
protected boolean accepts(final HttpServletRequest request) { if (!super.accepts(request)) { log.debug("Not accepting request because it is not coming from the dispatcher."); return false; } if (request instanceof SlingHttpServletRequest) { SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; Resource resource = getResource(slingRequest); return verifyResourceType(resource); } return false; }
Source:
<code>protected Iterable<EntityStorageRecord> readBulkInternal(final Iterable<I> givenIds, FieldMask fieldMask) { final Map<I, EntityStorageRecord> storage = getStorage(); final Collection<EntityStorageRecord> result = new LinkedList<>(); TypeUrl typeUrl = null; for (I recordId : storage.keySet()) { for (I givenId : givenIds) { if (recordId.equals(givenId)) { final EntityStorageRecord.Builder matchingRecord = storage.get(recordId).toBuilder(); final Any state = matchingRecord.getState(); if (typeUrl == null) { typeUrl = TypeUrl.of(state.getTypeUrl()); } final Any processed = AnyPacker.pack( <START> FieldMasks.applyIfValid( <END> fieldMask, AnyPacker.unpack(state), typeUrl)); matchingRecord.setState(processed); result.add(matchingRecord.build()); continue; } result.add(null); } } return result; }</code><technical_language>Please split expressions. criterion is exact line in case of unexpected Throwable. Right is impossible trace expression caused failure</technical_language>

Target:
protected Iterable<EntityStorageRecord> readBulkInternal(final Iterable<I> givenIds, FieldMask fieldMask) { final Map<I, EntityStorageRecord> storage = getStorage(); final Collection<EntityStorageRecord> result = new LinkedList<>(); TypeUrl typeUrl = null; for (I recordId : storage.keySet()) { for (I givenId : givenIds) { if (recordId.equals(givenId)) { final EntityStorageRecord.Builder matchingRecord = storage.get(recordId).toBuilder(); final Any state = matchingRecord.getState(); if (typeUrl == null) { typeUrl = TypeUrl.of(state.getTypeUrl()); } final Message wholeState = AnyPacker.unpack(state); final Message maskedState = FieldMasks.applyIfValid(fieldMask, wholeState, typeUrl); final Any processed = AnyPacker.pack(maskedState); matchingRecord.setState(processed); result.add(matchingRecord.build()); } else { result.add(null); } } } return result; }
Source:
<code>public void start() { int count = Runtime.getRuntime().availableProcessors(); if (count > 4) { count = count / 2; } if (count > 8) { count = 8; } ScheduledExecutorService[] execs = new ScheduledExecutorService[count]; for (int i = 0; i < count; i++) { <START> execs[i] = Executors.newScheduledThreadPool(count, THREAD_FACTORY); <END> } if (executor.compareAndSet(NONE, execs)) { for (ScheduledExecutorService exec : execs) { if (!NewThreadWorker.tryEnableCancelPolicy(exec)) { if (exec instanceof ScheduledThreadPoolExecutor) { NewThreadWorker.registerExecutor((ScheduledThreadPoolExecutor)exec); } } } } else { for (ScheduledExecutorService exec : execs) { exec.shutdownNow(); } } }</code><technical_language>count replaced 1 guarantee FIFO. Right</technical_language>

Target:
public void start() { int count = Runtime.getRuntime().availableProcessors(); if (count > 4) { count = count / 2; } if (count > 8) { count = 8; } ScheduledExecutorService[] execs = new ScheduledExecutorService[count]; for (int i = 0; i < count; i++) { execs[i] = Executors.newScheduledThreadPool(1, THREAD_FACTORY); } if (executor.compareAndSet(NONE, execs)) { for (ScheduledExecutorService exec : execs) { if (!NewThreadWorker.tryEnableCancelPolicy(exec)) { if (exec instanceof ScheduledThreadPoolExecutor) { NewThreadWorker.registerExecutor((ScheduledThreadPoolExecutor)exec); } } } } else { for (ScheduledExecutorService exec : execs) { exec.shutdownNow(); } } }
Source:
<code>protected static void validateEnumVersionValue(Enum<?> enumValue, ExchangeVersion requestVersion) throws ServiceVersionException { Map<String, ExchangeVersion> enumVersionDict = enumVersionDictionaries .getMember().get(enumValue.getClass()); if (enumVersionDict.containsKey(enumValue.toString())) { ExchangeVersion enumVersion = enumVersionDict.get(enumValue .toString()); int i = requestVersion.compareTo(enumVersion); if (i < 0) { throw new ServiceVersionException(String.format("%S,%S,%S,%S", <START> "Enumeration value %s in enumeration type %s is only valid for Exchange version %s or later.", <END> enumValue.toString(), enumValue.getClass().getName(), enumVersion)); } } }</code><technical_language>please check intentation</technical_language>

Target:
protected static void validateEnumVersionValue(Enum<?> enumValue, ExchangeVersion requestVersion) throws ServiceVersionException { Map<String, ExchangeVersion> enumVersionDict = enumVersionDictionaries .getMember().get(enumValue.getClass()); if (enumVersionDict.containsKey(enumValue.toString())) { ExchangeVersion enumVersion = enumVersionDict.get(enumValue .toString()); int i = requestVersion.compareTo(enumVersion); if (i < 0) { throw new ServiceVersionException( String.format("Enumeration value %s in enumeration type %s is only valid for Exchange version %s " + "or later.", enumValue.toString(), enumValue.getClass().getName(), enumVersion)); } } }
Source:
<code>private void updateBecauseYouRead() { for (Card card : cards) { if (card instanceof BecauseYouReadCard) { cards.remove(card); } } <START> new MainPageReadMoreTopicTask(getActivity()) { <END> @Override public void onFinish(final PageTitle title) { try { byrClient.get(title.getText(), new BecauseYouReadClient.BecauseYouReadCallback() { @Override public void success(MwQueryResponse<BecauseYouReadClient.Pages> pages) { if (!isAdded()) { return; } if (!pages.hasError() && pages.query() != null && pages.query().results() != null) { SearchResults results = SearchResults.filter(pages.query().results(), title.getText(), false); List<BecauseYouReadItemCard> itemCards = MwApiResultPage.searchResultsToCards(results); cards.add(new BecauseYouReadCard(title.getText(), itemCards)); feedView.update(); } } @Override public void failure(Throwable t) { L.w("Error fetching 'because you read' suggestions", t); } }); } catch (IOException e) { L.w("Error fetching 'because you read' suggestions", e); } } @Override public void onCatch(Throwable caught) { L.w("Error getting history entry for 'because you read' card", caught); } }.execute(); }</code><technical_language>Is break this out a separate file a subclass? I adding Activity Fragment is tempting get a card type in start a bit hazy</technical_language>

Target:
private void updateBecauseYouRead() { for (Card card : cards) { if (card instanceof BecauseYouReadCard) { cards.remove(card); } } new BecauseYouReadTopicTask(getActivity(), this, byrClient).execute(); }
Source:
<code>public Player(int playerId){ super("Player " + playerId); this.playerId = playerId; <START> powerups = new ArrayList<Powerup>(); END> addedBombs = 0; addedBombRange = 0; invulnerableTill = 0; immuneToBombs = false; factory = new BombFactory(); }</code><technical_language>Pick one: store powerups bonuses confer. either: 1. Remove addedBombs, addedBombRange attributes, setters. getters (e.g. getBombRange()) instead iterate list of powerups return result. 2. Remove list of powerups attributes. Get rid of setters too, private</technical_language>

Target:
public Player(int playerId){ super("Player " + playerId); this.playerId = playerId; invulnerableTill = 0; immuneToBombsTill = 0; factory = new BombFactory(); }
Source:
<code>public List<FieldVariable> byFieldVariableKey(final String key) throws DotDataException { DotConnect dc = new DotConnect(); dc.setSQL(sql.selectFieldVarByKey); dc.addParam(key); List<Map<String, Object>> results = dc.loadObjectResults(); <START> if (results.size() == 0) { <END> return Collections.emptyList(); } return new DbFieldVariableTransformer(dc.loadObjectResults()).asList(); }</code><technical_language>this wrote as: return UtilMethods.isSet(results)?new DbFieldVariableTransformer(dc.loadObjectResults()).asList(): Collections.emptyList();</technical_language>

Target:
public List<FieldVariable> byFieldVariableKey(final String key) throws DotDataException { final DotConnect dc = new DotConnect(); dc.setSQL(sql.selectFieldVarByKey); dc.addParam(key); final List<Map<String, Object>> results = dc.loadObjectResults(); return UtilMethods.isSet(results) ? new DbFieldVariableTransformer(dc.loadObjectResults()) .asList() : Collections.emptyList(); }
Source:
<code>private void setRepairLogTruncationHandle(long newHandle) { if (newHandle < m_repairLogTruncationHandle) { throw new RuntimeException("Updating truncation point from " + TxnEgo.debugTxnId(m_repairLogTruncationHandle) + "to" + TxnEgo.debugTxnId(newHandle)); } <START> assert newHandle >= m_repairLogTruncationHandle; <END> if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; if (! m_isLeader) { return; } if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } }</code><technical_language>If guard above, need this</technical_language>

Target:
private void setRepairLogTruncationHandle(long newHandle) { if (newHandle < m_repairLogTruncationHandle) { throw new RuntimeException("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle)); } if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; if (! m_isLeader) { return; } if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } }
Source:
<code>public JavaScriptParseSpec( @JsonProperty("timestampSpec") TimestampSpec timestampSpec, @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec, @JsonProperty("function") String function, @JacksonInject JavaScriptConfig config ) { super(timestampSpec, dimensionsSpec); <START> Preconditions.checkState(config.isEnabled(), "JavaScript is disabled"); <END> this.function = function; this.config = config; }</code><technical_language>original idea delaying checks actual usage is disable JavaScript, want Druid nodes able deserialize JavaScript-based objects. For example, JavaScript aggregators in ingest tasks, disabling JavaScript want able view completed tasks task table in metadata store. I worth able create objects if JavaScript is disabled, JavaScript is compiled</technical_language>

Target:
public JavaScriptParseSpec( @JsonProperty("timestampSpec") TimestampSpec timestampSpec, @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec, @JsonProperty("function") String function, @JacksonInject JavaScriptConfig config ) { super(timestampSpec, dimensionsSpec); this.function = function; this.config = config; }
Source:
<code>public Map<String, String> toConfig(Config jobConfig) { validate(); Map<String, String> tableConfig = new HashMap<>(config); tableConfig.put( String.format(JavaTableConfig.TABLE_PROVIDER_FACTORY, tableId), getProviderFactoryClassName()); <START> generateConfig(jobConfig, tableConfig); <END> return Collections.unmodifiableMap(tableConfig); }</code><technical_language>pattern in StreamDescriptors is extending classes override toConfig method base class call super.toConfig step. a simpler interface for extending classes is config related interface method. If do that, need call addTableConfig mutate passed in tableConfig map in generateConfig</technical_language>

Target:
public Map<String, String> toConfig(Config jobConfig) { validate(); Map<String, String> tableConfig = new HashMap<>(config); tableConfig.put( String.format(JavaTableConfig.TABLE_PROVIDER_FACTORY, tableId), getProviderFactoryClassName()); return Collections.unmodifiableMap(tableConfig); }
Source:
<code>protected ServiceRegistration<?> unregisterService(final String interfaceName) { ServiceRegistration<?> reg = null; List<ServiceRegistration<?>> regList = registeredServices.remove(interfaceName); if (regList != null) { reg = regList.get(0); <START> registeredServices.get(interfaceName).forEach(r -> r.unregister()); <END> registeredServices.remove(interfaceName); } return reg; }</code><technical_language>removed map entry for interfaceName this call result in NPE</technical_language>

Target:
protected ServiceRegistration<?> unregisterService(final String interfaceName) { ServiceRegistration<?> reg = null; List<ServiceRegistration<?>> regList = registeredServices.get(interfaceName); if (regList != null) { reg = regList.get(0); regList.forEach(r -> r.unregister()); registeredServices.remove(interfaceName); } return reg; }
Source:
<code>public Collection<FormElementFilter> provideFilters(String elementUUID, Object definition) { <START> Predicate predicate = o -> isParentAnEventSubProcess(elementUUID) && isInterruptingEnabled(elementUUID); <END> FormElementFilter isInterruptingFilter = new FormElementFilter("executionSet.isInterrupting", predicate); return Collections.singletonList(isInterruptingFilter); }</code><technical_language>predicate.and( next condition) here. release, a blocking reason</technical_language>

Target:
public Collection<FormElementFilter> provideFilters(String elementUUID, Object definition) { Predicate parentPredicate = o -> isParentAnEventSubProcess(elementUUID); Predicate isInterruptingPredicate = o -> isInterruptingEnabled(elementUUID); Predicate predicate = parentPredicate.and(isInterruptingPredicate); FormElementFilter isInterruptingFilter = new FormElementFilter("executionSet.isInterrupting", parentPredicate.and(predicate)); return Collections.singletonList(isInterruptingFilter); }
Source:
<code>public Command getCommand() { <START> return null; <END> }</code><technical_language>getSelectedPattern().getCommand()</technical_language>

Target:
public Command getCommand() { return this.currentCommand; }
Source:
<code>public SerializationContext getGlobalCtx() { <START> synchronized (global) { <END> return global.ctx; } }</code><technical_language>this is throwing red flags me.. is this synchronized? Do plan concurrent access underlying SerializationContext? is insufficient synchronization in collections in SerializationContext class itself, if so. For example multiple threads invoke SerializationContext#addContextIntializer time</technical_language>

Target:
public ImmutableSerializationContext getGlobalCtx() { synchronized (global) { return global.ctx; } }
Source:
<code>private int totalFileCount(File inputFile) throws IOException { if (inputFile.isDirectory()) { <START> int currentFileCount = 0; <END> try (DirectoryStream<Path> stream = Files.newDirectoryStream(inputFile.toPath())) { return (int) StreamSupport.stream(stream.spliterator(), false) .map(Path::toFile) .filter(file -> !file.isHidden()) .count(); } } return inputFile.isHidden() ? 0 : 1; }</code><technical_language>If stream route remove this variable</technical_language>

Target:
private int totalFileCount(File inputFile) throws IOException { if (inputFile.isDirectory()) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(inputFile.toPath())) { return (int) StreamSupport.stream(stream.spliterator(), false) .map(Path::toFile) .filter(file -> !file.isHidden()) .count(); } } return inputFile.isHidden() ? 0 : 1; }
Source:
<code>public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { <START> runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null); <END> }</code><technical_language>I default is aggregation. in runMultipleAction</technical_language>

Target:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null, null); }
Source:
<code>public Object getTransactionId() { <START> throw LOG.transactionIdIsNull(); <END> }</code><technical_language>I named transactionIdIsNotAvailable message of exception states it</technical_language>

Target:
public Object getTransactionId() { throw LOG.transactionIdIsNotAvailable(); }
Source:
<code><START> public BasicAuthentication() throws Exception { <END> File passwdFile = new File(HTPASSWD_FILE); if (passwdFile.exists() && passwdFile.isFile()) { BufferedReader reader = new BufferedReader(new FileReader(passwdFile)); String line = reader.readLine(); while (line != null) { String[] values = line.split(":", 2); if (values.length == 2) { users.put(values[0], values[1]); } line = reader.readLine(); } } }</code><technical_language>Lets throw generic exceptions (even IOException is better), catching Exception catches RuntimeExceptions also</technical_language>

Target:
public BasicAuthentication() throws IOException { File passwdFile = new File(HTPASSWD_FILE); if (passwdFile.exists() && passwdFile.isFile()) { try (BufferedReader reader = new BufferedReader(new FileReader(passwdFile))) { String line = reader.readLine(); while (line != null) { String[] values = line.split(":", 2); if (values.length == 2) { users.put(values[0], values[1]); } line = reader.readLine(); } } } }