auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static SourceFile scan(String target, CodeVisitor visitor) { final File baseDir = new File("src/test/java/"); File file = new File(baseDir, "org/sonar/java/checks/targets/" + target + ".java"); File bytecodeFile = new File("target/test-classes/"); if (!file.isFile()) { throw new IllegalArgumentException("File '" + file.getName() + "' not found."); } Project project = mock(Project.class); ProjectFileSystem pfs = mock(ProjectFileSystem.class); <START> SuppressWarningsFilter filter = mock(SuppressWarningsFilter.class); <END> when(project.getFileSystem()).thenReturn(pfs); when(pfs.getBasedir()).thenReturn(baseDir); DefaultJavaResourceLocator javaResourceLocator = new DefaultJavaResourceLocator(project, null, filter); JavaSquid javaSquid = new JavaSquid(new JavaConfiguration(Charset.forName("UTF-8")), javaResourceLocator, visitor); javaSquid.scan(Collections.singleton(file), Collections.<File>emptyList(), Collections.singleton(bytecodeFile)); Collection<SourceCode> sources = javaSquid.getIndex().search(new QueryByType(SourceFile.class)); if (sources.size() != 1) { throw new IllegalStateException("Only one SourceFile was expected whereas " + sources.size() + " has been returned."); } return (SourceFile) sources.iterator().next(); }</code><technical_language>Do need a mock here</technical_language>

Target:
public static SourceFile scan(String target, CodeVisitor visitor) { final File baseDir = new File("src/test/java/"); File file = new File(baseDir, "org/sonar/java/checks/targets/" + target + ".java"); File bytecodeFile = new File("target/test-classes/"); if (!file.isFile()) { throw new IllegalArgumentException("File '" + file.getName() + "' not found."); } SensorContext sensorContext = mock(SensorContext.class); when(sensorContext.getResource(Matchers.any(org.sonar.api.resources.File.class))).thenAnswer(new Answer<org.sonar.api.resources.File>() { @Override public org.sonar.api.resources.File answer(InvocationOnMock invocation) throws Throwable { org.sonar.api.resources.File response = (org.sonar.api.resources.File) invocation.getArguments()[0]; response.setEffectiveKey(""); return response; } }); Project project = mock(Project.class); ProjectFileSystem pfs = mock(ProjectFileSystem.class); when(project.getFileSystem()).thenReturn(pfs); when(pfs.getBasedir()).thenReturn(baseDir); DefaultJavaResourceLocator javaResourceLocator = new DefaultJavaResourceLocator(project, null, new SuppressWarningsFilter()); javaResourceLocator.setSensorContext(sensorContext); JavaSquid javaSquid = new JavaSquid(new JavaConfiguration(Charset.forName("UTF-8")), javaResourceLocator, visitor); javaSquid.scan(Collections.singleton(file), Collections.<File>emptyList(), Collections.singleton(bytecodeFile)); Collection<SourceCode> sources = javaSquid.getIndex().search(new QueryByType(SourceFile.class)); if (sources.size() != 1) { throw new IllegalStateException("Only one SourceFile was expected whereas " + sources.size() + " has been returned."); } return (SourceFile) sources.iterator().next(); }
Source:
<code>public void startSwitch(String filename, int uploadId) { synchronized (switchLock) { <START> if (!switching && new File(filename) != currentFile) <END> { switchFilename = filename; switchUploadId = uploadId; switchData = 0; switching = true; doSwitch(); } } }</code><technical_language>comparison equal constructing a new File object object reference existing one. .equals File object instead</technical_language>

Target:
public void startSwitch(String filename, int uploadId) { synchronized (switchLock) { if (!switching && !new File(filename).equals(currentFile)) { switchFilename = filename; switchUploadId = uploadId; switchData = 0; switching = true; doSwitch(); } } }
Source:
<code>public void testSourceSymbolNotReferenced() throws Exception { tester().assertThat(new PruneMarkDistinctColumns()) .on(p -> { Symbol key = p.symbol("key", BIGINT); Symbol mark = p.symbol("mark", BIGINT); Symbol hash = p.symbol("hash", BIGINT); Symbol unused = p.symbol("unused", BIGINT); return p.project( Assignments.identity(mark), p.markDistinct( mark, ImmutableList.of(key), Optional.of(hash), p.values(key, hash, unused))); }) .matches( strictProject( ImmutableMap.of("mark", PlanMatchPattern.expression("mark")), markDistinct("mark", ImmutableList.of("key"), Optional.of("hash"), strictProject( ImmutableMap.of( "key", PlanMatchPattern.expression("key"), <START> "hash", PlanMatchPattern.expression("hash")), <END> values(ImmutableList.of("key", "hash", "unused")))))); }</code><technical_language>static import of expression</technical_language>

Target:
public void testSourceSymbolNotReferenced() throws Exception { tester().assertThat(new PruneMarkDistinctColumns()) .on(p -> { Symbol key = p.symbol("key", BIGINT); Symbol mark = p.symbol("mark", BIGINT); Symbol hash = p.symbol("hash", BIGINT); Symbol unused = p.symbol("unused", BIGINT); return p.project( Assignments.identity(mark), p.markDistinct( mark, ImmutableList.of(key), hash, p.values(key, hash, unused))); }) .matches( strictProject( ImmutableMap.of("mark", expression("mark")), markDistinct("mark", ImmutableList.of("key"), "hash", strictProject( ImmutableMap.of( "key", expression("key"), "hash", expression("hash")), values(ImmutableList.of("key", "hash", "unused")))))); }
Source:
<code>public void testActionParameters() { hostService.setupNetworks() .modifiedBonds( hostNic() .name("bond0") .bonding( bonding() .options( option() .name("mode") .type("4") <START> .build() <END> ) .slaves( hostNic() .name("eth1") .build(), hostNic() .name("eth2") .build() ) .build() ) .build() ).send(); }</code><technical_language>If I remember correctly this call "build" required, "options" method accepts object a builder. If is a builder call "build" method internally. for other calls "build"</technical_language>

Target:
public void testActionParameters() { hostService.setupNetworks() .modifiedBonds( hostNic() .name("bond0") .bonding( bonding() .options( option() .name("mode") .type("4") ) .slaves( hostNic() .name("eth1"), hostNic() .name("eth2") ) ) ).send(); }
Source:
<code>private void checkFieldSeparator(String separator) { <START> if (separator.contains("\t") || separator.contains("\n") <END> || separator.contains("=")) { throw new IllegalArgumentException("Illegal field separator: " + separator); } }</code><technical_language>I define list of illegal characters in static list check check if separator is there</technical_language>

Target:
private void checkFieldSeparator(String separator) { if (ILLEGAL_SEPARATORS.contains(separator)) { throw new IllegalArgumentException("Illegal field separator: " + separator); } }
Source:
<code>private CompletableFuture<Void> executeInternal(boolean skipIndex) { if (lock.lock()) { List<CompletableFuture<Void>> futures = new ArrayList<>(); Deque<IndexedTypeIdentifier> toFlush = new LinkedList<>(); BiConsumer<Void, Throwable> flushIfNeeded = (v, t) -> { try { indexUpdater.flush(toFlush); } finally { lock.unlock(); } }; Set<IndexedTypeIdentifier> indexedTypes = new HashSet<>(); for (IndexedTypeIdentifier indexedType : searchIntegrator.getIndexBindings().keySet()) { indexedTypes.add(indexedType); } try { IndexWorker indexWork = new IndexWorker(cache.getName(), indexedTypes, skipIndex, null); futures.add(executor.submitConsumer(indexWork, TRI_CONSUMER)); CompletableFuture<Void> compositeFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); <START> return compositeFuture.whenComplete(flushIfNeeded); <END> } catch (Throwable t) { lock.unlock(); return CompletableFutures.completedExceptionFuture(t); } } else { return CompletableFutures.completedExceptionFuture(new MassIndexerAlreadyStartedException()); } }</code><technical_language>flushIfNeeded block</technical_language>

Target:
private CompletableFuture<Void> executeInternal(boolean skipIndex) { if (lock.lock()) { List<CompletableFuture<Void>> futures = new ArrayList<>(); Deque<IndexedTypeIdentifier> toFlush = new LinkedList<>(); BiConsumer<Void, Throwable> flushIfNeeded = (v, t) -> { try { indexUpdater.flush(toFlush); } finally { lock.unlock(); } }; Set<IndexedTypeIdentifier> indexedTypes = new HashSet<>(); for (IndexedTypeIdentifier indexedType : searchIntegrator.getIndexBindings().keySet()) { indexedTypes.add(indexedType); } try { IndexWorker indexWork = new IndexWorker(cache.getName(), indexedTypes, skipIndex, null); futures.add(executor.submitConsumer(indexWork, TRI_CONSUMER)); CompletableFuture<Void> compositeFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); return compositeFuture.whenCompleteAsync(flushIfNeeded, localExecutor); } catch (Throwable t) { lock.unlock(); return CompletableFutures.completedExceptionFuture(t); } } else { return CompletableFutures.completedExceptionFuture(new MassIndexerAlreadyStartedException()); } }
Source:
<code>protected void createMainControl(Composite parent, IEEFFormContainer formContainer) { EEFWidgetFactory widgetFactory = formContainer.getWidgetFactory(); FormData buttonFormData = new FormData(); buttonFormData.left = new FormAttachment(0, LABEL_WIDTH); this.checkbox = widgetFactory.createButton(parent, "", SWT.CHECK); this.checkbox.setLayoutData(buttonFormData); <START> if (!isEnabled()) { this.checkbox.setEnabled(false); } <END> this.controller = new EEFControllersFactory().createCheckboxController(this.description, this.variableManager, this.interpreter, this.editingDomain); }</code><technical_language>this need done in refresh instead of creation of controls</technical_language>

Target:
protected void createMainControl(Composite parent, IEEFFormContainer formContainer) { EEFWidgetFactory widgetFactory = formContainer.getWidgetFactory(); FormData buttonFormData = new FormData(); buttonFormData.left = new FormAttachment(0, LABEL_WIDTH); this.checkbox = widgetFactory.createButton(parent, "", SWT.CHECK); this.checkbox.setLayoutData(buttonFormData); this.controller = new EEFControllersFactory().createCheckboxController(this.description, this.variableManager, this.interpreter, this.editingDomain); }
Source:
<code><START> public @NonNull String getSymbolText(long address) { <END> if ((address & (0xFFFFFFFF << 32)) != 0) { return String.format("%08x", address); } return String.format("%016x", address); }</code><technical_language>this implementation apply cases? a generic utility method. defined a default, a static, method in interface</technical_language>

Target:
public @NonNull String getSymbolText(long address) { if ((address & (0xFFFFFFFF << 32)) == 0) { return String.format("%08x", address); } return String.format("%016x", address); }
Source:
<code>public boolean verifySchema(Config configType, String jsonConfig) throws IOException, ProcessingException { ProcessingReport results = null; boolean isSuccess = false; switch (configType) { case TABLE : results = this.tableSchema.validate(new ObjectMapper().readTree(jsonConfig)); break; case SECURITY : results = this.securitySchema.validate(new ObjectMapper().readTree(jsonConfig)); break; case VARIABLE : results = this.variableSchema.validate(new ObjectMapper().readTree(jsonConfig)); break; default : log.error("Not a valid config type :" + configType); <START> return false; <END> } isSuccess = results.isSuccess(); if (!isSuccess) { throw new ProcessingException("Schema validation failed"); } return isSuccess; }</code><technical_language>A method this return false throw exception both. contract is confusing</technical_language>

Target:
public boolean verifySchema(Config configType, String jsonConfig) throws IOException, ProcessingException { ProcessingReport results = null; boolean isSuccess = false; switch (configType) { case TABLE : results = this.tableSchema.validate(new ObjectMapper().readTree(jsonConfig)); break; case SECURITY : results = this.securitySchema.validate(new ObjectMapper().readTree(jsonConfig)); break; case VARIABLE : results = this.variableSchema.validate(new ObjectMapper().readTree(jsonConfig)); break; default : log.error("Not a valid config type :" + configType); break; } isSuccess = (results == null ? false : results.isSuccess()); if (!isSuccess) { throw new ProcessingException("Schema validation failed"); } return isSuccess; }
Source:
<code><START> public void addListenerOnMainMenuButton(){ <END> mainMenu = (Button) findViewById(R.id.main_menu_button_puzzle); mainMenu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(v.getContext(), MainMenuActivity.class); startActivity(i); } }); }</code><technical_language>methods private</technical_language>

Target:
private void addListenerOnMainMenuButton() { mainMenu = (Button) findViewById(R.id.main_menu_button_puzzle); mainMenu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(v.getContext(), MainMenuActivity.class); startActivity(i); } }); }
Source:
<code>private String getWebConsoleUrl(Connection connection, IResource resource) { StringBuilder url = new StringBuilder(connection.getHost()).append("/console"); String projectName = resource == null? null : resource.getNamespace(); if (projectName != null) { url.append("/project/").append(projectName); } if (resource != null && !(resource instanceof IProject)) { url.append("/browse"); if (resource instanceof IBuildConfig ) { url.append("/builds/").append(resource.getName()); } else if ( resource instanceof IBuild) { String buildConfig = resource.getLabels().get("buildconfig"); url.append("/builds/").append(buildConfig).append("/").append(resource.getName()); } else if (resource instanceof IDeploymentConfig) { url.append("/deployments/").append(resource.getName()); } else if (resource instanceof IPod) { url.append("/pods/").append(resource.getName()); } else if (resource instanceof IService) { url.append("/services/").append(resource.getName()); } else if (resource instanceof IImageStream) { url.append("/images/").append(resource.getName()); <START> } else if (resource instanceof IPersistentVolumeClaim) { <END> url.append("/persistentvolumeclaims/").append(resource.getName()); } } return url.toString(); }</code><technical_language>I this surrounding 'if' block refactored of logic; introduce a map</technical_language>

Target:
protected String getWebConsoleUrl(Connection connection, IResource resource) { StringBuilder url = new StringBuilder(connection.getHost()).append("/console"); String projectName = resource == null? null : resource.getNamespace(); if (projectName != null) { url.append("/project/").append(projectName); } if (resource != null && !(resource instanceof IProject)) { url.append(getResourceURL(resource)); } return url.toString(); }
Source:
<code>public MetronomeBuilder withRatePerSecond(double ratePerSecond) { if (ratePerSecond <= 0) { <START> throw new IllegalArgumentException("ratePerSecond can't smaller than 0"); <END> } long intervalMicros = round(SECONDS.toMicros(1) / ratePerSecond); return withIntervalMicros(intervalMicros); }</code><technical_language>smaller 1</technical_language>

Target:
public MetronomeBuilder withRatePerSecond(double ratePerSecond) { long intervalMicros = round(SECONDS.toMicros(1) / ratePerSecond); return withIntervalMicros(intervalMicros); }
Source:
<code>public void visitVariable(VariableTree tree) { ExpressionTree initializer = tree.initializer(); <START> boolean newArray = initializer != null && initializer.is(Kind.NEW_ARRAY) && ((NewArrayTree) initializer).newKeyword() != null; <END> if (newArray || !ModifiersUtils.hasModifier(tree.modifiers(), Modifier.FINAL)) { super.visitVariable(tree); } }</code><technical_language>Instead of for presence of new keyword, check for presence of initializers. Currently, issue code : final long[] array = new long[] {3L, 4L}; // compliant</technical_language>

Target:
public void visitVariable(VariableTree tree) { ExpressionTree initializer = tree.initializer(); boolean arrayNotInitialized = initializer != null && initializer.is(Kind.NEW_ARRAY) && ((NewArrayTree) initializer).initializers().size() == 0; if (arrayNotInitialized || !ModifiersUtils.hasModifier(tree.modifiers(), Modifier.FINAL)) { super.visitVariable(tree); } }
Source:
<code>private void checkFstab() { File f = new File(getBasePath(), ETC_FSTAB_LOCATION); if (f.exists()) { String line = null; status = RsyncStatus.ETC_FSTAB_INVALID; try (BufferedReader reader = new BufferedReader(new FileReader(f))) { while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { <START> if (line.contains("cygdrive") && line.contains("noacl")) { <END> status = RsyncStatus.OK; } } } } catch (IOException e) { status = RsyncStatus.ETC_FSTAB_INVALID; } } else { status = RsyncStatus.ETC_FSTAB_NOT_FOUND; } }</code><technical_language>extract 3 strings constants for improved readability</technical_language>

Target:
private void checkFstab() { File f = new File(getBasePath(), ETC_FSTAB_LOCATION); if (f.exists()) { String line = null; status = RsyncStatus.ETC_FSTAB_INVALID; try (BufferedReader reader = new BufferedReader(new FileReader(f))) { while ((line = reader.readLine()) != null) { if (!line.startsWith(COMMENT_PREFIX) && line.contains(CYGDRIVE) && line.contains(NOACL_FLAG)) { status = RsyncStatus.OK; } } } catch (IOException e) { status = RsyncStatus.ETC_FSTAB_INVALID; } } else { status = RsyncStatus.ETC_FSTAB_NOT_FOUND; } }
Source:
<code>private void onPendingResolution(@Nullable PendingResolution resolution) { if (resolution == null) { Log.e(TAG, "Got null resolution, can't do anything"); return; } try { startIntentSenderForResult(resolution.getPendingIntent().getIntentSender(), resolution.getRequestCode(), null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Failed to send resolution.", e); <START> finish(); <END> } }</code><technical_language>Yeah, I thinking of custom exceptions. IdpResponse.fromError(...)</technical_language>

Target:
private void onPendingResolution(@Nullable PendingResolution resolution) { if (resolution == null) { Log.e(TAG, "Got null resolution, can't do anything"); return; } try { startIntentSenderForResult(resolution.getPendingIntent().getIntentSender(), resolution.getRequestCode(), null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Failed to send resolution.", e); IdpResponse errorResponse = IdpResponse.fromError( new FirebaseUiException(ErrorCodes.UNKNOWN_ERROR, getString(R.string.fui_general_error), e)); finish(RESULT_OK, errorResponse.toIntent()); } }
Source:
<code><START> public WorkunitInfo setApplicationValues(org.hpccsystems.ws.client.gen.wsworkunits.v1_69.ApplicationValue[] vals) <END> { if (vals==null) { return this; } applicationValues=new ArrayList<ApplicationValueInfo>(); for (int i=0; i < vals.length;i++) { applicationValues.add(new ApplicationValueInfo(vals[i])); } return this; }</code><technical_language>ApplicationValueWrapper</technical_language>

Target:
public WorkunitInfo setApplicationValues(org.hpccsystems.ws.client.gen.wsworkunits.v1_69.ApplicationValue[] vals) { if (vals==null) { return this; } applicationValues=new ArrayList<ApplicationValueWrapper>(); for (int i=0; i < vals.length;i++) { applicationValues.add(new ApplicationValueWrapper(vals[i])); } return this; }
Source:
<code>public void onCompleted() { synchronized (this) { if (parentCompleted) { <START> delegate.onCompleted(); <END> } childCompleted = true; } }</code><technical_language>call onXXX methods while holding a lock</technical_language>

Target:
public void onCompleted() { boolean bothCompleted = false; synchronized (this) { if (parentCompleted) { bothCompleted = true; } childCompleted = true; } if (bothCompleted) { delegate.onCompleted(); } }
Source:
<code>protected List<String> getTokens() { <START> return tokenExpirations.keySet().stream().collect(Collectors.toList()); <END> }</code><technical_language>synchronize too</technical_language>

Target:
protected List<String> getTokens() { synchronized (tokenExpirations) { return tokenExpirations.keySet().stream().collect(Collectors.toList()); } }
Source:
<code>public static ConfigEntry newConfigEntry(String name, String value, ConfigEntry.ConfigSource source, boolean isSensitive, boolean isReadOnly, List<ConfigEntry.ConfigSynonym> synonyms) { <START> return new ConfigEntry(name, value, source, isSensitive, isReadOnly, synonyms, null, null); <END> }</code><technical_language>ConfigType.UNKNOWN instead of null</technical_language>

Target:
public static ConfigEntry newConfigEntry(String name, String value, ConfigEntry.ConfigSource source, boolean isSensitive, boolean isReadOnly, List<ConfigEntry.ConfigSynonym> synonyms) { return new ConfigEntry(name, value, source, isSensitive, isReadOnly, synonyms, ConfigType.UNKNOWN, null); }
Source:
<code>void emit(CodeWriter codeWriter) { codeWriter.emitAnnotations(annotations); <START> codeWriter.emitModifiers(modifiers); <END> codeWriter.emit("$T $L", type, name); }</code><technical_language>I builder approach .build() throw if modifiers inappropriate modifiers private</technical_language>

Target:
void emit(CodeWriter codeWriter) { codeWriter.emitAnnotations(annotations, true); codeWriter.emitModifiers(modifiers); codeWriter.emit("$T $L", type, name); }
Source:
<code>public void testSimple() throws Exception { <START> Coordinate coordinate = new Coordinate( <END> 42 , "service", "user", "cell", false ); assertEquals("/cn/cell/user/service/42/config", ZkCoordinatePath.getConfigPath(coordinate, null)); assertEquals("/cn/cell/user/service/42/config/name", ZkCoordinatePath.getConfigPath(coordinate, "name")); assertEquals("/cn/cell/user/service/42", ZkCoordinatePath.getCoordinateRoot(coordinate)); assertEquals("/cn/cell/user/service/42/status", ZkCoordinatePath.getStatusPath(coordinate)); assertEquals("/cn/cell/user/service", ZkCoordinatePath.coordinateWithoutInstanceAsPath( "cell", "user", "service")); assertEquals("/cn/cell/user/service/42/status", ZkCoordinatePath.getStatusPath("cell", "user", "service", 42)); }</code><technical_language>final</technical_language>

Target:
public void testSimple() throws Exception { final Coordinate coordinate = new Coordinate( 42 , "service", "user", "cell", false ); assertEquals("/cn/cell/user/service/42/config", ZkCoordinatePath.getConfigPath(coordinate, null)); assertEquals("/cn/cell/user/service/42/config/name", ZkCoordinatePath.getConfigPath(coordinate, "name")); assertEquals("/cn/cell/user/service/42", ZkCoordinatePath.getCoordinateRoot(coordinate)); assertEquals("/cn/cell/user/service/42/status", ZkCoordinatePath.getStatusPath(coordinate)); assertEquals("/cn/cell/user/service", ZkCoordinatePath.coordinateWithoutInstanceAsPath( "cell", "user", "service")); assertEquals("/cn/cell/user/service/42/status", ZkCoordinatePath.getStatusPath("cell", "user", "service", 42)); }
Source:
<code>public void testWriteAttributeWithCredentialReferenceWithAliasOnly() throws Exception { try { getNonEmptyCredentialStore(); addKeyStoreWithCredentialReference(KS_NAME, NON_EMPTY_CS_NAME, EXISTING_ALIAS, null, true); testWriteCredentialReferenceAttribute("key-store", KS_NAME, null, NEW_ALIAS, null, true); <START> assertEquals(null, readAttribute(KS_NAME, CLEAR_TEXT_ATTRIBUTE_NAME)); <END> assertEquals(EXISTING_ALIAS, readAttribute(KS_NAME, ALIAS_ATTRIBUTE_NAME)); assertEquals(NON_EMPTY_CS_NAME, readAttribute(KS_NAME, STORE_ATTRIBUTE_NAME)); } finally { removeKeyStore(KS_NAME); } }</code><technical_language>simplified assertNull</technical_language>

Target:
public void testWriteAttributeWithCredentialReferenceWithAliasOnly() throws Exception { try { getNonEmptyCredentialStore(); addKeyStoreWithCredentialReference(KS_NAME, NON_EMPTY_CS_NAME, EXISTING_ALIAS, null, true); testWriteCredentialReferenceAttribute("key-store", KS_NAME, null, NEW_ALIAS, null, true); assertNull(readAttribute(KS_NAME, CLEAR_TEXT_ATTRIBUTE_NAME)); assertEquals(EXISTING_ALIAS, readAttribute(KS_NAME, ALIAS_ATTRIBUTE_NAME)); assertEquals(NON_EMPTY_CS_NAME, readAttribute(KS_NAME, STORE_ATTRIBUTE_NAME)); } finally { removeKeyStore(KS_NAME); } }
Source:
<code>public boolean existsAnyEmPcrLibrary(Collection<LibraryDilution> projectLibraryDilutions) throws IOException { for (LibraryDilution dil : projectLibraryDilutions) { <START> if (PlatformType.valueOf(dil.getLibrary().getPlatformName()).usesEmPCR()) { <END> return true; } } return false; }</code><technical_language>I I goofed this needs toUpperCase</technical_language>

Target:
public boolean existsAnyEmPcrLibrary(Collection<LibraryDilution> projectLibraryDilutions) throws IOException { for (LibraryDilution dil : projectLibraryDilutions) { if (PlatformType.valueOf(dil.getLibrary().getPlatformName().toUpperCase()).usesEmPCR()) { return true; } } return false; }
Source:
<code>public long receivePower(long microJoules, boolean simulate) { if (toWaitTicks > 0) { return microJoules; } EnumFacing openFace = getOpenFace(); <START> if(openFace != null){ <END> for (int d = 1; d < 5; d++) { AxisAlignedBB aabb = getSuckingBox(openFace, d); List<Entity> discoveredEntities = pipe.getHolder().getPipeWorld().getEntitiesWithinAABB(Entity.class, aabb); for (Entity entity : discoveredEntities) { long leftOver = trySuckEntity(entity, openFace, microJoules, simulate); if (leftOver < microJoules) { return leftOver; } } } return microJoules - MjAPI.MJ; }else{ return microJoules; } }</code><technical_language>cleaner do if statement: do "if openFace == null return microJoules" wrapping in additional indent level</technical_language>

Target:
public long receivePower(long microJoules, boolean simulate) { if (toWaitTicks > 0) { return microJoules; } EnumFacing openFace = getOpenFace(); if(openFace == null) { return microJoules; } for (int d = 1; d < 5; d++) { AxisAlignedBB aabb = getSuckingBox(openFace, d); List<Entity> discoveredEntities = pipe.getHolder().getPipeWorld().getEntitiesWithinAABB(Entity.class, aabb); for (Entity entity : discoveredEntities) { long leftOver = trySuckEntity(entity, openFace, microJoules, simulate); if (leftOver < microJoules) { return leftOver; } } } return microJoules - MjAPI.MJ; }
Source:
<code>private void deleteSuccessVideos(ITestResult result, String className) { if (result.isSuccess() && (null != System.getenv("KEEP_ALL_VIDEOS")) && !(System.getenv("KEEP_ALL_VIDEOS").equalsIgnoreCase("true"))) { File videoFile = new File(System.getProperty("user.dir") + FileLocations.ANDROID_SCREENSHOTS_DIRECTORY + AppiumDeviceManager.getAppiumDevice().getDevice().getUdid() + "/" + className + "/" + result.getMethod().getMethodName() + "/" + result.getMethod().getMethodName() + ".mp4"); <START> System.out.println(String.format("Deleting video file - %s, if it exists", videoFile)); <END> if (videoFile.exists()) { videoFile.delete(); } } }</code><technical_language>change this LOGGER.INFO</technical_language>

Target:
private void deleteSuccessVideos(ITestResult result, String className) { if (result.isSuccess() && (null != System.getenv("KEEP_ALL_VIDEOS")) && !(System.getenv("KEEP_ALL_VIDEOS").equalsIgnoreCase("true"))) { File videoFile = new File(System.getProperty("user.dir") + FileLocations.ANDROID_SCREENSHOTS_DIRECTORY + AppiumDeviceManager.getAppiumDevice().getDevice().getUdid() + "/" + className + "/" + result.getMethod().getMethodName() + "/" + result.getMethod().getMethodName() + ".mp4"); if (videoFile.exists()) { videoFile.delete(); } } }
Source:
<code>public void onError(Throwable throwable) { <START> log.error("onError for CorfuReplicationDiscoveryServeiceLisener"); <END> }</code><technical_language>print throwable</technical_language>

Target:
public void onError(Throwable throwable) { log.error("onError with a throwable {}", throwable); }
Source:
<code>public static boolean hasConstexprStaticIntegralValueField(ICPPClassType type, long expectedValue) { return Arrays.stream(ClassTypeHelper.getFields(type)).filter(IS_STATIC_VARIABLE).filter(IS_NAMED_VALUE) .filter(HAS_INTEGRAL_TYPE).filter(IS_CONSTEXPR_FIELD).filter(field -> { <START> return field.getInitialValue().numberValue().longValue() == expectedValue; <END> }).findFirst().isPresent(); }</code><technical_language>getInitialValue() numberValue() need null checks</technical_language>

Target:
public static boolean hasConstexprStaticIntegralValueField(ICPPClassType type, long expectedValue) { return Arrays.stream(ClassTypeHelper.getFields(type)).filter(IS_STATIC_VARIABLE).filter(IS_NAMED_VALUE) .filter(HAS_INTEGRAL_TYPE).filter(HAS_CONST_TYPE).filter(field -> { return variableHasInitialNumberValue(field, expectedValue); }).findFirst().isPresent(); }
Source:
<code>public URL getEntryUrlOrNull(String entryName) { if (jarFile.findEntry(entryName) != null) { try { return new URL("jar", null, -1, fileUri + "!/" + entryName, this); } catch (MalformedURLException e) { <START> throw new RuntimeException("Unexpectedly invalid entry name", e); <END> } } return null; }</code><technical_language>"invalid entry name" sufficient. "unexpected" is implied :)</technical_language>

Target:
public URL getEntryUrlOrNull(String entryName) { if (jarFile.findEntry(entryName) != null) { try { return new URL("jar", null, -1, fileUri + "!/" + entryName, this); } catch (MalformedURLException e) { throw new RuntimeException("Invalid entry name", e); } } return null; }
Source:
<code>@Test public void testExchange() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .exchange(RelDistributions.hash(ImmutableList.of(0, 1))) .build(); <START> String relJson = RelOptUtil.dumpPlan("", rel, <END> SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES); String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson); final String expected = "" + "LogicalExchange(distribution=[hash[0, 1]])\n" + " LogicalTableScan(table=[[scott, EMP]])\n"; assertThat(s, isLinux(expected)); }</code><technical_language>final</technical_language>

Target:
@Test public void testExchange() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .exchange(RelDistributions.hash(ImmutableList.of(0, 1))) .build(); final String relJson = RelOptUtil.dumpPlan("", rel, SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES); String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson); final String expected = "" + "LogicalExchange(distribution=[hash[0, 1]])\n" + " LogicalTableScan(table=[[scott, EMP]])\n"; assertThat(s, isLinux(expected)); }
Source:
<code>public void initialize() { logger.debug("Initializing thing {}", getThing().getUID()); config = getConfigAs(LIRCRemoteConfiguration.class); remoteName = config.getRemote(); if (remoteName == null) { logger.error("Remote name is not set in {}", getThing().getUID()); <START> return; <END> } initializeBridge((getBridge() == null) ? null : getBridge().getHandler(), (getBridge() == null) ? null : getBridge().getStatus()); }</code><technical_language>guarantee Thing's status is set sooner later. If simply return here, this happen stay in INITIALIZING forever. Therefore, e.g. java updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION ERROR, "Remote name is set") a choice, in initializeBridge()</technical_language>

Target:
public void initialize() { logger.debug("Initializing thing {}", getThing().getUID()); config = getConfigAs(LIRCRemoteConfiguration.class); remoteName = config.getRemote(); if (remoteName == null) { logger.error("Remote name is not set in {}", getThing().getUID()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Remote name is not set"); } else { bridgeHandler = (LIRCBridgeHandler) getBridge().getHandler(); bridgeHandler.registerMessageListener(this); if (getBridge().getStatus() == ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); } } }
Source:
<code>public TextAnalyticsClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); <START> Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); <END> clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); }</code><technical_language>I noticed in recording for tests, SDK version name UnknownName/UnknownVersion. Is this correct</technical_language>

Target:
public TextAnalyticsClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); Map<String, String> properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); }
Source:
<code>public void testDeployServerReturnsUnexpectedError() throws InterruptedException { server.enqueue(responseUnexpectedError()); NetworkInfo networkInfo = NetworkInfo .create("networkDomainId", NIC.builder().vlanId("vlanId").build(), Lists.<NIC>newArrayList()); try { serverApi().deployServer(ServerApiMockTest.class.getSimpleName(), "imageId", true, networkInfo, "administratorPassword"); <START> failBecauseExceptionWasNotThrown(ResourceNotFoundException.class); <END> } catch (HttpResponseException e) { assertNotNull(e); assertSent(POST, "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/deployServer"); } }</code><technical_language>this need changed</technical_language>

Target:
public void testDeployServerReturnsUnexpectedError() throws InterruptedException { server.enqueue(responseUnexpectedError()); NetworkInfo networkInfo = NetworkInfo .create("networkDomainId", NIC.builder().vlanId("vlanId").build(), Lists.<NIC>newArrayList()); try { serverApi().deployServer(ServerApiMockTest.class.getSimpleName(), "imageId", true, networkInfo, "administratorPassword"); failBecauseExceptionWasNotThrown(HttpResponseException.class); } catch (HttpResponseException e) { assertNotNull(e); assertSent(POST, "/caas/2.4/6ac1e746-b1ea-4da5-a24e-caf1a978789d/server/deployServer"); } }
Source:
<code>private Employment getEmployment(boolean full) throws JAXBException { JAXBContext context = JAXBContext.newInstance(new Class[] { Employment.class }); Unmarshaller unmarshaller = context.createUnmarshaller(); String name = "/record_2.0/samples/read_samples/employment-2.0.xml"; if(full) { <START> name = "/record_2.0/samples/read_samples END> } InputStream inputStream = getClass().getResourceAsStream(name); return (Employment) unmarshaller.unmarshal(inputStream); }</code><technical_language>double slashes</technical_language>

Target:
private Employment getEmployment(boolean full) throws JAXBException { JAXBContext context = JAXBContext.newInstance(new Class[] { Employment.class }); Unmarshaller unmarshaller = context.createUnmarshaller(); String name = "/record_2.0/samples/read_samples/employment-2.0.xml"; if(full) { name = "/record_2.0/samples/read_samples/employment-full-2.0.xml"; } InputStream inputStream = getClass().getResourceAsStream(name); return (Employment) unmarshaller.unmarshal(inputStream); }
Source:
<code>public PluginInfoWrapper getPluginInfo(String plugname) { for (PluginInfoWrapper pluginInfoWrapper : pluginWrappers) { if (pluginInfoWrapper.getPluginClassName().equals(plugname) || pluginInfoWrapper.getFilename().equals(plugname)) { return pluginInfoWrapper; } } return null; <START> } <END></code><technical_language>above, please deprecate this first</technical_language>

Target:
public PluginInfoWrapper getPluginInfo(String plugname) { for (PluginInfoWrapper pluginInfoWrapper : loadedPlugins.getLoadedPlugins()) { if (pluginInfoWrapper.getPluginClassName().equals(plugname) || pluginInfoWrapper.getFilename().equals(plugname)) { return pluginInfoWrapper; } } return null; }
Source:
<code>protected X509Certificate loadCACertificate(String path) { try ( InputStream inStream = new FileInputStream(path); ) { X509Certificate cert = (X509Certificate) this.certFactory.generateCertificate(inStream); <START> inStream.close(); <END> return cert; } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>This line unnecessary try-with-resources syntax..</technical_language>

Target:
protected X509Certificate loadCACertificate(String path) { try ( InputStream inStream = new FileInputStream(path); ) { return (X509Certificate) this.certFactory.generateCertificate(inStream); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public static File getRemovableStorageAppDir(@NonNull Context context) { int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP) { File[] fileList = context.getExternalFilesDirs("Android"); <START> for (File extFile : fileList){ <END> if (extFile != null && Environment.isExternalStorageRemovable(extFile)){ return extFile; } } } return null; }</code><technical_language>context.getExternalFilesDirs required API level 19 above, minSdkVersion is 14. support library function: <LINK_0></technical_language>

Target:
public static File getRemovableStorageAppDir(@NonNull Context context) { int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP) { File[] fileList = context.getExternalFilesDirs(null); for (File extFile : fileList){ if (extFile != null && Environment.isExternalStorageRemovable(extFile)){ return extFile; } } } return null; }
Source:
<code>private void loadBackdrop() { getSharedPreferences(); <START> if (!name.equals(Preferences.DEF_VALUE)) <END> tvName.setText(name); if (!email.equals(Preferences.DEF_VALUE)) tvEmail.setText(email); if (!profilePicUrl.equals(Preferences.DEF_VALUE)) Glide.with(this).load(profilePicUrl).into(ivProfilePic); if (!coverPicUrl.equals(Preferences.DEF_VALUE)) Picasso.with(this).load(coverPicUrl).resize(DeviceDimensionsHelper.getDisplayWidth(this), 0).into(ivCoverPic); }</code><technical_language>in avoid NullPointerException Preferences.DEF_VALUE null. !Preferences.DEF_VALUE.equals(name) If check if a String reference is equal another string is a null reference, do this: String x = "this is a null reference" if (x.equalsIgnoreCase(yourStringReferenceThatMightBeNull) ) { //do fun stuff } If is doubt null references for Strings comparing, need check for a null reference of avoid possibility of a NullPointerException</technical_language>

Target:
private void loadBackdrop() { getSharedPreferences(); if (!Preferences.DEF_VALUE.equals(name)) tvName.setText(name); if (!Preferences.DEF_VALUE.equals(email)) tvEmail.setText(email); if (!Preferences.DEF_VALUE.equals(profilePicUrl)) Glide.with(this).load(profilePicUrl).into(ivProfilePic); if (!Preferences.DEF_VALUE.equals(coverPicUrl)) Picasso.with(this).load(coverPicUrl).resize(DeviceDimensionsHelper.getDisplayWidth(this), 0).into(ivCoverPic); }
Source:
<code>void markContainersInactive(Set<Container> inactiveContainerCandidateSet) throws InterruptedException { if (inactiveContainerCandidateSet != null) { boolean success = false; Exception updateException = null; int retry = 0; while (!success && retry < config.maxRetryCountOnUpdateFailure) { Map<Short, Account> accountToUpdateMap = new HashMap<>(); inactiveContainerCandidateSet.forEach(container -> { short accountId = container.getParentAccountId(); Account accountToEdit = accountToUpdateMap.computeIfAbsent(accountId, this::getAccountById); Container containerToEdit = accountToEdit.getContainerById(container.getId()); Container editedContainer = new ContainerBuilder(containerToEdit).setStatus(Container.ContainerStatus.INACTIVE).build(); accountToUpdateMap.put(accountId, new AccountBuilder(accountToEdit).addOrUpdateContainer(editedContainer).build()); }); try { updateAccounts(accountToUpdateMap.values()); success = true; } catch (AccountServiceException ase) { updateException = ase; retry++; Thread.sleep(config.retryDelayMs); } } if (updateException != null) { logger.error("Failed to mark containers INACTIVE in set : after retries", inactiveContainerCandidateSet, config.maxRetryCountOnUpdateFailure, updateException); <START> accountServiceMetrics.accountUpdatesToZkErrorCount.inc(); <END> } } }</code><technical_language>This wrong metric (or needs name change)</technical_language>

Target:
void markContainersInactive(Set<Container> inactiveContainerCandidateSet) throws InterruptedException { if (inactiveContainerCandidateSet != null) { Exception updateException = null; int retry = 0; Map<Short, Account> accountToUpdateMap = new HashMap<>(); inactiveContainerCandidateSet.forEach(container -> { short accountId = container.getParentAccountId(); Account accountToEdit = accountToUpdateMap.computeIfAbsent(accountId, this::getAccountById); Container containerToEdit = accountToEdit.getContainerById(container.getId()); Container editedContainer = new ContainerBuilder(containerToEdit).setStatus(Container.ContainerStatus.INACTIVE).build(); accountToUpdateMap.put(accountId, new AccountBuilder(accountToEdit).addOrUpdateContainer(editedContainer).build()); }); do { try { updateAccounts(accountToUpdateMap.values()); updateException = null; } catch (AccountServiceException ase) { updateException = ase; retry++; Thread.sleep(config.retryDelayMs); } } while (updateException != null && retry < config.maxRetryCountOnUpdateFailure); if (updateException != null) { logger.error("Failed to mark containers INACTIVE in set : after retries", inactiveContainerCandidateSet, config.maxRetryCountOnUpdateFailure, updateException); accountServiceMetrics.accountUpdatesToStoreErrorCount.inc(); } } }
Source:
<code>private void expandPoolIfNecessary(int channelCount) { if (!asyncExpantionExceptionOccurred.get()) { try { this.channelPool.ensureCapacity(channelCount); } catch (IOException e) { <START> LOG.info("Could not expand the channel pool.", e); <END> asyncExpantionExceptionOccurred.set(true); } } }</code><technical_language>error encounter IOException expanding channel pool</technical_language>

Target:
private void expandPoolIfNecessary(int channelCount) { try { this.channelPool.ensureChannelCount(channelCount); } catch (IOException e) { LOG.info("Could not expand the channel pool.", e); } }
Source:
<code>private List<PageTitle> getExpectedResults() { List<PageTitle> result = new ArrayList<>(); result.add(new PageTitle(null, <START> "Sciëntologie", new <END> WikiSite("af.wikipedia.org"))); result.add(new PageTitle(null, "سينتولوجيا", new WikiSite("ar.wikipedia.org"))); result.add(new PageTitle(null, "سيينتولوجيا", new WikiSite("arz.wikipedia.org"))); return result; }</code><technical_language>title in parameter? (confusing) PageTitle docs: prefixedText title of page optional namespace prefix</technical_language>

Target:
private List<PageTitle> getExpectedResults() { List<PageTitle> result = new ArrayList<>(); result.add(new PageTitle("Sciëntologie", WikiSite.forLanguageCode("af"))); result.add(new PageTitle("سينتولوجيا", WikiSite.forLanguageCode("ar"))); result.add(new PageTitle("سيينتولوجيا", WikiSite.forLanguageCode("arz"))); return result; }
Source:
<code>public B readEnvironment(SystemReader sr) { if (getGitDir() == null) { String val = sr.getenv(GIT_DIR_KEY); if (val != null) setGitDir(new File(val)); } if (getGitCommonDir() == null) { String val = sr.getenv(GIT_COMMON_DIR_KEY); <START> if (val != null) <END> setGitCommonDir(new File(val)); } if (getObjectDirectory() == null) { String val = sr.getenv(GIT_OBJECT_DIRECTORY_KEY); if (val != null) setObjectDirectory(new File(val)); } if (getAlternateObjectDirectories() == null) { String val = sr.getenv(GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addAlternateObjectDirectory(new File(path)); } } if (getWorkTree() == null) { String val = sr.getenv(GIT_WORK_TREE_KEY); if (val != null) setWorkTree(new File(val)); } if (getIndexFile() == null) { String val = sr.getenv(GIT_INDEX_FILE_KEY); if (val != null) setIndexFile(new File(val)); } if (ceilingDirectories == null) { String val = sr.getenv(GIT_CEILING_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addCeilingDirectory(new File(path)); } } return self(); }</code><technical_language>style nit: missing braces</technical_language>

Target:
public B readEnvironment(SystemReader sr) { if (getGitDir() == null) { String val = sr.getenv(GIT_DIR_KEY); if (val != null) setGitDir(new File(val)); } if (getGitCommonDir() == null) { String val = sr.getenv(GIT_COMMON_DIR_KEY); if (val != null) { setGitCommonDir(new File(val)); } } if (getObjectDirectory() == null) { String val = sr.getenv(GIT_OBJECT_DIRECTORY_KEY); if (val != null) setObjectDirectory(new File(val)); } if (getAlternateObjectDirectories() == null) { String val = sr.getenv(GIT_ALTERNATE_OBJECT_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addAlternateObjectDirectory(new File(path)); } } if (getWorkTree() == null) { String val = sr.getenv(GIT_WORK_TREE_KEY); if (val != null) setWorkTree(new File(val)); } if (getIndexFile() == null) { String val = sr.getenv(GIT_INDEX_FILE_KEY); if (val != null) setIndexFile(new File(val)); } if (ceilingDirectories == null) { String val = sr.getenv(GIT_CEILING_DIRECTORIES_KEY); if (val != null) { for (String path : val.split(File.pathSeparator)) addCeilingDirectory(new File(path)); } } return self(); }
Source:
<code>public List<Diagnosis> getUniqueDiagnoses(Patient patient, Date fromDate) { List<Diagnosis> diagnoses = getDiagnoses(patient, fromDate); Set<CodedOrFreeText> uniqueDiagnoses = new HashSet<CodedOrFreeText>(); Iterator<Diagnosis> it = diagnoses.iterator(); while (it.hasNext()) { <START> Diagnosis diagnosis = it.next(); <END> if (!uniqueDiagnoses.add(diagnosis.getDiagnosis())) { it.remove(); } } return diagnoses; }</code><technical_language>uniqueDiagnoses is a Set design allow duplicates, need get rid of duplicates is call below: uniqueDiagnoses.addAll(diagnoses);</technical_language>

Target:
public List<Diagnosis> getUniqueDiagnoses(Patient patient, Date fromDate) { Set<Diagnosis> uniqueDiagnoses = new HashSet<Diagnosis>(); uniqueDiagnoses.addAll(getDiagnoses(patient, fromDate)); return new ArrayList(uniqueDiagnoses); }