auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void applyStateChanges(Set<String> brokers, String state) { if (state == null) { return; } switch (state) { <START> case "ONLINE": <END> brokers.retainAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; case "OFFLINE": brokers.removeAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; } }</code><technical_language>constant statemodel</technical_language>

Target:
private void applyStateChanges(Set<String> brokers, String state) { if (state == null) { return; } switch (state) { case CommonConstants.Helix.StateModel.BrokerResourceStateModel.ONLINE: brokers.retainAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; case CommonConstants.Helix.StateModel.BrokerResourceStateModel.OFFLINE: brokers.removeAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; } }
Source:
<code>public void checkIfConnectionIsClosedInAfterCompletion() throws Exception { transactionManager.begin(); Connection connectionToTest = getConnectionToTest(); connectionToTest.clearWarnings(); transactionManager.getTransaction().registerSynchronization(new Synchronization() { @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { try { connectionToTest.isClosed(); <START> connectionToTest.close(); <END> } catch (SQLException e) { fail("Could not close connection: " + e.getMessage()); } } }); transactionManager.commit(); verify(connection, times(2)).isClosed(); }</code><technical_language>that. This test is specifically for isClosed method. Close method is tested closeConnectionInAfterCompletion. I purpose test units small possible</technical_language>

Target:
public void checkIfConnectionIsClosedInAfterCompletion() throws Exception { transactionManager.begin(); ConnectionImple connectionToTest = getConnectionToTest(); connectionToTest.clearWarnings(); transactionManager.getTransaction().registerSynchronization(new Synchronization() { @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { try { connectionToTest.isClosed(); } catch (SQLException e) { fail("Could not check isClosed on connection: " + e.getMessage()); } } }); transactionManager.commit(); verify(connection, times(1)).isClosed(); }
Source:
<code>public void checkDecisionServerContainerAMQ() throws NamingException { log.info("Running test checkDecisionServerContainerAMQ"); log.info("Trying to connect to AMQ HOST: " + AMQ_HOST); getKieJmsServiceClient().listContainers().getResult().getContainers().stream().forEach(container -> { <START> String containerAliasToID = new SumCoder.MD5().encode(container.getResolvedReleaseId().getArtifactId() + "=" + container.getReleaseId()); <END> if (!containerAliasToID.equals(container.getContainerId())){ containerAliasToID = new SumCoder.MD5().encode("AnotherContainer=" + container.getReleaseId()); } Assert.assertTrue(container.getContainerId().equals(containerAliasToID)); Assert.assertEquals(org.kie.server.api.model.KieContainerStatus.STARTED, container.getStatus()); }); }</code><technical_language>for lambdas</technical_language>

Target:
public void checkDecisionServerContainerAMQ() throws NamingException { log.info("Running test checkDecisionServerContainerAMQ"); log.info("Trying to connect to AMQ HOST: " + AMQ_HOST); for (KieContainerResource container : getKieJmsServiceClient().listContainers().getResult().getContainers()) { String containerAliasToID = new SumCoder.MD5().encode(container.getResolvedReleaseId().getArtifactId() + "=" + container.getReleaseId()); if (!containerAliasToID.equals(container.getContainerId())) { containerAliasToID = new SumCoder.MD5().encode("AnotherContainer=" + container.getReleaseId()); } Assert.assertTrue(container.getContainerId().equals(containerAliasToID)); Assert.assertEquals(org.kie.server.api.model.KieContainerStatus.STARTED, container.getStatus()); } }
Source:
<code>public Response generateBuyKey(@Context HttpServletRequest request) { Hashtable<String, String> props = new Hashtable<String, String>(); TOTPManager totpManager = (TOTPManager) CarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class, props); String secretKey = CharacterEncoder.getSafeText(request.getParameter("secretKey")); <START> String token = null; <END> try { token = totpManager.generateTOTPToken(secretKey); return Response.ok("{\"token\":\"" + token + "\"}", MediaType.APPLICATION_JSON_TYPE).build(); } catch (TOTPException e) { log.error("TOTPKeyGenerator endpoint could not generate the token", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the token") .type(MediaType.APPLICATION_JSON_TYPE).build(); } }</code><technical_language>need initialize null</technical_language>

Target:
public Response generateBuyKey(@Context HttpServletRequest request) { Hashtable<String, String> props = new Hashtable<String, String>(); TOTPManager totpManager = (TOTPManager) CarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class, props); String secretKey = CharacterEncoder.getSafeText(request.getParameter("secretKey")); String token; try { token = totpManager.generateTOTPToken(secretKey); return Response.ok("{\"token\":\"" + token + "\"}", MediaType.APPLICATION_JSON_TYPE).build(); } catch (TOTPException e) { log.error("TOTPKeyGenerator endpoint could not generate the token", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the token") .type(MediaType.APPLICATION_JSON_TYPE).build(); } }
Source:
<code>public void writeVertex(Vertex<VKmer, VertexValueWritable, NullWritable, ?> vertex) throws IOException, InterruptedException { byte state = (byte) (vertex.getVertexValue().getState() & State.VERTEX_MASK); <START> if (state == State.IS_MARK) <END> getRecordWriter().write(vertex.getVertexId(), vertex.getVertexValue().getCopyAsNode()); }</code><technical_language>meaning of "IS_MARK"</technical_language>

Target:
public void writeVertex(Vertex<VKmer, VertexValueWritable, NullWritable, ?> vertex) throws IOException, InterruptedException { byte state = (byte) (vertex.getVertexValue().getState() & State.VERTEX_MASK); if (state == State.KEEP_NODE) getRecordWriter().write(vertex.getVertexId(), vertex.getVertexValue().getCopyAsNode()); }
Source:
<code>private String streamOutput(InputStream inputStream) throws IOException, InterruptedException, ExecutionException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable() { public String call() throws IOException { try { String line = null; while ((line = br.readLine()) != null) { <START> System.out.print("."); <END> if (line.contains(ready_marker)) { break; } } } finally { br.close(); } return "\nIAM Microservice started"; } }); try { return future.get(timeout, TimeUnit.SECONDS); } catch (TimeoutException toe) { br.close(); return "\nWarning: IAM Microservice timed out to start. See the logs for the details."; } finally { executor.shutdownNow(); future.cancel(true); } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Replace this of System.out System.err a logger. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static String streamOutput(InputStream inputStream) throws IOException, InterruptedException, ExecutionException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable() { public String call() throws IOException { try { String line = null; while ((line = br.readLine()) != null) { System.out.print("."); if (line.contains(READY_MARKER)) { break; } } } finally { br.close(); } return "\nIAM Microservice started"; } }); try { return future.get(TIMEOUT, TimeUnit.SECONDS); } catch (TimeoutException toe) { br.close(); LOGGER.warn("Warning: IAM Microservice timed out to start. See the logs for the details."); return "\nWarning: IAM Microservice timed out to start. See the logs for the details."; } finally { executor.shutdownNow(); future.cancel(true); } }
Source:
<code><START> private List<QueryParameters.SpatialRelationship> getSpatialRelationships(Geometry a, Geometry b) { <END> List<QueryParameters.SpatialRelationship> relationships = new ArrayList<>(); if (GeometryEngine.crosses(a, b)) relationships.add(QueryParameters.SpatialRelationship.CROSSES); if (GeometryEngine.contains(a, b)) relationships.add(QueryParameters.SpatialRelationship.CONTAINS); if (GeometryEngine.disjoint(a, b)) relationships.add(QueryParameters.SpatialRelationship.DISJOINT); if (GeometryEngine.intersects(a, b)) relationships.add(QueryParameters.SpatialRelationship.INTERSECTS); if (GeometryEngine.overlaps(a, b)) relationships.add(QueryParameters.SpatialRelationship.OVERLAPS); if (GeometryEngine.touches(a, b)) relationships.add(QueryParameters.SpatialRelationship.TOUCHES); if (GeometryEngine.within(a, b)) relationships.add(QueryParameters.SpatialRelationship.WITHIN); return relationships; }</code><technical_language>static</technical_language>

Target:
private static List<QueryParameters.SpatialRelationship> getSpatialRelationships(Geometry a, Geometry b) { List<QueryParameters.SpatialRelationship> relationships = new ArrayList<>(); if (GeometryEngine.crosses(a, b)) relationships.add(QueryParameters.SpatialRelationship.CROSSES); if (GeometryEngine.contains(a, b)) relationships.add(QueryParameters.SpatialRelationship.CONTAINS); if (GeometryEngine.disjoint(a, b)) relationships.add(QueryParameters.SpatialRelationship.DISJOINT); if (GeometryEngine.intersects(a, b)) relationships.add(QueryParameters.SpatialRelationship.INTERSECTS); if (GeometryEngine.overlaps(a, b)) relationships.add(QueryParameters.SpatialRelationship.OVERLAPS); if (GeometryEngine.touches(a, b)) relationships.add(QueryParameters.SpatialRelationship.TOUCHES); if (GeometryEngine.within(a, b)) relationships.add(QueryParameters.SpatialRelationship.WITHIN); return relationships; }
Source:
<code>public List<MetricFamilySamples> collect() { return Arrays.asList( createSample("hikaricp_active_connections", "Active connections", poolStats.getActiveConnections()), createSample("hikaricp_idle_connections", "Idle connections", poolStats.getIdleConnections()), createSample("hikaricp_pending_threads", "Pending threads", poolStats.getPendingThreads()), <START> createSample("hikaricp_total_connections", "Total connections", poolStats.getTotalConnections()) <END> ); }</code><technical_language>Is this current connections, connections created time</technical_language>

Target:
public List<MetricFamilySamples> collect() { return Arrays.asList( createSample("hikaricp_active_connections", "Active connections", poolStats.getActiveConnections()), createSample("hikaricp_idle_connections", "Idle connections", poolStats.getIdleConnections()), createSample("hikaricp_pending_threads", "Pending threads", poolStats.getPendingThreads()), createSample("hikaricp_connections", "The number of current connections", poolStats.getTotalConnections()) ); }
Source:
<code>public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (mItemList.get(position) instanceof ParentObject) { ParentViewHolder parentViewHolder = (ParentViewHolder) holder; <START> if (mCustomParentAnimationViewId != -1l && mAnimationDuration != -1l) { <END> parentViewHolder.setCustomClickableView(mCustomParentAnimationViewId); parentViewHolder.setAnimationDuration(mAnimationDuration); } else if (mCustomParentAnimationViewId != -1l) { parentViewHolder.setCustomClickableView(mCustomParentAnimationViewId); parentViewHolder.cancelAnimation(); } else { parentViewHolder.setMainItemClickToExpand(); } parentViewHolder.setExpanded(((ParentObject) mItemList.get(position)).isExpanded()); onBindParentViewHolder(parentViewHolder, position); } else if (mItemList.get(position) instanceof ChildObject) { onBindChildViewHolder((ChildViewHolder) holder, position); } else { throw new IllegalStateException("Incorrect ViewHolder found"); } }</code><technical_language>fact -1 duration means is disabled needs stored a public constant somewhere, a user of library hard -1 does. (unless misunderstanding -1 is)</technical_language>

Target:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (mItemList.get(position) instanceof ParentObject) { ParentViewHolder parentViewHolder = (ParentViewHolder) holder; if (mParentAndIconClickable) { if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET && mAnimationDuration != CUSTOM_ANIMATION_DURATION_NOT_SET) { parentViewHolder.setCustomClickableViewAndItem(mCustomParentAnimationViewId); parentViewHolder.setAnimationDuration(mAnimationDuration); } else if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET) { parentViewHolder.setCustomClickableViewAndItem(mCustomParentAnimationViewId); parentViewHolder.cancelAnimation(); } else { parentViewHolder.setMainItemClickToExpand(); } } else { if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET && mAnimationDuration != CUSTOM_ANIMATION_DURATION_NOT_SET) { parentViewHolder.setCustomClickableViewOnly(mCustomParentAnimationViewId); parentViewHolder.setAnimationDuration(mAnimationDuration); } else if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET) { parentViewHolder.setCustomClickableViewOnly(mCustomParentAnimationViewId); parentViewHolder.cancelAnimation(); } else { parentViewHolder.setMainItemClickToExpand(); } } parentViewHolder.setExpanded(((ParentObject) mItemList.get(position)).isExpanded()); onBindParentViewHolder(parentViewHolder, position); } else if (mItemList.get(position) instanceof ChildObject) { onBindChildViewHolder((ChildViewHolder) holder, position); } else { throw new IllegalStateException("Incorrect ViewHolder found"); } }
Source:
<code>public static String prettyPrintRule(Rule rule) { <START> StringBuilder sb = new StringBuilder(); <END> if (rule instanceof Context) { final Context ctx = (Context) rule; WindupRuleProvider ruleProvider = (WindupRuleProvider) ctx.get(RuleMetadata.RULE_PROVIDER); if (ruleProvider != null) { sb.append(ruleProvider.getPhase()).append(" - "); sb.append(ruleProvider.getID()).append(' '); } Object categories = (String) ctx.get(RuleMetadata.CATEGORY); if (categories instanceof String ) sb.append('[').append(categories).append("] "); if (categories instanceof Iterable){ sb.append('['); for(Object cat : (Iterable) categories) sb.append(cat).append(", "); sb.append("] "); } } return sb.append(rule.getId()).toString(); }</code><technical_language>please rename sb -> builder</technical_language>

Target:
public static String prettyPrintRule(Rule rule) { StringBuilder sb = new StringBuilder(); if (rule instanceof Context) { final Context ctx = (Context) rule; WindupRuleProvider ruleProvider = (WindupRuleProvider) ctx.get(RuleMetadata.RULE_PROVIDER); if (ruleProvider != null) { sb.append(ruleProvider.getPhase()).append(" - "); sb.append(ruleProvider.getID()).append(' '); } Object categories = ctx.get(RuleMetadata.TAGS); if (categories instanceof String ) sb.append('[').append(categories).append("] "); else if (categories instanceof Iterable) { sb.append('['); for(Object cat : (Iterable) categories) sb.append(cat).append(", "); sb.append("] "); } } return sb.append(rule.getId()).toString(); }
Source:
<code>public void ignoreCaseShouldNotBeApplicableToComparisonOtherThanEquals() { final String emi = "EMI Studios, London"; session.save(new Studio(emi)); <START> assertThat(session.loadAll(Studio.class, new Filter("name", ComparisonOperator.EQUALS, "eMi Studios, London").ignoreCase(), 0)) <END> .hasSize(1) .extracting(Studio::getName) .containsExactly(emi); }</code><technical_language>Extract Filter part run a code formatter avoid line break occur</technical_language>

Target:
public void ignoreCaseShouldNotBeApplicableToComparisonOtherThanEquals() { final String emi = "EMI Studios, London"; session.save(new Studio(emi)); final Filter nameFilter = new Filter("name", ComparisonOperator.EQUALS, "eMi Studios, London").ignoreCase(); assertThat(session.loadAll(Studio.class, nameFilter, 0)) .hasSize(1) .extracting(Studio::getName) .containsExactly(emi); }
Source:
<code>private Credentials getUserCredentials(HttpServletRequest request) throws AuthenticationException { String[] creds = new String( Base64.decodeBase64(request.getHeader(SSOUtils.HEADER_AUTHORIZATION).substring("Basic".length())), Charset.forName("UTF-8") <START> ).split(":", 2); <END> return translateUser(creds[0], creds[1]); }</code><technical_language>if do 2 components, assume do credentials, please do generate exceptions in authentication</technical_language>

Target:
private Credentials getUserCredentials(HttpServletRequest request) { String header = request.getHeader(SSOUtils.HEADER_AUTHORIZATION).substring("Basic".length()); Credentials credentials = null; if (StringUtils.isNotEmpty(header)) { String[] creds = new String( Base64.decodeBase64(request.getHeader(SSOUtils.HEADER_AUTHORIZATION).substring("Basic".length())), Charset.forName("UTF-8") ).split(":", 2); credentials = translateUser(creds[0], creds[1]); } return credentials; }
Source:
<code>public ActionResult execute() { String frontendUrl = getRequestParamValue("frontendUrl"); if (frontendUrl == null) { frontendUrl = ""; } AuthInfo output; if (userInfo == null) { output = new AuthInfo( gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.STUDENT_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.INSTRUCTOR_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.ADMIN_HOME_PAGE) ); } else { String googleId = userInfo.getId(); AccountAttributes accountInfo = logic.getAccount(googleId); <START> output = new AuthInfo(userInfo, accountInfo.getInstitute(), authType == AuthType.MASQUERADE, <END> gateKeeper.getLogoutUrl(frontendUrl + "/web")); } String csrfToken = StringHelper.encrypt(req.getSession().getId()); String existingCsrfToken = HttpRequestHelper.getCookieValueFromRequest(req, Const.CsrfConfig.TOKEN_COOKIE_NAME); if (!csrfToken.equals(existingCsrfToken)) { Cookie csrfTokenCookie = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, csrfToken); csrfTokenCookie.setSecure(!Config.isDevServer()); csrfTokenCookie.setPath("/"); resp.addCookie(csrfTokenCookie); } return new JsonResult(output); }</code><technical_language>If accountInfo is null, hit NPE here. Need add a guard</technical_language>

Target:
public ActionResult execute() { String frontendUrl = getRequestParamValue("frontendUrl"); if (frontendUrl == null) { frontendUrl = ""; } AuthInfo output; if (userInfo == null) { output = new AuthInfo( gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.STUDENT_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.INSTRUCTOR_HOME_PAGE), gateKeeper.getLoginUrl(frontendUrl + Const.WebPageURIs.ADMIN_HOME_PAGE) ); } else { String googleId = userInfo.getId(); AccountAttributes accountInfo = logic.getAccount(googleId); String institute = null; if (accountInfo != null) { institute = accountInfo.getInstitute(); } output = new AuthInfo(userInfo, institute, authType == AuthType.MASQUERADE, gateKeeper.getLogoutUrl(frontendUrl + "/web")); } String csrfToken = StringHelper.encrypt(req.getSession().getId()); String existingCsrfToken = HttpRequestHelper.getCookieValueFromRequest(req, Const.CsrfConfig.TOKEN_COOKIE_NAME); if (!csrfToken.equals(existingCsrfToken)) { Cookie csrfTokenCookie = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, csrfToken); csrfTokenCookie.setSecure(!Config.isDevServer()); csrfTokenCookie.setPath("/"); resp.addCookie(csrfTokenCookie); } return new JsonResult(output); }
Source:
<code>public List<String> getRequiredDirectoryNames() { <START> return new ArrayList<String>() {{add(incomingDirectoryName); }}; <END> }</code><technical_language>formatting is a bit odd. I some extra curly brackets removed</technical_language>

Target:
public List<String> getRequiredDirectoryNames() { List<String> directoryNames = new ArrayList<String>(); directoryNames.add(getIncomingDirectoryName()); directoryNames.add(getAcceptedDirectoryName()); directoryNames.add(getRejectedDirectoryName()); return directoryNames; }
Source:
<code>protected void shutdownNodeSourceServices(Client initiator) { logger.info("[" + name + "] Shutdown finalization"); if (descriptor.getStatus().equals(NodeSourceStatus.NODES_DEPLOYED)) { <START> nodeSourcePolicy.shutdown(initiator); <END> infrastructureManager.internalShutDown(); } }</code><technical_language>this keyword is missing in code. fix automatically in IntelliJ: <LINK_0></technical_language>

Target:
protected void shutdownNodeSourceServices(Client initiator) { logger.info("[" + this.name + "] Shutdown finalization"); if (this.descriptor.getStatus().equals(NodeSourceStatus.NODES_DEPLOYED)) { this.activeNodeSourcePolicy.shutdown(initiator); this.infrastructureManager.internalShutDown(); } }
Source:
<code>protected Optional<UniqueConstraint> getPrimaryKey(DatabaseMetaData metaData, String schema, String table) throws SQLException { ResultSet rs = metaData.getPrimaryKeys(null, schema, table); Map<Integer, String> keySeqColumnName = new HashMap<>(); String pkName = null; <START> while (rs.next()) { <END> String columnName = rs.getString("COLUMN_NAME"); pkName = rs.getString("PK_NAME"); int keySeq = rs.getInt("KEY_SEQ"); keySeqColumnName.put(keySeq - 1, columnName); } List<String> pkFields = Arrays.asList(new String[keySeqColumnName.size()]); keySeqColumnName.forEach(pkFields::set); if (!pkFields.isEmpty()) { pkName = pkName != null ? pkName : "pk_" + String.join("_", pkFields); return Optional.of(UniqueConstraint.primaryKey(pkName, pkFields)); } return Optional.empty(); }</code><technical_language>ident</technical_language>

Target:
protected Optional<UniqueConstraint> getPrimaryKey(DatabaseMetaData metaData, String schema, String table) throws SQLException { ResultSet rs = metaData.getPrimaryKeys(null, schema, table); Map<Integer, String> keySeqColumnName = new HashMap<>(); String pkName = null; while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); pkName = rs.getString("PK_NAME"); int keySeq = rs.getInt("KEY_SEQ"); keySeqColumnName.put(keySeq - 1, columnName); } List<String> pkFields = Arrays.asList(new String[keySeqColumnName.size()]); keySeqColumnName.forEach(pkFields::set); if (!pkFields.isEmpty()) { pkName = pkName == null ? "pk_" + String.join("_", pkFields) : pkName; return Optional.of(UniqueConstraint.primaryKey(pkName, pkFields)); } return Optional.empty(); }
Source:
<code>public void killQuery(String queryId, String message) { QueryId query = parseQueryId(queryId); try { <START> Optional<QueryState> state = queryManager.getQueryState(query); <END> if (!state.isPresent()) { throw new NoSuchElementException(); } if (state.get().isDone()) { throw new PrestoException(NOT_SUPPORTED, "Target query is not running: " + queryId); } queryManager.failQuery(query, createKillQueryException(message)); if (!ADMINISTRATIVELY_KILLED.toErrorCode().equals(queryManager.getQueryInfo(query).getErrorCode())) { throw new PrestoException(NOT_SUPPORTED, "Target query is not running: " + queryId); } } catch (NoSuchElementException e) { throw new PrestoException(NOT_FOUND, "Target query not found: " + queryId); } }</code><technical_language>Hmm I feel named a getter returns optional, a search. This misinterpreted cases queries _don't have_ states</technical_language>

Target:
public void killQuery(String queryId, String message) { QueryId query = parseQueryId(queryId); try { QueryState state = queryManager.getQueryState(query); if (state.isDone()) { throw new PrestoException(NOT_SUPPORTED, "Target query is not running: " + queryId); } queryManager.failQuery(query, createKillQueryException(message)); if (!ADMINISTRATIVELY_KILLED.toErrorCode().equals(queryManager.getQueryInfo(query).getErrorCode())) { throw new PrestoException(NOT_SUPPORTED, "Target query is not running: " + queryId); } } catch (NoSuchElementException e) { throw new PrestoException(NOT_FOUND, "Target query not found: " + queryId); } }
Source:
<code>private ApiResponseSet alertToSet(Alert alert) { Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(alert.getAlertId())); <START> map.put("name", alert.getName()); <END> map.put("description", alert.getDescription()); map.put("risk", Alert.MSG_RISK[alert.getRisk()]); map.put("confidence", Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put("url", alert.getUri()); map.put("other", alert.getOtherInfo()); map.put("param", alert.getParam()); map.put("attack", alert.getAttack()); map.put("evidence", alert.getEvidence()); map.put("reference", alert.getReference()); map.put("cweid", String.valueOf(alert.getCweId())); map.put("wascid", String.valueOf(alert.getWascId())); map.put("solution", alert.getSolution()); if (alert.getHistoryRef() != null) { map.put("messageId", String.valueOf(alert.getHistoryRef().getHistoryId())); } return new ApiResponseSet("alert", map); }</code><technical_language>"alert" property returned, compatibility older tools</technical_language>

Target:
private ApiResponseSet alertToSet(Alert alert) { Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(alert.getAlertId())); map.put("pluginId", String.valueOf(alert.getPluginId())); map.put("alert", alert.getName()); map.put("name", alert.getName()); map.put("description", alert.getDescription()); map.put("risk", Alert.MSG_RISK[alert.getRisk()]); map.put("confidence", Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put("url", alert.getUri()); map.put("other", alert.getOtherInfo()); map.put("param", alert.getParam()); map.put("attack", alert.getAttack()); map.put("evidence", alert.getEvidence()); map.put("reference", alert.getReference()); map.put("cweid", String.valueOf(alert.getCweId())); map.put("wascid", String.valueOf(alert.getWascId())); map.put("solution", alert.getSolution()); if (alert.getHistoryRef() != null) { map.put("messageId", String.valueOf(alert.getHistoryRef().getHistoryId())); } return new ApiResponseSet("alert", map); }
Source:
<code>public SVGReadParam() { super(); <START> allowExternalResources = true; <END> }</code><technical_language>here, remove this, leave false</technical_language>

Target:
public SVGReadParam() { super(); }
Source:
<code>public void testDistinctCountGroupByPushdown() { PlanNode justScan = buildPlan(planBuilder -> tableScan(planBuilder, pinotTable, regionId, secondsSinceEpoch, city, fare)); PlanNode distinctAggregation = buildPlan(planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(justScan).singleGroupingSet(v("city"), v("regionid")))); <START> testPQL(planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(distinctAggregation).singleGroupingSet(v("city")).addAggregation(v("count_regionid"), getRowExpression("count(regionid)", defaultSessionHolder))), <END> "SELECT DISTINCTCOUNT(regionId) FROM realtimeOnly GROUP BY city TOP 10000"); }</code><technical_language>put param line line param</technical_language>

Target:
public void testDistinctCountGroupByPushdown() { PlanNode justScan = buildPlan(planBuilder -> tableScan(planBuilder, pinotTable, regionId, secondsSinceEpoch, city, fare)); PlanNode distinctAggregation = buildPlan(planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(justScan).singleGroupingSet(variable("city"), variable("regionid")))); testPQL( planBuilder -> planBuilder.aggregation(aggBuilder -> aggBuilder.source(distinctAggregation).singleGroupingSet(variable("city")).addAggregation(variable("count_regionid"), getRowExpression("count(regionid)", defaultSessionHolder))), "SELECT DISTINCTCOUNT(regionId) FROM realtimeOnly GROUP BY city TOP 10000"); }
Source:
<code>public InputStatus pollNext(ReaderOutput<T> output) throws Exception { RecordsWithSplitIds<E> recordsWithSplitId = this.currentFetch; if (recordsWithSplitId == null) { recordsWithSplitId = getNextFetch(output); if (recordsWithSplitId == null) { idleSince = clock.absoluteTimeMillis(); return trace(finishedOrAvailableLater()); } } idleSince = -1L; while (true) { final E record = recordsWithSplitId.nextRecordFromSplit(); if (record != null) { <START> context.metricGroup().getNumRecordsInCounter().inc(); <END> recordEmitter.emitRecord(record, currentSplitOutput, currentSplitContext.state); LOG.trace("Emitted record: {}", record); return trace(InputStatus.MORE_AVAILABLE); } else if (!moveToNextSplit(recordsWithSplitId, output)) { return pollNext(output); } } }</code><technical_language>this a field? Avoid additional (virtual) method calls here</technical_language>

Target:
public InputStatus pollNext(ReaderOutput<T> output) throws Exception { RecordsWithSplitIds<E> recordsWithSplitId = this.currentFetch; if (recordsWithSplitId == null) { recordsWithSplitId = getNextFetch(output); if (recordsWithSplitId == null) { return trace(finishedOrAvailableLater()); } } while (true) { final E record = recordsWithSplitId.nextRecordFromSplit(); if (record != null) { numRecordsInCounter.inc(); recordEmitter.emitRecord(record, currentSplitOutput, currentSplitContext.state); LOG.trace("Emitted record: {}", record); return trace(InputStatus.MORE_AVAILABLE); } else if (!moveToNextSplit(recordsWithSplitId, output)) { return pollNext(output); } } }
Source:
<code><START> public int hashCode() <END> { final int prime = 31; int result = 1; result = prime * result + (full ? 1231 : 1237); result = prime * result + ((leftRot == null) ? 0 : leftRot.hashCode()); result = prime * result + ((matrix == null) ? 0 : matrix.hashCode()); result = prime * result + ((rightRot == null) ? 0 : rightRot.hashCode()); result = prime * result + ((scale == null) ? 0 : scale.hashCode()); result = prime * result + ((translation == null) ? 0 : translation.hashCode()); return result; }</code><technical_language>matrix for equals/hashcode, other fields count for identity comparisons; rely IDE method generators</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((matrix == null) ? 0 : matrix.hashCode()); return result; }
Source:
<code><START> private ParseHttpRequest getParseHttpRequest(Request okHttpRequest) { <END> ParseHttpRequest.Builder parseRequestBuilder = new ParseHttpRequest.Builder(); switch (okHttpRequest.method()) { case OKHTTP_GET: parseRequestBuilder.setMethod(ParseRequest.Method.GET); break; case OKHTTP_DELETE: parseRequestBuilder.setMethod(ParseRequest.Method.DELETE); break; case OKHTTP_POST: parseRequestBuilder.setMethod(ParseRequest.Method.POST); break; case OKHTTP_PUT: parseRequestBuilder.setMethod(ParseRequest.Method.PUT); break; default: throw new IllegalArgumentException( "Invalid http method " + okHttpRequest.method()); } parseRequestBuilder.setUrl(okHttpRequest.urlString()); for (Map.Entry<String, List<String>> entry : okHttpRequest.headers().toMultimap().entrySet()) { parseRequestBuilder.addHeader(entry.getKey(), entry.getValue().get(0)); } if (okHttpRequest.body() instanceof CountingOkHttpRequestBody) { CountingOkHttpRequestBody okHttpBody = (CountingOkHttpRequestBody) okHttpRequest.body(); parseRequestBuilder.setBody(okHttpBody.getParseHttpBody()); } return parseRequestBuilder.build(); }</code><technical_language>static</technical_language>

Target:
private ParseHttpRequest getParseHttpRequest(Request okHttpRequest) { ParseHttpRequest.Builder parseRequestBuilder = new ParseHttpRequest.Builder(); switch (okHttpRequest.method()) { case OKHTTP_GET: parseRequestBuilder.setMethod(ParseRequest.Method.GET); break; case OKHTTP_DELETE: parseRequestBuilder.setMethod(ParseRequest.Method.DELETE); break; case OKHTTP_POST: parseRequestBuilder.setMethod(ParseRequest.Method.POST); break; case OKHTTP_PUT: parseRequestBuilder.setMethod(ParseRequest.Method.PUT); break; default: throw new IllegalArgumentException( "Invalid http method " + okHttpRequest.method()); } parseRequestBuilder.setUrl(okHttpRequest.urlString()); for (Map.Entry<String, List<String>> entry : okHttpRequest.headers().toMultimap().entrySet()) { parseRequestBuilder.addHeader(entry.getKey(), entry.getValue().get(0)); } ParseOkHttpRequestBody okHttpBody = (ParseOkHttpRequestBody) okHttpRequest.body(); if (okHttpBody != null) { parseRequestBuilder.setBody(okHttpBody.getParseHttpBody()); } return parseRequestBuilder.build(); }
Source:
<code>public String getLabelText() { int nbTraces = getTraces().size(); if (nbTraces > 0) { return getName() + " [" + <START> getTraces().size() + <END> "]"; } return getName(); }</code><technical_language>nbTraces, I guess</technical_language>

Target:
public String getLabelText() { int nbTraces = getTraces().size(); if (nbTraces > 0) { return (getName() + " [" + nbTraces + ']'); } return getName(); }
Source:
<code>public SlackNotifier(final String teamDomain, final String authToken, final String authTokenCredentialId, final String room, final String buildServerUrl, final String sendAs, final boolean startNotification, final boolean notifyAborted, final boolean notifyFailure, final boolean notifyNotBuilt, final boolean notifySuccess, final boolean notifyUnstable, final boolean notifyBackToNormal, final boolean notifyRepeatedFailure, final boolean includeTestSummary, CommitInfoChoice commitInfoChoice, boolean includeCustomMessage, String customMessage) { super(); this.teamDomain = teamDomain; this.authToken = authToken; <START> this.authTokenCredentialId = authTokenCredentialId.trim(); <END> this.buildServerUrl = buildServerUrl; this.room = room; this.sendAs = sendAs; this.startNotification = startNotification; this.notifyAborted = notifyAborted; this.notifyFailure = notifyFailure; this.notifyNotBuilt = notifyNotBuilt; this.notifySuccess = notifySuccess; this.notifyUnstable = notifyUnstable; this.notifyBackToNormal = notifyBackToNormal; this.notifyRepeatedFailure = notifyRepeatedFailure; this.includeTestSummary = includeTestSummary; this.commitInfoChoice = commitInfoChoice; this.includeCustomMessage = includeCustomMessage; this.customMessage = customMessage; }</code><technical_language>a null pointer if credentialId is configured. use: import org.apache.commons.lang.StringUtils; ... this.authTokenCredentialId = StringUtils.trim(authTokenCredentialId); needs fixed in StandardSlackService</technical_language>

Target:
public SlackNotifier(final String teamDomain, final String authToken, final String authTokenCredentialId, final String room, final String buildServerUrl, final String sendAs, final boolean startNotification, final boolean notifyAborted, final boolean notifyFailure, final boolean notifyNotBuilt, final boolean notifySuccess, final boolean notifyUnstable, final boolean notifyBackToNormal, final boolean notifyRepeatedFailure, final boolean includeTestSummary, CommitInfoChoice commitInfoChoice, boolean includeCustomMessage, String customMessage) { super(); this.teamDomain = teamDomain; this.authToken = authToken; this.authTokenCredentialId = StringUtils.trim(authTokenCredentialId); this.buildServerUrl = buildServerUrl; this.room = room; this.sendAs = sendAs; this.startNotification = startNotification; this.notifyAborted = notifyAborted; this.notifyFailure = notifyFailure; this.notifyNotBuilt = notifyNotBuilt; this.notifySuccess = notifySuccess; this.notifyUnstable = notifyUnstable; this.notifyBackToNormal = notifyBackToNormal; this.notifyRepeatedFailure = notifyRepeatedFailure; this.includeTestSummary = includeTestSummary; this.commitInfoChoice = commitInfoChoice; this.includeCustomMessage = includeCustomMessage; this.customMessage = customMessage; }
Source:
<code>private void checkUpdateDataPermission(HttpServletRequest request) throws InsufficientPermissionException { Boolean auth = true; UserAccountBean userBean =(UserAccountBean) request.getSession().getAttribute(USER_BEAN_NAME); ArrayList userRoles = userBean.getRoles(); String submitted =(String) request.getParameter("submitted"); String checkInputs = (String)request.getParameter("checkInputs"); if(submitted !=null && submitted.equals("1") && checkInputs!=null && checkInputs.equals("1")) { for (int i = 0; i < userRoles.size(); i++) { StudyUserRoleBean studyRole = (StudyUserRoleBean) userRoles.get(i); if(studyRole.getRole().equals(Role.MONITOR)) { <START> auth = false; <END> } } } if(!auth) { addPageMessage(respage.getString("you_not_have_permission_update_a_CRF"), request); throw new InsufficientPermissionException(Page.MENU_SERVLET, resexception.getString("no_permission_to_perform_data_entry"), "1"); } }</code><technical_language>This prevent users Monitor access of studies entering data. check specific study's user role</technical_language>

Target:
private void checkUpdateDataPermission(HttpServletRequest request) throws InsufficientPermissionException { Boolean auth = true; UserAccountBean userBean =(UserAccountBean) request.getSession().getAttribute(USER_BEAN_NAME); StudyBean currentStudy = (StudyBean) request.getSession().getAttribute("study"); ArrayList userRoles = userBean.getRoles(); String submitted =(String) request.getParameter("submitted"); String checkInputs = (String)request.getParameter("checkInputs"); if(submitted !=null && submitted.equals("1") && checkInputs!=null && checkInputs.equals("1")) { for (int i = 0; i < userRoles.size(); i++) { StudyUserRoleBean studyRole = (StudyUserRoleBean) userRoles.get(i); if(studyRole.getRole().equals(Role.MONITOR) && studyRole.getStudyId() == currentStudy.getId()) { auth = false; break; } } } if(!auth) { addPageMessage(respage.getString("you_not_have_permission_update_a_CRF"), request); throw new InsufficientPermissionException(Page.MENU_SERVLET, resexception.getString("no_permission_to_perform_data_entry"), "1"); } }
Source:
<code>public String toString() { return Objects.toStringHelper(this) .omitNullValues() .add("revision", revision.getName()) <START> .add("oldRevision", oldRevision.getName()) <END> .add("path", path) .toString(); }</code><technical_language>nan</technical_language>

Target:
public String toString() { return Objects.toStringHelper(this) .omitNullValues() .add("revision", revision.getName()) .add("oldRevision", oldRevision != null ? oldRevision.getName() : null) .add("path", path) .toString(); }
Source:
<code>public String getDeletedAtDateString() { if (this.deletedAt == null) { return Const.DELETION_DATE_NOT_APPLICABLE; } else { <START> return TimeHelper.formatDateForInstructorCoursesPage(deletedAt, timeZone); <END> } }</code><technical_language>drop else branch return TimeHelper.formatDateForInstructor... right if block, i.e. java if (this.deletedAt == null) { return Const.DELETION_DATE_NOT_APPLICABLE; } return TimeHelper.formatDateForInstructorCoursesPage(deletedAt, timeZone); cleaner</technical_language>

Target:
public String getDeletedAtDateString() { if (this.deletedAt == null) { return Const.DELETION_DATE_NOT_APPLICABLE; } return TimeHelper.formatDateForInstructorCoursesPage(deletedAt, timeZone); }
Source:
<code>private void setWayGeometry_( PointList pillarNodes, long edgePointer, boolean reverse ) { if (pillarNodes != null && !pillarNodes.isEmpty()) { if (pillarNodes.getDimension() != nodeAccess.getDimension()) throw new IllegalArgumentException("Cannot use pointlist which is " + pillarNodes.getDimension() + "D for graph which is " + nodeAccess.getDimension() + "D"); long existingGeoRef = Helper.toUnsignedLong(edges.getInt(edgePointer + E_GEO)); int len = pillarNodes.getSize(); int dim = nodeAccess.getDimension(); if (existingGeoRef > 0) { long existingGeoRefPos = existingGeoRef * 4L; final int count = wayGeometry.getInt(existingGeoRefPos); if (len <= count) { if (len < count) { <START> eraseWayGeometryAtGeoRef(count, existingGeoRef); <END> } setWayGeometryAtGeoRef(pillarNodes, edgePointer, reverse, existingGeoRef); return; } } long nextGeoRef = nextGeoRef(len * dim); setWayGeometryAtGeoRef(pillarNodes, edgePointer, reverse, nextGeoRef); } else { edges.setInt(edgePointer + E_GEO, 0); } }</code><technical_language>I is cleaner: need erase this</technical_language>

Target:
private void setWayGeometry_( PointList pillarNodes, long edgePointer, boolean reverse ) { if (pillarNodes != null && !pillarNodes.isEmpty()) { if (pillarNodes.getDimension() != nodeAccess.getDimension()) throw new IllegalArgumentException("Cannot use pointlist which is " + pillarNodes.getDimension() + "D for graph which is " + nodeAccess.getDimension() + "D"); long existingGeoRef = Helper.toUnsignedLong(edges.getInt(edgePointer + E_GEO)); int len = pillarNodes.getSize(); int dim = nodeAccess.getDimension(); if (existingGeoRef > 0) { long existingGeoRefPos = existingGeoRef * 4L; final int count = wayGeometry.getInt(existingGeoRefPos); if (len <= count) { setWayGeometryAtGeoRef(pillarNodes, edgePointer, reverse, existingGeoRef); return; } } long nextGeoRef = nextGeoRef(len * dim); setWayGeometryAtGeoRef(pillarNodes, edgePointer, reverse, nextGeoRef); } else { edges.setInt(edgePointer + E_GEO, 0); } }
Source:
<code>private void moveProductsUpward() { $(allCarrouselDivs).addClass(stateTransitionStyleName); $(allCarrouselDivs).addClass(stateAboveStyleName); <START> <END> Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() { public boolean execute() { removeProductClasses(); switchInteger(); setEnabled(productInt); return false; } }, 500); }</code><technical_language>rm 116</technical_language>

Target:
private void moveProductsUpward() { toggleClass(true); Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() { public boolean execute() { removeProductClasses(); switchInteger(); setEnabled(productInt); return false; } }, animationTopDownDuration); }
Source:
<code>public Artifact getRequirementFromArtifactId(ArtifactId artId) { <START> for (Artifact art : directRequirements) { <END> if (art.getId().equals(artId.getId())) { return art; } } return null; }</code><technical_language>Nit: able do "if (art.equals(artId))"</technical_language>

Target:
public Artifact getRequirementFromArtifactId(ArtifactId artId) { for (Artifact art : directRequirements) { if (art.equals(artId)) { return art; } } return null; }
Source:
<code>public static void main(final String... args) { LOGGER.info("\n==========================================================" + "\n " + "\n Welcome to the Spring Integration Dynamic Poller Sample! " + "\n " + "\n For more information please visit: " + "\n <LINK_0> " + "\n " + "\n==========================================================" ); final AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml"); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); final DynamicPeriodicTrigger trigger = context.getBean(DynamicPeriodicTrigger.class); LOGGER.info("\n=========================================================" + "\n " + "\n Please press 'q + Enter' to quit the application. " + "\n " + "\n=========================================================" ); System.out.print("Please enter a non-negative numeric value and press <enter>: "); while (!scanner.hasNext("q")) { <START> int triggerPeriod = scanner.nextInt(); <END> System.out.println(String.format("Setting trigger period to '%s' ms", triggerPeriod)); trigger.setPeriod(triggerPeriod); System.out.print("Please enter a non-negative numeric value and press <enter>: "); } LOGGER.info("Exiting application...bye."); System.exit(0); }</code><technical_language>Need catch exceptions for invalid input, put System.exit() in a finally block</technical_language>

Target:
public static void main(final String... args) { LOGGER.info("\n==========================================================" + "\n " + "\n Welcome to the Spring Integration Dynamic Poller Sample! " + "\n " + "\n For more information please visit: " + "\n <LINK_0> " + "\n " + "\n==========================================================" ); final AbstractApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml"); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); final DynamicPeriodicTrigger trigger = context.getBean(DynamicPeriodicTrigger.class); LOGGER.info("\n=========================================================" + "\n " + "\n Please press 'q + Enter' to quit the application. " + "\n " + "\n=========================================================" ); System.out.print("Please enter a non-negative numeric value and press <enter>: "); while (true) { final String input = scanner.nextLine(); if("q".equals(input.trim())) { break; } try { int triggerPeriod = Integer.valueOf(input); System.out.println(String.format("Setting trigger period to '%s' ms", triggerPeriod)); trigger.setPeriod(triggerPeriod); } catch (Exception e) { LOGGER.error("An exception was caught: " + e); } System.out.print("Please enter a non-negative numeric value and press <enter>: "); } LOGGER.info("Exiting application...bye."); System.exit(0); }
Source:
<code><START> public DataCenter <END> reInitializeDataCenter(String dcId) throws RuntimeException { log.info("about to reinitialize dc"); DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; }</code><technical_language>public? planning of this class</technical_language>

Target:
private DataCenter reInitializeDataCenter(String dcId) throws RuntimeException { log.info("about to reinitialize dc"); DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; }
Source:
<code>public Response previewSnapshot(Action action) { validateParameters(action, "snapshot.id"); TryBackToAllSnapshotsOfVmParameters tryBackParams = new TryBackToAllSnapshotsOfVmParameters(guid, asGuid(action.getSnapshot().getId())); if (action.isSetRestoreMemory()) { tryBackParams.setRestoreMemory(action.isRestoreMemory()); } if (action.isSetDisks()) { List<DiskImage> disks = getParent().mapDisks(action.getDisks()); if (disks != null) { String noImageId = disks.stream() <START> .filter(disk -> disk.getImageId().toString().equals("00000000-0000-0000-0000-000000000000")) <END> .map(disk -> disk.getId().toString()) .collect(Collectors.joining(",")); if (!noImageId.isEmpty()) { badRequest("Missing image ids for disks: " + noImageId); } } tryBackParams.setImageIds(getDisksGuidSet(disks)); } Response response = doAction(ActionType.TryBackToAllSnapshotsOfVm, tryBackParams, action); return response; }</code><technical_language>why</technical_language>

Target:
public Response previewSnapshot(Action action) { validateParameters(action, "snapshot.id"); TryBackToAllSnapshotsOfVmParameters tryBackParams = new TryBackToAllSnapshotsOfVmParameters(guid, asGuid(action.getSnapshot().getId())); if (action.isSetRestoreMemory()) { tryBackParams.setRestoreMemory(action.isRestoreMemory()); } if (action.isSetDisks()) { List<DiskImage> disks = getParent().mapDisks(action.getDisks()); if (disks != null) { String noImageId = disks.stream() .filter(disk -> disk.getImageId().equals(Guid.Empty)) .map(disk -> disk.getId().toString()) .collect(Collectors.joining(",")); if (!noImageId.isEmpty()) { badRequest("Missing image ids for disks: " + noImageId); } } tryBackParams.setImageIds(getDisksGuidSet(disks)); } Response response = doAction(ActionType.TryBackToAllSnapshotsOfVm, tryBackParams, action); return response; }