auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>static Integer resolveHistoricalNullIfNeeded(@Nullable Integer val) { <START> return (val == null || val == HISTORICAL_NULL) ? null : val; <END> }</code><technical_language>nit: return isEffectivelyNull(val) ? null : val;</technical_language>

Target:
static Integer resolveHistoricalNullIfNeeded(@Nullable Integer val) { return isEffectivelyNull(val) ? null : val; }
Source:
<code>private static PushCertificate read(TreeWalk tw) throws IOException { if (tw == null || <START> (tw.getRawMode(0) & FileMode.TYPE_FILE) == 0) { <END> return null; } ObjectLoader loader = tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB); try (InputStream in = loader.openStream(); Reader r = new BufferedReader(new InputStreamReader(in))) { return PushCertificateParser.fromReader(r); } }</code><technical_language>This test is wrong. If tree entry is a gitlink non-zero fall read commit exist is a blob. Safer test is: (rawMode & TYPE_FILE) != TYPE_FILE</technical_language>

Target:
private static PushCertificate read(TreeWalk tw) throws IOException { if (tw == null || (tw.getRawMode(0) & TYPE_FILE) != TYPE_FILE) { return null; } ObjectLoader loader = tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB); try (InputStream in = loader.openStream(); Reader r = new BufferedReader(new InputStreamReader(in, UTF_8))) { return PushCertificateParser.fromReader(r); } }
Source:
<code>public static File makeMetricFile(File dir, String metricName, ByteOrder order) { <START> return new File(dir, StringUtils.safeFormat("met_%s_%s.drd", metricName, order)); <END> }</code><technical_language>crash if bad format string</technical_language>

Target:
public static File makeMetricFile(File dir, String metricName, ByteOrder order) { return new File(dir, StringUtils.format("met_%s_%s.drd", metricName, order)); }
Source:
<code>public void verifyResolverResolvesWithFileUri() throws Exception { val props = new SamlIdPProperties(); val resolver = new JsonResourceMetadataResolver(props, openSamlConfigBean); <START> assertNotNull(resolver); <END> }</code><technical_language>set property test is accurate, in cas default changes</technical_language>

Target:
public void verifyResolverResolvesWithFileUri() throws Exception { val props = new SamlIdPProperties(); props.getMetadata().setLocation("file:/etc/cas/saml"); val resolver = new JsonResourceMetadataResolver(props, openSamlConfigBean); assertNotNull(resolver); }
Source:
<code>protected void buildScript(int age) { if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); <START> addPendingClient(new RandomClient(new RandomCard(getContext(), getSite()))); <END> }</code><technical_language>This kind of breaks clean streak of "new Client()" calls arguments. adhere this pattern</technical_language>

Target:
protected void buildScript(int age) { if (age == 0) { init(); } addPendingClient(new BecauseYouReadClient()); addPendingClient(new ContinueReadingClient()); addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new IntegerListClient()); addPendingClient(new MostReadClient()); addPendingClient(new RandomClient()); }
Source:
<code><START> public static int findElement(final JSONArray array, final String element) { <END> for (int i = 0; i < array.length(); i++) { if (element.equals(array.getString(i))) { return i; } } return -1; }</code><technical_language>function finds element's index, element itself. more name indexOfElement</technical_language>

Target:
private static int findElement(final JSONArray array, final String element) { for (int i = 0; i < array.length(); i++) { if (element.equals(array.getString(i))) { return i; } } return -1; }
Source:
<code>private void maybeRemoveStatisticsFromMetricsRecorder() { if (isRecordingLevelDebug) { metricsRecorder.removeStatistics(name); <START> isRecordingLevelDebug = false; <END> } }</code><technical_language>This a mis-named, recording level change remove stats. isStatsRegistered? other hand, idempotently "remove" stats if registered? I.e., no-op in case</technical_language>

Target:
private void maybeRemoveStatisticsFromMetricsRecorder() { if (isStatisticsRegistered) { metricsRecorder.removeStatistics(name); isStatisticsRegistered = false; } }
Source:
<code>private boolean isOwnedTransaction() { TransactionAdapter transaction = (TransactionAdapter) TransactionCoordination.getInstance().getTransaction(); if (transaction == null || !transaction.getComponentLocation().isPresent()) { return false; } String transactionLocation = transaction.getComponentLocation().get().getLocation(); if (this.getLocation() == null) { if (flowLocation.isPresent()) { return transactionLocation.equals(flowLocation.get().toString()); } else { return sameRootContainerLocation(transaction); } } if (isTransactionInGlobalErrorHandler((transaction))) { return true; } else if (flowLocation.isPresent()) { return false; } String errorHandlerLocation = this.getLocation().getLocation(); <START> if (!errorHandlerLocation.matches(".*/.*/.*")) { <END> return sameRootContainerLocation(transaction); } errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); return (sameRootContainerLocation(transaction) && errorHandlerLocation.equals(transactionLocation)); }</code><technical_language>Pattern.compile precompile regex</technical_language>

Target:
private boolean isOwnedTransaction() { TransactionAdapter transaction = (TransactionAdapter) TransactionCoordination.getInstance().getTransaction(); if (transaction == null || !transaction.getComponentLocation().isPresent()) { return false; } if (inDefaultErrorHandler()) { return defaultErrorHandlerOwnsTransaction(transaction); } else if (isTransactionInGlobalErrorHandler((transaction))) { return true; } else if (flowLocation.isPresent()) { return false; } else { String errorHandlerLocation = this.getLocation().getLocation(); if (!ERROR_HANDLER_LOCATION_PATTERN.matcher(errorHandlerLocation).find()) { return sameRootContainerLocation(transaction); } String transactionLocation = transaction.getComponentLocation().get().getLocation(); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); errorHandlerLocation = errorHandlerLocation.substring(0, errorHandlerLocation.lastIndexOf('/')); return (sameRootContainerLocation(transaction) && errorHandlerLocation.equals(transactionLocation)); } }
Source:
<code>public boolean handles(String s) { return s.startsWith(CloudHandler.CLOUD_PREFIX_BOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_DROPBOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE) || s.startsWith(CloudHandler.CLOUD_PREFIX_ONE_DRIVE) || s.startsWith("smb:/") <START> || s.startsWith("sftp:/"); <END> }</code><technical_language>ssh:/ instead. I a constant..</technical_language>

Target:
public boolean handles(String s) { return s.startsWith(CloudHandler.CLOUD_PREFIX_BOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_DROPBOX) || s.startsWith(CloudHandler.CLOUD_PREFIX_GOOGLE_DRIVE) || s.startsWith(CloudHandler.CLOUD_PREFIX_ONE_DRIVE) || s.startsWith("smb:/") || s.startsWith("ssh:/"); }
Source:
<code>private MavenProject findProjectFromReactor(final Dependency d) { VersionRange depVersionAsRange; try { depVersionAsRange = VersionRange.createFromVersionSpec(d.getVersion()); } catch (InvalidVersionSpecificationException e) { throw new IllegalStateException("Could not parse the version of the dependency even though Maven" + <START> " could: " + d); <END> } for (final MavenProject p : reactorProjects) { DefaultArtifactVersion pv = new DefaultArtifactVersion(p.getVersion()); if (p.getGroupId().equals(d.getGroupId()) && p.getArtifactId().equals(d.getArtifactId()) && depVersionAsRange.containsVersion(pv)) { return p; } } return null; }</code><technical_language>this happen</technical_language>

Target:
private MavenProject findProjectFromReactor(final Dependency d) { final VersionRange depVersionAsRange; try { depVersionAsRange = VersionRange .createFromVersionSpec(d.getVersion()); } catch (InvalidVersionSpecificationException e) { throw new AssertionError(e); } for (final MavenProject p : reactorProjects) { final DefaultArtifactVersion pv = new DefaultArtifactVersion( p.getVersion()); if (p.getGroupId().equals(d.getGroupId()) && p.getArtifactId().equals(d.getArtifactId()) && depVersionAsRange.containsVersion(pv)) { return p; } } return null; }
Source:
<code>private static boolean loadSourceFiles(ISessionInfoVisitor infoStore, IExecutionDataVisitor dataStore, File... reports) { Boolean isCurrentVersionFormat = null; for (File report : reports) { if (report.isFile()) { try { JacocoReportReader jacocoReportReader = new JacocoReportReader(report).readJacocoReport(dataStore, infoStore); isCurrentVersionFormat = jacocoReportReader.useCurrentBinaryFormat(); } catch (IOException e) { throw new SonarException(String.format("Unable to read %s", report.getAbsolutePath()), e); } } } <START> return BooleanUtils.isNotFalse(isCurrentVersionFormat); <END> }</code><technical_language>I miss test case in place, code obvious</technical_language>

Target:
private static boolean loadSourceFiles(ISessionInfoVisitor infoStore, IExecutionDataVisitor dataStore, File... reports) { Boolean isCurrentVersionFormat = null; for (File report : reports) { if (report.isFile()) { JacocoReportReader jacocoReportReader = new JacocoReportReader(report).readJacocoReport(dataStore, infoStore); boolean reportFormatIsCurrent = jacocoReportReader.useCurrentBinaryFormat(); if (isCurrentVersionFormat == null) { isCurrentVersionFormat = reportFormatIsCurrent; } else if (!isCurrentVersionFormat.equals(reportFormatIsCurrent)) { throw new IllegalStateException("You are trying to merge two different JaCoCo binary formats. Please use only one version of JaCoCo."); } } } return BooleanUtils.isNotFalse(isCurrentVersionFormat); }
Source:
<code><START> public IArtifactType getArtifactType(IAtsWorkItem workItem) { <END> return ((Artifact) workItem.getStoreObject()).getArtifactType(); }</code><technical_language>Consider adding null checks for methods</technical_language>

Target:
public IArtifactType getArtifactType(IAtsWorkItem workItem) { Assert.isNotNull(workItem, "Work Item can not be null"); return ((Artifact) workItem.getStoreObject()).getArtifactType(); }
Source:
<code>protected void startProcess(ExecutorDriver driver, Task task) { if (task.process == null) { try { task.run(); redirectProcess(task.process); <START> scheduleHealthCheck(driver, task.executableInfo.hostname(), task.executableInfo.httpPort()); <END> try { Thread.sleep(10000); task.process.exitValue(); fail(driver); } catch (InterruptedException | IllegalThreadStateException e) { LOGGER.debug("task still running after 10s"); } } catch (IOException e) { LOGGER.error("Failed to run command", e); fail(driver); } } else { LOGGER.error("Tried to start process, but process already running"); } }</code><technical_language>host is localhost</technical_language>

Target:
protected void startProcess(ExecutorDriver driver, Task task) { if (task.process == null) { try { task.run(); redirectProcess(task.process); try { Thread.sleep(10000); task.process.exitValue(); fail(driver); } catch (InterruptedException | IllegalThreadStateException e) { LOGGER.debug("task still running after 10s"); } } catch (IOException e) { LOGGER.error("Failed to run command", e); fail(driver); } } else { LOGGER.error("Tried to start process, but process already running"); } }
Source:
<code>protected IProject getOrCreateProject(ILangProjectSupport projectSupport, String projectName, String targetLanguage) throws TransformationException { IProject genProject = ProjectManagement.getNamedProject(projectName); if ((genProject == null) || !genProject.exists()) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject[] projectsBeforeCreation = root.getProjects(); genProject = projectSupport.createProject(projectName); try { root.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); IProject[] projectsAfterCreation = root.getProjects(); boolean found = false; for(int i=0;i<projectsBeforeCreation.length; i++){ if(!projectsAfterCreation[i].getName().equals(projectsBeforeCreation[i].getName())){ genProject = projectsAfterCreation[i]; found = true; break; } } if((found == false) && (projectsBeforeCreation.length < projectsAfterCreation.length)){ genProject = projectsAfterCreation[projectsAfterCreation.length -1]; } } catch (CoreException e) { e.printStackTrace(); } if ((genProject == null) || !genProject.exists()) { if(targetLanguage.equals("Java")){ <START> throw new RuntimeException("Could not create JDT project. This might indicate that there is a problem with your JDT installation."); END> }else if(targetLanguage.equals("C++")){ throw new RuntimeException("Could not create CDT project. This might indicate that there is a problem with your CDT installation."); } } UIContext.configureProject = true; } return genProject; }</code><technical_language>is C++ Java, extension point. Replace generic message, i.e. create project for <language> ..</technical_language>

Target:
protected IProject getOrCreateProject(ILangProjectSupport projectSupport, String projectName, String targetLanguage) throws TransformationException { IProject genProject = ProjectManagement.getNamedProject(projectName); if ((genProject == null) || !genProject.exists()) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject[] projectsBeforeCreation = root.getProjects(); genProject = projectSupport.createProject(projectName); try { root.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); IProject[] projectsAfterCreation = root.getProjects(); boolean found = false; for (int i = 0; i < projectsBeforeCreation.length; i++) { if (!projectsAfterCreation[i].getName().equals(projectsBeforeCreation[i].getName())) { genProject = projectsAfterCreation[i]; found = true; break; } } if ((found == false) && (projectsBeforeCreation.length < projectsAfterCreation.length)) { genProject = projectsAfterCreation[projectsAfterCreation.length - 1]; } } catch (CoreException e) { e.printStackTrace(); } if ((genProject == null) || !genProject.exists()) { throw new RuntimeException( "Could not create "+ targetLanguage +" project. This might indicate that there is a problem with your "+ targetLanguage +" installation."); } UIContext.configureProject = true; } return genProject; }
Source:
<code>private void allTags() { allTags = new ArrayList<TagDto>(); SessionDataService.Async.getInstance().getAllTags(new AsyncCallback<List<TagDto>>() { @Override public void onFailure(Throwable throwable) { <START> new ExceptionPanel("Fail to save data: " + throwable.getMessage()); <END> } @Override public void onSuccess(List<TagDto> tagDtos) { allTags.addAll(tagDtos); allTagsLoadComplete = true; } }); }</code><technical_language>save data</technical_language>

Target:
private void allTags() { allTags = new ArrayList<TagDto>(); SessionDataService.Async.getInstance().getAllTags(new AsyncCallback<List<TagDto>>() { @Override public void onFailure(Throwable throwable) { new ExceptionPanel("Fail to fetch all tags from the database: " + throwable.getMessage()); } @Override public void onSuccess(List<TagDto> tagDtos) { allTags.addAll(tagDtos); allTagsLoadComplete = true; } }); }
Source:
<code>public List<String> setUGI(String userName, List<String> groupNames) { <START> groupNames.add(userName); <END> return groupNames; }</code><technical_language>do modify input paratemeter. instead of this please return a copied list</technical_language>

Target:
public List<String> setUGI(String userName, List<String> groupNames) { List<String> result = new ArrayList(groupNames); result.add(userName); return result; }
Source:
<code>public synchronized void loadProperties() { Properties properties = checkNotNull(home).getProperties("system.conf"); properties.put("NGRINDER_HOME", home.getDirectory().getAbsolutePath()); if (exHome.exists()) { Properties exProperties = exHome.getProperties("system-ex.conf"); if (exProperties.isEmpty()) { exProperties = exHome.getProperties("system.conf"); } properties.putAll(exProperties); } properties.putAll(System.getProperties()); controllerProperties = new PropertiesWrapper(properties, controllerPropertiesKeyMapper); <START> System.setProperty("ngrinder.lib.path", getCurrentUnpackedFolder()); <END> clusterProperties = new PropertiesWrapper(properties, clusterPropertiesKeyMapper); }</code><technical_language>resolve unpack folder requested putting system property</technical_language>

Target:
public synchronized void loadProperties() { Properties properties = checkNotNull(home).getProperties("system.conf"); properties.put("NGRINDER_HOME", home.getDirectory().getAbsolutePath()); if (exHome.exists()) { Properties exProperties = exHome.getProperties("system-ex.conf"); if (exProperties.isEmpty()) { exProperties = exHome.getProperties("system.conf"); } properties.putAll(exProperties); } properties.putAll(System.getProperties()); controllerProperties = new PropertiesWrapper(properties, controllerPropertiesKeyMapper); clusterProperties = new PropertiesWrapper(properties, clusterPropertiesKeyMapper); }
Source:
<code>public void restoreAll(int itemcount){ if (excludedFolders.size()!=0){ for (int i=0;i<itemcount;i++){ h.clearAlbumExclude(excludedFolders.remove(0).getAbsolutePath()); } <START> Toast.makeText(ExcludedAlbumsActivity.this,"All folders are restored!",Toast.LENGTH_SHORT).show(); <END> finish(); } }</code><technical_language>Replace this toast a snackbar</technical_language>

Target:
public void restoreAll(int itemcount){ if (excludedFolders.size()!=0){ for (int i=0;i<itemcount;i++){ h.clearAlbumExclude(excludedFolders.remove(0).getAbsolutePath()); } SnackBarHandler.show(findViewById(R.id.rl_ea), "All folders are restored", Snackbar.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); } },1000); } }
Source:
<code>public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { <START> boolean hasComma = false; <END> int length = this.length(); writer.write('['); if (length == 1) { try { JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: 0", e); } } else if (length != 0) { final int newIndent = indent + indentFactor; for (int i = 0; i < length; i += 1) { if (hasComma) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, newIndent); try { JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newIndent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: " + i, e); } hasComma = true; } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }</code><technical_language>needsComma I a name hasComma</technical_language>

Target:
public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { boolean needsComma = false; int length = this.length(); writer.write('['); if (length == 1) { try { JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: 0", e); } } else if (length != 0) { final int newIndent = indent + indentFactor; for (int i = 0; i < length; i += 1) { if (needsComma) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, newIndent); try { JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newIndent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: " + i, e); } needsComma = true; } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
Source:
<code>public ImmutableValue<Boolean> adult() { <START> return new ImmutableSpongeValue<>(Keys.ADULT, this.adult); <END> }</code><technical_language>immutable cache</technical_language>

Target:
public ImmutableValue<Boolean> adult() { return ImmutableSpongeValue.cachedOf(Keys.IS_ADULT, true, this.adult); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_paged_list_shrink_view); CarToolbar toolbar = findViewById(R.id.car_toolbar); toolbar.setTitle(R.string.paged_list_view_title); toolbar.setNavigationIconOnClickListener(v -> finish()); PagedListView pagedListView = findViewById(R.id.paged_list_view); pagedListView.setAdapter(new DemoAdapter()); RadioGroup radioGroup = findViewById(R.id.radiogroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { ViewGroup.LayoutParams params = pagedListView.getLayoutParams(); switch(checkedId) { case R.id.radio1: <START> params.height = 50; <END> break; case R.id.radio2: params.height = 150; break; case R.id.radio3: params.height = 250; break; } pagedListView.requestLayout(); } }); }</code><technical_language>height in a dimens file "dp". Right now, values pixels, remain constant screen densities</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_paged_list_shrink_view); Resources res = this.getResources(); CarToolbar toolbar = findViewById(R.id.car_toolbar); toolbar.setTitle(R.string.paged_list_view_title); toolbar.setNavigationIconOnClickListener(v -> finish()); PagedListView pagedListView = findViewById(R.id.paged_list_view); pagedListView.setAdapter(new DemoAdapter()); RadioGroup radioGroup = findViewById(R.id.radiogroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { ViewGroup.LayoutParams params = pagedListView.getLayoutParams(); switch(checkedId) { case R.id.radio1: params.height = res.getDimensionPixelSize( androidx.car.R.dimen.car_padding_5); break; case R.id.radio2: params.height = 2 * res.getDimensionPixelSize( androidx.car.R.dimen.car_single_line_list_item_height); break; case R.id.radio3: params.height = 2 * res.getDimensionPixelSize( androidx.car.R.dimen.car_keyline_4); break; default: break; } pagedListView.requestLayout(); } }); }
Source:
<code>@Override public void afterTest() { stripedExecSvc.shutdown(); <START> if (origStarvationThreshold != null) <END> System.setProperty(IGNITE_STRIPED_POOL_STARVATION_THRESHOLD, origStarvationThreshold); }</code><technical_language>line feed is desired</technical_language>

Target:
@Override public void afterTest() { stripedExecSvc.shutdown(); }
Source:
<code>public void cleanUpOrphanConnectorTasks(boolean cleanUpOrphanTasksInConnector) { if (!_isLeader) { return; } Map<String, Set<DatastreamTask>> assignmentsByInstance = getAllAssignedDatastreamTasks(); Set<DatastreamTask> validTasks = assignmentsByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); List<String> allConnectors = getAllConnectors(); for (String connector : allConnectors) { Set<String> connectorTaskList = getConnectorTasks(connector); connectorTaskList.removeAll(validTasks.stream() .filter(x -> x.getConnectorType().equals(connector)) .map(DatastreamTask::getDatastreamTaskName) .collect(Collectors.toSet())); if (connectorTaskList.size() > 0) { <START> LOG.warn("Found orphan tasks: in connector: {}", connectorTaskList, connector); <END> if (cleanUpOrphanTasksInConnector) { connectorTaskList.forEach(t -> deleteConnectorTask(connector, t)); } } } }</code><technical_language>add a metric for this monitor it</technical_language>

Target:
public int cleanUpOrphanConnectorTasks(boolean cleanUpOrphanTasksInConnector) { if (!_isLeader) { return 0; } Map<String, Set<DatastreamTask>> assignmentsByInstance = getAllAssignedDatastreamTasks(); Set<DatastreamTask> validTasks = assignmentsByInstance.values().stream().flatMap(Collection::stream).collect(Collectors.toSet()); List<String> allConnectors = getAllConnectors(); int orphanCount = 0; for (String connector : allConnectors) { Set<String> connectorTaskList = getConnectorTasks(connector); connectorTaskList.removeAll(validTasks.stream() .filter(x -> x.getConnectorType().equals(connector)) .map(DatastreamTask::getDatastreamTaskName) .collect(Collectors.toSet())); if (connectorTaskList.size() > 0) { LOG.warn("Found orphan tasks: in connector: {}", connectorTaskList, connector); if (cleanUpOrphanTasksInConnector) { connectorTaskList.forEach(t -> deleteConnectorTask(connector, t)); } } orphanCount += connectorTaskList.size(); } return orphanCount; }
Source:
<code>public void testTransformItemWithEventRefs() { <START> given(idCodec.decode("12345")).willReturn(BigInteger.valueOf(12345)); <END> given(idCodec.decode("1234")).willReturn(BigInteger.valueOf(1234)); org.atlasapi.media.entity.Item complex = transformer.transform(getItemWithEventRefs()); assertEquals(1, complex.events().size()); assertThat(complex.events().get(0).id(), is(1234L)); }</code><technical_language>do BDD methods in tests BDDs, this when(mock.thing()).thenReturn(null)</technical_language>

Target:
public void testTransformItemWithEventRefs() { when(idCodec.decode("12345")).thenReturn(BigInteger.valueOf(12345)); when(idCodec.decode("1234")).thenReturn(BigInteger.valueOf(1234)); org.atlasapi.media.entity.Item complex = transformer.transform(getItemWithEventRefs()); assertEquals(1, complex.events().size()); assertThat(complex.events().get(0).id(), is(1234L)); }
Source:
<code>public boolean onStopJob(JobParameters params) { <START> AppLog.i(AppLog.T.READER, "reader service > stopped"); <END> jobFinished(params, false); return false; }</code><technical_language>Minor nit: change "reader job service" differentiate existing logging in ReaderUpdateService</technical_language>

Target:
public boolean onStopJob(JobParameters params) { AppLog.i(AppLog.T.READER, "reader job service > stopped"); jobFinished(params, false); return false; }
Source:
<code>public SpecialVideosPageObject openSpecialVideoPage(){ <START> getUrl(Domain+URLsContent.specialNewVideo); <END> return new SpecialVideosPageObject(driver, Domain); }</code><technical_language>Global.DOMAIN instead of Domain</technical_language>

Target:
public SpecialVideosPageObject openSpecialVideoPage(){ getUrl(Global.DOMAIN+URLsContent.specialNewVideo); return new SpecialVideosPageObject(driver, Global.DOMAIN); }
Source:
<code>protected void setActionMessageParameters() { <START> addValidationMessage(EngineMessage.VAR__ACTION__ADD); <END> addValidationMessage(EngineMessage.VAR__TYPE__USER_PROFILE); }</code><technical_language>this result in a weird flow: user wants update ssh-key validation in UserProfilesOperationCommandBase#validate fail (for some reason) - error add profile operation fails, no</technical_language>

Target:
protected void setActionMessageParameters() { UserProfile existingProfile = getUserProfile(); if (existingProfile != null && isSSHPublicKeyUpdate(existingProfile)) { addValidationMessage(EngineMessage.VAR__ACTION__UPDATE); } else { addValidationMessage(EngineMessage.VAR__ACTION__ADD); } addValidationMessage(EngineMessage.VAR__TYPE__USER_PROFILE); }
Source:
<code>public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { Assert.notNull(processor, "'processor' must not be null"); Assert.notNull(store, "'store' must not be null"); setMessageStore(store); this.outputProcessor = processor; this.correlationStrategy = (correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy); this.releaseStrategy = releaseStrategy == null ? new SimpleSequenceSizeReleaseStrategy() : releaseStrategy; this.sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy; <START> this.groupIds = new HashSet<>(); <END> }</code><technical_language>This done property level: private final Set<Object> groupIds = new HashSet<>(); change property. More final provides some performance optimization. volatile some degradation careful choosing use. For example a convention do for properties strictly configuration options. for properties changed concurrently internally end-user control ensure proper access. running for example</technical_language>

Target:
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { Assert.notNull(processor, "'processor' must not be null"); Assert.notNull(store, "'store' must not be null"); setMessageStore(store); this.outputProcessor = processor; this.correlationStrategy = (correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy); this.releaseStrategy = releaseStrategy == null ? new SimpleSequenceSizeReleaseStrategy() : releaseStrategy; this.sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy; }
Source:
<code>protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); <START> getDiskDao().getAllForVm(vm.getId()); <END> disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), true)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }</code><technical_language>please remove</technical_language>

Target:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), true)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }
Source:
<code>void publishErrorRecord(ZNRecord record, String instanceName, String updateSubPath, String updateKey, String sessionId, HelixDataAccessor accessor, boolean isController) { <START> _logger.error("StatusUpdate Error record: {}", record.toString()); <END> if (!ERROR_LOG_TO_ZK_ENABLED) { return; } Builder keyBuilder = accessor.keyBuilder(); if (isController) { accessor.setProperty(keyBuilder.controllerTaskError(updateSubPath), new Error(record)); } else { accessor.updateProperty(keyBuilder.stateTransitionError(instanceName, sessionId, updateSubPath, updateKey), new Error(record)); } }</code><technical_language>Nit, record.toString() is redundant, record is enough toString() auto called</technical_language>

Target:
void publishErrorRecord(ZNRecord record, String instanceName, String updateSubPath, String updateKey, String sessionId, HelixDataAccessor accessor, boolean isController) { _logger.error("StatusUpdate Error record: {}", record); if (!ERROR_LOG_TO_ZK_ENABLED) { return; } Builder keyBuilder = accessor.keyBuilder(); if (isController) { accessor.setProperty(keyBuilder.controllerTaskError(updateSubPath), new Error(record)); } else { accessor.updateProperty(keyBuilder.stateTransitionError(instanceName, sessionId, updateSubPath, updateKey), new Error(record)); } }
Source:
<code>protected boolean checkIfDisksExist(Iterable<DiskImage> disksList) { for (DiskImage disk : disksList) { GetImagesListVDSCommandParameters params = new GetImagesListVDSCommandParameters( imageToDestinationDomainMap.get(disk.getId()), getStoragePoolId()); <START> VDSReturnValue runVdsCommand = getBackend().getResourceManager().RunVdsCommand( <END> VDSCommandType.GetImagesList, params); if (runVdsCommand.getSucceeded()) { List<Guid> imagesOnStorageDomain = (List<Guid>) runVdsCommand.getReturnValue(); if (imagesOnStorageDomain.contains(disk.getId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_ALREADY_CONTAINS_DISK); return false; } } else { addCanDoActionMessage(VdcBllMessages.ERROR_GET_IMAGE_LIST); return false; } } return true; }</code><technical_language>please runVdsCommand instead of getBackend().getResourceManager().RunVdsComand</technical_language>

Target:
protected boolean checkIfDisksExist(Iterable<DiskImage> disksList) { Map<Guid, List<Guid>> alreadyRetrieved = new HashMap<>(); for (DiskImage disk : disksList) { Guid targetStorageDomainId = imageToDestinationDomainMap.get(disk.getId()); List<Guid> imagesOnStorageDomain = alreadyRetrieved.get(targetStorageDomainId); if (imagesOnStorageDomain == null) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GetImagesList, new GetImagesListVDSCommandParameters(targetStorageDomainId, getStoragePoolId()) ); if (returnValue.getSucceeded()) { imagesOnStorageDomain = (List<Guid>) returnValue.getReturnValue(); alreadyRetrieved.put(targetStorageDomainId, imagesOnStorageDomain); } else { addCanDoActionMessage(String.format("$sdName %1$s", getStorageDomain(targetStorageDomainId).getName())); addCanDoActionMessage(VdcBllMessages.ERROR_GET_IMAGE_LIST); return false; } } if (imagesOnStorageDomain.contains(disk.getId())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_ALREADY_CONTAINS_DISK); return false; } } return true; }
Source:
<code>public ImmutablePathsBuilder add(Map<String, List<String>> pathEntries) throws DuplicateResourceKeyException { <START> for (Iterator<Map.Entry<String, List<String>>> it = pathEntries.entrySet().iterator(); it.hasNext();) { <END> Map.Entry<String, List<String>> en = it.next(); List<String> availableValue = this.paths.get(en.getKey()); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring path entry " + en + " because the given resource path was already provided: " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding path entry " + en); } this.paths.put(en.getKey(), Collections.unmodifiableList(new ArrayList<String>(en.getValue()))); } } return this; }</code><technical_language>This more readable, giving result (if missing something): for (Entry<String, List<String>> en : pathEntries.entrySet()) {</technical_language>

Target:
public ImmutablePathsBuilder add(Map<String, List<String>> pathEntries) throws DuplicateResourceKeyException { for (Entry<String, List<String>> en : pathEntries.entrySet()) { List<String> availableValue = this.paths.get(en.getKey()); if (availableValue != null) { throw new DuplicateResourceKeyException("Ignoring path entry " + en + " because the given resource path was already provided: " + availableValue); } else { if (log.isDebugEnabled()) { log.debug("Adding path entry " + en); } this.paths.put(en.getKey(), Collections.unmodifiableList(new ArrayList<String>(en.getValue()))); } } return this; }
Source:
<code>public void startLifecyclesInRole(String role) { if (this.lazyLifecycles.size() > 0) { addLazyLifecycles(); } List<SmartLifecycle> lifecycles = new ArrayList<SmartLifecycle>(this.lifecycles.get(role)); <START> if (lifecycles != null) { <END> Collections.sort(lifecycles, new Comparator<SmartLifecycle>() { @Override public int compare(SmartLifecycle o1, SmartLifecycle o2) { return o1.getPhase() < o2.getPhase() ? -1 : o1.getPhase() > o2.getPhase() ? 1 : 0; } }); for (SmartLifecycle lifecycle : lifecycles) { try { lifecycle.start(); } catch (Exception e) { logger.error("Failed to start " + lifecycle + " in role " + role); } } } }</code><technical_language>!lifecycles.isEmpty()? new ArrayList produces a new instance. other side: sense a copy for MultiMap.get() result</technical_language>

Target:
public void startLifecyclesInRole(String role) { if (this.lazyLifecycles.size() > 0) { addLazyLifecycles(); } List<SmartLifecycle> lifecycles = this.lifecycles.get(role); if (lifecycles != null) { lifecycles = new ArrayList<SmartLifecycle>(lifecycles); Collections.sort(lifecycles, new Comparator<SmartLifecycle>() { @Override public int compare(SmartLifecycle o1, SmartLifecycle o2) { return o1.getPhase() < o2.getPhase() ? -1 : o1.getPhase() > o2.getPhase() ? 1 : 0; } }); for (SmartLifecycle lifecycle : lifecycles) { try { lifecycle.start(); } catch (Exception e) { logger.error("Failed to start " + lifecycle + " in role " + role); } } } }
Source:
<code>public void testClientReconnectOnExchangeHistoryExhaustion() throws Exception { startGrids(SRV_CNT); <START> client = true; <END> startClientGridsMultiThreaded(SRV_CNT, CLIENTS_CNT); waitForTopology(SRV_CNT + CLIENTS_CNT); awaitPartitionMapExchange(); verifyPartitionToNodeMappings(); verifyAffinityTopologyVersions(); verifyCacheOperationsOnClients(); }</code><technical_language>If i correct, remove 'client' field all, in 'getConfiguration' method this condition: if (!cfg.isClient) {</technical_language>

Target:
public void testClientReconnectOnExchangeHistoryExhaustion() throws Exception { startGrids(SRV_CNT); startClientGridsMultiThreaded(SRV_CNT, CLIENTS_CNT); waitForTopology(SRV_CNT + CLIENTS_CNT); awaitPartitionMapExchange(); verifyPartitionToNodeMappings(); verifyAffinityTopologyVersions(); verifyCacheOperationsOnClients(); }
Source:
<code>public Response setCompactionTaskLimit( @QueryParam("slotRatio") Double compactionTaskSlotRatio, @QueryParam("maxSlots") Integer maxCompactionTaskSlots, @HeaderParam(AuditManager.X_DRUID_AUTHOR) @DefaultValue("") final String author, @HeaderParam(AuditManager.X_DRUID_COMMENT) @DefaultValue("") final String comment, @Context HttpServletRequest req ) { CoordinatorCompactionConfig current = manager.watch( CoordinatorCompactionConfig.CONFIG_KEY, CoordinatorCompactionConfig.class ).get(); final CoordinatorCompactionConfig newCompactionConfig; if (current != null) { newCompactionConfig = CoordinatorCompactionConfig.from(current, compactionTaskSlotRatio, maxCompactionTaskSlots); } else { newCompactionConfig = new CoordinatorCompactionConfig(null, compactionTaskSlotRatio, maxCompactionTaskSlots); } if (!manager.set( CoordinatorCompactionConfig.CONFIG_KEY, newCompactionConfig, new AuditInfo(author, comment, req.getRemoteAddr()) )) { <START> return Response.status(Response.Status.BAD_REQUEST).build(); <END> } return Response.ok().build(); }</code><technical_language>minor nit: is add some message failure ? lines - Failed set config..</technical_language>

Target:
public Response setCompactionTaskLimit( @QueryParam("slotRatio") Double compactionTaskSlotRatio, @QueryParam("maxSlots") Integer maxCompactionTaskSlots, @HeaderParam(AuditManager.X_DRUID_AUTHOR) @DefaultValue("") final String author, @HeaderParam(AuditManager.X_DRUID_COMMENT) @DefaultValue("") final String comment, @Context HttpServletRequest req ) { CoordinatorCompactionConfig current = manager.watch( CoordinatorCompactionConfig.CONFIG_KEY, CoordinatorCompactionConfig.class ).get(); final CoordinatorCompactionConfig newCompactionConfig; if (current != null) { newCompactionConfig = CoordinatorCompactionConfig.from(current, compactionTaskSlotRatio, maxCompactionTaskSlots); } else { newCompactionConfig = new CoordinatorCompactionConfig(null, compactionTaskSlotRatio, maxCompactionTaskSlots); } final SetResult setResult = manager.set( CoordinatorCompactionConfig.CONFIG_KEY, newCompactionConfig, new AuditInfo(author, comment, req.getRemoteAddr()) ); if (setResult.isOk()) { return Response.ok().build(); } else { return Response.status(Response.Status.BAD_REQUEST) .entity(ImmutableMap.of("error", setResult.getException())) .build(); } }
Source:
<code>public void embeddedLdapServerRegistersExpectedAuthenticationProvider() { UserDetails ldapUser = ldapUserDetailsService.loadUserByUsername("przemyslaw.fusik"); assertThat(ldapUser, CoreMatchers.instanceOf(LdapUserDetailsImpl.class)); LdapUserDetails ldapUserDetails = (LdapUserDetailsImpl) ldapUser; assertThat(ldapUserDetails.getDn(), CoreMatchers.equalTo("uid=przemyslaw.fusik,ou=Users,dc=carlspring,dc=com")); assertThat(ldapUserDetails.getPassword(), CoreMatchers.equalTo("password")); assertThat(ldapUserDetails.getUsername(), CoreMatchers.equalTo("przemyslaw.fusik")); assertThat(ldapUser.getAuthorities(), CoreMatchers.hasItems(CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_DELETE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO))); <START> } <END></code><technical_language>@ogryniuk code changes affect this test</technical_language>

Target:
public void embeddedLdapServerRegistersExpectedAuthenticationProvider() { UserDetails ldapUser = ldapUserDetailsService.loadUserByUsername("przemyslaw.fusik"); assertThat(ldapUser, CoreMatchers.instanceOf(LdapUserDetailsImpl.class)); LdapUserDetails ldapUserDetails = (LdapUserDetailsImpl) ldapUser; assertThat(ldapUserDetails.getDn(), CoreMatchers.equalTo("uid=przemyslaw.fusik,ou=Users,dc=carlspring,dc=com")); assertThat(ldapUserDetails.getPassword(), CoreMatchers.equalTo("password")); assertThat(ldapUserDetails.getUsername(), CoreMatchers.equalTo("przemyslaw.fusik")); assertThat(ldapUser.getAuthorities(), CoreMatchers.hasItems(CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_DELETE_REPO), CoreMatchers.equalTo((GrantedAuthority) Privileges.ADMIN_CREATE_REPO), CoreMatchers.equalTo(new SimpleGrantedAuthority("VIEW_USER")))); }
Source:
<code>public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final DlmsPushNotification message = (DlmsPushNotification) e.getMessage(); final String correlationId = UUID.randomUUID().toString().replace("-", ""); final String deviceIdentification = message.getEquipmentIdentifier(); final String ipAddress = this.retrieveIpAddress(ctx, deviceIdentification); <START> if (PUSH_SMS_TRIGGER.equals(message.getTriggerType())) { <END> this.logMessage(message); final PushNotificationSms pushNotificationSms = new PushNotificationSms(deviceIdentification, ipAddress); final RequestMessage requestMessage = new RequestMessage(correlationId, "no-organisation", deviceIdentification, ipAddress, pushNotificationSms); LOGGER.info("Sending push notification sms wakeup to OSGP with correlation ID: " + correlationId); this.osgpRequestMessageSender.send(requestMessage, DeviceFunction.PUSH_NOTIFICATION_SMS.name()); } else if (PUSH_ALARM_TRIGGER.equals(message.getTriggerType())) { this.logMessage(message); final PushNotificationAlarm pushNotificationAlarm = new PushNotificationAlarm(deviceIdentification, message.getAlarms()); final RequestMessage requestMessage = new RequestMessage(correlationId, "no-organisation", deviceIdentification, ipAddress, pushNotificationAlarm); LOGGER.info("Sending push notification alarm to OSGP with correlation ID: " + correlationId); this.osgpRequestMessageSender.send(requestMessage, DeviceFunction.PUSH_NOTIFICATION_ALARM.name()); } else { LOGGER.info("Unknown received message, skip processing"); } }</code><technical_language>move contents of IF ELSE IF a function a descriptive name improve readability</technical_language>

Target:
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final DlmsPushNotification message = (DlmsPushNotification) e.getMessage(); final String correlationId = UUID.randomUUID().toString().replace("-", ""); final String deviceIdentification = message.getEquipmentIdentifier(); final String ipAddress = this.retrieveIpAddress(ctx, deviceIdentification); this.processPushedMessage(message, correlationId, deviceIdentification, ipAddress); }
Source:
<code>public static String formatSmsMessage(long userId, Event event, Position position) { <START> VelocityContext velocityContext = prepareContext(userId, event, position); <END> String smsTemplatesPath = Context.getConfig().getString("sms.templatesPath", "sms") + "/"; Template template = null; try { template = Context.getVelocityEngine().getTemplate(smsTemplatesPath + event.getType() + ".vm", StandardCharsets.UTF_8.name()); } catch (ResourceNotFoundException error) { Log.warning(error); template = Context.getVelocityEngine().getTemplate(smsTemplatesPath + "unknown.vm", StandardCharsets.UTF_8.name()); } StringWriter writer = new StringWriter(); template.merge(velocityContext, writer); return writer.toString(); }</code><technical_language>I share of code in this method</technical_language>

Target:
public static String formatSmsMessage(long userId, Event event, Position position) { VelocityContext velocityContext = prepareContext(userId, event, position); StringWriter writer = new StringWriter(); getTemplate(event, Context.getConfig().getString("sms.templatesPath", "sms") + "/") .merge(velocityContext, writer); return writer.toString(); }