auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private JSONObject buildDetailResult(final String extensionName) throws FalconException { ExtensionMetaStore metaStore = ExtensionStore.get().getMetaStore(); if (!metaStore.checkIfExtensionExists(extensionName)){ throw new StoreAccessException(new Exception("No extension resources found for " + extensionName)); } ExtensionMetadataBean bean = metaStore.getDetail(extensionName); JSONObject resultObject = new JSONObject(); try { <START> resultObject.put(EXTENSION_NAME, bean.getExtensionName().toLowerCase()); <END> resultObject.put(EXTENSION_TYPE, bean.getExtensionType()); resultObject.put(EXTENSION_DESC, bean.getDescription()); resultObject.put(EXTENSION_LOCATION, bean.getLocation()); } catch (JSONException e) { throw new FalconException(e); } return resultObject; }</code><technical_language>toLowerCase? changes Bean handle for consumers worried same</technical_language>

Target:
private JSONObject buildDetailResult(final String extensionName) throws FalconException { ExtensionMetaStore metaStore = ExtensionStore.get().getMetaStore(); if (!metaStore.checkIfExtensionExists(extensionName)){ throw new ValidationException("No extension resources found for " + extensionName); } ExtensionMetadataBean bean = metaStore.getDetail(extensionName); JSONObject resultObject = new JSONObject(); try { resultObject.put(EXTENSION_NAME, bean.getExtensionName()); resultObject.put(EXTENSION_TYPE, bean.getExtensionType()); resultObject.put(EXTENSION_DESC, bean.getDescription()); resultObject.put(EXTENSION_LOCATION, bean.getLocation()); } catch (JSONException e) { LOG.error("Exception in buildDetailResults:", e); throw new FalconException(e); } return resultObject; }
Source:
<code><START> public void shouldAddNewFieldForLookupAndSaveEntity() throws IOException { <END> EntityDto entityDto = new EntityDto(); entityDto.setName("myEntity"); Map<String, Object> values = new HashMap<>(); values.put("path", DraftData.ADD_NEW_FIELD); values.put("advanced", true); DraftData draftData = new DraftData(); draftData.setEdit(true); draftData.setValues(values); entityDto = entityService.createEntity(entityDto); FieldDto testField = FieldTestHelper.fieldDto("firstField", Boolean.class); entityService.addFields(entityDto, asList(testField)); List<LookupFieldDto> lookupFieldDtos = lookupFieldsFromNames("firstField"); LookupDto lookup = new LookupDto("lookup", false, false, lookupFieldDtos, true); entityService.addLookups(entityDto.getId(), asList(lookup)); entityService.saveDraftEntityChanges(entityDto.getId(), DraftBuilder.forNewField("disp", "f1name", Long.class.getName())); entityService.getFields(entityDto.getId()); FieldDto field = selectFirst(entityService.getFields(entityDto.getId()), having(on(FieldDto.class).getBasic().getName(), equalTo("f1name"))); values.put("value", asList(field.getId())); entityService.saveDraftEntityChanges(entityDto.getId(), draftData); entityService.commitChanges(entityDto.getId()); assertEquals(entityService.getLookupByName(entityDto.getId(),"lookup").getLookupField("f1name").getName(), "f1name"); }</code><technical_language>please remove redundant line this test</technical_language>

Target:
public void shouldAddNewFieldForLookupAndSaveEntity() throws IOException { EntityDto entityDto = new EntityDto(); entityDto.setName("myEntity"); entityDto = entityService.createEntity(entityDto); EntityDraft entityDraft = entityService.getEntityDraft(entityDto.getId()); entityService.saveDraftEntityChanges(entityDraft.getId(), DraftBuilder.forNewField("disp", "testFieldName", Long.class.getName())); FieldDto field = selectFirst(entityService.getFields(entityDraft.getId()), having(on(FieldDto.class).getBasic().getName(), equalTo("testFieldName"))); LookupDto lookup = new LookupDto("lookup", false, false, null, true); entityService.addLookups(entityDraft.getId(), Collections.singletonList(lookup)); Map<String, Object> values = new HashMap<>(); values.put("path", "indexes.0.$addField"); values.put("advanced", true); values.put("value", Collections.singletonList(field.getId())); DraftData draftData = new DraftData(); draftData.setEdit(true); draftData.setValues(values); entityService.saveDraftEntityChanges(entityDraft.getId(), draftData); entityService.commitChanges(entityDto.getId()); assertNotNull(entityService.getLookupByName(entityDto.getId(),"lookup").getLookupField("testFieldName")); }
Source:
<code>public void getMetaDataParams(AMFPacket metaDataPacket, IMediaStream stream) { WMSProperties props = stream.getProperties(); AMFDataList dataList = new AMFDataList(metaDataPacket.getData()); IMediaStreamActionNotify2 actionNotify; if (dataList.size() < 2) return; <START> if (dataList.get(1).getType() == AMFData.DATA_TYPE_OBJECT) <END> { AMFDataObj obj = (AMFDataObj) dataList.get(1); if (obj.containsKey(ONMETADATA_VIDEOCODECID)){ obj.put(ONMETADATA_VIDEOCODECIDSTR, FLVUtils.videoCodecToString(obj.getInt(ONMETADATA_VIDEOCODECID))); } if (obj.containsKey(ONMETADATA_AUDIOCODECID)){ obj.put(ONMETADATA_AUDIOCODECIDSTR, FLVUtils.audioCodecToString(obj.getInt(ONMETADATA_AUDIOCODECID))); } synchronized (props) { props.put(AMFSETDATAFRAME, obj); actionNotify = (IMediaStreamActionNotify2) stream.getProperties().get("streamActionNotifier"); } if (actionNotify != null) { stream.removeClientListener(actionNotify); logger.info("removeClientListener: " + stream.getSrc()); } } }</code><technical_language>1? a position</technical_language>

Target:
public void getMetaDataParams(AMFPacket metaDataPacket, IMediaStream stream) { AMFDataList dataList = new AMFDataList(metaDataPacket.getData()); for (int i = 0 ; i < dataList.size(); i++ ){ logger.debug("[" + stream.getName() +" ] Found DATA_TYPE_OBJECT"); AMFData amfData = dataList.get(i); if (amfData.getType() == AMFData.DATA_TYPE_OBJECT) { AMFDataObj obj = (AMFDataObj) amfData; String videocodec, audiocodec; if (obj.containsKey(ONMETADATA_VIDEOCODECID)){ try { videocodec = FLVUtils.videoCodecToString(obj.getInt(ONMETADATA_VIDEOCODECID)); } catch (NumberFormatException e){ videocodec = obj.getString(ONMETADATA_VIDEOCODECID); } obj.put(ONMETADATA_VIDEOCODECIDSTR, videocodec); } if (obj.containsKey(ONMETADATA_AUDIOCODECID)){ try{ audiocodec = FLVUtils.audioCodecToString(obj.getInt(ONMETADATA_AUDIOCODECID)); } catch (NumberFormatException e){ audiocodec = obj.getString(ONMETADATA_VIDEOCODECID); } obj.put(ONMETADATA_AUDIOCODECIDSTR, audiocodec); } WMSProperties props = stream.getProperties(); synchronized (props) { props.put(AMFSETDATAFRAME, obj); } removeListener(stream); return; } } logger.warn("[" + stream.getName() +" ] metadata not found"); }
Source:
<code>private void init() { setTitle(constants.newGeoRepSessionTitle()); setShowEligibleVolumes(new EntityModel<Boolean>()); setSlaveClusters(new ListModel<String>()); setSlaveVolumes(new ListModel<GlusterVolumeEntity>()); setSlaveHosts(new ListModel<String>()); setStartSession(new EntityModel<Boolean>()); setSlaveUserName(new EntityModel<String>()); setSlaveHostRootPassword(new EntityModel<String>()); getShowEligibleVolumes().setEntity(false); <START> getSlaveUserName().setIsChangable(true); <END> getSlaveUserName().setIsAvailable(true); getSlaveUserName().setEntity("root"); }</code><technical_language>'true' is default value, need set explicitly</technical_language>

Target:
private void init() { setTitle(constants.newGeoRepSessionTitle()); setShowEligibleVolumes(new EntityModel<Boolean>()); setSlaveClusters(new ListModel<String>()); setSlaveVolumes(new ListModel<GlusterVolumeEntity>()); setSlaveHosts(new ListModel<String>()); setStartSession(new EntityModel<Boolean>()); setSlaveUserName(new EntityModel<String>()); setSlaveHostRootPassword(new EntityModel<String>()); getShowEligibleVolumes().setEntity(false); getSlaveUserName().setEntity("root"); setSlaveUserGroupName(new EntityModel<String>()); }
Source:
<code>public Rectangle2D getBounds() { Rectangle2D result; Point2D ep1 = getCoordsCenter(), ep2 = getCoordsCenter(); if (getConnect1() != null) { ep1 = layoutEditor.getCoords(getConnect1(), getType1()); } if (getConnect2() != null) { ep2 = layoutEditor.getCoords(getConnect2(), getType2()); } result = new Rectangle2D.Double(ep1.getX(), ep1.getY(), 0, 0); result.add(ep2); if (isCircle()) { result.add(getCoordsCenterCircle()); } else if (isBezier()) { for (int index = 0; index < bezierControlPoints.size(); index++) { result.add(bezierControlPoints.get(index)); } } <START> result.add(getCentreSeg()); <END> return result; }</code><technical_language>infinite loop @danielb987 in CI here. Line 1909 of TrackSegment view in getCentreSeg a setCoordsCenter call, getBounds, in line 574 calls getCentreSeg again. underlying problem is in line 1909 (why is a get call _setting_ something?), this is new code</technical_language>

Target:
public Rectangle2D getBounds() { Point2D ep1 = getCoordsCenter(), ep2 = getCoordsCenter(); if (getConnect1() != null) { ep1 = layoutEditor.getCoords(getConnect1(), getType1()); } if (getConnect2() != null) { ep2 = layoutEditor.getCoords(getConnect2(), getType2()); } Rectangle2D result = new Rectangle2D.Double(ep1.getX(), ep1.getY(), 0, 0); result.add(ep2); if (isArc()) { result.add(getCentreSeg()); if (isCircle()) { result.add(getCoordsCenterCircle()); } } else if (isBezier()) { for (int index = 0; index < bezierControlPoints.size(); index++) { result.add(bezierControlPoints.get(index)); } } result.add(getCoordsCenter()); return result; }
Source:
<code>public TestResult test(TestMethodExecutor testMethodExecutor) throws Exception { Validate.notNull(testMethodExecutor, "TestMethodExecutor must be specified"); final List<TestResult> result = new ArrayList<TestResult>(); TestExecutionDecider testExecutionDecider = resolveTestExecutionDecider(manager); if (testExecutionDecider != null && !testExecutionDecider.execute(testMethodExecutor.getMethod())) { <START> result.add(TestResult.skipped(null)); <END> return result.get(0); } manager.fire(new Test(testMethodExecutor), new NonManagedObserver<Test>() { @Inject private Instance<TestResult> testResult; @Override public void fired(Test event) { result.add(testResult.get()); } }); return result.get(0); }</code><technical_language>In JUnit integration check if testResult.hasException() {throw Exception}.. If test is skipped JUnit specific exception AssumptionViolatedException is caught JUnit rethrown.. need update JUnit integration check for State==skipped recreate a AssumptionViolatedException</technical_language>

Target:
public TestResult test(TestMethodExecutor testMethodExecutor) throws Exception { Validate.notNull(testMethodExecutor, "TestMethodExecutor must be specified"); final List<TestResult> result = new ArrayList<TestResult>(); ExecutionDecision executionDecision = resolveExecutionDecision(manager, testMethodExecutor.getMethod()); if (executionDecision.getDecision() == Decision.DONT_EXECUTE) { result.add(TestResult.skipped(new SkippedTestExecutionException(executionDecision.getReason()))); return result.get(0); } manager.fire(new Test(testMethodExecutor), new NonManagedObserver<Test>() { @Inject private Instance<TestResult> testResult; @Override public void fired(Test event) { result.add(testResult.get()); } }); return result.get(0); }
Source:
<code>public void testFailedAmendWithNoQcowVolumes() { DiskImage oldDisk = createDiskImage(); oldDisk.setQcowCompat(QcowCompat.QCOW2_V2); when(diskDao.get(diskImageGuid)).thenReturn(oldDisk); DiskImage newDisk = DiskImage.copyOf(oldDisk); newDisk.setQcowCompat(QcowCompat.QCOW2_V3); command.getParameters().setDiskInfo(newDisk); initializeCommand(); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_CANT_AMEND_RAW_DISK); verify(command, <START> times(0)).amendDiskImage(); <END> }</code><technical_language>rly</technical_language>

Target:
public void testFailedAmendWithNoQcowVolumes() { DiskImage oldDisk = createDiskImage(); oldDisk.setQcowCompat(QcowCompat.QCOW2_V2); when(diskDao.get(diskImageGuid)).thenReturn(oldDisk); DiskImage newDisk = DiskImage.copyOf(oldDisk); newDisk.setQcowCompat(QcowCompat.QCOW2_V3); command.getParameters().setDiskInfo(newDisk); initializeCommand(); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_CANT_AMEND_RAW_DISK); verify(command, never()).amendDiskImage(); }
Source:
<code>public void verifyForumNotExists(String forumName, String wikiURL) { <START> String temp = driver.getCurrentUrl(); <END> getUrl(wikiURL + URLsContent.WIKI_DIR + URLsContent.SPECIAL_FORUM); wait.forElementNotVisible(By.xpath( " getUrl(temp); Log.log("verifyForumNotExists", "verified forum not exists", true); }</code><technical_language>if page loaded yet</technical_language>

Target:
public boolean verifyForumNotExists(String forumName, String wikiURL) { String temp = driver.getCurrentUrl(); try { getUrl(wikiURL + "/wiki/Board:" + URLEncoder.encode(forumName, "UTF-8").replace("+", "_")); } catch (UnsupportedEncodingException e) { Log.info("Forum exists", e); return false; } wait.forElementNotVisible(By.xpath( " getUrl(temp); return true; }
Source:
<code>public void testPickBroadcastEquality() throws Exception { String sqlText = format("explain select count(*) from %s as a inner join %s as b " + "--SPLICE-PROPERTIES useSpark=%s \n" + " on a.a1 = b.a1" , s1, s1, useSpark); <START> String expected = useSpark ? "CrossJoin" : "Broadcast"; <END> rowContainsQuery(6, sqlText, expected, classWatcher); }</code><technical_language>@ascend1 check pick cross join broadcast join? equality join condition, pick pick broadcast join instead of cross join. Thanks</technical_language>

Target:
public void testPickBroadcastEquality() throws Exception { String sqlText = format("explain select count(*) from %s as a inner join %s as b " + "--SPLICE-PROPERTIES useSpark=%s \n" + " on a.a1 = b.a1" , s1, s1, useSpark); rowContainsQuery(6, sqlText,"Broadcast", classWatcher); }
Source:
<code>private PatternDSL.PatternDef<T> build(PatternDSL.PatternDef<T> basePattern) { PatternDSL.PatternDef<T> result = builder.apply(basePattern); <START> LOGGER.trace("Pattern for finished: {}.", baseVariable, result); <END> return result; }</code><technical_language>in mind: encourage users turn "TRACE" logging actual moves optaplanner is taking. Therefore, trace log _readable_ useful information for (advanced?) user. trick works well, is ident trace logging 2 spaces, easier "solving started" "step ended" log lines etc. If trace loggings purely for debugging purposes, I recommend "debugger log messages" instead. I useful drools constraints build CS, in trace logging, end of creating a constraint. I useful "start" "end" messages - I if worth weight</technical_language>

Target:
private PatternDSL.PatternDef<T> build(PatternDSL.PatternDef<T> basePattern) { return builder.apply(basePattern); }
Source:
<code>public void whenCreateTopicThenTopicIsCreated() throws InterruptedException { final String topicName = TestUtils.randomString(); final CuratorZookeeperClient zookeeperClient = mock(CuratorZookeeperClient.class); when(zookeeperClient.getCurrentConnectionString()).thenReturn(zookeeperURL); final CuratorFramework curatorFramework = mock(CuratorFramework.class); when(curatorFramework.getZookeeperClient()).thenReturn(zookeeperClient); final ZooKeeperHolder zooKeeperHolder = mock(ZooKeeperHolder.class); when(zooKeeperHolder.get()).thenReturn(curatorFramework); final KafkaRepository kafkaRepository = new KafkaRepository(zooKeeperHolder, mock(KafkaFactory.class), repositorySettings); kafkaRepository.createTopic(topicName); <START> Thread.sleep(2000); <END> final KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(kafkaProperties); final Map<String, List<PartitionInfo>> topics = kafkaConsumer.listTopics(); assertThat(topics.keySet(), hasItem(topicName)); final List<PartitionInfo> partitionInfos = topics.get(topicName); assertThat(partitionInfos, hasSize(defaultPartitionNum)); partitionInfos .stream() .forEach(pInfo -> assertThat(pInfo.replicas(), arrayWithSize(defaultReplicaFactor))); }</code><technical_language>Is rational 2000 sleep time? I thinking if interesting a "retry strategy" for async assertions. running assertions passed **or** a timeout reached. Wdyt</technical_language>

Target:
public void whenCreateTopicThenTopicIsCreated() throws InterruptedException { final String topicName = TestUtils.randomString(); final CuratorZookeeperClient zookeeperClient = mock(CuratorZookeeperClient.class); when(zookeeperClient.getCurrentConnectionString()).thenReturn(zookeeperURL); final CuratorFramework curatorFramework = mock(CuratorFramework.class); when(curatorFramework.getZookeeperClient()).thenReturn(zookeeperClient); final ZooKeeperHolder zooKeeperHolder = mock(ZooKeeperHolder.class); when(zooKeeperHolder.get()).thenReturn(curatorFramework); final KafkaRepository kafkaRepository = new KafkaRepository(zooKeeperHolder, mock(KafkaFactory.class), repositorySettings); kafkaRepository.createTopic(topicName); executeWithRetry(() -> { final KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(kafkaProperties); final Map<String, List<PartitionInfo>> topics = kafkaConsumer.listTopics(); assertThat(topics.keySet(), hasItem(topicName)); final List<PartitionInfo> partitionInfos = topics.get(topicName); assertThat(partitionInfos, hasSize(defaultPartitionNum)); partitionInfos .stream() .forEach(pInfo -> assertThat(pInfo.replicas(), arrayWithSize(defaultReplicaFactor))); }, new RetryForSpecifiedTimeStrategy<Void>(5000) .withExceptionsThatForceRetry(AssertionError.class) .withWaitBetweenEachTry(500)); }
Source:
<code>private static InetAddress toInetAddress(Slice ipAddress) { InetAddress address; try { <START> address = InetAddress.getByAddress(ipAddress.getBytes()); <END> } catch (UnknownHostException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid IP address binary: " + ipAddress.toStringUtf8(), e); } return address; }</code><technical_language>this is a standalone function. do return InetAdress.get... here, remove temporary variable</technical_language>

Target:
private static InetAddress toInetAddress(Slice ipAddress) { try { return InetAddress.getByAddress(ipAddress.getBytes()); } catch (UnknownHostException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Invalid IP address binary: " + ipAddress.toStringUtf8(), e); } }
Source:
<code>public boolean needsInput() { return !finishing && lookupSourceProviderFuture.isDone() && spillInProgress.isDone() && probe == null && outputPage == null <START> && !isLookupSourceEmpty(); <END> }</code><technical_language>Check this right lookupSourceProviderFuture.isDone()... yet, check all, check in tryFetchLookupSourceProvider</technical_language>

Target:
public boolean needsInput() { return !finishing && lookupSourceProviderFuture.isDone() && spillInProgress.isDone() && probe == null && outputPage == null; }
Source:
<code>private HashMap<String, String> extractAndReadPluginXmlFromArtifact(PluginArtifact artifact) { FileInputStream fileInputStream = null; ZipInputStream zipInputStream; ZipEntry zipEntry; HashMap<String, String> pluginMap = null; try { fileInputStream = new FileInputStream(artifact.getFile().getCanonicalPath()); zipInputStream = new ZipInputStream(fileInputStream); while ((zipEntry = zipInputStream.getNextEntry()) != null) { <START> if (zipEntry.getName().endsWith("plugin.xml")) <END> { pluginMap = readPluginXmlFile(zipInputStream); break; } } } catch (IOException e) { logger.error( "*** Error occurred while trying to extract plugin.xml from artifact " + artifact.getArtifactId() + " " + e.getMessage()); } return pluginMap; }</code><technical_language>I a more explicit check for exact path META-INF/maven/plungin.xml, because... happen, if, say, is coincidentally some other plugin.xml file...</technical_language>

Target:
private HashMap<String, String> extractAndReadPluginXmlFromArtifact(PluginArtifact artifact) { FileInputStream fileInputStream = null; ZipInputStream zipInputStream; ZipEntry zipEntry; HashMap<String, String> pluginMap = null; try { fileInputStream = new FileInputStream(artifact.getFile().getCanonicalPath()); zipInputStream = new ZipInputStream(fileInputStream); while ((zipEntry = zipInputStream.getNextEntry()) != null) { if (zipEntry.getName().endsWith("META-INF/maven/plugin.xml")) { pluginMap = readPluginXmlFile(zipInputStream); break; } } } catch (IOException e) { logger.error( "*** Error occurred while trying to extract plugin.xml from artifact " + artifact.getArtifactId() + " " + e.getMessage()); } return pluginMap; }
Source:
<code>public void checkTruncateRule() { final String original[] = { "foo", "bar", "foobar", "foobarbaz" }; <START> final String expected[] = { "foo", "bar", "foo", "foo" }; <END> ConfigSource config = Exec.newConfigSource().set("rules", ImmutableList.of(ImmutableMap.of("rule", "truncate", "max_length", "3"))); renameAndCheckSchema(config, original, expected); }</code><technical_language>Please add 2-length names "fo" original expected arrays</technical_language>

Target:
public void checkTruncateRule() { final String original[] = { "foo", "bar", "gj", "foobar", "foobarbaz" }; final String expected[] = { "foo", "bar", "gj", "foo", "foo" }; ConfigSource config = Exec.newConfigSource().set("rules", ImmutableList.of(ImmutableMap.of("rule", "truncate", "max_length", "3"))); renameAndCheckSchema(config, original, expected); }
Source:
<code>public FileSystem getFileSystem() { if (locateConf()) { conf.addResource(new Path(this.conf_path + "/core-site.xml")); conf.addResource(new Path(this.conf_path + "/hdfs-site.xml")); try { fs = FileSystem.get(conf); return this.fs; } catch (IOException ex) { System.err.println(ex); } } else { <START> System.err.println("Could not locate hdfs configuarion folder."); <END> } return null; }</code><technical_language>this print user throw exception. I concerned printing user while logged throw exception</technical_language>

Target:
public FileSystem getFileSystem() { if (locateConf()) { conf.addResource(new Path(this.conf_path + "/core-site.xml")); conf.addResource(new Path(this.conf_path + "/hdfs-site.xml")); try { fs = FileSystem.get(conf); return this.fs; } catch (IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(e.getMessage()); } } } else { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe("Could not locate HDFS configuration folder."); } } return null; }
Source:
<code>public static <T> Sequence<T> withEffect(final Sequence<T> seq, final Runnable effect, final Executor exec) { return new YieldingSequenceBase<T>() { @Override <START> public <OutType> Yielder<OutType> toYielder(OutType initValSupplier, YieldingAccumulator<OutType, T> accumulator) <END> { return new ExecuteWhenDoneYielder<>(seq.toYielder(initValSupplier, accumulator), effect, exec); } @Override public <OutType> Yielder<OutType> toYielder( Supplier<OutType> initValSupplier, YieldingAccumulator<OutType, T> accumulator ) { return new ExecuteWhenDoneYielder<>(seq.toYielder(initValSupplier, accumulator), effect, exec); } }; }</code><technical_language>Rename wild? This a Supplier</technical_language>

Target:
public static <T> Sequence<T> withEffect(final Sequence <T> seq, final Runnable effect, final Executor exec) { return new YieldingSequenceBase<T>() { @Override public <OutType> Yielder<OutType> toYielder(OutType initValue, YieldingAccumulator<OutType, T> accumulator) { return new ExecuteWhenDoneYielder<>(seq.toYielder(initValue, accumulator), effect, exec); } }; }
Source:
<code>void setOperationException(Exception exception) { <START> operationException.set(exception); <END> }</code><technical_language>compareAndSet(), do is a volatile Exception (Since is AtomicException)? Also, is this function required? set() call this is improving code readability, reducing repeated code making modular</technical_language>

Target:
void setOperationException(Exception exception) { operationException.set(exception); operationCompleted = true; }
Source:
<code>public void writeDouble(double v) { <START> final long bits = Double.doubleToLongBits(v); <END> int newcount = ensureCapacity(8); final int s = pos; bytes[s] = (byte) (bits >> 56L); bytes[s+1] = (byte) (bits >> 48L); bytes[s+2] = (byte) (bits >> 40L); bytes[s+3] = (byte) (bits >> 32L); bytes[s+4] = (byte) (bits >> 24L); bytes[s+5] = (byte) (bits >> 16L); bytes[s+6] = (byte) (bits >> 8L); bytes[s+7] = (byte) bits; pos = newcount; }</code><technical_language>writeLong(Double.doubleToLongBits(v)) avoid code duplication</technical_language>

Target:
public void writeDouble(double v) { writeLong(Double.doubleToLongBits(v)); }
Source:
<code>public ExchangeContext(boolean crd, GridDhtPartitionsExchangeFuture fut) { int protocolVer = exchangeProtocolVersion(fut.firstEventCache().minimumNodeVersion()); GridDiscoveryManager disco = fut.sharedContext().discovery(); <START> if (protocolVer > 2 && fut.exchangeId().isLeft() && fut.isEventNodeInBaseline() && <END> disco.baselineChanged(fut.sharedContext().exchange().readyAffinityVersion(), fut.initialVersion())) { baselineNodeLeft = true; merge = false; locRecovery = localRecoveryNeeded(fut); } else if (compatibilityNode || (crd && fut.localJoinExchange())) { fetchAffOnJoin = true; merge = false; } else { boolean startCaches = fut.exchangeId().isJoined() && fut.sharedContext().cache().hasCachesReceivedFromJoin(fut.exchangeId().eventNode()); fetchAffOnJoin = protocolVer == 1; merge = !startCaches && protocolVer > 1 && fut.firstEvent().type() != EVT_DISCOVERY_CUSTOM_EVT; } evts = new ExchangeDiscoveryEvents(fut); }</code><technical_language>This protocol works if cluster is in-memory baseline-autoadjust is enabled. works persistence is enabled with/without baseline autoadjust is enabled</technical_language>

Target:
public ExchangeContext(boolean crd, GridDhtPartitionsExchangeFuture fut) { int ver = exchangeProtocolVersion(fut.firstEventCache().minimumNodeVersion()); if (!compatibilityNode && ver > 2 && fut.isBaselineNodeFailed() && !fut.isBaselineAutoAdjusted() && fut.wasRebalanced()) { baselineNodeLeft = true; merge = false; locRecovery = localRecoveryNeeded(fut); } else if (compatibilityNode || (crd && fut.localJoinExchange())) { fetchAffOnJoin = true; merge = false; } else { boolean startCaches = fut.exchangeId().isJoined() && fut.sharedContext().cache().hasCachesReceivedFromJoin(fut.exchangeId().eventNode()); fetchAffOnJoin = ver == 1; merge = !startCaches && ver > 1 && fut.firstEvent().type() != EVT_DISCOVERY_CUSTOM_EVT; } evts = new ExchangeDiscoveryEvents(fut); }
Source:
<code>public void start(StartContext context) throws StartException { JChannel channel = this.getValue(); <START> if (channel instanceof JChannel) { <END> try { JmxConfigurator.registerChannel((JChannel) channel, this.server.getValue(), this.name); } catch (Exception e) { LOGGER.debug(e.getMessage(), e); } } try { channel.connect(this.name); } catch (Exception e) { throw new StartException(e); } }</code><technical_language>I this is needed..</technical_language>

Target:
public void start(StartContext context) throws StartException { JChannel channel = this.getValue(); try { JmxConfigurator.registerChannel(channel, this.server.getValue(), this.name); } catch (Exception e) { LOGGER.debug(e.getMessage(), e); } try { channel.connect(this.name); } catch (Exception e) { throw new StartException(e); } }
Source:
<code>public Stream<DeletedConsumerDTO> listByDate(String dateStr) { CandlepinQuery<DeletedConsumerDTO> query = this.translator.translateQuery(dateStr != null ? this.deletedConsumerCurator.findByDate(ResourceDateParser.parseDateString(dateStr)) : this.deletedConsumerCurator.listAll(), DeletedConsumerDTO.class); <START> return StreamSupport.stream(query.spliterator(), false); <END> }</code><technical_language>This work in cases. processing of stream occurs later, connection backing CPQ close trigger exception instead of returning result. For now, return CandlepinQuery object normal, set container type "Iterable" in yaml</technical_language>

Target:
public CandlepinQuery<DeletedConsumerDTO> listByDate(String dateStr) { return this.translator.translateQuery(dateStr != null ? this.deletedConsumerCurator.findByDate(ResourceDateParser.parseDateString(dateStr)) : this.deletedConsumerCurator.listAll(), DeletedConsumerDTO.class); }
Source:
<code>private void setDateRangeFilter(DateRangeFilter dateFilter) { ZonedDateTime zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getStartDate()), Utils.getUserPreferredZoneId()); startDatePicker.setEnabled(dateFilter.isStartDateEnabled()); <START> startCheckBox.setEnabled(dateFilter.isStartDateEnabled()); <END> startDatePicker.setDate(zoneDate.toLocalDate()); zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getEndDate()), Utils.getUserPreferredZoneId()); endDatePicker.setEnabled(dateFilter.isEndDateEnabled()); endCheckBox.setEnabled(dateFilter.isEndDateEnabled()); endDatePicker.setDate(zoneDate.toLocalDate()); }</code><technical_language>I this setSelected setEnabled</technical_language>

Target:
private void setDateRangeFilter(DateRangeFilter dateFilter) { ZonedDateTime zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getStartDate()), Utils.getUserPreferredZoneId()); startDatePicker.setEnabled(dateFilter.isStartDateEnabled()); startCheckBox.setSelected(dateFilter.isStartDateEnabled()); startDatePicker.setDate(zoneDate.toLocalDate()); zoneDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(dateFilter.getEndDate()), Utils.getUserPreferredZoneId()); endDatePicker.setEnabled(dateFilter.isEndDateEnabled()); endCheckBox.setSelected(dateFilter.isEndDateEnabled()); endDatePicker.setDate(zoneDate.toLocalDate()); }
Source:
<code><START> private boolean extractJarUpdater() { <END> logger.info("Extracting jarUpdater"); File jarUpdaterFile = new File(JAR_UPDATER_APP_PATH); try { jarUpdaterFile.createNewFile(); } catch (IOException e) { logger.error("Can't create empty file for jarUpdater"); return false; } try (InputStream in = UpdateManager.class.getClassLoader().getResourceAsStream("updater/jarUpdater"); OutputStream out = new FileOutputStream(jarUpdaterFile)) { IOUtils.copy(in, out); } catch (IOException e) { logger.error("Can't extract jarUpdater", e); return false; } return true; }</code><technical_language>if exceptions instead of booleans exceptional situations</technical_language>

Target:
private void extractJarUpdater() throws IOException { logger.info("Extracting jarUpdater"); File jarUpdaterFile = new File(JAR_UPDATER_APP_PATH); if (!jarUpdaterFile.exists() && !jarUpdaterFile.createNewFile()) { logger.error("Failed to create Jar Updater empty file"); throw new IOException("Failed to create Jar Updater empty file"); } try (InputStream in = UpdateManager.class.getClassLoader().getResourceAsStream("updater/jarUpdater"); OutputStream out = new FileOutputStream(jarUpdaterFile)) { IOUtils.copy(in, out); } catch (IOException e) { throw e; } }
Source:
<code>protected void doChecks(RunContext context, HttpServletRequest req, HttpServletResponse resp) throws IOException { List<IHealthChecker> checks = getActiveHealthCheckers(); List<IHealthChecker> failed = new ArrayList<>(); for (IHealthChecker check : checks) { try { if (!check.checkHealth(context)) { failed.add(check); } } catch (Throwable t) { LOG.error("HealthChecker[{}] failed", check.getName(), t); failed.add(check); } } int statusCode = failed.isEmpty() ? HttpServletResponse.SC_OK : HttpServletResponse.SC_SERVICE_UNAVAILABLE; String output = generateOutput(statusCode, checks, failed, false); String detailedOutput = output; if (LOG.isDebugEnabled() || Platform.get().inDevelopmentMode()) { detailedOutput = generateOutput(statusCode, checks, failed, true); } <START> LOG.debug(detailedOutput); <END> resp.setContentType("text/plain"); resp.setStatus(statusCode); resp.getWriter().print(Platform.get().inDevelopmentMode() ? detailedOutput : output); }</code><technical_language>This line moved upper if block save additional log level check in logging case</technical_language>

Target:
protected void doChecks(RunContext context, HttpServletRequest req, HttpServletResponse resp) throws IOException { List<IHealthChecker> checks = getActiveHealthCheckers(); List<IHealthChecker> failed = new ArrayList<>(); for (IHealthChecker check : checks) { try { if (!check.checkHealth(context)) { failed.add(check); } } catch (Throwable t) { LOG.error("HealthChecker[{}] failed", check.getName(), t); failed.add(check); } } int statusCode = failed.isEmpty() ? HttpServletResponse.SC_OK : HttpServletResponse.SC_SERVICE_UNAVAILABLE; String output = generateOutput(statusCode, checks, failed, false); resp.setContentType("text/plain"); resp.setStatus(statusCode); if (LOG.isDebugEnabled() || Platform.get().inDevelopmentMode()) { String detailedOutput = generateOutput(statusCode, checks, failed, true); LOG.debug(detailedOutput); resp.getWriter().print(Platform.get().inDevelopmentMode() ? detailedOutput : output); } else { resp.getWriter().print(output); } }
Source:
<code>public void testWPComLoginLogout() { wpLogin(); sleep(); new MePage().go().verifyUsername(E2E_WP_COM_USER_USERNAME); <START> wpLogout(); <END> }</code><technical_language>consistently this failure logout step of this test (running tests a Pixel, API 26): android.support.test.espresso.NoMatchingViewException: views in hierarchy matching: id: android:id/button1 test successfully tapped logout button fails confirmation appear, watching test run I successfully taps logout button. However, I replace wpLogout() page logout() passes consistently: new MePage() .go() .verifyUsername(E2E_DEFAULT_USER_USERNAME) .logout();</technical_language>

Target:
public void testWPComLoginLogout() { wpLogin(); sleep(); new MePage().go().verifyUsername(E2E_WP_COM_USER_USERNAME).logout(); }
Source:
<code>public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { synchronized (this) { if (authenticated) { super.write(ctx, msg, promise); } else if (msg instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.Request req = (BookkeeperProtocol.Request) msg; if (req.getHeader().getOperation() == BookkeeperProtocol.OperationType.AUTH) { super.write(ctx, msg, promise); } else { waitingForAuth.add(msg); } <START> } END> } }</code><technical_language>I in this else case need fail promise, notify write completed badly</technical_language>

Target:
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { synchronized (this) { if (authenticated) { super.write(ctx, msg, promise); } else if (msg instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.Request req = (BookkeeperProtocol.Request) msg; if (req.getHeader().getOperation() == BookkeeperProtocol.OperationType.AUTH) { super.write(ctx, msg, promise); } else { waitingForAuth.add(msg); } } else if (msg instanceof BookieProtocol.Request) { BookieProtocol.Request req = (BookieProtocol.Request)msg; if (BookkeeperProtocol.OperationType.AUTH.getNumber() == req.getOpCode()) { super.write(ctx, msg, promise); } else { waitingForAuth.add(msg); } } } }
Source:
<code>public static WeightedDoubleReservoirSample deserialize(SliceInput input) { <START> int size = input.readInt(); <END> int maxSamples = input.readInt(); checkArgument(size <= maxSamples, "size must not be larger than number of samples"); double[] samples = new double[maxSamples]; input.readBytes( Slices.wrappedDoubleArray(samples), size * SizeOf.SIZE_OF_DOUBLE); double[] weights = new double[maxSamples]; input.readBytes( Slices.wrappedDoubleArray(weights), size * SizeOf.SIZE_OF_DOUBLE); return new WeightedDoubleReservoirSample(size, samples, weights); }</code><technical_language>size -> count</technical_language>

Target:
public static WeightedDoubleReservoirSample deserialize(SliceInput input) { int count = input.readInt(); int maxSamples = input.readInt(); checkArgument(count <= maxSamples, "count must not be larger than number of samples"); double[] samples = new double[maxSamples]; input.readBytes(Slices.wrappedDoubleArray(samples), count * SizeOf.SIZE_OF_DOUBLE); double[] weights = new double[maxSamples]; input.readBytes(Slices.wrappedDoubleArray(weights), count * SizeOf.SIZE_OF_DOUBLE); return new WeightedDoubleReservoirSample(count, samples, weights); }
Source:
<code><START> public void testCompareTo() { <END> ColumnCombinationBitset set1 = new ColumnCombinationBitset().addColumn(2); ColumnCombinationBitset set2 = new ColumnCombinationBitset().addColumn(1); ColumnCombinationBitset set3 = new ColumnCombinationBitset().addColumn(1).addColumn(3); ColumnCombinationBitset set4 = new ColumnCombinationBitset().addColumn(2); assertTrue(set1.compareTo(set2) > 0); assertTrue(set1.compareTo(set3) < 0); assertTrue(set1.compareTo(set4) == 0); assertTrue(set2.compareTo(set4) < 0); assertTrue(set1.compareTo(set1) == 0); assertTrue(set2.compareTo(set3) < 0); }</code><technical_language>I is equals test helper, similar nice for compareTo</technical_language>

Target:
public void testCompareTo() { ColumnCombinationBitset set1 = new ColumnCombinationBitset().addColumn(2); ColumnCombinationBitset set2 = new ColumnCombinationBitset().addColumn(1); ColumnCombinationBitset set3 = new ColumnCombinationBitset().addColumn(1).addColumn(3); ColumnCombinationBitset set4 = new ColumnCombinationBitset().addColumn(2); CompareToTester<ColumnCombinationBitset> testerSet1 = new CompareToTester<>(set1); CompareToTester<ColumnCombinationBitset> testerSet2 = new CompareToTester<>(set2); testerSet1.performCompareToTestEqual(set1, set4); testerSet1.performCompareToTestGreater(set3); testerSet1.performCompareToTestSmaller(set2); testerSet2.performCompareToTestGreater(set3, set4); }
Source:
<code>private void clearAll() { <START> for (int stage = 0; stage < 2; stage++) { <END> for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap .entrySet().iterator(); i.hasNext();) { final Map.Entry<Key, Reference<Repository>> e = i.next(); unregisterAndCloseRepository(e.getKey(), null); } } }</code><technical_language>longer leak usage count purpose usage count is anyway, I get rid of this</technical_language>

Target:
private void clearAll() { for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap .entrySet().iterator(); i.hasNext();) { final Map.Entry<Key, Reference<Repository>> e = i.next(); unregisterAndCloseRepository(e.getKey(), null); } }
Source:
<code>public JavaSecureRandom(Properties properties) throws NoSuchAlgorithmException { <START> if (instance == null) { <END> instance = java.security.SecureRandom .getInstance(properties.getProperty( ConfigurationKeys.CHIMERA_JAVA_SECURE_RANDOM_ALGORITHM_KEY, ConfigurationKeys.CHIMERA_JAVA_SECURE_RANDOM_ALGORITHM_DEFAULT)); } }</code><technical_language>check needed, this is done in constructor. if (instance == null) {</technical_language>

Target:
public JavaSecureRandom(Properties properties) { try { instance = java.security.SecureRandom .getInstance(properties.getProperty( ConfigurationKeys.CHIMERA_JAVA_SECURE_RANDOM_ALGORITHM_KEY, ConfigurationKeys.CHIMERA_JAVA_SECURE_RANDOM_ALGORITHM_DEFAULT)); } catch (NoSuchAlgorithmException e) { LOG.error("Failed to create java secure random due to error: " + e); } }
Source:
<code>public ProjectJson create( final MultipartForm form ) throws Exception { final Project project = projectService.create( createParams( form ) ); final ProjectPermissions projectPermissions = getPermissionsFromForm( form ); <START> projectService.modifyPermissions( project.getName(), getPermissionsFromForm( form ) ); <END> return new ProjectJson( project, projectPermissions ); }</code><technical_language>@vbradnitski projectPermissions variable instead of recall getPermissionsFromForm( form ) method</technical_language>

Target:
public ProjectJson create( final MultipartForm form ) throws Exception { final Project project = projectService.create( createParams( form ) ); final ProjectPermissions projectPermissions = getPermissionsFromForm( form ); projectService.modifyPermissions( project.getName(), projectPermissions ); return new ProjectJson( project, projectPermissions ); }
Source:
<code>public Set<String> keys() { if (!closed) { final RequestMessage msg = RequestMessage.build(Tokens.OPS_KEYS) .addArg(Tokens.ARGS_SIDE_EFFECT, serverSideEffect) .addArg(Tokens.ARGS_HOST, host) .processor("traversal").create(); try { <START> keys = client.submitAsync(msg).get().all().get().stream().map(r -> r.getString()).collect(Collectors.toSet()); <END> } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); final String exMsg = null == root ? "" : root.getMessage(); if (!exMsg.equals("Could not find side-effects for " + serverSideEffect + ".")) throw new RuntimeException("Could not get keys", root); } } return keys; }</code><technical_language>first, I this replaced Set - if called get() this set get re-initialized keys in it. I suppose a problem. If do check if Set initialized if new up: java if (keys == Collections.emptySet()) keys = new HashSet<>(); client.submitAsync(msg).get().all().get().forEach(r -> keys.add(r.getString()) A tad nicer rid of stream()....i dunno is fine i guess</technical_language>

Target:
public Set<String> keys() { if (!closed) { final RequestMessage msg = RequestMessage.build(Tokens.OPS_KEYS) .addArg(Tokens.ARGS_SIDE_EFFECT, serverSideEffect) .addArg(Tokens.ARGS_HOST, host) .processor("traversal").create(); try { if (keys.equals(Collections.emptySet())) keys = new HashSet<>(); client.submitAsync(msg).get().all().get().forEach(r -> keys.add(r.getString())); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); final String exMsg = null == root ? "" : root.getMessage(); if (!exMsg.equals("Could not find side-effects for " + serverSideEffect + ".")) throw new RuntimeException("Could not get keys", root); } } return keys; }
Source:
<code>public void handle(Person person, User creator, Date dateCreated, String other) { if (person.getAddresses() != null && person.getAddresses().size() > 0) { for (PersonAddress pAddress : person.getAddresses()) { <START> if (pAddress.isBlank()){ <END> person.removeAddress(pAddress); } pAddress.setPerson(person); } } if (person.getNames() != null && person.getNames().size() > 0) { for (PersonName pName : person.getNames()) { pName.setPerson(person); } } if (person.getAttributes() != null && person.getAttributes().size() > 0) { for (PersonAttribute pAttr : person.getAttributes()) { pAttr.setPerson(person); } } if (!person.isDead() && person.getCauseOfDeath() != null) { person.setCauseOfDeath(null); } if (person.isPersonVoided()) { if (!StringUtils.hasLength(person.getPersonVoidReason())) { throw new APIException("Person.voided.bit", new Object[] { person }); } if (person.getPersonVoidedBy() == null) { person.setPersonVoidedBy(creator); } if (person.getPersonDateVoided() == null) { person.setPersonDateVoided(dateCreated); } } else { person.setPersonVoidedBy(null); person.setPersonDateVoided(null); person.setPersonVoidReason(null); } }</code><technical_language>I imagine removeAddress call PersonAddress.setPerson technically mutually exclusive, this if-else clause call continue removing it. I ConceptSaveHandler code for descriptions this issue, i fix</technical_language>

Target:
public void handle(Person person, User creator, Date dateCreated, String other) { if (person.getAddresses() != null && person.getAddresses().size() > 0) { for (PersonAddress pAddress : person.getAddresses()) { if (pAddress.isBlank()){ person.removeAddress(pAddress); continue; } pAddress.setPerson(person); } } if (person.getNames() != null && person.getNames().size() > 0) { for (PersonName pName : person.getNames()) { pName.setPerson(person); } } if (person.getAttributes() != null && person.getAttributes().size() > 0) { for (PersonAttribute pAttr : person.getAttributes()) { pAttr.setPerson(person); } } if (!person.isDead() && person.getCauseOfDeath() != null) { person.setCauseOfDeath(null); } if (person.isPersonVoided()) { if (!StringUtils.hasLength(person.getPersonVoidReason())) { throw new APIException("Person.voided.bit", new Object[] { person }); } if (person.getPersonVoidedBy() == null) { person.setPersonVoidedBy(creator); } if (person.getPersonDateVoided() == null) { person.setPersonDateVoided(dateCreated); } } else { person.setPersonVoidedBy(null); person.setPersonDateVoided(null); person.setPersonVoidReason(null); } }
Source:
<code>public GenericAggregateFactory(AggregateModel<T> aggregateModel) { super(aggregateModel); aggregateModel.types() .filter(type -> !Modifier.isInterface(type.getModifiers())) .filter(type -> !Modifier.isAbstract(type.getModifiers())) .forEach(type -> { try { Constructor<?> constructor = ensureAccessible(type.getDeclaredConstructor()); constructors.put(type, constructor); } catch (NoSuchMethodException e) { throw new IncompatibleAggregateException(format( <START> "The aggregate (or some of its subtypes) [%s] doesn't provide a no-arg constructor.", <END> aggregateModel.entityClass().getSimpleName())); } }); }</code><technical_language>mention actual type No-Arg Constructor found? developer</technical_language>

Target:
public GenericAggregateFactory(AggregateModel<T> aggregateModel) { super(aggregateModel); aggregateModel.types() .filter(type -> !Modifier.isInterface(type.getModifiers())) .filter(type -> !Modifier.isAbstract(type.getModifiers())) .forEach(type -> { try { Constructor<?> constructor = ensureAccessible(type.getDeclaredConstructor()); constructors.put(type, constructor); } catch (NoSuchMethodException e) { throw new IncompatibleAggregateException(format( "The aggregate [%s] doesn't provide a no-arg constructor.", type.getName())); } }); }
Source:
<code>public void onError(Channel channel, Throwable error) { if (error instanceof OutOfMemoryError) { OutOfMemoryErrorDispatcher.onOutOfMemory((OutOfMemoryError) error); } if (channel == null) { logger.severe(error); } else { TcpIpConnection connection = (TcpIpConnection) channel.attributeMap().get(TcpIpConnection.class); if (error instanceof EOFException) { connection.close("Connection closed by the other side", error); <START> } else if (connection != null) { <END> connection.close("Exception in " + connection + ", thread=" + Thread.currentThread().getName(), error); } } }</code><technical_language>Do scenario connection is null? impossible in branch</technical_language>

Target:
public void onError(Channel channel, Throwable error) { if (error instanceof OutOfMemoryError) { OutOfMemoryErrorDispatcher.onOutOfMemory((OutOfMemoryError) error); } if (channel == null) { logger.severe(error); } else { TcpIpConnection connection = (TcpIpConnection) channel.attributeMap().get(TcpIpConnection.class); if (connection != null) { String closeReason = (error instanceof EOFException) ? "Connection closed by the other side" : "Exception in " + connection + ", thread=" + Thread.currentThread().getName(); connection.close(closeReason, error); } else { logger.warning("Channel error occured", error); } } }