auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object onConvert(Type targetType, Class targetTypeErasure, Object jsonSource) { <START> if (jsonSource instanceof JSONObject) { <END> LOGGER.log(Level.FINE, "potentially converting {0} {1} {2}", new Object[] {targetType, targetTypeErasure, jsonSource}); return instantiate(targetTypeErasure, (JSONObject) jsonSource); } else { LOGGER.log(Level.FINE, "ignoring non-object {0}", jsonSource); return oldInterceptor.onConvert(targetType, targetTypeErasure, jsonSource); } }</code><technical_language>JSON Arrays? a valid case</technical_language>

Target:
public Object onConvert(Type targetType, Class targetTypeErasure, Object jsonSource) { if (jsonSource instanceof JSONObject) { JSONObject json = (JSONObject) jsonSource; if (isApplicable(targetTypeErasure, json)) { LOGGER.log(Level.FINE, "switching to newInstance {0} {1}", new Object[] {targetTypeErasure.getName(), json}); try { return Jenkins.getActiveInstance().getDescriptor(targetTypeErasure).newInstance(Stapler.getCurrentRequest(), json); } catch (Exception x) { LOGGER.log(Level.WARNING, "falling back to default instantiation " + targetTypeErasure.getName() + " " + json, x); } } } else { LOGGER.log(Level.FINER, "ignoring non-object {0}", jsonSource); } return oldInterceptor.onConvert(targetType, targetTypeErasure, jsonSource); }
Source:
<code><START> private CompletionStage<RestResponse> getConfig(RestRequest request) { <END> NettyRestResponse.Builder responseBuilder = checkCacheManager(request); if (responseBuilder.getHttpStatus() == NOT_FOUND) return completedFuture(responseBuilder.build()); GlobalConfiguration globalConfiguration = Security.doAs(request.getSubject(), (PrivilegedAction<GlobalConfiguration>) () -> cacheManager.getCacheManagerConfiguration()); MediaType format = MediaTypeUtils.negotiateMediaType(request, APPLICATION_JSON, APPLICATION_XML); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); parserRegistry.serialize(baos, globalConfiguration, emptyMap()); if (format.match(APPLICATION_XML)) { responseBuilder.contentType(APPLICATION_XML); responseBuilder.entity(baos.toByteArray()); } else { responseBuilder.contentType(APPLICATION_JSON); responseBuilder.entity(jsonWriter.toJSON(globalConfiguration)); } } catch (XMLStreamException e) { responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return completedFuture(responseBuilder.build()); }</code><technical_language>suggestion cacheManager::getCacheManagerConfiguration);</technical_language>

Target:
private CompletionStage<RestResponse> getConfig(RestRequest request) { NettyRestResponse.Builder responseBuilder = checkCacheManager(request); if (responseBuilder.getHttpStatus() == NOT_FOUND) return completedFuture(responseBuilder.build()); EmbeddedCacheManager embeddedCacheManager = cacheManager.withSubject(request.getSubject()); GlobalConfiguration globalConfiguration = SecurityActions.getCacheManagerConfiguration(embeddedCacheManager); MediaType format = MediaTypeUtils.negotiateMediaType(request, APPLICATION_JSON, APPLICATION_XML); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); parserRegistry.serialize(baos, globalConfiguration, emptyMap()); if (format.match(APPLICATION_XML)) { responseBuilder.contentType(APPLICATION_XML); responseBuilder.entity(baos.toByteArray()); } else { responseBuilder.contentType(APPLICATION_JSON); responseBuilder.entity(jsonWriter.toJSON(globalConfiguration)); } } catch (XMLStreamException e) { responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return completedFuture(responseBuilder.build()); }
Source:
<code>public void seek(long position) throws IOException { inputStream.seek(position); <START> originInputStream.seek(position); <END> }</code><technical_language>done if validation is enabled</technical_language>

Target:
public void seek(long position) throws IOException { inputStream.seek(position); if (cacheValidationEnabled) { dataTierInputStream.get().seek(position); } }
Source:
<code>public List<Room> getBuildingRooms(String campusCode, String buildingCode) { Criteria criteria = new Criteria(); criteria.addEqualTo(CuCamsConstants.CapAssetApi.CAMPUS_CODE_PARAMETER, campusCode); <START> criteria.addEqualTo("buildingCode", buildingCode); <END> Query query = QueryFactory.newQuery(Room.class, criteria); return (List<Room>) getPersistenceBrokerTemplate().getCollectionByQuery(query); }</code><technical_language>good constants for property names</technical_language>

Target:
public List<Room> getBuildingRooms(String campusCode, String buildingCode) { Criteria criteria = new Criteria(); criteria.addEqualTo(CuCamsConstants.CapAssetApi.CAMPUS_CODE_PARAMETER, campusCode); criteria.addEqualTo(KFSPropertyConstants.BUILDING_CODE, buildingCode); Query query = QueryFactory.newQuery(Room.class, criteria); return (List<Room>) getPersistenceBrokerTemplate().getCollectionByQuery(query); }
Source:
<code>switch (platform) { case "win32": COLUMN_TRIM= 4; break; <START> case "cocoa": END> COLUMN_TRIM= 24; break; default: COLUMN_TRIM= 3; break; }</code><technical_language>Sorry, this is a behavior change. code COLUMN_TRIM=3 for cocoa, too. This change is switch strings instead of ifs. this a purely mechanical change. try fix oddities in this change. Do in a separate change this one</technical_language>

Target:
switch (platform) { case "win32": COLUMN_TRIM= 4; break; case "carbon": COLUMN_TRIM= 24; break; default: COLUMN_TRIM= 3; break; }
Source:
<code>public <T> T doWithRetries(Callable<T> action, String actionName, String partitionPath) throws CloudStorageException { int attempts = 0; while (attempts < maxAttempts) { try { return action.call(); } catch (Exception e) { attempts++; throwOrDelay(e, actionName, partitionPath, attempts); } } throw new CloudStorageException( <START> actionName + (!Utils.isNullOrEmpty(partitionPath) ? (" failed partition " + partitionPath) : "") + " made " + attempts <END> + " attempts"); }</code><technical_language>word "failed" need way</technical_language>

Target:
public <T> T doWithRetries(Callable<T> action, String actionName, String partitionPath) throws CloudStorageException { int attempts = 0; while (attempts < maxAttempts) { try { return action.call(); } catch (Exception e) { attempts++; throwOrDelay(e, actionName, partitionPath, attempts); } } throw new CloudStorageException( actionName + " failed, " + (!Utils.isNullOrEmpty(partitionPath) ? ("partition " + partitionPath) : "") + " made " + attempts + " attempts"); }
Source:
<code>public void testBuildBlobId() throws Exception { for (Short version : versions) { for (Boolean shouldUseSetter : setterChoice) { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, null, referenceDatacenterId, referenceAccountId, referenceContainerId, <START> referencePartitionId, shouldUseSetter); <END> buildBlobIdAndAssert(version, referenceFlag, null, referenceAccountId, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, null, referenceContainerId, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, null, referencePartitionId, shouldUseSetter); buildBlobIdAndAssert(version, null, null, null, null, referencePartitionId, shouldUseSetter); } } }</code><technical_language>null values for new fields in V2</technical_language>

Target:
public void testBuildBlobId() throws Exception { buildBlobIdAndAssert(version, referenceFlag, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId); }
Source:
<code>protected Boolean visitBetweenPredicate(BetweenPredicate actual, Expression expectedExpression) { if (expectedExpression instanceof BetweenPredicate) { BetweenPredicate expected = (BetweenPredicate) expectedExpression; <START> return process(actual.getMin(), expected.getMin()) && process(actual.getMax(), expected.getMax()); <END> } return false; }</code><technical_language>needs process "value" predicate, too</technical_language>

Target:
protected Boolean visitBetweenPredicate(BetweenPredicate actual, Expression expectedExpression) { if (expectedExpression instanceof BetweenPredicate) { BetweenPredicate expected = (BetweenPredicate) expectedExpression; return process(actual.getValue(), expected.getValue()) && process(actual.getMin(), expected.getMin()) && process(actual.getMax(), expected.getMax()); } return false; }
Source:
<code>public List<Host> addHosts(PerunSession sess, List<Host> hosts, Facility facility) throws FacilityNotExistsException, InternalErrorException, PrivilegeException, HostExistsException { Utils.checkPerunSession(sess); getFacilitiesManagerBl().checkFacilityExists(sess, facility); if (!AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { throw new PrivilegeException(sess, "addHosts"); } Utils.notNull(hosts, "hosts"); for(Host host: hosts) { List<Facility> facilitiesByHostname = getFacilitiesManagerBl().getFacilitiesByHostName(sess, host.getHostname()); List<Facility> facilitiesByDestination = getFacilitiesByDestination(sess, host.getHostname()); if(facilitiesByHostname.isEmpty() && facilitiesByDestination.isEmpty()) { continue; } if(!facilitiesByHostname.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByHostname) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } if(!facilitiesByDestination.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByDestination) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } <START> throw new PrivilegeException(sess, "You can't add these hosts."); <END> } return getFacilitiesManagerBl().addHosts(sess, hosts, facility); }</code><technical_language>user host is problem of privilegeException. privilages for adding specific host</technical_language>

Target:
public List<Host> addHosts(PerunSession sess, List<Host> hosts, Facility facility) throws FacilityNotExistsException, InternalErrorException, PrivilegeException, HostExistsException { Utils.checkPerunSession(sess); getFacilitiesManagerBl().checkFacilityExists(sess, facility); if (!AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { throw new PrivilegeException(sess, "addHosts"); } Utils.notNull(hosts, "hosts"); for(Host host: hosts) { List<Facility> facilitiesByHostname = getFacilitiesManagerBl().getFacilitiesByHostName(sess, host.getHostname()); List<Facility> facilitiesByDestination = getFacilitiesByDestination(sess, host.getHostname()); if(facilitiesByHostname.isEmpty() && facilitiesByDestination.isEmpty()) { continue; } if(!facilitiesByHostname.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByHostname) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } if(!facilitiesByDestination.isEmpty()) { boolean hasRight = false; for(Facility f: facilitiesByDestination) { if(AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, f)) { hasRight = true; break; } } if(hasRight) continue; } throw new PrivilegeException(sess, "You can't add host " + host + ", because you don't have privileges to use this hostName"); } return getFacilitiesManagerBl().addHosts(sess, hosts, facility); }
Source:
<code>public static boolean reportErrorToProducer(PMode pmode) { boolean notifyProducer = false; if(pmode.getErrorHandling() != null) { <START> if(pmode.getErrorHandling().getReport() != null) { <END> notifyProducer = pmode.getErrorHandling().getReport().isProcessErrorNotifyProducer(); } } return notifyProducer; }</code><technical_language>merge if statements</technical_language>

Target:
public static boolean reportErrorToProducer(PMode pmode) { boolean notifyProducer = false; if(pmode.getErrorHandling() != null && pmode.getErrorHandling().getReport() != null) { notifyProducer = pmode.getErrorHandling().getReport().isProcessErrorNotifyProducer(); } return notifyProducer; }
Source:
<code>public IReadAccess getReader(IContentAccessFactory factory) { <START> return factory.getPluginRepositoryReader(RepositoryHelper.appendPath( "src/main", basePath)); <END> }</code><technical_language>@diogofscmariano this right</technical_language>

Target:
public IReadAccess getReader(IContentAccessFactory factory) { return factory.getPluginRepositoryReader(RepositoryHelper.appendPath("..", basePath)); }
Source:
<code>public int hashCode() { <START> int result = spec != null ? spec.hashCode() : 0; <END> result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (config != null ? config.hashCode() : 0); return result; }</code><technical_language>return Objects.hashCode(spec, name, config); auto-generated, I accept verbose version, soon modifying code put in easier-to-read-and-maintain approach</technical_language>

Target:
public int hashCode() { return Objects.hashCode(spec, name, config); }
Source:
<code>public ResponseEntity<?> deleteSubscription(@PathVariable("id") final String subscriptionId, <START> final NativeWebRequest request) { <END> subscriptionService.deleteSubscription(subscriptionId); return status(NO_CONTENT).build(); }</code><technical_language>declare throws please</technical_language>

Target:
public ResponseEntity<?> deleteSubscription(@PathVariable("id") final String subscriptionId, final NativeWebRequest request) throws DbWriteOperationsBlockedException, NoSuchSubscriptionException, NoSuchEventTypeException, ServiceTemporarilyUnavailableException, InternalNakadiException { subscriptionService.deleteSubscription(subscriptionId); return status(NO_CONTENT).build(); }
Source:
<code>protected void doRun(IProgressMonitor monitor) throws CoreException { <START> if (monitor == null) { monitor = new NullProgressMonitor(); } <END> SubMonitor progress = SubMonitor.convert(monitor, MakeUIPlugin.getResourceString("MakeCCWizard.task_name"), 10); super.doRun(progress.split(9)); if (newProject != null) { CCorePlugin.getDefault().convertProjectFromCtoCC(newProject, progress.split(1)); } monitor.done(); }</code><technical_language>SubMonitor.convert() takes care of that. needed for monitor.done() end. is this called from? do monitor.done() calling site? SubMonitor consistently, call done() anymore, _except_ for top-level monitors get passed in Job.run() similar framework operations. SubMonitor inconsistently in a call chain lead strange effects, convert(original_monitor) consume ticks left in original_monitor. if switches SubMonitor, drill top-level Job.run() similar call sites. I if done here</technical_language>

Target:
protected void doRun(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, MakeUIPlugin.getResourceString("MakeCCWizard.task_name"), 10); super.doRun(progress.split(9)); if (newProject != null) { CCorePlugin.getDefault().convertProjectFromCtoCC(newProject, progress.split(1)); } else progress.worked(1); }
Source:
<code>public List<Map<String, String>> getDataRows() { return dataRows.stream().map(m -> { return m.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().toString())); <START> }).collect(Collectors.toList()); <END> }</code><technical_language>Note this change strictly compatible. is *binary* compatible, resulting object originally mutable is guaranteed mutable. In general, return mutable objects methods this, if behavior needs guaranteed (in case Collectors.toCollection(Supplier) used</technical_language>

Target:
public List<Map<String, String>> getDataRows() { return getDataRowsAsCompositeVariants().stream().map(m -> { return m.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().toString())); }).collect(Collectors.toList()); }
Source:
<code>public boolean bat$isAwake() { <START> return getIsBatHanging(); <END> }</code><technical_language>!getIsBatHanging() method is</technical_language>

Target:
public boolean bat$isAwake() { return !getIsBatHanging(); }
Source:
<code>private int getNumRubricRows(int questionNum) { <START> return getQuestionForm(questionNum).findElements(By.cssSelector("tm-rubric-question-edit-details-form tr")).size(); <END> }</code><technical_language>Is a selector here? While this works, rely Angular component name is preferred</technical_language>

Target:
private int getNumRubricRows(int questionNum) { return getQuestionForm(questionNum).findElements(By.cssSelector("#rubric-table tr")).size(); }
Source:
<code>public Action getNextEventAction() { if (fNextEventAction == null) { fNextEventAction = new Action() { @Override public void runWithEvent(Event event) { boolean extend = (event.stateMask & SWT.SHIFT) != 0; selectNextEvent(extend); } }; <START> fNextEventAction.setText(Messages.TmfTimeGraphViewer_NextStateChangeActionNameText); <END> fNextEventAction.setToolTipText(Messages.TmfTimeGraphViewer_NextStateChangeActionToolTipText); fNextEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEXT_EVENT)); } return fNextEventAction; }</code><technical_language>point of view of time graph viewer, actions select next/previous event (time graph's ITimeEvent, trace's ITmfEvent time graph about). I if in Control Flow/Resources view override action texts</technical_language>

Target:
public Action getNextEventAction() { if (fNextEventAction == null) { fNextEventAction = new Action() { @Override public void runWithEvent(Event event) { boolean extend = (event.stateMask & SWT.SHIFT) != 0; selectNextEvent(extend); } }; fNextEventAction.setText(Messages.TmfTimeGraphViewer_NextStateChangeActionNameText); fNextEventAction.setToolTipText(Messages.TmfTimeGraphViewer_NextStateChangeActionToolTipText); fNextEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_NEXT_STATE_CHANGE)); } return fNextEventAction; }
Source:
<code>public void commit() throws CommitException { if (updates.size() == 0) { deleteWeakRow(); return; } for (Map<Column,Bytes> cols : updates.values()) stats.incrementEntriesSet(cols.size()); CommitData cd = createCommitData(); try { if (!preCommit(cd)) { readUnread(cd); throw new CommitException(); } long commitTs = OracleClient.getInstance(env).getTimestamp(); if (commitPrimaryColumn(cd, commitTs)) { finishCommit(cd, commitTs); } else { throw new CommitException(); } } catch (CommitException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } finally { stats.setFinishTime(System.currentTimeMillis()); for (Set<Column> cols : cd.getRejected().values()) { stats.incrementCollisions(cols.size()); } <START> close(); <END> } }</code><technical_language>is execution path in this method close() is called</technical_language>

Target:
public synchronized void commit() throws CommitException { if (status == TxStatus.CLOSED) { throw new CommitException("Transaction was previously closed"); } else if (status == TxStatus.COMMITTED) { throw new CommitException("Transaction was previously committed"); } if (updates.size() == 0) { deleteWeakRow(); return; } for (Map<Column,Bytes> cols : updates.values()) stats.incrementEntriesSet(cols.size()); CommitData cd = createCommitData(); try { if (!preCommit(cd)) { readUnread(cd); throw new CommitException("Pre-commit failed"); } long commitTs = OracleClient.getInstance(env).getTimestamp(); if (commitPrimaryColumn(cd, commitTs)) { finishCommit(cd, commitTs); } else { throw new CommitException("Commit failed"); } } catch (CommitException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } finally { stats.setFinishTime(System.currentTimeMillis()); for (Set<Column> cols : cd.getRejected().values()) { stats.incrementCollisions(cols.size()); } status = TxStatus.COMMITTED; } }
Source:
<code>public String[] getConfigInformation(int id) { try { try { Class.forName(jdbcDriver); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection connection = DriverManager.getConnection(mysqlURL, username, password); String sql = "SELECT teamName, description, datasetName, evaluator, id FROM configurations WHERE id = " + id + ";"; PreparedStatement insertStmt = connection.prepareStatement(sql); ResultSet configInfoList = insertStmt.executeQuery(); configInfoList.next(); <START> String configInfo[] = new String[6]; <END> configInfo[0] = configInfoList.getString(1); configInfo[1] = configInfoList.getString(2); configInfo[2] = configInfoList.getString(3); configInfo[3] = "task_variant_b"; configInfo[4] = configInfoList.getString(4); configInfo[5] = Integer.toString(configInfoList.getInt(5)); connection.close(); return configInfo; } catch (SQLException e) { e.printStackTrace(); return null; } }</code><technical_language>return List<String[]>, return List<Configuration></technical_language>

Target:
public models.Configuration getConfigInformation(int id) { try { try { Class.forName(jdbcDriver); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection connection = DriverManager.getConnection(mysqlURL, username, password); String sql = "SELECT teamName, description, datasetName, evaluator, id FROM configurations WHERE id = " + id + ";"; PreparedStatement insertStmt = connection.prepareStatement(sql); ResultSet configInfoList = insertStmt.executeQuery(); configInfoList.next(); models.Configuration config = new models.Configuration(configInfoList.getString(1), configInfoList.getString(2), configInfoList.getString(3), "task_variant_b", configInfoList.getString(4), Integer.toString(configInfoList.getInt(5))); connection.close(); return config; } catch (SQLException e) { e.printStackTrace(); return null; } }
Source:
<code>public Pair<List<Guid>, Guid> balance(VDSGroup cluster, List<VDS> hosts, Map<String, String> parameters, ArrayList<String> messages) { final Pair<List<Guid>, Guid> migrationRule = super.balance(cluster, hosts, parameters, messages); <START> List<VDS> allHosts = DbFacade.getInstance().getVdsDao().getAllForVdsGroup(cluster.getId()); <END> Pair<VDS, VDSStatus> action = evaluatePowerManagementSituation( getDownHosts(allHosts, parameters), getMaintenanceHosts(allHosts, parameters), getEmptyHosts(allHosts, parameters), parameters ); if (action != null) processPmAction(action); return migrationRule; }</code><technical_language>I prefer handling host migratable vms (###) host list supplied in method params</technical_language>

Target:
public Pair<List<Guid>, Guid> balance(VDSGroup cluster, List<VDS> hosts, Map<String, String> parameters, ArrayList<String> messages) { final Pair<List<Guid>, Guid> migrationRule = super.balance(cluster, hosts, parameters, messages); List<VDS> allHosts = DbFacade.getInstance().getVdsDao().getAllForVdsGroup(cluster.getId()); Pair<VDS, VDSStatus> action = evaluatePowerManagementSituation( getDownHosts(allHosts, parameters), getMaintenanceHosts(allHosts, parameters), getEmptyHosts(allHosts, parameters), parameters); if (action != null) { processPmAction(action); } return migrationRule; }
Source:
<code>public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { <START> if (cursor == null) { <END> return; } callingFragment.setPageSaved(cursor.getCount() != 0); callingFragment.setSavedPageCheckComplete(true); }</code><technical_language>Is for this null? return a CursorLoader in onCreateLoader()</technical_language>

Target:
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { callingFragment.setPageSaved(cursor.getCount() != 0); callingFragment.setSavedPageCheckComplete(true); Menu optionsMenu = callingFragment.getOptionsMenu(); if (optionsMenu != null) { MenuItem savePageItem = optionsMenu.findItem(R.id.menu_page_save); if (savePageItem == null) { return; } callingFragment.updateSavePageMenuItem(savePageItem); } }
Source:
<code>public Object apply(ConfigResource resource) throws AuthException, BadRequestException, ResourceConflictException, Exception { final Map<String, CapabilityInfo> output = Maps.newTreeMap(); Class<? extends CapabilityConstants> bundleClass = CapabilityConstants.get().getClass(); CapabilityConstants c = CapabilityConstants.get(); <START> for (String s : Splitter.on(", ").split(CapabilityConstants.get().capabilityNames)) { <END> String v = (String) bundleClass.getField(s).get(c); CapabilityInfo info = new CapabilityInfo(s, v); output.put(s, info); } return OutputFormat.JSON.newGson().toJsonTree(output, new TypeToken<Map<String, GroupInfo>>() {}.getType()); }</code><technical_language>I need this duplication. Instead drive GlobalCapability.getAllNames() here. duplicate entry in properties file a hack for GWT</technical_language>

Target:
public Map<String, CapabilityInfo> apply(ConfigResource resource) throws AuthException, BadRequestException, ResourceConflictException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException { Map<String, CapabilityInfo> output = Maps.newTreeMap(); Class<? extends CapabilityConstants> bundleClass = CapabilityConstants.get().getClass(); CapabilityConstants c = CapabilityConstants.get(); for (String id : GlobalCapability.getAllNames()) { String name = (String) bundleClass.getField(id).get(c); output.put(id, new CapabilityInfo(id, name)); } return output; }
Source:
<code>private void cancelJob(GerritTriggeredEvent event) { <START> List<hudson.model.Queue.Item> itemsInQueue = Queue.getInstance().getItems(myProject); <END> for (hudson.model.Queue.Item item : itemsInQueue) { if (checkCausedByGerrit(event, item.getCauses())) { Queue.getInstance().cancel(item); } } for (Computer c : Hudson.getInstance().getComputers()) { List<Executor> executors = new ArrayList<Executor>(); executors.addAll(c.getOneOffExecutors()); executors.addAll(c.getExecutors()); for (Executor e : executors) { if (e.getCurrentExecutable() instanceof Run<?,?>) { Run<?,?> run = (Run<?,?>) e.getCurrentExecutable(); if (checkCausedByGerrit(event, run.getCauses())) { e.interrupt( Result.ABORTED, new NewPatchSetInterruption() ); } } } } }</code><technical_language>myProject exist anymore merged pull request. getJob job instead. build failure</technical_language>

Target:
private void cancelJob(GerritTriggeredEvent event) { List<hudson.model.Queue.Item> itemsInQueue = Queue.getInstance().getItems(getJob()); for (hudson.model.Queue.Item item : itemsInQueue) { if (checkCausedByGerrit(event, item.getCauses())) { Queue.getInstance().cancel(item); } } for (Computer c : Jenkins.getInstance().getComputers()) { List<Executor> executors = new ArrayList<Executor>(); executors.addAll(c.getOneOffExecutors()); executors.addAll(c.getExecutors()); for (Executor e : executors) { if (e.getCurrentExecutable() instanceof Run<?,?>) { Run<?,?> run = (Run<?,?>) e.getCurrentExecutable(); if (checkCausedByGerrit(event, run.getCauses())) { e.interrupt( Result.ABORTED, new NewPatchSetInterruption() ); } } } } }
Source:
<code>private void process() { boolean justProcessedEquals = false; while (pos < max) { char ch = toProcess[pos]; if (justProcessedEquals) { if (!isWhitespace(ch) && ch != 0) { lexArgValueIdentifier(); } justProcessedEquals = false; continue; } if (isAlphabetic(ch) || isDigit(ch) || ch == '_' || ch == '.') { lexIdentifier(); } else { switch (ch) { case '&': pushCharToken(TokenKind.AMPERSAND); break; case '<': pushCharToken(TokenKind.SPLIT_OPEN); break; case '>': pushCharToken(TokenKind.SPLIT_CLOSE); break; case '|': if (isTwoCharToken(TokenKind.DOUBLE_PIPE)) { pushPairToken(TokenKind.DOUBLE_PIPE); } else { pushPairToken(TokenKind.PIPE); } break; case '-': if (!isTwoCharToken(TokenKind.DOUBLE_MINUS)) { throw new JobSpecificationException( expressionString, pos, JobDSLMessage.MISSING_CHARACTER, "-"); } pushPairToken(TokenKind.DOUBLE_MINUS); break; case '=': justProcessedEquals = true; pushCharToken(TokenKind.EQUALS); break; case ' ': case '\t': case '\r': pos++; break; <START> case '\n': <END> pos++; break; case '(': pushCharToken(TokenKind.OPEN_PAREN); break; case ')': pushCharToken(TokenKind.CLOSE_PAREN); break; case '\'': lexQuotedStringLiteral(); break; case '"': lexDoubleQuotedStringLiteral(); break; case 0: pos++; break; case '\\': throw new StreamDefinitionException( expressionString, pos, XDDSLMessages.UNEXPECTED_ESCAPE_CHAR); default: throw new StreamDefinitionException( expressionString, pos, XDDSLMessages.UNEXPECTED_DATA, Character.valueOf(ch).toString()); } } } }</code><technical_language>move \n other cases: i.e. ' ', '\t', '\r' a</technical_language>

Target:
private void process() { boolean justProcessedEquals = false; while (pos < max) { char ch = toProcess[pos]; if (justProcessedEquals) { if (!isWhitespace(ch) && ch != 0) { lexArgValueIdentifier(); } justProcessedEquals = false; continue; } if (isAlphabetic(ch) || isDigit(ch) || ch == '_' || ch == '.') { lexIdentifier(); } else { switch (ch) { case '&': pushCharToken(TokenKind.AMPERSAND); break; case '<': pushCharToken(TokenKind.SPLIT_OPEN); break; case '>': pushCharToken(TokenKind.SPLIT_CLOSE); break; case '|': if (isTwoCharToken(TokenKind.DOUBLE_PIPE)) { pushPairToken(TokenKind.DOUBLE_PIPE); } else { pushPairToken(TokenKind.PIPE); } break; case '-': if (!isTwoCharToken(TokenKind.DOUBLE_MINUS)) { throw new JobSpecificationException( expressionString, pos, JobDSLMessage.MISSING_CHARACTER, "-"); } pushPairToken(TokenKind.DOUBLE_MINUS); break; case '=': justProcessedEquals = true; pushCharToken(TokenKind.EQUALS); break; case ' ': case '\t': case '\r': case '\n': pos++; break; case '(': pushCharToken(TokenKind.OPEN_PAREN); break; case ')': pushCharToken(TokenKind.CLOSE_PAREN); break; case '\'': lexQuotedStringLiteral(); break; case '"': lexDoubleQuotedStringLiteral(); break; case 0: pos++; break; case '\\': throw new JobSpecificationException( expressionString, pos, JobDSLMessage.UNEXPECTED_ESCAPE_CHAR); default: throw new JobSpecificationException( expressionString, pos, JobDSLMessage.UNEXPECTED_DATA, Character.valueOf(ch).toString()); } } } }
Source:
<code>public PythonFunctionRegistrar getPythonFunctionRegistrar() { <START> Preconditions.checkNotNull(pyFuncReg); <END> return pyFuncReg; }</code><technical_language>write this is needed</technical_language>

Target:
public PythonFunctionRegistrar getPythonFunctionRegistrar() throws DbException { PythonFunctionRegistrar pyFuncRegistrar = null; if (!execEnvVars.containsKey(MyriaConstants.EXEC_ENV_VAR_TEST_MODE)) { if (getLocalSubQuery() instanceof WorkerSubQuery) { pyFuncRegistrar = ((WorkerSubQuery) getLocalSubQuery()).getWorker().getPythonFunctionRegistrar(); } } return pyFuncRegistrar; }
Source:
<code>public Schema getSchema(FormatContext context) { if (conf.containsMacro(PathTrackingConfig.NAME_SCHEMA) || !Strings.isNullOrEmpty(conf.schema)) { return super.getSchema(context); } String filePath = conf.getProperties().getProperties().getOrDefault("path", null); try { Job job = JobUtils.createInstance(); Configuration hconf = job.getConfiguration(); <START> final Path file = conf.getFilePathForSchemaGeneration(filePath, "parquet", hconf); <END> final ParquetReader reader = AvroParquetReader.builder(file).build(); GenericData.Record record = (GenericData.Record) reader.read(); return Schema.parseJson(record.getSchema().toString()); } catch (IOException e) { context.getFailureCollector().addFailure("Schema error", e.getMessage()); } return super.getSchema(context); }</code><technical_language>Reader needs closing ? If in final block</technical_language>

Target:
public Schema getSchema(FormatContext context) { if (conf.containsMacro(PathTrackingConfig.NAME_SCHEMA) || !Strings.isNullOrEmpty(conf.schema)) { return super.getSchema(context); } try { return getDefaultSchema(context); } catch (IOException e) { throw new IllegalArgumentException("Invalid schema: " + e.getMessage(), e); } }
Source:
<code>protected void modified(Map<String, Object> config) { if (config != null) { <START> this.defaultServiceId = (String) config.get("default"); <END> } }</code><technical_language>'this.' is needed here. I personally prefer remove needed..</technical_language>

Target:
protected void modified(Map<String, Object> config) { if (config != null) { defaultServiceId = (String) config.get("default"); } }
Source:
<code>protected void handleNotificationEvent(final Notification notification) { Set<EditPart> partToRefresh1 = DiagramElementEditPartOperation.handleNotificationEvent(this, notification, false); for (EditPart editPart : partToRefresh1) { editPart.refresh(); } super.handleNotificationEvent(notification); Set<EditPart> partToRefresh2 = AbstractDiagramNodeEditPartOperation.handleNotificationEvent(this, notification, false); List<EditPart> partToRefreshFromNode = <START> partToRefresh2.stream().filter(part->!partToRefresh1.contains(part)).collect(Collectors.toList()); <END> for (EditPart editPart : partToRefreshFromNode) { editPart.refresh(); } handleDefaultSizeNotification(notification); if (NotationPackage.eINSTANCE.getDrawerStyle_Collapsed() == notification.getFeature()) { refreshBounds(); } if (isRegion() && getParent() != null && new NotificationQuery(notification).isNotationLayoutChange()) { EditPart regionContainer = getParent().getParent(); if (regionContainer instanceof AbstractDiagramContainerEditPart && shouldRefreshRegionContainerBounds(regionContainer)) { ((AbstractDiagramContainerEditPart) regionContainer).refreshBounds(); } } }</code><technical_language>partToRefresh2.removeAll(partToRefresh1): simplest solutions :-)</technical_language>

Target:
protected void handleNotificationEvent(final Notification notification) { Set<EditPart> partToRefresh1 = DiagramElementEditPartOperation.handleNotificationEvent(this, notification, false); for (EditPart editPart : partToRefresh1) { editPart.refresh(); } super.handleNotificationEvent(notification); Set<EditPart> partToRefresh2 = AbstractDiagramNodeEditPartOperation.handleNotificationEvent(this, notification, false); partToRefresh2.removeAll(partToRefresh1); for (EditPart editPart : partToRefresh2) { editPart.refresh(); } handleDefaultSizeNotification(notification); if (NotationPackage.eINSTANCE.getDrawerStyle_Collapsed() == notification.getFeature()) { refreshBounds(); } if (isRegion() && getParent() != null && new NotificationQuery(notification).isNotationLayoutChange()) { EditPart regionContainer = getParent().getParent(); if (regionContainer instanceof AbstractDiagramContainerEditPart && shouldRefreshRegionContainerBounds(regionContainer)) { ((AbstractDiagramContainerEditPart) regionContainer).refreshBounds(); } } }
Source:
<code>private AddressProvider createAddressProvider(ClientConfig config) { boolean discoveryEnabled = new HazelcastProperties(config.getProperties()) .getBoolean(ClientProperty.DISCOVERY_SPI_ENABLED); ClientAwsConfig awsConfig = config.getNetworkConfig().getAwsConfig(); List<String> userConfiguredAddresses = config.getNetworkConfig().getAddresses(); <START> if (discoveryEnabled || (awsConfig != null && awsConfig.isEnabled()) || !userConfiguredAddresses.isEmpty()) { <END> return null; } return new AddressProvider() { @Override public Collection<Address> loadAddresses() { Collection<Address> possibleAddresses = new ArrayList<Address>(); for (Address address : getKnownAddresses()) { Collection<Address> addresses = AddressHelper.getPossibleSocketAddresses(address.getPort(), address.getHost(), 1); possibleAddresses.addAll(addresses); } return possibleAddresses; } }; }</code><technical_language>TBH I find this useful. condition is long, previous approach nice advantage - right variable's name, means. I vote for previous approach then</technical_language>

Target:
private AddressProvider createAddressProvider(ClientConfig config) { boolean discoveryEnabled = new HazelcastProperties(config.getProperties()) .getBoolean(ClientProperty.DISCOVERY_SPI_ENABLED); ClientAwsConfig awsConfig = config.getNetworkConfig().getAwsConfig(); List<String> userConfiguredAddresses = config.getNetworkConfig().getAddresses(); boolean isAtLeastAProviderConfigured = discoveryEnabled || (awsConfig != null && awsConfig.isEnabled()) || !userConfiguredAddresses.isEmpty(); if (isAtLeastAProviderConfigured) { return null; } return new AddressProvider() { @Override public Collection<Address> loadAddresses() { Collection<Address> possibleAddresses = new ArrayList<Address>(); for (Address address : getKnownAddresses()) { Collection<Address> addresses = AddressHelper.getPossibleSocketAddresses(address.getPort(), address.getHost(), 1); possibleAddresses.addAll(addresses); } return possibleAddresses; } }; }
Source:
<code>public static <T> T getInstance( Injector injector, String configClassName, Class<? extends T> classRunByCoordinator, Class<? extends T> defaultClass ) throws ClassNotFoundException { if (configClassName != null) { @SuppressWarnings("unchecked") final T instance = (T) injector.getInstance(Class.forName(configClassName)); return instance; } if (classRunByCoordinator != null && isCoordinator(injector)) { return injector.getInstance(classRunByCoordinator); } if (defaultClass != null) { return injector.getInstance(defaultClass); } <START> return null; <END> }</code><technical_language>returning null for method. Is a failure? IllegalArgumentException? In case, avoid returning null in a simpler method</technical_language>

Target:
private static <T> T getInstance( Injector injector, String configClassName, Class<? extends T> classRunByCoordinator, Class<? extends T> defaultClass ) throws ClassNotFoundException { if (configClassName != null) { @SuppressWarnings("unchecked") final T instance = (T) injector.getInstance(Class.forName(configClassName)); return instance; } if (isCoordinator(injector)) { return injector.getInstance(classRunByCoordinator); } return injector.getInstance(defaultClass); }
Source:
<code>private void validateForRequireDrug(DrugOrder order, Errors errors) { AdministrationService administrationService = Context.getAdministrationService(); <START> String requireDrug = administrationService.getGlobalProperty( <END> OpenmrsConstants.GLOBAL_PROPERTY_DRUG_ORDER_REQUIRE_DRUG, "false"); if (requireDrug == null || (requireDrug != null && Boolean.parseBoolean(requireDrug))) { if (order.getDrug() == null) { ValidationUtils.rejectIfEmpty(errors, "drug", "DrugOrder.error.drugIsRequire"); } } }</code><technical_language>If administrationService.getGlobalPropertyValue(String propertyName, T defaultValue), simplify if clause line 124</technical_language>

Target:
private void validateForRequireDrug(DrugOrder order, Errors errors) { AdministrationService administrationService = Context.getAdministrationService(); String requireDrug = administrationService.getGlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DRUG_ORDER_REQUIRE_DRUG, "false"); if (Boolean.parseBoolean(requireDrug)) { if (order.getDrug() == null) { ValidationUtils.rejectIfEmpty(errors, "drug", "DrugOrder.error.drugIsRequired"); } } }
Source:
<code>public void onCloseFileSystem(final JGitFileSystem fileSystem) { fsManager.addClosedFileSystems(fileSystem); synchronized (postponedEventsLock) { fileSystem.clearPostponedWatchEvents(); } if (fsManager.allTheFSAreClosed()) { forceStopDaemon(); shutdownSSH(); <START> shutdownCluster(); <END> } }</code><technical_language>@jhrcek close jms connection here. @adrielparedes a name is shutdown eventsmanager right</technical_language>

Target:
public void onCloseFileSystem(final JGitFileSystem fileSystem) { fsManager.addClosedFileSystems(fileSystem); synchronized (postponedEventsLock) { fileSystem.clearPostponedWatchEvents(); } if (fsManager.allTheFSAreClosed()) { forceStopDaemon(); shutdownSSH(); shutdownEventsManager(); } }
Source:
<code>public InterpolatedSmileFunction(final GeneralSmileInterpolator interpolator, final double forward, final double[] strikes, final double expiry, final double[] impliedVols) { ArgumentChecker.notNull(interpolator, "interpolator"); ArgumentChecker.notNull(strikes, "strikes"); ArgumentChecker.notNull(impliedVols, "impliedVols"); <START> <END> _interpolator = interpolator; _smileFunction = interpolator.getVolatilityFunction(forward, strikes, expiry, impliedVols); }</code><technical_language>Check equal lengths for strikes impliedVols</technical_language>

Target:
public InterpolatedSmileFunction(final GeneralSmileInterpolator interpolator, final double forward, final double[] strikes, final double expiry, final double[] impliedVols) { ArgumentChecker.notNull(interpolator, "interpolator"); ArgumentChecker.notNull(strikes, "strikes"); ArgumentChecker.notNull(impliedVols, "impliedVols"); ArgumentChecker.isTrue(strikes.length == impliedVols.length, "strikes and impliedVols should have the same length"); _interpolator = interpolator; _smileFunction = interpolator.getVolatilityFunction(forward, strikes, expiry, impliedVols); }
Source:
<code>public static <T extends Comparable> DateTimeExpression<T> currentDate(Class<T> cl) { <START> return Expressions.<T>dateTimeOperation(cl, Ops.DateTimeOps.CURRENT_DATE); <END> }</code><technical_language>This explicit type argument is necessary</technical_language>

Target:
public static <T extends Comparable> DateTimeExpression<T> currentDate(Class<T> cl) { return Expressions.dateTimeOperation(cl, Ops.DateTimeOps.CURRENT_DATE); }
Source:
<code>public List<ContextMenuItem> getDefaultItems() { String idScheme = getIdScheme(); List<ContextMenuItem> items = new ArrayList<>(); for (ContextMenuItem item : this.items) { String id = item.getId(); <START> if (id != null && (id.startsWith(idScheme) && !APP_PROFILES_ID.equals(id) || id.startsWith(AIDL_LAYERS_PREFIX))) { <END> items.add(item); } } return items; }</code><technical_language>Wrong code. "if (id != null && (id.startsWith(idScheme))" only</technical_language>

Target:
public List<ContextMenuItem> getDefaultItems() { String idScheme = getIdScheme(); List<ContextMenuItem> items = new ArrayList<>(); for (ContextMenuItem item : this.items) { String id = item.getId(); if (id != null && (id.startsWith(idScheme))) { items.add(item); } } return items; }
Source:
<code>protected final Cluster getUpcomingCluster(String host, int port) throws Exception { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(host, port), getClass().getSimpleName(), OP_TIMEOUT, <START> OP_TIMEOUT, <END> null)) { return diagnosticService.getProxy(TopologyService.class).getUpcomingNodeContext().getCluster(); } }</code><technical_language>overridable getOperationTimeout() method instead</technical_language>

Target:
protected final Cluster getUpcomingCluster(String host, int port) throws Exception { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(host, port), getClass().getSimpleName(), getConnectionTimeout(), getConnectionTimeout(), null)) { return diagnosticService.getProxy(TopologyService.class).getUpcomingNodeContext().getCluster(); } }
Source:
<code>public void write(NullWritable key, AbstractFileMetadata fileMetadata) throws IOException, InterruptedException { <START> AbstractFileMetadata.Credentials sourceCredentials = fileMetadata.getCredentials(); <END> if (!sourceFilesystemMap.containsKey(sourceCredentials)) { sourceFilesystemMap.put(sourceCredentials, getSourceFilesystemFromCredentials(sourceCredentials)); } FileSystem sourceFilesystem = sourceFilesystemMap.get(sourceCredentials); Path srcPath = new Path(fileMetadata.fullPath); Path destPath = new Path(basePath + "/" + fileMetadata.basePath); FsPermission permission = new FsPermission(fileMetadata.getPermission()); if (fileMetadata.isFolder) { if (!destFileSystem.exists(destPath) && sourceFilesystem.isDirectory(srcPath)) { destFileSystem.mkdirs(destPath, permission); } return; } else if (!sourceFilesystem.exists(srcPath)) { return; } if (!enableOverwrite && destFileSystem.exists(destPath)) { return; } FSDataInputStream inputStream = sourceFilesystem.open(srcPath); FSDataOutputStream outputStream = FileSystem.create(destFileSystem, destPath, permission); byte[] buf = new byte[bufferSize]; int len; while ((len = inputStream.read(buf)) >= 0) { outputStream.write(buf, 0, len); } inputStream.close(); outputStream.close(); }</code><technical_language>insecure credentials in record. address this in a follow PR, sink require source credentials in configuration well</technical_language>

Target:
public void write(NullWritable key, AbstractFileMetadata fileMetadata) throws IOException, InterruptedException { if (fileMetadata.getRelativePath().isEmpty()) { return; } Path srcPath = new Path(fileMetadata.getFullPath()); Path destPath = new Path(basePath, fileMetadata.getRelativePath()); FsPermission permission = new FsPermission(fileMetadata.getPermission()); if (!enableOverwrite && destFileSystem.exists(destPath)) { return; } String uriString = fileMetadata.getHostURI(); if (!sourceFilesystemMap.containsKey(uriString)) { sourceFilesystemMap.put(uriString, getSourceFilesystemConnection(fileMetadata)); } FileSystem sourceFilesystem = sourceFilesystemMap.get(uriString); if (fileMetadata.isFolder()) { if (!destFileSystem.exists(destPath) && sourceFilesystem.isDirectory(srcPath)) { destFileSystem.mkdirs(destPath, permission); if (preserveOwner) { destFileSystem.setOwner(destPath, fileMetadata.getOwner(), fileMetadata.getGroup()); } } return; } else if (!sourceFilesystem.exists(srcPath)) { LOG.warn("{} doesn't exist in source filesystem.", fileMetadata.getFullPath()); return; } FSDataInputStream inputStream = sourceFilesystem.open(srcPath, bufferSize); FSDataOutputStream outputStream = FileSystem.create(destFileSystem, destPath, permission); try { byte[] buf = new byte[bufferSize]; int len; while ((len = inputStream.read(buf)) >= 0) { outputStream.write(buf, 0, len); } } finally { try { inputStream.close(); } finally { outputStream.close(); if (preserveOwner) { destFileSystem.setOwner(destPath, fileMetadata.getOwner(), fileMetadata.getGroup()); } } } }
Source:
<code>public VoltTable[] run(byte[] licenseBytes) throws InterruptedException, ExecutionException { log.info("Received user request to update database license."); VoltTable vt = constructResultTable(); Map<Integer, ClientResponse> result; result = callNTProcedureOnAllHosts("@LicenseValidation", licenseBytes).get(); String err = checkResult(result); if (err != null) { vt.addRow(VoltSystemProcedure.STATUS_FAILURE, err); return new VoltTable[] { vt }; } result = callNTProcedureOnAllHosts("@LiveLicenseUpdate").get(); err = checkResult(result); if (err != null) { vt.addRow(VoltSystemProcedure.STATUS_FAILURE, err); return new VoltTable[] { vt }; } log.info("License is updated successfully."); <START> vt.addRow(VoltSystemProcedure.STATUS_OK, ""); <END> return new VoltTable[] { vt }; }</code><technical_language>Wording nitpick - I omit "is". reads me; I a principle of grammar justify it,</technical_language>

Target:
public VoltTable[] run(byte[] licenseBytes) throws InterruptedException, ExecutionException { log.info("Received user request to update database license."); VoltTable vt = constructResultTable(); Map<Integer, ClientResponse> result; result = callNTProcedureOnAllHosts("@LicenseValidation", licenseBytes).get(); String err = checkResult(result); if (err != null) { vt.addRow(VoltSystemProcedure.STATUS_FAILURE, err); return new VoltTable[] { vt }; } result = callNTProcedureOnAllHosts("@LiveLicenseUpdate").get(); err = checkResult(result); if (err != null) { vt.addRow(VoltSystemProcedure.STATUS_FAILURE, err); return new VoltTable[] { vt }; } log.info("License updated successfully."); vt.addRow(VoltSystemProcedure.STATUS_OK, "SUCCESS"); return new VoltTable[] { vt }; }