auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) { Set<Language> languages = new HashSet<>(); LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer(); for (Rule rule : ruleSets.getAllRules()) { Language language = rule.getLanguage(); if (languages.contains(language)) continue; LanguageVersion version = discoverer.getDefaultLanguageVersion(language); if (RuleSet.applies(rule, version)) { languages.add(language); <START> log.debug("Using " + language.getShortName() + " version: " + version.getShortName()); <END> } } return languages; }</code><technical_language>please refactor notation here</technical_language>

Target:
private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) { Set<Language> languages = new HashSet<>(); LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer(); for (Rule rule : ruleSets.getAllRules()) { Language language = rule.getLanguage(); if (languages.contains(language)) continue; LanguageVersion version = discoverer.getDefaultLanguageVersion(language); if (RuleSet.applies(rule, version)) { languages.add(language); log.debug("Using version: {}", language.getShortName(), version.getShortName()); } } return languages; }
Source:
<code>private static void closeResponse(final Response response) { try { if (response != null) { response.close(); } } catch (ProcessingException e) { log.warn("Couldn't close response", e); } finally { <START> if (response != null) { <END> response.close(); } } }</code><technical_language>retry</technical_language>

Target:
private static void closeResponse(final Response response) { try { if (response != null) { response.close(); } } catch (ProcessingException e) { log.warn("Couldn't close response", e); } }
Source:
<code>private String getAllCfdefsString(Collection<CfDef> updatedCfs) { <START> StringBuilder sb = new StringBuilder("CfDefs("); <END> updatedCfs.stream() .forEach(def -> sb.append(def.toString()).append(", ")); sb.append(")"); return sb.toString(); }</code><technical_language>get "... Cfdefs CfDefs(...)" a a bit odd - updated major issue is resolved though</technical_language>

Target:
private String getAllCfdefsString(Collection<CfDef> updatedCfs) { return updatedCfs.stream().map(CfDef::toString).collect(Collectors.joining(",")); }
Source:
<code><START> public LibraryDilution save(LibraryDilution dilution) throws IOException { <END> dilution.setLastModifier(authorizationManager.getCurrentUser()); try { Long newId = dilutionDao.save(dilution); LibraryDilution managed = dilutionDao.get(newId); boolean needsUpdate = false; if (hasTemporaryName(dilution)) { managed.setName(namingScheme.generateNameFor(managed)); validateNameOrThrow(managed, namingScheme); if (autoGenerateIdBarcodes && isStringEmptyOrNull(managed.getIdentificationBarcode())) generateAndSetIdBarcode(managed); needsUpdate = true; } if (needsUpdate) dilutionDao.save(managed); return managed; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate valid name for library"); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } }</code><technical_language>this public declared in interface? called create update methods in this class - especially for create save fail if name generated</technical_language>

Target:
private LibraryDilution save(LibraryDilution dilution) throws IOException { dilution.setLastModifier(authorizationManager.getCurrentUser()); try { Long newId = dilutionDao.save(dilution); LibraryDilution managed = dilutionDao.get(newId); boolean needsUpdate = false; if (hasTemporaryName(dilution)) { managed.setName(namingScheme.generateNameFor(managed)); validateNameOrThrow(managed, namingScheme); needsUpdate = true; } if (autoGenerateIdBarcodes && isStringEmptyOrNull(managed.getIdentificationBarcode())) { generateAndSetIdBarcode(managed); needsUpdate = true; } if (needsUpdate) dilutionDao.save(managed); return managed; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate valid name for library"); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } }
Source:
<code>protected void writeDeliveryAnnotationsForSendBuffer(ByteBuf result, DeliveryAnnotations deliveryAnnotations) { <START> DeliveryAnnotations daToUse = deliveryAnnotations != null ? deliveryAnnotations : deliveryAnnotationsForSendBuffer; <END> if (daToUse != null && !daToUse.getValue().isEmpty()) { TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result)); TLSEncode.getEncoder().writeObject(daToUse); TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null); } }</code><technical_language>This method is called a levels deep encode/send, wont arg passed write. For clarity I this passed in value, decision of send start of process in getSendBuffer method (already case, suggesting this bit currently doesnt do confuse things)</technical_language>

Target:
protected void writeDeliveryAnnotationsForSendBuffer(ByteBuf result, DeliveryAnnotations deliveryAnnotations) { if (deliveryAnnotations != null && !deliveryAnnotations.getValue().isEmpty()) { TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result)); TLSEncode.getEncoder().writeObject(deliveryAnnotations); TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null); } }
Source:
<code>public String getValue(String value) throws GeneralSecurityException { String returnedValue = "Empty"; if (value != null && !value.equals("")){ try { decrypt(value); returnedValue = "Set"; } catch (Exception exception) { String msg = "Failed to decrypt the current value."; console.writeLine(msg); <START> log.error("", exception); <END> throw new GeneralSecurityException(msg); } } return returnedValue; }</code><technical_language>write "Exception" instead of empty in cases</technical_language>

Target:
public String getValue(String value) throws GeneralSecurityException { String returnedValue = "Empty"; if (value != null && !value.equals("")){ try { decrypt(value); returnedValue = "Set"; } catch (Exception exception) { String msg = "Failed to decrypt the current value."; console.writeLine(msg); log.error("Exception", exception); throw new GeneralSecurityException(msg); } } return returnedValue; }
Source:
<code>private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); new Label(handlerComposite, SWT.NONE).setText(IDEWorkbenchMessages.UrlHandlerPreferencePage_Handler_Label); <START> handlerLocation = new Text(handlerComposite, SWT.READ_ONLY); <END> handlerLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); handlerComposite.setVisible(false); }</code><technical_language>SWT.Read_only text context menu items {undo, cut, copy, paste, delete, select , right left reading order, show unicode control char , insert unicode control char, open IME, Reconversion} objective is copy restrict text selection context menu select copy</technical_language>

Target:
private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); new Label(handlerComposite, SWT.NONE).setText(IDEWorkbenchMessages.UrlHandlerPreferencePage_Handler_Label); handlerLocation = new Text(handlerComposite, SWT.READ_ONLY | SWT.BORDER); handlerLocation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); handlerComposite.setVisible(false); }
Source:
<code>public void testAddWork() throws Exception { AdminUnit adminUnit = repositoryObjectFactory.createAdminUnit(null); contentRoot.addMember(adminUnit); CollectionObject collObj = repositoryObjectFactory.createCollectionObject(null); adminUnit.addMember(collObj); treeIndexer.indexAll(baseAddress); String label = "work_label"; MvcResult result = mvc.perform(post("/edit/create/work/" + collObj.getPid().getId()) .param("label", label) <START> .param("patronOnly", (String) null)) <END> .andExpect(status().is2xxSuccessful()) .andReturn(); treeIndexer.indexAll(baseAddress); assertChildContainerAdded(collObj, label, WorkObject.class); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(collObj.getPid().getId(), respMap.get("pid")); assertEquals("create", respMap.get("action")); }</code><technical_language>parameter need required, leave provide default value. reasonable a separate test verify default behavior though</technical_language>

Target:
public void testAddWork() throws Exception { AdminUnit adminUnit = repositoryObjectFactory.createAdminUnit(null); contentRoot.addMember(adminUnit); CollectionObject collObj = repositoryObjectFactory.createCollectionObject(null); adminUnit.addMember(collObj); treeIndexer.indexAll(baseAddress); String label = "work_label"; MvcResult result = mvc.perform(post("/edit/create/work/" + collObj.getPid().getId()) .param("label", label)) .andExpect(status().is2xxSuccessful()) .andReturn(); treeIndexer.indexAll(baseAddress); assertChildContainerAdded(collObj, label, WorkObject.class); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(collObj.getPid().getId(), respMap.get("pid")); assertEquals("create", respMap.get("action")); assertPatronDoesNotHaveNonePermission(collObj, label); }
Source:
<code>@Test public void indexedElseIf() throws Exception { TypeSpec taco = TypeSpec.classBuilder("Taco") .addMethod(MethodSpec.methodBuilder("choices") <START> .beginControlFlow("if ($1L != null || $1L == $2L)", "mTaco", "mOtherTaco") <END> .addStatement("$T.out.println($S)", System.class, "only one taco? NOO!") .nextControlFlow("else if ($1L.$3L && $2L.$3L)", "mTaco", "mOtherTaco", "isSupreme()") .addStatement("$T.out.println($S)", System.class, "taco heaven") .endControlFlow() .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.System;\n" + "\n" + "class Taco {\n" + " void choices() {\n" + " if (mTaco != null || mTaco == mOtherTaco) {\n" + " System.out.println(\"only one taco? NOO!\");\n" + " } else if (mTaco.isSupreme() && mOtherTaco.isSupreme()) {\n" + " System.out.println(\"taco heaven\");\n" + " }\n" + " }\n" + "}\n"); }</code><technical_language>mind dropping m prefix here? want endorse code style, in generated code</technical_language>

Target:
@Test public void indexedElseIf() throws Exception { TypeSpec taco = TypeSpec.classBuilder("Taco") .addMethod(MethodSpec.methodBuilder("choices") .beginControlFlow("if ($1L != null || $1L == $2L)", "taco", "otherTaco") .addStatement("$T.out.println($S)", System.class, "only one taco? NOO!") .nextControlFlow("else if ($1L.$3L && $2L.$3L)", "taco", "otherTaco", "isSupreme()") .addStatement("$T.out.println($S)", System.class, "taco heaven") .endControlFlow() .build()) .build(); assertThat(toString(taco)).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "import java.lang.System;\n" + "\n" + "class Taco {\n" + " void choices() {\n" + " if (taco != null || taco == otherTaco) {\n" + " System.out.println(\"only one taco? NOO!\");\n" + " } else if (taco.isSupreme() && otherTaco.isSupreme()) {\n" + " System.out.println(\"taco heaven\");\n" + " }\n" + " }\n" + "}\n"); }
Source:
<code>public void setUp() throws Exception { File sandbox; do { <START> currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(r.nextInt(Integer.MAX_VALUE)); <END> sandbox = new File(currSandbox); } while (sandbox.exists()); mavenSandbox = new FileSystemMavenSandbox(currSandbox); mojo = new GitCommitIdMojo(); initializeMojoWithDefaults(mojo); }</code><technical_language>ThreadLocalRandom.current() if want enable parallel tests</technical_language>

Target:
public void setUp() throws Exception { File sandbox; do { currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE)); sandbox = new File(currSandbox); } while (sandbox.exists()); mavenSandbox = new FileSystemMavenSandbox(currSandbox); mojo = new GitCommitIdMojo(); initializeMojoWithDefaults(mojo); }
Source:
<code>public void testInstallDirAndRunDir() throws Exception { MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)); <START> ((EntityLocal)entity).setConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR, "/tmp/brooklyn-foo"); <END> Entities.manage(entity); String installDir = ConfigToAttributes.apply((EntityLocal)entity, SoftwareProcess.INSTALL_DIR); LOG.info("install dir = "+installDir); String runDir = ConfigToAttributes.apply((EntityLocal)entity, SoftwareProcess.RUN_DIR); LOG.info("run dir = "+runDir); Assert.assertEquals(installDir, "/tmp/brooklyn-foo/installs/MyService"); Assert.assertEquals(runDir, "/tmp/brooklyn-foo/apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId()); }</code><technical_language>do EntitySpec.create(MyService.class).configure(BrooklynConfigKeys.BROOKLYN_DATA_DIR, "/tmp/brooklyn-foo") avoid need for casting subsequently call setConfig</technical_language>

Target:
public void testInstallDirAndRunDir() throws Exception { MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class) .configure(BrooklynConfigKeys.BROOKLYN_DATA_DIR, "/tmp/brooklyn-foo")); entity.start(ImmutableList.of(loc)); Assert.assertEquals(entity.getAttribute(SoftwareProcess.INSTALL_DIR), "/tmp/brooklyn-foo/installs/MyService"); Assert.assertEquals(entity.getAttribute(SoftwareProcess.RUN_DIR), "/tmp/brooklyn-foo/apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId()); }
Source:
<code>static boolean insertDefaultAccountsTablesContent(Connection conn, CentralRepoPlatforms selectedPlatform) { try (Statement stmt = conn.createStatement();) { for (Account.Type type : Account.Type.PREDEFINED_ACCOUNT_TYPES) { int correlationTypeId = getCorrelationTypeIdForAccountType(conn, type); if (correlationTypeId > 0) { String sqlString = String.format("INSERT INTO account_types (type_name, display_name, correlation_type_id) VALUES ('%s', '%s', %d)" + getOnConflictDoNothingClause(selectedPlatform), type.getTypeName(), type.getDisplayName(), correlationTypeId); stmt.execute(sqlString); } } } catch (SQLException ex) { <START> LOGGER.log(Level.SEVERE, String.format("Failed to populate default data in Persona tables."), ex); <END> return false; } return true; }</code><technical_language>This error message a copy-paste error</technical_language>

Target:
static boolean insertDefaultAccountsTablesContent(Connection conn, CentralRepoPlatforms selectedPlatform) { try (Statement stmt = conn.createStatement();) { for (Account.Type type : Account.Type.PREDEFINED_ACCOUNT_TYPES) { int correlationTypeId = getCorrelationTypeIdForAccountType(conn, type); if (correlationTypeId > 0) { String sqlString = String.format("INSERT INTO account_types (type_name, display_name, correlation_type_id) VALUES ('%s', '%s', %d)" + getOnConflictDoNothingClause(selectedPlatform), type.getTypeName(), type.getDisplayName(), correlationTypeId); stmt.execute(sqlString); } } } catch (SQLException ex) { LOGGER.log(Level.SEVERE, String.format("Failed to populate default data in account_types table."), ex); return false; } return true; }
Source:
<code>private boolean onlyBranchesAreSelected(TreeSelection selection) { Iterator selIterator = selection.iterator(); for (Object sel = selIterator.next(); selIterator.hasNext(); sel = selIterator <START> .next()) { <END> if (sel instanceof RefNode) { RefNode node = (RefNode) sel; String refName = node.getObject().getName(); if (!refName.startsWith(Constants.R_HEADS)) return false; } } return true; }</code><technical_language>Java nicer syntax for for.loops</technical_language>

Target:
private boolean onlyBranchesAreSelected(TreeSelection selection) { Iterator selIterator = selection.iterator(); for (Object sel = selIterator.next(); selIterator.hasNext(); sel = selIterator .next()) { if (sel instanceof RefNode) { RefNode node = (RefNode) sel; String refName = node.getObject().getName(); if (!refName.startsWith(Constants.R_HEADS)) return false; } else return false; } return true; }
Source:
<code>public void spec203_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete() throws Throwable { subscriberTestWithoutSetup(new TestStageTestRun() { @Override public void run(WhiteboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { Throwable thr = new Throwable(); <START> for (StackTraceElement stackElem : thr.getStackTrace()) { <END> if (stackElem.getMethodName().equals("onComplete")) { env.flop(String.format("Subscription::request MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } @Override public void cancel() { Throwable thr = new Throwable(); for (StackTraceElement stackElem : thr.getStackTrace()) { if (stackElem.getMethodName().equals("onComplete")) { env.flop(String.format("Subscription::cancel MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } } }; stage.probe = stage.createWhiteboxSubscriberProbe(env); final Subscriber<T> sub = createSubscriber(stage.probe); sub.onSubscribe(subs); sub.onComplete(); env.verifyNoAsyncErrors(); } }); }</code><technical_language>Get rid of this duplication please :)</technical_language>

Target:
public void spec203_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete() throws Throwable { subscriberTestWithoutSetup(new TestStageTestRun() { @Override public void run(WhiteboxTestStage stage) throws Throwable { final Subscription subs = new Subscription() { @Override public void request(long n) { final Optional<StackTraceElement> onCompleteStackTraceElement = env.findCallerMethodInStackTrace("onComplete"); if (onCompleteStackTraceElement.isDefined()) { final StackTraceElement stackElem = onCompleteStackTraceElement.get(); env.flop(String.format("Subscription::request MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } @Override public void cancel() { final Optional<StackTraceElement> onCompleteStackElement = env.findCallerMethodInStackTrace("onComplete"); if (onCompleteStackElement.isDefined()) { final StackTraceElement stackElem = onCompleteStackElement.get(); env.flop(String.format("Subscription::cancel MUST NOT be called from Subscriber::onComplete (Rule 2.3)! (Caller: %s::%s line %d)", stackElem.getClassName(), stackElem.getMethodName(), stackElem.getLineNumber())); } } }; stage.probe = stage.createWhiteboxSubscriberProbe(env); final Subscriber<T> sub = createSubscriber(stage.probe); sub.onSubscribe(subs); sub.onComplete(); env.verifyNoAsyncErrors(); } }); }
Source:
<code>public void testProducerFencedException() throws InterruptedException { final long pid = 13131L; final short epoch = 1; doInitTransactions(pid, epoch); transactionManager.beginTransaction(); transactionManager.maybeAddPartitionToTransaction(tp0); Future<RecordMetadata> responseFuture = accumulator.append(tp0, time.milliseconds(), "key".getBytes(), "value".getBytes(), Record.EMPTY_HEADERS, null, MAX_BLOCK_TIMEOUT).future; assertFalse(responseFuture.isDone()); prepareAddPartitionsToTxnResponse(Errors.NONE, tp0, epoch, pid); prepareProduceResponse(Errors.INVALID_PRODUCER_EPOCH, pid, epoch); sender.runOnce(); sender.runOnce(); assertTrue(responseFuture.isDone()); assertTrue(transactionManager.hasError()); try { responseFuture.get(); fail("Expected to get a ExecutionException from the response"); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof ProducerFencedException); } try { transactionManager.beginTransaction(); <START> fail("Expected to get a ExecutionException from the beginTransaction call"); <END> } catch (RuntimeException e) { assertTrue(e instanceof ProducerFencedException); } try { transactionManager.beginCommit(); fail("Expected to get a ProducerFencedException from the beginCommit call"); } catch (RuntimeException e) { assertTrue(e instanceof ProducerFencedException); } try { transactionManager.beginAbort(); fail("Expected to get a ProducerFencedException from the beginAbort call"); } catch (RuntimeException e) { assertTrue(e instanceof ProducerFencedException); } try { transactionManager.sendOffsetsToTransaction(Collections.emptyMap(), "dummyId"); fail("Expected to get a ProducerFencedException from the sendOffsetsToTransaction call"); } catch (RuntimeException e) { assertTrue(e instanceof ProducerFencedException); } }</code><technical_language>assertThrows. is more concise</technical_language>

Target:
public void testProducerFencedException() throws InterruptedException { final long pid = 13131L; final short epoch = 1; doInitTransactions(pid, epoch); transactionManager.beginTransaction(); transactionManager.maybeAddPartitionToTransaction(tp0); Future<RecordMetadata> responseFuture = accumulator.append(tp0, time.milliseconds(), "key".getBytes(), "value".getBytes(), Record.EMPTY_HEADERS, null, MAX_BLOCK_TIMEOUT).future; assertFalse(responseFuture.isDone()); prepareAddPartitionsToTxnResponse(Errors.NONE, tp0, epoch, pid); prepareProduceResponse(Errors.INVALID_PRODUCER_EPOCH, pid, epoch); sender.runOnce(); sender.runOnce(); assertTrue(responseFuture.isDone()); assertTrue(transactionManager.hasError()); try { responseFuture.get(); fail("Expected to get a ExecutionException from the response"); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof ProducerFencedException); } assertThrows(ProducerFencedException.class, () -> transactionManager.beginTransaction()); assertThrows(ProducerFencedException.class, () -> transactionManager.beginCommit()); assertThrows(ProducerFencedException.class, () -> transactionManager.beginAbort()); assertThrows(ProducerFencedException.class, () -> transactionManager.sendOffsetsToTransaction(Collections.emptyMap(), "dummyId")); }
Source:
<code>public void testXMLEmbedding() throws Exception { String clusterXml = namedCluster.toXmlForEmbed(); System.out.println( clusterXml ); Element node = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream( ( "<NamedCluster>" + clusterXml + "</NamedCluster>" ).getBytes() ) ) .getDocumentElement(); NamedCluster nc = new NamedClusterImpl(); nc = nc.fromXmlForEmbed( node ); <START> assertEquals( namedCluster.getHdfsHost(), nc.getHdfsHost() ); <END> assertEquals( namedCluster.getHdfsPort(), nc.getHdfsPort() ); assertEquals( namedCluster.getHdfsUsername(), nc.getHdfsUsername() ); assertEquals( namedCluster.getHdfsPassword(), nc.getHdfsPassword() ); assertEquals( namedCluster.getName(), nc.getName() ); assertEquals( namedCluster.getShimIdentifier(), nc.getShimIdentifier() ); assertEquals( namedCluster.getStorageScheme(), nc.getStorageScheme() ); assertEquals( namedCluster.getJobTrackerHost(), nc.getJobTrackerHost() ); assertEquals( namedCluster.getJobTrackerPort(), nc.getJobTrackerPort() ); assertEquals( namedCluster.getZooKeeperHost(), nc.getZooKeeperHost() ); assertEquals( namedCluster.getZooKeeperPort(), nc.getZooKeeperPort() ); assertEquals( namedCluster.getOozieUrl(), nc.getOozieUrl() ); assertEquals( namedCluster.getLastModifiedDate(), nc.getLastModifiedDate() ); }</code><technical_language>implement equals() NamedClusterImpl do a assertEquals( namedCluster, nc )</technical_language>

Target:
public void testXMLEmbedding() throws Exception { String clusterXml = namedCluster.toXmlForEmbed( "NamedCluster" ); System.out.println( clusterXml ); Element node = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( new ByteArrayInputStream( clusterXml.getBytes() ) ) .getDocumentElement(); NamedCluster nc = new NamedClusterImpl(); nc = nc.fromXmlForEmbed( node ); assertEquals( namedCluster.getHdfsHost(), nc.getHdfsHost() ); assertEquals( namedCluster.getHdfsPort(), nc.getHdfsPort() ); assertEquals( namedCluster.getHdfsUsername(), nc.getHdfsUsername() ); assertEquals( namedCluster.getHdfsPassword(), nc.getHdfsPassword() ); assertEquals( namedCluster.getName(), nc.getName() ); assertEquals( namedCluster.getShimIdentifier(), nc.getShimIdentifier() ); assertEquals( namedCluster.getStorageScheme(), nc.getStorageScheme() ); assertEquals( namedCluster.getJobTrackerHost(), nc.getJobTrackerHost() ); assertEquals( namedCluster.getJobTrackerPort(), nc.getJobTrackerPort() ); assertEquals( namedCluster.getZooKeeperHost(), nc.getZooKeeperHost() ); assertEquals( namedCluster.getZooKeeperPort(), nc.getZooKeeperPort() ); assertEquals( namedCluster.getOozieUrl(), nc.getOozieUrl() ); assertEquals( namedCluster.getLastModifiedDate(), nc.getLastModifiedDate() ); }
Source:
<code>public final ResponseType process(SimulatorOperation operation, SimulatorAddress sourceAddress) { OperationType operationType = getOperationType(operation); if (LOGGER.isTraceEnabled()) { LOGGER.trace(getClass().getSimpleName() + ".process(" + operation.getClass().getSimpleName() + ')'); } OperationTypeCounter.received(operationType); try { switch (operationType) { case INTEGRATION_TEST: return processIntegrationTest(operationType, (IntegrationTestOperation) operation, sourceAddress); case LOG: processLog((LogOperation) operation, sourceAddress); break; case CHAOS_MONKEY: processChaosMonkey((ChaosMonkeyOperation) operation); break; default: return processOperation(operationType, operation, sourceAddress); } } catch (Throwable e) { <START> LOGGER.warn(e); <END> return EXCEPTION_DURING_OPERATION_EXECUTION; } return SUCCESS; }</code><technical_language>ExceptionReporter here, lose exception WorkerOperationProcessor</technical_language>

Target:
public final ResponseType process(SimulatorOperation operation, SimulatorAddress sourceAddress) { OperationType operationType = getOperationType(operation); if (LOGGER.isTraceEnabled()) { LOGGER.trace(getClass().getSimpleName() + ".process(" + operation.getClass().getSimpleName() + ')'); } OperationTypeCounter.received(operationType); try { switch (operationType) { case INTEGRATION_TEST: return processIntegrationTest(operationType, (IntegrationTestOperation) operation, sourceAddress); case LOG: processLog((LogOperation) operation, sourceAddress); break; case CHAOS_MONKEY: processChaosMonkey((ChaosMonkeyOperation) operation); break; default: return processOperation(operationType, operation, sourceAddress); } } catch (Throwable e) { onException(e); return EXCEPTION_DURING_OPERATION_EXECUTION; } return SUCCESS; }
Source:
<code>public void onStart() { super.onStart(); if (callback().getReferencesGroup().size() == 1) { pageIndicatorView.setVisibility(View.GONE); <START> ((ViewGroup) pageIndicatorView.getParent()).removeView(pageIndicatorView); <END> pageIndicatorDivider.setVisibility(View.GONE); } else { BottomSheetBehavior<View> behavior = BottomSheetBehavior.from((View) getView().getParent()); behavior.setPeekHeight(DimenUtil.getDisplayHeightPx() / 2); } }</code><technical_language>If try switch other app back, app crash. void android.view.ViewGroup.removeView(android.view.View)' a null object reference</technical_language>

Target:
public void onStart() { super.onStart(); if (callback().getReferencesGroup().size() == 1) { pageIndicatorView.setVisibility(View.GONE); pageIndicatorDivider.setVisibility(View.GONE); } else { BottomSheetBehavior<View> behavior = BottomSheetBehavior.from((View) getView().getParent()); behavior.setPeekHeight(DimenUtil.getDisplayHeightPx() / 2); } }
Source:
<code>private static UnificationRegistry<IBlockState> createBlockStateUnificationRegistry() { Function<IBlockState, ResourceLocation> namer = blockState -> { ResourceLocation registryName = blockState.getBlock().getRegistryName(); <START> Preconditions.checkNotNull(registryName, "registry name must not be null"); <END> return registryName; }; Function<IBlockState, IBlockState> validator = blockState -> { Preconditions.checkNotNull(blockState, "blockState must not be null"); Preconditions.checkNotNull(blockState.getBlock(), "blockState's block must not be null"); return blockState; }; return createRegistry(namer, validator, blockState -> blockState); }</code><technical_language>return Preconditions.checkNotNull(registryName, "registry name null");</technical_language>

Target:
private static Unifier<IBlockState> createBlockStateUnificationRegistry() { Consumer<IBlockState> validator = blockState -> { Preconditions.checkNotNull(blockState, "blockState must not be null"); Preconditions.checkNotNull(blockState.getBlock(), "blockState's block must not be null"); }; Function<IBlockState, ResourceLocation> namer = blockState -> blockState.getBlock().getRegistryName(); return createUnifier(validator, namer, Function.identity(), true); }
Source:
<code>protected List<?> createOperationSet() { List<?> selection = getSelectedObjects(); if (selection.isEmpty() || !(selection.get(0) instanceof IGraphicalEditPart)) { selection = Collections.EMPTY_LIST; } else { selection = ToolUtilities.getSelectionWithoutDependants(selection); selection = Lists.newArrayList(Iterables.filter(selection, Predicates.not(Predicates.instanceOf(ConnectionEditPart.class)))); if (selection.size() < 3) { selection = Collections.EMPTY_LIST; } else { EditPart parent = ((EditPart) selection.get(0)).getParent(); int sideOfFirstSelection = PositionConstants.NONE; if (selection.get(0) instanceof IBorderItemEditPart) { sideOfFirstSelection = ((IBorderItemEditPart) selection.get(0)).getBorderItemLocator().getCurrentSideOfParent(); if (!isHorizontalAxisAuthorizedForBorderNode(sideOfFirstSelection) && !isVerticalAxisAuthorizedForBorderNode(sideOfFirstSelection)) { selection = Collections.EMPTY_LIST; } } for (int i = 1; i < selection.size(); i++) { EditPart part = (EditPart) selection.get(i); if (part.getParent() != parent) { selection = Collections.EMPTY_LIST; break; } else if (sideOfFirstSelection != PositionConstants.NONE && !isABorderNodeOnSameAxis(part, sideOfFirstSelection)) { selection = Collections.EMPTY_LIST; break; } else if (part instanceof DNodeListElementEditPart) { selection = Collections.EMPTY_LIST; break; } else if <START> (part.getParent() instanceof CompartmentEditPart && !(part instanceof AbstractDiagramNodeEditPart)) { <END> selection = Collections.EMPTY_LIST; break; } } } } return selection; }</code><technical_language>This condition is wrong: CompartmentEditPart is a GMF classes a specific class handle Sirius compartment & region</technical_language>

Target:
protected List<?> createOperationSet() { List<?> selection = getSelectedObjects(); if (selection.isEmpty() || !(selection.get(0) instanceof IGraphicalEditPart)) { selection = Collections.EMPTY_LIST; } else { selection = ToolUtilities.getSelectionWithoutDependants(selection); selection = Lists.newArrayList(Iterables.filter(selection, Predicates.not(Predicates.instanceOf(ConnectionEditPart.class)))); if (selection.size() < 3) { selection = Collections.EMPTY_LIST; } else { EditPart parent = ((EditPart) selection.get(0)).getParent(); int sideOfFirstSelection = PositionConstants.NONE; if (selection.get(0) instanceof IBorderItemEditPart) { sideOfFirstSelection = ((IBorderItemEditPart) selection.get(0)).getBorderItemLocator().getCurrentSideOfParent(); if (!isHorizontalAxisAuthorizedForBorderNode(sideOfFirstSelection) && !isVerticalAxisAuthorizedForBorderNode(sideOfFirstSelection)) { selection = Collections.EMPTY_LIST; } } for (int i = 1; i < selection.size(); i++) { EditPart part = (EditPart) selection.get(i); if (part.getParent() != parent) { selection = Collections.EMPTY_LIST; break; } else if (sideOfFirstSelection != PositionConstants.NONE && !isABorderNodeOnSameAxis(part, sideOfFirstSelection)) { selection = Collections.EMPTY_LIST; break; } else { if (!isFreeFormContainerChildrenPresentation(selection)) { selection = Collections.EMPTY_LIST; } break; } } } } return selection; }
Source:
<code>private static Collection<CustomEventTableColumn> generateColumns(CustomTraceDefinition definition) { <START> List<CustomEventTableColumn> columns = new LinkedList<>(); <END> List<OutputColumn> outputs = definition.outputs; for (int i = 0; i < outputs.size(); i++) { String name = outputs.get(i).name; if (name != null) { columns.add(new CustomEventTableColumn(name, i)); } } return columns; }</code><technical_language>LinkedList :(</technical_language>

Target:
private static Collection<CustomEventTableColumn> generateColumns(CustomTraceDefinition definition) { ImmutableList.Builder<CustomEventTableColumn> builder = new ImmutableList.Builder<>(); List<OutputColumn> outputs = definition.outputs; for (int i = 0; i < outputs.size(); i++) { String name = outputs.get(i).name; if (name != null) { builder.add(new CustomEventTableColumn(name, i)); } } return builder.build(); }
Source:
<code>public void forbidsNonSimplifiedTernaryOperators() throws Exception { <START> final String file = "SimplifiedTernary.java"; <END> new PMDAssert( file, Matchers.is(false), Matchers.containsString( String.format( PMDValidatorTest.BRACKETS, "SimplifiedTernary" ) ) ).validate(); }</code><technical_language>@Happy-Neko inline this variable</technical_language>

Target:
public void forbidsNonSimplifiedTernaryOperators() throws Exception { new PMDAssert( "SimplifiedTernary.java", Matchers.is(false), Matchers.containsString( String.format( PMDValidatorTest.BRACKETS, "SimplifiedTernary" ) ) ).validate(); }
Source:
<code>public void addContainers(Set<PackingPlan.ContainerPlan> containers) { synchronized (processToContainer) { Set<Integer> containerIds = new HashSet<>(); containerIds.addAll(processToContainer.values()); for (PackingPlan.ContainerPlan container : containers) { <START> if (containerIds.contains(container.getId())) { <END> throw new RuntimeException(String.format("Found active container for %s, " + "cannot launch a duplicate container.", container.getId())); } startExecutor(container.getId()); containerIds.add(container.getId()); } } }</code><technical_language>Great catch! Instead of maintaining another Set check processToContainer.values().containsKey(container.getId())? guarantees in sync startExecutor started, updates processToContainer</technical_language>

Target:
public void addContainers(Set<PackingPlan.ContainerPlan> containers) { synchronized (processToContainer) { for (PackingPlan.ContainerPlan container : containers) { if (processToContainer.values().contains(container.getId())) { throw new RuntimeException(String.format("Found active container for %s, " + "cannot launch a duplicate container.", container.getId())); } startExecutor(container.getId()); } } }
Source:
<code>public InsertQuery build() { <START> Checks.checkNotEmpty(table, "Please specify table name"); <END> return new InsertQuery( table, nullColumnHack ); }</code><technical_language>Static import</technical_language>

Target:
public InsertQuery build() { checkNotEmpty(table, "Please specify table name"); return new InsertQuery( table, nullColumnHack ); }
Source:
<code>protected void skipMojo() { final String name = getEffectivePropertyName(); final Properties projectProperties = getProject().getProperties(); final String oldValue = projectProperties.getProperty(name); if (oldValue == null) { getLog().info(name + " set to empty"); projectProperties.setProperty(name, ""); } else { <START> getLog().info(name + " set to " + oldValue); <END> } }</code><technical_language>set here: log log like: "Keep [property] [oldValue]"</technical_language>

Target:
protected void skipMojo() { final String name = getEffectivePropertyName(); final Properties projectProperties = getProject().getProperties(); final String oldValue = projectProperties.getProperty(name); if (oldValue == null) { getLog().info(name + " set to empty"); projectProperties.setProperty(name, ""); } }
Source:
<code>public void test() { connect(); click(jq("@button")); waitResponse(); getActions() .dragAndDropBy(toElement(jq(".z-window-header-move")), 0, 100) .perform(); assertNoJSError(); <START> } <END></code><technical_language>test window moved 100px (and page scrolled) for this underlying page larger 100% scrolling occur. dragging move window page scrollbar</technical_language>

Target:
public void test() { connect(); click(jq("@button")); waitResponse(); getActions() .dragAndDropBy(toElement(jq(".z-window-header-move")), 0, -100) .perform(); assertNoJSError(); Assert.assertEquals(0, jq("html").scrollTop()); }
Source:
<code>String buildSparkSubmitOptions() { StringBuilder options = new StringBuilder(); options.append(" --master k8s://<LINK_0>"); <START> options.append(" --deploy-mode client"); <END> options.append(" --conf spark.kubernetes.namespace=" + kubectl.getNamespace()); options.append(" --conf spark.executor.instances=1"); options.append(" --conf spark.kubernetes.driver.pod.name=" + getPodName()); options.append(" --conf spark.kubernetes.container.image=" + sparkImage); options.append(" --conf spark.driver.bindAddress=0.0.0.0"); options.append(" --conf spark.driver.host=" + getInterpreterPodDnsName()); options.append(" --conf spark.driver.port=" + String.format("%d", getSparkDriverPort())); options.append(" --conf spark.blockManager.port=" + String.format("%d", getSparkBlockmanagerPort())); return options.toString(); }</code><technical_language>this Cluster mode for spark work. needed spark-interpreter is launched in a new pod. driver memory require changes application run</technical_language>

Target:
String buildSparkSubmitOptions() { StringBuilder options = new StringBuilder(); options.append(" --master k8s://<LINK_0>"); options.append(" --deploy-mode client"); if (properties.containsKey("spark.driver.memory")) { options.append(" --driver-memory " + properties.get("spark.driver.memory")); } options.append(" --conf spark.kubernetes.namespace=" + kubectl.getNamespace()); options.append(" --conf spark.executor.instances=1"); options.append(" --conf spark.kubernetes.driver.pod.name=" + getPodName()); options.append(" --conf spark.kubernetes.container.image=" + sparkImage); options.append(" --conf spark.driver.bindAddress=0.0.0.0"); options.append(" --conf spark.driver.host=" + getInterpreterPodDnsName()); options.append(" --conf spark.driver.port=" + String.format("%d", getSparkDriverPort())); options.append(" --conf spark.blockManager.port=" + String.format("%d", getSparkBlockmanagerPort())); return options.toString(); }
Source:
<code><START> private <T extends BaseProtocolResponse> Optional<T> decodeProtocolResponse( TriFunction<StatusCode, String, Integer, T> constructor, ByteBuf in ) <END> { int statusCodeValue = in.readInt(); String identifier = StringMarshal.unmarshal( in ); int version = in.readInt(); Optional<StatusCode> statusCode = StatusCode.fromCodeValue( statusCodeValue ); return statusCode.map( status -> constructor.apply( status, identifier, version ) ); }</code><technical_language>Optional good. want fail throw exception if is some sort of protocol violation. Decoding completely correctly is optional</technical_language>

Target:
private <T extends BaseProtocolResponse> T decodeProtocolResponse( TriFunction<StatusCode, String, Integer, T> constructor, ByteBuf in ) throws ClientHandshakeException { int statusCodeValue = in.readInt(); String identifier = StringMarshal.unmarshal( in ); int version = in.readInt(); Optional<StatusCode> statusCode = StatusCode.fromCodeValue( statusCodeValue ); return statusCode .map( status -> constructor.apply( status, identifier, version ) ) .orElseThrow( () -> new ClientHandshakeException( String.format( "Unknown status code %s for protocol %s version %d", statusCodeValue, identifier, version ) ) ); }
Source:
<code><START> static private void validateAlleles(final VariantContext vc) { <END> boolean alreadySeenRef = false; for (final Allele allele : vc.alleles) { if (allele.isReference()) { if (alreadySeenRef) { throw new IllegalArgumentException("BUG: Received two reference tagged alleles in VariantContext " + vc.alleles + " vc=" + vc); } alreadySeenRef = true; } if (allele.isNoCall()) { throw new IllegalArgumentException("BUG: Cannot add a no call allele to a variant context " + vc.alleles + " vc=" + vc); } } if (!alreadySeenRef) { throw new IllegalArgumentException("No reference allele found in VariantContext"); } }</code><technical_language>suggestion private static void validateAlleles(final VariantContext vc) {</technical_language>

Target:
private static void validateAlleles(final VariantContext vc) { boolean alreadySeenRef = false; for (final Allele allele : vc.alleles) { if (allele.isReference()) { if (alreadySeenRef) { throw new IllegalArgumentException("BUG: Received two reference tagged alleles in VariantContext " + vc.alleles + " vc=" + vc); } alreadySeenRef = true; } if (allele.isNoCall()) { throw new IllegalArgumentException("BUG: Cannot add a no call allele to a variant context " + vc.alleles + " vc=" + vc); } } if (!alreadySeenRef) { throw new IllegalArgumentException("No reference allele found in VariantContext"); } }
Source:
<code>public Type convertReadValueToType(String pvReadValue) { Type lvType = convertReadValueToUnmodifiedType(pvReadValue); for (InterfaceOneWireTypeModifier lvTypeModifier : getTypeModifieryList()) { logger.debug("type of before modifier:{} type={}", getDevicePropertyPath(), <START> lvTypeModifier.getModifierName(), lvType.toString()); <END> lvType = lvTypeModifier.modify4Read(lvType); logger.debug("type of after modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType.toString()); } return lvType; }</code><technical_language>need for .toString()</technical_language>

Target:
public Type convertReadValueToType(String pvReadValue) { Type lvType = convertReadValueToUnmodifiedType(pvReadValue); for (InterfaceOneWireTypeModifier lvTypeModifier : getTypeModifieryList()) { logger.debug("type of before modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType); lvType = lvTypeModifier.modify4Read(lvType); logger.debug("type of after modifier:{} type={}", getDevicePropertyPath(), lvTypeModifier.getModifierName(), lvType); } return lvType; }
Source:
<code>public Set<FloatingIP> expected() { return ImmutableSet.of( FloatingIP.builder().id("1").instanceId("12").ip("10.0.0.3").fixedIp("11.0.0.1").pool("nova").build(), FloatingIP.builder().id("2").instanceId(null).ip("10.0.0.5").fixedIp(null).pool("nova").build(), <START> FloatingIP.builder().id("3").instanceId("13").ip("10.0.0.13").fixedIp("11.0.0.3").build()); <END> }</code><technical_language>theme of pool nullable: do need a version explicit .pool(null) call</technical_language>

Target:
public Set<FloatingIP> expected() { return ImmutableSet.of( FloatingIP.builder().id("1").instanceId("12").ip("10.0.0.3").fixedIp("11.0.0.1").pool("nova").build(), FloatingIP.builder().id("2").instanceId(null).ip("10.0.0.5").fixedIp(null).pool("nova").build(), FloatingIP.builder().id("3").instanceId("13").ip("10.0.0.13").fixedIp("11.0.0.3").build(), FloatingIP.builder().id("4").instanceId("14").ip("10.0.0.14").fixedIp("11.0.0.4").pool(null).build()); }
Source:
<code>public void setLabels(double[] labels) { <START> this.labels = labels; <END> }</code><technical_language>CD, This is a Sonar violation; <LINK_0> . Sample fix is below. Please fix other places in PR too. /** \* @param features Sets features of a cluster point */ public void setFeatures(double[] features) { if (features == null) { this.features = new double[0]; } else { this.features = Arrays.copyOf(features, features.length); } }</technical_language>

Target:
public void setLabels(double[] labels) { if (labels == null) { this.labels = new double[0]; } else { this.labels = Arrays.copyOf(labels, labels.length); } }
Source:
<code>public void clusterDown() { if (cluster != null) { cluster.close(); } <START> if (yarnCluster != null) { <END> yarnCluster.stop(); } }</code><technical_language>services closeable, IOUtil.cleanupWithLogger() & handle null checks exceptions</technical_language>

Target:
public void clusterDown() { if (cluster != null) { cluster.close(); } IOUtils.cleanupWithLogger(LOG, yarnCluster); }
Source:
<code>public void onRemove(Entity entity) throws FalconException{ if (entity.getEntityType() != EntityType.PROCESS){ return; } <START> synchronized (this){ <END> backlogMetricStore.deleteEntityInstance(entity.getName()); entityBacklogs.remove(entity); } }</code><technical_language>sufficient synchronize entityBacklogs, right? applies for onChange method</technical_language>

Target:
public void onRemove(Entity entity) throws FalconException{ if (entity.getEntityType() != EntityType.PROCESS){ return; } synchronized (entityBacklogs){ backlogMetricStore.deleteEntityInstance(entity.getName()); entityBacklogs.remove(entity); } }
Source:
<code>public List<WebElement> apply(By by) { List<WebElement> result = new ArrayList<>(); Throwable shouldBeThrown = null; boolean isRootCauseInvalidSelector; boolean isRootCauseStaleElementReferenceException = false; foundStaleElementReferenceException = null; try { result.addAll(searchContext.findElements(by)); } catch (Throwable e){ isRootCauseInvalidSelector = isInvalidSelectorRootCause(e); if (!isRootCauseInvalidSelector) isRootCauseStaleElementReferenceException = isStaleElementReferenceException(e); if (isRootCauseStaleElementReferenceException) foundStaleElementReferenceException = extractReadableException(e); <START> if (!isRootCauseInvalidSelector & !isRootCauseStaleElementReferenceException) <END> shouldBeThrown = extractReadableException(e); } if (shouldBeThrown != null) { if (RuntimeException.class.isAssignableFrom(shouldBeThrown.getClass())) throw (RuntimeException) shouldBeThrown; throw new RuntimeException(shouldBeThrown); } if (result.size() > 0) { return result; } else { return null; } }</code><technical_language>I this && &</technical_language>

Target:
public List<WebElement> apply(By by) { List<WebElement> result = new ArrayList<>(); Throwable shouldBeThrown = null; boolean isRootCauseInvalidSelector; boolean isRootCauseStaleElementReferenceException = false; foundStaleElementReferenceException = null; try { result.addAll(searchContext.findElements(by)); } catch (Throwable e) { isRootCauseInvalidSelector = isInvalidSelectorRootCause(e); if (!isRootCauseInvalidSelector) { isRootCauseStaleElementReferenceException = isStaleElementReferenceException(e); } if (isRootCauseStaleElementReferenceException) { foundStaleElementReferenceException = extractReadableException(e); } if (!isRootCauseInvalidSelector & !isRootCauseStaleElementReferenceException) { shouldBeThrown = extractReadableException(e); } } if (shouldBeThrown != null) { if (RuntimeException.class.isAssignableFrom(shouldBeThrown.getClass())) { throw (RuntimeException) shouldBeThrown; } throw new RuntimeException(shouldBeThrown); } if (result.size() > 0) { return result; } else { return null; } }
Source:
<code>public synchronized void updateDataCenter(DataCenter dataCenter) { try { storeObject(dataCenter); } catch <START> (RuntimeException e) <END> { log.error("failed to create new dataCenter"); return; } if (!dataCenterMap.containsKey(dataCenter.getId())) { dataCenterMap.put(dataCenter.getId(), dataCenter); } log.info("Data center stored", dataCenter.getId()); }</code><technical_language>This is generic. Please handle proper exception here</technical_language>

Target:
public synchronized void updateDataCenter(DataCenter dataCenter) { try { storeObject(dataCenter); } catch (Exception e) { log.error("failed to store object {}", e.getStackTrace()); } dataCenterMap.put(dataCenter.getId(), dataCenter); log.info("Data center restored", dataCenter.getId()); }