auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public default void bulkDelete(Collection<T> objects) throws IOException { List<T> managedObjects = new ArrayList<>(); for (T object : objects) { managedObjects.add(get(object.getId())); } for (T object : managedObjects) { authorizeDeletion(object); } ValidationResult result = new ValidationResult(); for (T object : managedObjects) { result.merge(validateDeletion(object)); } result.throwIfInvalid(); for (T object : managedObjects) { beforeDelete(object); try { try { getDeletionStore().delete(object, getAuthorizationManager().getCurrentUser()); <START> } catch (DataIntegrityViolationException e) { <END> if (e.getCause() != null && e.getCause() instanceof ConstraintViolationException) { throw (ConstraintViolationException) e.getCause(); } } } catch (ConstraintViolationException e) { throw new ValidationException(String.format("%s %s cannot be deleted because it is connected to other items", object.getDeleteType(), object.getDeleteDescription())); } afterDelete(object); } }</code><technical_language>I this nested try flattened</technical_language>

Target:
public default void bulkDelete(Collection<T> objects) throws IOException { List<T> managedObjects = new ArrayList<>(); for (T object : objects) { managedObjects.add(get(object.getId())); } for (T object : managedObjects) { authorizeDeletion(object); } ValidationResult result = new ValidationResult(); for (T object : managedObjects) { result.merge(validateDeletion(object)); } result.throwIfInvalid(); for (T object : managedObjects) { beforeDelete(object); try { getDeletionStore().delete(object, getAuthorizationManager().getCurrentUser()); } catch (ConstraintViolationException | DataIntegrityViolationException e) { if (e instanceof ConstraintViolationException || e.getCause() instanceof ConstraintViolationException) { if (!(object instanceof User)) { LoggerFactory.getLogger(DeleterService.class).error("Unhandled foreign key failure on delete", e); } throw new ValidationException(String.format("%s %s cannot be deleted because it is connected to other items", object.getDeleteType(), object.getDeleteDescription())); } else { throw e; } } afterDelete(object); } }
Source:
<code>public String getCategory() { <START> return "MAINTENANCE"; <END> }</code><technical_language>JobCategory.CATEGORY_MISC</technical_language>

Target:
public String getCategory() { return JobCategory.CATEGORY_MISC; }
Source:
<code>public void bulkUpsert(List<Entry> entries) { entries.forEach(this::eagerLoadEntry); entries = filterCheckerWorkflows(entries); List<Entry> workflows = entries.stream().filter(entry -> (entry instanceof BioWorkflow)).collect(Collectors.toList()); List<Entry> tools = entries.stream().filter(entry -> (entry instanceof Tool)).collect(Collectors.toList()); <START> if (entries.isEmpty()) { <END> return; } try (RestClient restClient = RestClient.builder(new HttpHost(hostname, port, "http")).build()) { String toolsNewlineDJSON = getNDJSON(tools); HttpEntity toolsBulkEntity = new NStringEntity(toolsNewlineDJSON, ContentType.APPLICATION_JSON); Response post = restClient.performRequest("POST", "/tools/_doc/_bulk", Collections.emptyMap(), toolsBulkEntity); if (post.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new CustomWebApplicationException("Could not submit tools index to elastic search", HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e) { LOGGER.error("Could not submit tools index to elastic search. " + e.getMessage()); } try (RestClient restClient = RestClient.builder(new HttpHost(hostname, port, "http")).build()) { String workflowsNewlineDJSON = getNDJSON(workflows); HttpEntity workflowsBulkEntity = new NStringEntity(workflowsNewlineDJSON, ContentType.APPLICATION_JSON); Response post = restClient.performRequest("POST", "/workflows/_doc/_bulk", Collections.emptyMap(), workflowsBulkEntity); if (post.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new CustomWebApplicationException("Could not submit workflows index to elastic search", HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e) { LOGGER.error("Could not submit workflows index to elastic search. " + e.getMessage()); } }</code><technical_language>This check done sort entries. In theory, need test in of blocks below, e.g., if tools is empty workflows is not, I want skip block</technical_language>

Target:
public void bulkUpsert(List<Entry> entries) { entries.forEach(this::eagerLoadEntry); entries = filterCheckerWorkflows(entries); if (entries.isEmpty()) { return; } List<Entry> workflowsEntryList = entries.stream().filter(entry -> (entry instanceof BioWorkflow)).collect(Collectors.toList()); List<Entry> toolsEntryList = entries.stream().filter(entry -> (entry instanceof Tool)).collect(Collectors.toList()); if (!workflowsEntryList.isEmpty()) { postBulkUpdate("workflows", workflowsEntryList); } if (!toolsEntryList.isEmpty()) { postBulkUpdate("tools", toolsEntryList); } }
Source:
<code>public void test_scanAndRegister() { <START> MetricsRegistryImpl mr = new MetricsRegistryImpl(Logger.getLogger(MetricsRegistryImpl.class), ProbeLevel.INFO); <END> mr.newProbeBuilder() .withTag("tag1", "value1") .scanAndRegister(this); assertEquals(new HashSet<String>(asList( "[tag1=value1,unit=count,metric=probe1]", "[tag1=value1,unit=bytes,metric=secondProbe]" )), mr.getNames()); }</code><technical_language>call this metricRegistry registry</technical_language>

Target:
public void test_scanAndRegister() { MetricsRegistryImpl registry = new MetricsRegistryImpl(Logger.getLogger(MetricsRegistryImpl.class), ProbeLevel.INFO); registry.newProbeBuilder() .withTag("tag1", "value1") .scanAndRegister(this); assertProbes(registry); }
Source:
<code>public Allergy getByUniqueId(String uuid) { try { <START> int allergyId = Integer.parseInt(uuid); <END> return Context.getPatientService().getAllergy(allergyId); } catch (NumberFormatException ex) { throw new ObjectNotFoundException(); } }</code><technical_language>this Integer primary key id instead of UUID</technical_language>

Target:
public Allergy getByUniqueId(String uuid) { return Context.getPatientService().getAllergyByUuid(uuid); }
Source:
<code>protected synchronized void upgradeAccMgr() { String installedVersion = getInstalledAccMgrVersion(); if (installedVersion.equals(SalesforceSDKManager.SDK_VERSION)) { return; } writeCurVersion(ACC_MGR_KEY, SalesforceSDKManager.SDK_VERSION); if (TextUtils.isEmpty(installedVersion)) { installedVersion = getInstalledAccMgrVersion(); } try { final String majorVersionNum = installedVersion.substring(0, 3); double installedVerDouble = Double.parseDouble(majorVersionNum); if (installedVerDouble < 2.2) { upgradeTo2Dot2(); } } catch (NumberFormatException e) { <START> SalesforceLogger.getLogger(SalesforceSDKManager.SF_SDK_COMPONENT_NAME, <END> SalesforceSDKManager.getInstance().getAppContext()).log(SalesforceLogger.Level.ERROR, TAG, "Failed to parse installed version", e); } }</code><technical_language>shorter? SalesforceSDKManager a static method getLogger(String componentName) logger a e method (for errors), import static SF_SDK_COMPONENT_NAME, java SalesforceSDKManager.getLogger(SF_SDK_COMPONENT_NAME).e(TAG, "Failed ...")</technical_language>

Target:
protected synchronized void upgradeAccMgr() { String installedVersion = getInstalledAccMgrVersion(); if (installedVersion.equals(SalesforceSDKManager.SDK_VERSION)) { return; } writeCurVersion(ACC_MGR_KEY, SalesforceSDKManager.SDK_VERSION); if (TextUtils.isEmpty(installedVersion)) { installedVersion = getInstalledAccMgrVersion(); } try { final String majorVersionNum = installedVersion.substring(0, 3); double installedVerDouble = Double.parseDouble(majorVersionNum); if (installedVerDouble < 2.2) { upgradeTo2Dot2(); } } catch (NumberFormatException e) { SalesforceSDKLogger.e(TAG, "Failed to parse installed version", e); } }
Source:
<code>public void write(T entity, FieldWriter writer, OutputContext ctxt) throws IOException { writer.writeObject(publisherWriter, entity.getSource(), ctxt); if (entity instanceof Tag) { Tag tag = (Tag) entity; writer.writeField("namespace", tag.getNamespace()); writer.writeField("value", tag.getValue()); <START> writer.writeField("topic_type", tag.getType()); <END> } writer.writeField("title", entity.getTitle()); writer.writeField("description", entity.getDescription()); writer.writeField("image", entity.getImage()); writer.writeField("thumbnail", entity.getThumbnail()); }</code><technical_language>tag_type</technical_language>

Target:
public void write(T entity, FieldWriter writer, OutputContext ctxt) throws IOException { writer.writeObject(publisherWriter, entity.getSource(), ctxt); if (entity instanceof Topic) { Topic topic = (Topic) entity; writer.writeField("namespace", topic.getNamespace()); writer.writeField("value", topic.getValue()); writer.writeField("topic_type", topic.getType()); } writer.writeField("title", entity.getTitle()); writer.writeField("description", entity.getDescription()); writer.writeField("image", entity.getImage()); writer.writeField("thumbnail", entity.getThumbnail()); }
Source:
<code>public IndentLevel getSuggestedChildIndent(AbstractExpressionHandler child) { if (child instanceof CatchHandler || child instanceof FinallyHandler) { return getIndent(); } <START> final DetailAST resSpecAst = getMainAst().getFirstChild(); <END> if (resSpecAst.getType() == TokenTypes.RESOURCE_SPECIFICATION) { final DetailAST resourcesAst = resSpecAst.findFirstToken(TokenTypes.RESOURCES); final IndentLevel expIndent = new IndentLevel(getIndent(), getBasicOffset()); DetailAST resourcesAstChild = resourcesAst.findFirstToken(TokenTypes.RESOURCE); for (int i = 0; i < resourcesAst.getChildCount(); i++) { if (resourcesAstChild.getType() == TokenTypes.RESOURCE && resourcesAstChild.getLineNo() != resSpecAst.getLineNo() && resourcesAstChild.getColumnNo() != Integer.parseInt(expIndent.toString())) { logError(resourcesAstChild, "", resourcesAstChild.getColumnNo(), expIndent); } resourcesAstChild = resourcesAstChild.getNextSibling(); } } return super.getSuggestedChildIndent(child); }</code><technical_language>remove unnecessary changes</technical_language>

Target:
public IndentLevel getSuggestedChildIndent(AbstractExpressionHandler child) { if (child instanceof CatchHandler || child instanceof FinallyHandler) { return getIndent(); } return super.getSuggestedChildIndent(child); }
Source:
<code>private String pid() { try { <START> List<String> cmd = new ArrayList<>(); <END> cmd.add("sh"); cmd.add("-c"); cmd.add("ps ax | grep \"" + id + "\""); final Process process = new ProcessBuilder(cmd).start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { final Matcher matcher = PS.matcher(line); if (matcher.find()) { return matcher.group(1); } } process.waitFor(); } catch (Exception e) { e.printStackTrace(out); } return null; }</code><technical_language>Arrays.asList a bit simpler</technical_language>

Target:
private String pid() { try { final Process process = new ProcessBuilder(Arrays.asList("sh", "-c", "ps ax | grep \"" + id + "\"")).start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { final Matcher matcher = PS.matcher(line); if (matcher.find()) { return matcher.group(1); } } process.waitFor(); reader.close(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(out); } catch (Exception e) { e.printStackTrace(out); } return null; }
Source:
<code><START> private VdcBllMessages vNicProfileInUseValidationMessage(int numberOfEntities) { <END> boolean singular = numberOfEntities == 1; return singular ? VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_IN_ONE_USE : VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_IN_MANY_USES; }</code><technical_language>A method name start a verb (like get...)</technical_language>

Target:
private VdcBllMessages vNicProfileInUseValidationMessage(int numberOfEntities) { boolean singular = numberOfEntities == 1; if (singular) { return VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_IN_ONE_USE; } else { return VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_IN_MANY_USES; } }
Source:
<code>public void handle(Encounter object, User creator, Date dateCreated, String other) { for (Obs obs : object.getAllObs()) { try { <START> if (obs.getConcept().getDatatype() != null && obs.getConcept().getDatatype().isComplex()) { <END> String handlerString = Context.getConceptService().getConceptComplex(obs.getConcept().getConceptId()) .getHandler(); Context.getObsService().getHandler(handlerString).saveObs(obs); } } catch (Exception e) { log.error("Unable to save complex obs", e); } } }</code><technical_language>This change is unnecessary, datatype is required, i leave atleast a NullPointerException is thrown</technical_language>

Target:
public void handle(Encounter object, User creator, Date dateCreated, String other) { for (Obs obs : object.getAllObs()) { try { if (obs.getConcept().getDatatype().isComplex()) { String handlerString = Context.getConceptService().getConceptComplex(obs.getConcept().getConceptId()) .getHandler(); Context.getObsService().getHandler(handlerString).saveObs(obs); } } catch (Exception e) { log.error("Unable to save complex obs", e); } } }
Source:
<code>protected void processModulesAndArgs() { super.processModulesAndArgs(); if ( contains(argLoader) ) { String loadername = getValue(argLoader).toLowerCase(); if ( loadername.matches("basic.*") ) loader = LoaderEnum.Basic; else if ( loadername.matches("phas.*") ) loader = LoaderEnum.Phased; else if ( loadername.matches("seq.*") ) loader = LoaderEnum.Sequential; else if ( loadername.matches("para.*") ) loader = LoaderEnum.Parallel; else if ( loadername.matches("para.*") ) loader = LoaderEnum.Parallel; else if ( loadername.matches("light") ) loader = LoaderEnum.Light; else throw new CmdException("Unrecognized value for --loader: "+loadername); } if ( super.contains(argStats) ) { if ( ! hasValueOfTrue(argStats) && ! hasValueOfFalse(argStats) ) throw new CmdException("Not a boolean value: "+getValue(argStats)); generateStats = super.hasValueOfTrue(argStats); } if ( super.contains(argSyntax) ) { String syntax = super.getValue(argSyntax) ; Lang lang$ = RDFLanguages.nameToLang(syntax) ; if ( lang$ == null ) throw new CmdException("Can not detemine the syntax from '" + syntax + "'") ; this.lang = lang$ ; } <START> if ( super.graphName != null ) <END> lang = Lang.NTRIPLES; }</code><technical_language>if I --syntax=LANG --graph=URL syntax spec is ignored</technical_language>

Target:
protected void processModulesAndArgs() { super.processModulesAndArgs(); if ( contains(argLoader) ) { String loadername = getValue(argLoader).toLowerCase(); if ( loadername.matches("basic.*") ) loader = LoaderEnum.Basic; else if ( loadername.matches("phas.*") ) loader = LoaderEnum.Phased; else if ( loadername.matches("seq.*") ) loader = LoaderEnum.Sequential; else if ( loadername.matches("para.*") ) loader = LoaderEnum.Parallel; else if ( loadername.matches("light") ) loader = LoaderEnum.Light; else throw new CmdException("Unrecognized value for --loader: "+loadername); } if ( super.contains(argStats) ) { if ( ! hasValueOfTrue(argStats) && ! hasValueOfFalse(argStats) ) throw new CmdException("Not a boolean value: "+getValue(argStats)); generateStats = super.hasValueOfTrue(argStats); } if ( super.graphName != null ) lang = Lang.NTRIPLES; if ( super.contains(argSyntax) ) { String syntax = super.getValue(argSyntax) ; Lang lang$ = RDFLanguages.nameToLang(syntax) ; if ( lang$ == null ) throw new CmdException("Can not detemine the syntax from '" + syntax + "'") ; this.lang = lang$ ; } }
Source:
<code>public void testExecuteScriptOnBusyNode() throws Exception { FileLock fileLock = new FileLock(); Path fileLockPath = fileLock.lock(); log("Submit job"); final JobId jobId = schedulerHelper.submitJob(createJobWithLock(fileLockPath.toString())); log("Wait when node becomes busy"); RMNodeEvent event; do { event = schedulerHelper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED, TIMEOUT); } while (!event.getNodeState().equals(NodeState.BUSY)); log("Wait when task starts"); schedulerHelper.waitForEventTaskRunning(jobId, "Test task"); log("Wait some time until task launcher is started"); Thread.sleep(5000); List<ScriptResult<Object>> results = schedulerHelper.getResourceManager() .executeScript("println \"Executing Script\";", <START> "groovy", <END> TargetType.NODE_URL.name(), Sets.newSet(testNode.getNodeURL())); Assert.assertEquals(1, results.size()); ScriptResult result = results.get(0); if (result.errorOccured()) { result.getException().printStackTrace(); Assert.fail("Script execution failed"); } log("Let task finish"); fileLock.unlock(); log("Wait when job finish"); schedulerHelper.waitForEventJobFinished(jobId, TIMEOUT); schedulerHelper.waitUntilState(testNode.getNodeURL(), NodeState.FREE, TIMEOUT); log("Check job result"); checkJobResult(schedulerHelper.getSchedulerInterface(), jobId); Assert.assertEquals("After the node is freed, no active object should remain", 0, testNode.getNode().getNumberOfActiveObjects()); }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Remove this of "Thread.sleep()". [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public void testExecuteScriptOnBusyNode() throws Exception { FileLock fileLock = new FileLock(); Path fileLockPath = fileLock.lock(); log("Submit job"); final JobId jobId = schedulerHelper.submitJob(createJobWithLock(fileLockPath.toString())); log("Wait when node becomes busy"); RMNodeEvent event; do { event = schedulerHelper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED, TIMEOUT); } while (!event.getNodeState().equals(NodeState.BUSY)); log("Wait when task starts"); schedulerHelper.waitForEventTaskRunning(jobId, "Test task"); log("Wait some time until task launcher is started"); Thread.sleep(5000); List<ScriptResult<Object>> results = schedulerHelper.getResourceManager() .executeScript("println \"Executing Script\";", "groovy", TargetType.NODE_URL.name(), Sets.newSet(testNode.getNodeURL())); Assert.assertEquals(1, results.size()); ScriptResult result = results.get(0); if (result.errorOccured()) { result.getException().printStackTrace(); Assert.fail("Script execution failed"); } log("Let task finish"); fileLock.unlock(); log("Wait when job finish"); schedulerHelper.waitForEventJobFinished(jobId, TIMEOUT); schedulerHelper.waitUntilState(testNode.getNodeURL(), NodeState.FREE, TIMEOUT); log("Check job result"); checkJobResult(schedulerHelper.getSchedulerInterface(), jobId); checkActiveObjects(); }
Source:
<code>public void testDestFileWithComma() { <START> AgentOptions options = new AgentOptions(); <END> AgentOptions options = new AgentOptions("destfile=build/jacoco/foo, bar.exec"); assertEquals("build/jacoco/foo, bar.exec", options.getDestfile()); }</code><technical_language>This line removed</technical_language>

Target:
public void testDestFileWithComma() { AgentOptions options = new AgentOptions("destfile=build/jacoco/foo, bar.exec"); assertEquals("build/jacoco/foo, bar.exec", options.getDestfile()); }
Source:
<code>protected List<Car> getAvailableCars() { List<Car> cars = Lists.newArrayList(); <START> for (int i = 0; i < CarBrand.values().length; i++) { <END> cars.add(new Car(i,CarBrand.values()[i])); } return cars; }</code><technical_language>Extract CarBrand.values() a variable</technical_language>

Target:
protected List<Car> getAvailableCars() { List<Car> cars = Lists.newArrayList(); CarBrand[] carBrands = CarBrand.values(); for (int i = 0; i < carBrands.length; i++) { cars.add(new Car(i, CarBrand.values()[i])); } return cars; }
Source:
<code>public void setArgs(List<String> args) { if (min != null) replace(args, "-Xms", String.valueOf(min)); if (max != null) replace(args, "-Xmx", String.valueOf(max)); if (eden != null) replace(args, "-Xmn", String.valueOf(eden)); if (threadStackSize != null) <START> replace(args, "ThreadStackSize", String.valueOf(threadStackSize)); <END> if (newRatio != null) replace(args, "-XX:NewRatio=", String.valueOf(newRatio)); if (useLargePages != null) set(args, "UseLargePages", useLargePages); }</code><technical_language>Xss is more 'portable' flag: <LINK_0></technical_language>

Target:
public void setArgs(List<String> args) { if (min != null) replace(args, "-Xms", String.valueOf(min)); if (max != null) replace(args, "-Xmx", String.valueOf(max)); if (newSize != null) replace(args, "-XX:NewSize=", String.valueOf(newSize)); if (maxNewSize != null) replace(args, "-XX:MaxNewSize=", String.valueOf(maxNewSize)); if (threadStackSize != null) replace(args, "-Xss", String.valueOf(threadStackSize)); if (newRatio != null) replace(args, "-XX:NewRatio=", String.valueOf(newRatio)); if (useLargePages != null) set(args, "UseLargePages", useLargePages); }
Source:
<code>private String[] getPayloads(HttpMessage msg) { <START> return this.name().equals("PORTSCAN") <END> ? new String[] {getXslForPortScan(msg)} : payloads; }</code><technical_language>check enum value, e.g. this == PORTSCAN</technical_language>

Target:
private String[] getPayloads(HttpMessage msg) { return this == PORTSCAN ? new String[] {getXslForPortScan(msg)} : payloads; }
Source:
<code>public void init() { final PayloadVerifierFactory factory = PayloadVerifierFactory.getInstance(); factory.register(Visibility.USER, new UserVerifier()); factory.register(Visibility.ROLE, new RoleVerifier()); <START> factory.register(Visibility.ROLES, new RolesVerifier()); <END> factory.register(Visibility.PERMISSION, new PermissionVerifier()); factory.register(Visibility.GLOBAL, new GlobalVerifier()); factory.register(Visibility.EXCLUDE_OWNER, new ExcludeOwnerVerifier()); }</code><technical_language>adding a new RolesVerifier class instead of modifying existing handle roles</technical_language>

Target:
public void init() { final PayloadVerifierFactory factory = PayloadVerifierFactory.getInstance(); factory.register(Visibility.USER, new UserVerifier()); factory.register(Visibility.ROLE, new RoleVerifier()); factory.register(Visibility.ROLES, new MultipleRolesVerifier()); factory.register(Visibility.PERMISSION, new PermissionVerifier()); factory.register(Visibility.GLOBAL, new GlobalVerifier()); factory.register(Visibility.EXCLUDE_OWNER, new ExcludeOwnerVerifier()); }
Source:
<code>public void testBuilder() { Parse.Configuration.Builder builder = new Parse.Configuration.Builder(null); builder.applicationId("foo"); builder.clientKey("bar"); <START> builder.server("<LINK_0>"); <END> builder.enableLocalDataStore(); Parse.Configuration configuration = builder.build(); assertNull(configuration.context); assertEquals(configuration.applicationId, "foo"); assertEquals(configuration.clientKey, "bar"); assertEquals(configuration.server, "<LINK_0>/"); assertEquals(configuration.localDataStoreEnabled, true); }</code><technical_language>duplicate this test case, instead of modifying in-place? test for branch</technical_language>

Target:
public void testBuilder() { Parse.Configuration.Builder builder = new Parse.Configuration.Builder(null); builder.applicationId("foo"); builder.clientKey("bar"); builder.enableLocalDataStore(); Parse.Configuration configuration = builder.build(); assertNull(configuration.context); assertEquals(configuration.applicationId, "foo"); assertEquals(configuration.clientKey, "bar"); assertEquals(configuration.localDataStoreEnabled, true); }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null) { permsList = new ArrayList<PermissionSubject>(); DiskImage image = getImage(); Guid guid = image == null ? Guid.Empty : image.getvm_guid(); if (getParameters().getOperation() == ImageOperation.Copy) { permsList.add(new PermissionSubject(guid, VdcObjectType.VmTemplate, ActionGroup.COPY_TEMPLATE)); } else { permsList.add(new PermissionSubject(guid, VdcObjectType.VM, ActionGroup.MOVE_VM)); <START> } <END> addStoragePermissionByQuotaMode(permsList, getParameters().getStoragePoolId(), getParameters().getStorageDomainId()); permsList = QuotaHelper.getInstance().addQuotaPermissionSubject(permsList, getStoragePool(), getQuotaId()); } return permsList; }</code><technical_language>need change copy/move disk</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { if (permsList == null) { permsList = new ArrayList<PermissionSubject>(); DiskImage image = getImage(); Guid diskId = image == null ? Guid.Empty : image.getimage_group_id(); permsList.add(new PermissionSubject(diskId, VdcObjectType.Disk, ActionGroup.CONFIGURE_DISK_STORAGE)); addStoragePermissionByQuotaMode(permsList, getParameters().getStoragePoolId(), getParameters().getStorageDomainId()); permsList = QuotaHelper.getInstance().addQuotaPermissionSubject(permsList, getStoragePool(), getQuotaId()); } return permsList; }
Source:
<code>public void traceOpened(TmfTraceOpenedSignal signal) { ITmfTrace trace = signal.getTrace(); if (signal.getTrace() instanceof TmfExperiment) { TmfExperiment experiment = (TmfExperiment) signal.getTrace(); for (ITmfTrace expTrace : experiment.getTraces()) { if (expTrace == this) { trace = expTrace; break; } } } if (trace == this) { try { buildStatistics(); } catch (TmfTraceException e) { e.printStackTrace(); } try { buildStateSystem(); } catch (TmfTraceException e) { e.printStackTrace(); } try { if (fResource != null) { fResource.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } } catch (CoreException e) { e.printStackTrace(); } <START> } <END> if (signal.getTrace() == this) { final ITmfContext context = seekEvent(0); final ITmfEvent event = getNext(context); context.dispose(); if (event == null) { return; } final TmfTimeRange timeRange = new TmfTimeRange(event.getTimestamp(), TmfTimestamp.BIG_CRUNCH); final TmfTraceRangeUpdatedSignal rangeUpdatedsignal = new TmfTraceRangeUpdatedSignal(this, this, timeRange); new Thread() { @Override public void run() { broadcast(rangeUpdatedsignal); } }.start(); return; } }</code><technical_language>get time of event store in trace call "buildStatistics" "buildStateSystem"? start time needed for building state system</technical_language>

Target:
public void traceOpened(TmfTraceOpenedSignal signal) { ITmfTrace trace = signal.getTrace(); if (signal.getTrace() instanceof TmfExperiment) { TmfExperiment experiment = (TmfExperiment) signal.getTrace(); for (ITmfTrace expTrace : experiment.getTraces()) { if (expTrace == this) { trace = expTrace; break; } } } if (signal.getTrace() == this || trace == this) { final ITmfContext context = seekEvent(0); getNext(context); context.dispose(); } if (trace == this) { try { buildStatistics(); } catch (TmfTraceException e) { e.printStackTrace(); } try { buildStateSystem(); } catch (TmfTraceException e) { e.printStackTrace(); } try { if (fResource != null) { fResource.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } } catch (CoreException e) { e.printStackTrace(); } } if (signal.getTrace() == this) { if (getNbEvents() == 0) { return; } final TmfTimeRange timeRange = new TmfTimeRange(getStartTime(), TmfTimestamp.BIG_CRUNCH); final TmfTraceRangeUpdatedSignal rangeUpdatedsignal = new TmfTraceRangeUpdatedSignal(this, this, timeRange); new Thread() { @Override public void run() { broadcast(rangeUpdatedsignal); } }.start(); return; } }
Source:
<code>public void flush() throws IOException { <START> asyncMutator.flush(); <END> }</code><technical_language>handleExceptions();</technical_language>

Target:
public void flush() throws IOException { asyncMutator.flush(); handleExceptions(); }
Source:
<code>public static Integer prepareConnectionForTransaction(Connection con, @Nullable TransactionDefinition definition) throws SQLException { Assert.notNull(con, "No Connection specified"); <START> final boolean debugEnabled = logger.isDebugEnabled(); <END> if (definition != null && definition.isReadOnly()) { try { if (debugEnabled) { logger.debug("Setting JDBC Connection [" + con + "] read-only"); } con.setReadOnly(true); } catch (SQLException | RuntimeException ex) { Throwable exToCheck = ex; while (exToCheck != null) { if (exToCheck.getClass().getSimpleName().contains("Timeout")) { throw ex; } exToCheck = exToCheck.getCause(); } logger.debug("Could not set JDBC Connection read-only", ex); } } Integer previousIsolationLevel = null; if (definition != null && definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { if (debugEnabled) { logger.debug("Changing isolation level of JDBC Connection [" + con + "] to " + definition.getIsolationLevel()); } int currentIsolation = con.getTransactionIsolation(); if (currentIsolation != definition.getIsolationLevel()) { previousIsolationLevel = currentIsolation; con.setTransactionIsolation(definition.getIsolationLevel()); } } return previousIsolationLevel; }</code><technical_language>local variables final. suggestion boolean debugEnabled = logger.isDebugEnabled();</technical_language>

Target:
public static Integer prepareConnectionForTransaction(Connection con, @Nullable TransactionDefinition definition) throws SQLException { Assert.notNull(con, "No Connection specified"); boolean debugEnabled = logger.isDebugEnabled(); if (definition != null && definition.isReadOnly()) { try { if (debugEnabled) { logger.debug("Setting JDBC Connection [" + con + "] read-only"); } con.setReadOnly(true); } catch (SQLException | RuntimeException ex) { Throwable exToCheck = ex; while (exToCheck != null) { if (exToCheck.getClass().getSimpleName().contains("Timeout")) { throw ex; } exToCheck = exToCheck.getCause(); } logger.debug("Could not set JDBC Connection read-only", ex); } } Integer previousIsolationLevel = null; if (definition != null && definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { if (debugEnabled) { logger.debug("Changing isolation level of JDBC Connection [" + con + "] to " + definition.getIsolationLevel()); } int currentIsolation = con.getTransactionIsolation(); if (currentIsolation != definition.getIsolationLevel()) { previousIsolationLevel = currentIsolation; con.setTransactionIsolation(definition.getIsolationLevel()); } } return previousIsolationLevel; }
Source:
<code>public static UserFragment newInstance(String login) { UserFragment f = new UserFragment(); Bundle args = new Bundle(); <START> args.putString(Constants.EXTRA_LOGIN, login); <END> f.setArguments(args); return f; }</code><technical_language>extra in this file</technical_language>

Target:
public static UserFragment newInstance(String login) { UserFragment f = new UserFragment(); Bundle args = new Bundle(); args.putString(EXTRA_LOGIN, login); f.setArguments(args); return f; }
Source:
<code>public static String loadJSON(URL src) throws IOException { URLConnection con = ProxyConfiguration.open(src); int responseCode = HttpURLConnection.HTTP_OK; if (con instanceof HttpURLConnection) { ((HttpURLConnection) con).setInstanceFollowRedirects(true); responseCode = ((HttpURLConnection) con).getResponseCode(); } if (HttpURLConnection.HTTP_OK != responseCode && HttpURLConnection.HTTP_MOVED_TEMP != responseCode && HttpURLConnection.HTTP_MOVED_PERM != responseCode && HttpURLConnection.HTTP_SEE_OTHER != responseCode) { throw new IOException("Could not find JSON in " + src); } else if (HttpURLConnection.HTTP_OK != responseCode) { <START> String redirection = ((HttpURLConnection) con).getHeaderField("Location"); <END> con = ProxyConfiguration.open(new URL(redirection)); responseCode = ((HttpURLConnection) con).getResponseCode(); } if (HttpURLConnection.HTTP_OK != responseCode) { throw new IOException("Could not find JSON in " + src); } try (InputStream is = con.getInputStream()) { String jsonp = IOUtils.toString(is, "UTF-8"); int start = jsonp.indexOf('{'); int end = jsonp.lastIndexOf('}'); if (start >= 0 && end > start) { return jsonp.substring(start, end + 1); } else { throw new IOException("Could not find JSON in " + src); } } }</code><technical_language>Unchecked cast</technical_language>

Target:
public static String loadJSON(URL src) throws IOException { URLConnection con; try { con = ProxyConfiguration.openURLAllowingCrossProtocolRedirects(src); } catch (IOException e) { throw new IOException("Could not find JSON in " + src, e); } try (InputStream is = con.getInputStream()) { String jsonp = IOUtils.toString(is, "UTF-8"); int start = jsonp.indexOf('{'); int end = jsonp.lastIndexOf('}'); if (start >= 0 && end > start) { return jsonp.substring(start, end + 1); } else { throw new IOException("Could not find JSON in " + src); } } }
Source:
<code><START> public boolean isFinished() { <END> return false; }</code><technical_language>methods part of upgrade</technical_language>

Target:
public boolean isFinished() { return this.isFinished(); }
Source:
<code>private void subscribeToEvents() { Client client = client(); this.subscriptions = subscribe(client, command, consumers, streamingErrorHandler()); <START> checkNotNull(subscriptions); <END> client.subscriptions() .addAll(subscriptions); }</code><technical_language>worth some words well</technical_language>

Target:
private void subscribeToEvents() { Client client = client(); this.subscriptions = subscribe(client, command, consumers, streamingErrorHandler()); client.subscriptions() .addAll(subscriptions); }
Source:
<code><START> public boolean isActivePeriod() { <END> if (getStart().isAfter(LocalDate.now())) { return false; } if (getEnd().isBefore(LocalDate.now())) { return false; } return true; }</code><technical_language>helpful</technical_language>

Target:
public boolean isActivePeriod() { LocalDate now = LocalDate.now(); return now.isAfter(getStart()) && now.isBefore(getEnd()); }
Source:
<code>public void failsToWriteBigDoc() throws IOException { final File file = new File( this.folder.newFolder(), "big_file" ); final String content = StringUtils.repeat('b', 101); final byte[] bytes = content.getBytes(StandardCharsets.UTF_8); <START> new SafeDoc(new SmallDoc(new MkDoc(file, "", ""), Tv.HUNDRED)).write( <END> new ByteArrayInputStream(bytes), bytes.length ); MatcherAssert.assertThat( Files.toString(file, StandardCharsets.UTF_8), Matchers.equalTo(content) ); }</code><technical_language>@dmzaytsev do need decor here? test fail of big file, a zero size</technical_language>

Target:
public void failsToWriteBigDoc() throws IOException { final File file = new File( this.folder.newFolder(), "big_file" ); final String content = StringUtils.repeat('b', 101); final byte[] bytes = content.getBytes(StandardCharsets.UTF_8); new SmallDoc(new MkDoc(file, "", ""), Tv.HUNDRED).write( new ByteArrayInputStream(bytes), bytes.length ); MatcherAssert.assertThat( Files.toString(file, StandardCharsets.UTF_8), Matchers.equalTo(content) ); }
Source:
<code>public boolean handleResponse(ZWaveController zController, SerialMessage lastSentMessage, SerialMessage incomingMessage) { logger.debug("Got RemoveFailedNode response."); int nodeId = lastSentMessage.getMessagePayloadByte(0); switch(incomingMessage.getMessagePayloadByte(0)) { case FAILED_NODE_REMOVE_STARTED: logger.debug("NODE {}: Remove failed node successfully placed on stack.", nodeId); <START> break; <END> case FAILED_NODE_NOT_PRIMARY_CONTROLLER: logger.error("NODE {}: Remove failed node failed as not Primary Controller for node!", nodeId); transactionComplete = true; break; case FAILED_NODE_NO_CALLBACK_FUNCTION: logger.error("NODE {}: Remove failed node failed as no callback function!", nodeId); transactionComplete = true; break; case FAILED_NODE_NOT_FOUND: logger.error("NODE {}: Remove failed node failed as node not found on controllers failed list!", nodeId); transactionComplete = true; break; case FAILED_NODE_REMOVE_PROCESS_BUSY: logger.error("NODE {}: Remove failed node failed as Controller Busy!", nodeId); transactionComplete = true; break; case FAILED_NODE_REMOVE_FAIL: logger.error("NODE {}: Remove failed node failed!", nodeId); transactionComplete = true; break; default: logger.error("NODE {}: Remove failed node not placed on stack due to error 0x{}.", nodeId, Integer.toHexString(incomingMessage.getMessagePayloadByte(0))); transactionComplete = true; break; } return true; }</code><technical_language>remove this line</technical_language>

Target:
public boolean handleResponse(ZWaveController zController, SerialMessage lastSentMessage, SerialMessage incomingMessage) { logger.debug("Got RemoveFailedNode response."); int nodeId = lastSentMessage.getMessagePayloadByte(0); switch(incomingMessage.getMessagePayloadByte(0)) { case FAILED_NODE_REMOVE_STARTED: logger.debug("NODE {}: Remove failed node successfully placed on stack.", nodeId); transactionComplete = true; break; case FAILED_NODE_NOT_PRIMARY_CONTROLLER: logger.error("NODE {}: Remove failed node failed as not Primary Controller for node!", nodeId); transactionComplete = true; break; case FAILED_NODE_NO_CALLBACK_FUNCTION: logger.error("NODE {}: Remove failed node failed as no callback function!", nodeId); transactionComplete = true; break; case FAILED_NODE_NOT_FOUND: logger.error("NODE {}: Remove failed node failed as node not found on controllers failed list!", nodeId); transactionComplete = true; break; case FAILED_NODE_REMOVE_PROCESS_BUSY: logger.error("NODE {}: Remove failed node failed as Controller Busy!", nodeId); transactionComplete = true; break; case FAILED_NODE_REMOVE_FAIL: logger.error("NODE {}: Remove failed node failed!", nodeId); transactionComplete = true; break; default: logger.error("NODE {}: Remove failed node not placed on stack due to error 0x{}.", nodeId, Integer.toHexString(incomingMessage.getMessagePayloadByte(0))); transactionComplete = true; break; } return true; }
Source:
<code><START> public CoberturaPublisher() { <END> }</code><technical_language>bug: This compatibility issues</technical_language>

Target:
public CoberturaPublisher() { this("", true, true, true, true, true, true, true, SourceEncoding.UTF_8, 42); }
Source:
<code>private ApplicationDTO(Builder builder) { this.typeId = builder.typeId; this.categoryId = builder.categoryId; if (builder.id != null) { <START> if (builder.id.matches("^[a-zA-Z0-9_.]+$")) { <END> this.id = builder.id; } else { LOGGER.warn(String.format("Application ID (%s) contains invalid characters, will remove them.", builder.id)); this.id = builder.id.replaceAll("[^a-zA-Z0-9_.]", ""); } } else { this.id = null; } this.name = builder.name == null ? builder.id : builder.name; this.description = builder.description; this.icon = builder.icon; this.miniatures = builder.miniatures; this.scripts = builder.scripts; this.resources = builder.resources; }</code><technical_language>moving this pattern a static final field</technical_language>

Target:
private ApplicationDTO(Builder builder) { this.typeId = builder.typeId; this.categoryId = builder.categoryId; if (builder.id != null) { if (builder.id.matches(ID_REGEX)) { this.id = builder.id; } else { LOGGER.warn(String.format("Application ID (%s) contains invalid characters, will remove them.", builder.id)); this.id = builder.id.replaceAll(INVALID_ID_CHARS_REGEX, ""); } } else { this.id = null; } this.name = builder.name == null ? builder.id : builder.name; this.description = builder.description; this.icon = builder.icon; this.miniatures = builder.miniatures; this.scripts = builder.scripts; this.resources = builder.resources; }
Source:
<code>private void ensureClassLoadingPropertyIsSet( Properties providerProperties ) { if (providerProperties.containsKey(FieldName.CLASSLOADER)) { return; } String providerClassName = providerProperties.getProperty(FieldName.CLASSNAME); if (StringUtil.isBlank(providerClassName)) { LOG.warnv("Required property: {0} not found among the index provider properties: {1}", FieldName.CLASSNAME, providerProperties); return; } String fqProviderClass = RepositoryConfiguration.getBuiltInIndexProviderClassName(providerClassName); if (fqProviderClass == null) { fqProviderClass = providerClassName; } int index = fqProviderClass.lastIndexOf("."); String providerModuleName = index != -1 ? fqProviderClass.substring(0, index) : fqProviderClass; <START> if (providerModuleName.startsWith("org.modeshape.jcr")) { <END> providerModuleName = ModeShapeExtension.ModuleID.MAIN; } providerProperties.setProperty(FieldName.CLASSLOADER, providerModuleName); }</code><technical_language>add this string a constant ? I this is ModuleId.MAIN, other "root package"</technical_language>

Target:
private void ensureClassLoadingPropertyIsSet( Properties providerProperties ) { if (providerProperties.containsKey(FieldName.CLASSLOADER)) { return; } String providerClassName = providerProperties.getProperty(FieldName.CLASSNAME); if (StringUtil.isBlank(providerClassName)) { LOG.warnv("Required property: {0} not found among the index provider properties: {1}", FieldName.CLASSNAME, providerProperties); return; } String fqProviderClass = RepositoryConfiguration.getBuiltInIndexProviderClassName(providerClassName); if (fqProviderClass == null) { fqProviderClass = providerClassName; } int index = fqProviderClass.lastIndexOf("."); String providerModuleName = index != -1 ? fqProviderClass.substring(0, index) : fqProviderClass; if (providerModuleName.startsWith(ModeShapeExtension.ModuleID.MAIN)) { providerModuleName = ModeShapeExtension.ModuleID.MAIN; } providerProperties.setProperty(FieldName.CLASSLOADER, providerModuleName); }
Source:
<code>private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { final Map<AliasedMappedProperty, Object> columnToValue = new HashMap<AliasedMappedProperty, Object>(); final boolean useUnsetForNullValue = !shouldSaveNullFields(options) && manager.protocolVersionAsInt >= 4; <START> final boolean includeColumnsWithNullValue = shouldSaveNullFields(options) || useUnsetForNullValue; <END> for (AliasedMappedProperty col : mapper.allColumns) { Object value = col.mappedProperty.getValue(entity); if (!col.mappedProperty.isComputed() && (includeColumnsWithNullValue || value != null)) { columnToValue.put(col, value); } } return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, columnToValue.keySet(), options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = input.bind(); int i = 0; for (Map.Entry<AliasedMappedProperty, Object> entry : columnToValue.entrySet()) { AliasedMappedProperty mapper = entry.getKey(); Object value = entry.getValue(); setObject(bs, i++, value, mapper, useUnsetForNullValue); } if (mapper.writeConsistency != null) bs.setConsistencyLevel(mapper.writeConsistency); for (Option option : options.values()) { option.validate(QueryType.SAVE, manager); i = option.apply(bs, i); } return bs; } }); }</code><technical_language>modifiesQueryString method some serious rewriting/refactor. reason generating prepared statement in QueryType.makePreparedQueryString need values for columns omit columns null values generating statement prepare support <ProtocolV4. modifiesQueryString relevant anyways. This is magic is happening, clever</technical_language>

Target:
private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { final Map<AliasedMappedProperty, Object> values = new HashMap<AliasedMappedProperty, Object>(); boolean saveNullFields = shouldSaveNullFields(options); for (AliasedMappedProperty col : mapper.allColumns) { Object value = col.mappedProperty.getValue(entity); if (!col.mappedProperty.isComputed() && (saveNullFields || value != null)) { values.put(col, value); } } return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, values.keySet(), options), new Function<PreparedStatement, BoundStatement>() { @Override public BoundStatement apply(PreparedStatement input) { BoundStatement bs = input.bind(); int i = 0; for (Map.Entry<AliasedMappedProperty, Object> entry : values.entrySet()) { AliasedMappedProperty mapper = entry.getKey(); Object value = entry.getValue(); setObject(bs, i++, value, mapper); } if (mapper.writeConsistency != null) bs.setConsistencyLevel(mapper.writeConsistency); for (Option option : options.values()) { option.validate(QueryType.SAVE, manager); i = option.apply(bs, i); } return bs; } }); }
Source:
<code>public void startClusterManagementServiceWithRestServiceEnabledInvokesStartManager() throws IOException { <START> LoggingSession loggingSession = mock(LoggingSession.class); <END> DistributionConfigImpl distributionConfig = mock(DistributionConfigImpl.class); when(distributionConfig.getJmxManager()).thenReturn(true); when(distributionConfig.getLocators()).thenReturn(""); when(distributionConfig.getSecurableCommunicationChannels()) .thenReturn(new SecurableCommunicationChannel[] {}); when(distributionConfig.getSecurityAuthTokenEnabledComponents()).thenReturn(new String[] {}); InternalLocator internalLocator = new InternalLocator(0, loggingSession, null, null, null, null, null, null, distributionConfig, null); InternalCacheForClientAccess cache = mock(InternalCacheForClientAccess.class); InternalRegionFactory regionFactory = mock(InternalRegionFactory.class); when(cache.createInternalRegionFactory(RegionShortcut.REPLICATE)).thenReturn(regionFactory); when(cache.getOptionalService(HttpService.class)) .thenReturn(Optional.of(mock(HttpService.class))); when(cache.getCacheForProcessingClientRequests()).thenReturn(cache); BaseManagementService managementService = mock(BaseManagementService.class); BaseManagementService.setManagementService(cache, managementService); internalLocator.setInternalCache(cache); when(distributionConfig.getEnableManagementRestService()).thenReturn(true); internalLocator.startClusterManagementService(); verify(managementService).startManager(); }</code><technical_language>I of common setup stuff moved a setup method. stuff differs test another remain. test-specific details stand out more, more express intent of test. If a setup details remain in test, intent is obvious, enough. If more a details, hidden in helper methods express intent</technical_language>

Target:
public void startClusterManagementServiceWithRestServiceEnabledInvokesStartManager() throws Exception { createInternalLocator(); setupForStartClusterManagementService(); when(distributionConfig.getEnableManagementRestService()).thenReturn(true); internalLocator.startClusterManagementService(cache, agentUtil); verify(managementService).startManager(); verify(httpService).addWebApplication(eq("/management"), any(), any()); }
Source:
<code>private void outputFloatingCommentFromBuffer(Node n) { Node parent = n.getParent(); if (TOKENS_SET_ACCEPT_EMPTY_CHILD.contains(parent.getToken())) { parent.addChildBefore(newFloatingCommentFromBuffer(), n); <START> } else if (canHaveComment(n)) { <END> linkCommentBufferToNode(n); } else { outputFloatingCommentFromBuffer(parent); } }</code><technical_language>last? Do guarantees GETPROP children? This AST is atrocious :)</technical_language>

Target:
private void outputFloatingCommentFromBuffer(Node n) { Node parent = n.getParent(); if (parent == null) { linkCommentBufferToNode(n); } else if (TOKENS_CAN_HAVE_EMPTY_CHILD.contains(parent.getToken())) { parent.addChildBefore(newFloatingCommentFromBuffer(), n); } else if (canHaveComment(n)) { linkCommentBufferToNode(n); } else { outputFloatingCommentFromBuffer(parent); } }