auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void configureColor() { ChatPrefs chatPrefs = preferencesService.getPreferences().getChatPrefs(); ObjectProperty<Color> colorProperty = null; Color color = null; <START> if (playerInfoBean.getModeratorInChannels().size() > 0) { <END> colorProperty = chatPrefs.modsChatColorProperty(); } else if (playerInfoBean.isFriend()) { colorProperty = chatPrefs.friendsChatColorProperty(); } else if (playerInfoBean.isFoe()) { colorProperty = chatPrefs.foesChatColorProperty(); } else if (playerInfoBean.getUsername().equals(userService.getUsername())) { colorProperty = chatPrefs.selfChatColorProperty(); } if (!chatPrefs.getPrettyColors() && colorProperty == null) { if (playerInfoBean.isChatOnly()) { colorProperty = chatPrefs.ircChatColorProperty(); } else { colorProperty = chatPrefs.othersChatColorProperty(); } } else if (chatPrefs.getPrettyColors() && colorProperty == null) { color = ColorGeneratorUtil.generatePrettyHexColor(); ChatUser chatUser = chatService.getChatUser(playerInfoBean.getUsername()); try { if (chatUser.getColor() == null) { chatUser.setColor(color); } else { color = chatUser.getColor(); } } catch (NullPointerException e) { logger.warn("Could not generate color for {}", playerInfoBean.getUsername()); } } if (colorProperty != null) { color = colorProperty.get(); addColorListenerToLabels(colorProperty); } usernameLabel.setTextFill(color); clanLabel.setTextFill(color); }</code><technical_language>isEmpty() (negate needed) instead. Rationale: <LINK_0></technical_language>

Target:
private void configureColor() { ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); if (playerInfoBean.getSocialStatus() == SELF) { getStyleClass().add(CSS_CLASS_SELF); return; } Color color = null; ChatUser chatUser = chatService.createOrGetChatUser(playerInfoBean.getUsername()); if (chatPrefs.getChatColorMode().equals(CUSTOM)) { if (chatPrefs.getUserToColor().containsKey(playerInfoBean.getUsername())) { color = chatPrefs.getUserToColor().get(playerInfoBean.getUsername()); } chatPrefs.getUserToColor().addListener((MapChangeListener<? super String, ? super Color>) change -> { if (playerInfoBean.getUsername().equals(change.getKey())) { Color newColor = chatPrefs.getUserToColor().get(playerInfoBean.getUsername()); assignColor(newColor); } }); } else if (chatPrefs.getChatColorMode().equals(ChatColorMode.RANDOM) && colorsAllowedInPane) { color = ColorGeneratorUtil.generateRandomHexColor(); } chatUser.setColor(color); assignColor(color); }
Source:
<code>public String toString() { return super.toString() + " TruncationHandleMessage truncation handle id: " <START> + CoreUtils.hsIdToString(m_truncationHandle); <END> }</code><technical_language>truncation handle is HSID, TxnEgo.txnIdToString() instead</technical_language>

Target:
public String toString() { return super.toString() + " TruncationHandleMessage truncation handle id: " + TxnEgo.txnIdToString(m_truncationHandle); }
Source:
<code>public OIndexRIDContainer(String name, boolean durableNonTxMode, AtomicLong bonsayFileId) { if (bonsayFileId.get() == 0) { fileId = resolveFileIdByName(name + INDEX_FILE_EXTENSION); bonsayFileId.set(fileId); } else { <START> fileId = bonsayFileId.get(); <END> } underlying = new HashSet<>(); isEmbedded = true; this.durableNonTxMode = durableNonTxMode; }</code><technical_language>I suppose avoid double get of volatile field cached in of cases do fileId = bonsayFileId.get(); if (fileId == 0) { fileId = resolveFileIdByName(name + INDEX_FILE_EXTENSION); bonsayFileId.set(fileId); } is minor</technical_language>

Target:
public OIndexRIDContainer(String name, boolean durableNonTxMode, AtomicLong bonsayFileId) { long gotFileId = bonsayFileId.get(); if (gotFileId == 0) { gotFileId = resolveFileIdByName(name + INDEX_FILE_EXTENSION); bonsayFileId.set(gotFileId); } this.fileId = gotFileId; underlying = new HashSet<>(); isEmbedded = true; this.durableNonTxMode = durableNonTxMode; }
Source:
<code>public boolean suppresses(Rule rule) { if (jjtGetChild(0) instanceof ASTMarkerAnnotation) { return false; } <START> if ("SuppressWarnings".equals(getAnnotationName()) || "java.lang.SuppressWarnings".equals(getAnnotationName())) { <END> for (ASTLiteral element : findDescendantsOfType(ASTLiteral.class)) { if (element.hasImageEqualTo("\"PMD\"") || element.hasImageEqualTo("\"PMD." + rule.getName() + "\"") || element.hasImageEqualTo("\"all\"") || element.hasImageEqualTo("\"serial\"") && SERIAL_RULES.contains(rule.getName()) || element.hasImageEqualTo("\"unused\"") && UNUSED_RULES.contains(rule.getName())) { return true; } } } return false; }</code><technical_language>SuppressWarnings.class.getSimpleName().equals(getAnnotationName()) instead of Strings ... for readability improvement, this a simple private method isSupressWarnings()</technical_language>

Target:
public boolean suppresses(Rule rule) { if (jjtGetChild(0) instanceof ASTMarkerAnnotation) { return false; } if (isSuppressWarnings()) { for (ASTLiteral element : findDescendantsOfType(ASTLiteral.class)) { if (element.hasImageEqualTo("\"PMD\"") || element.hasImageEqualTo("\"PMD." + rule.getName() + "\"") || element.hasImageEqualTo("\"all\"") || element.hasImageEqualTo("\"serial\"") && SERIAL_RULES.contains(rule.getName()) || element.hasImageEqualTo("\"unused\"") && UNUSED_RULES.contains(rule.getName())) { return true; } } } return false; }
Source:
<code>public void put(int fieldId, Datum value) { <START> this.offset = -1; <END> values[fieldId] = value; }</code><technical_language>put needs offset initialization</technical_language>

Target:
public void put(int fieldId, Datum value) { values[fieldId] = value; }
Source:
<code>public void returnsCorrectNamesSet() throws Exception { final String body = "441 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMtFake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), new FormattedText( "Content-Length: %s", body.getBytes().length ).asString(), "Content-Disposition: form-data; name=\"address\"" ), new RqWithHeaders( new RqFake("", "", ""), "Content-Length: 0", <START> "Content-Disposition: form-data; name=\"data\"; filename=\"a.bin\"" <END> ) ); try { MatcherAssert.assertThat( multi.names(), Matchers.<Iterable<String>>equalTo( new HashSet<String>(Arrays.asList("address", "data")) ) ); } finally { multi.body().close(); } }</code><technical_language>@Serranya here. above</technical_language>

Target:
public void returnsCorrectNamesSet() throws Exception { final String body = "441 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMtFake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), new FormattedText( RqMtFakeTest.CONTENT_LENGTH, body.getBytes().length ).asString(), new FormattedText( RqMtFakeTest.CONTENT_DISP, "name=\"address\"" ).asString() ), new RqWithHeaders( new RqFake("", "", ""), new FormattedText(RqMtFakeTest.CONTENT_LENGTH, 0).asString(), new FormattedText( RqMtFakeTest.CONTENT_DISP, "name=\"data\"; filename=\"a.bin\"" ).asString() ) ); try { MatcherAssert.assertThat( multi.names(), Matchers.<Iterable<String>>equalTo( new HashSet<String>(Arrays.asList("address", "data")) ) ); } finally { multi.body().close(); } }
Source:
<code>private void validateReportIndex(GraphContext context) { ReportService reportService = new ReportService(context); ReportModel reportModel = reportService.getUniqueByProperty( ReportModel.TEMPLATE_PATH, CreateReportIndexRuleProvider.TEMPLATE); Path appReportPath = reportService.getReportDirectory().resolve(reportModel.getReportFilename()); TestReportIndexReportUtil util = new TestReportIndexReportUtil(); util.loadPage(appReportPath); Assert.assertTrue(util.checkIncidentByCategoryRow("optional", 291, 2306)); Assert.assertTrue(util.checkIncidentByCategoryRow("mandatory", 0, 0)); Assert.assertTrue(util.checkIncidentByCategoryRow("information", 10, 0)); Assert.assertTrue(util.checkIncidentByCategoryRow("cloud-mandatory", 3, 3)); <START> Assert.assertTrue(util.checkIncidentByCategoryRow("mandatory", 0, 0)); <END> }</code><technical_language>this a duplicate removed (maybe better) changed potential</technical_language>

Target:
private void validateReportIndex(GraphContext context) { ReportService reportService = new ReportService(context); ReportModel reportModel = reportService.getUniqueByProperty( ReportModel.TEMPLATE_PATH, CreateReportIndexRuleProvider.TEMPLATE); Path appReportPath = reportService.getReportDirectory().resolve(reportModel.getReportFilename()); TestReportIndexReportUtil util = new TestReportIndexReportUtil(); util.loadPage(appReportPath); Assert.assertTrue(util.checkIncidentByCategoryRow("optional", 291, 2306)); Assert.assertTrue(util.checkIncidentByCategoryRow("mandatory", 0, 0)); Assert.assertTrue(util.checkIncidentByCategoryRow("information", 10, 0)); Assert.assertTrue(util.checkIncidentByCategoryRow("cloud-mandatory", 3, 3)); Assert.assertTrue(util.checkIncidentByCategoryRow("potential", 0, 0)); }
Source:
<code>protected List<E> getFilteredList() { List<E> filteredValues = new ArrayList<>(); Collections.addAll(filteredValues, enumeration.getEnumConstants()); <START> if (excludedValues != null) { <END> for (E element : excludedValues) { filteredValues.remove(element); } } return filteredValues; }</code><technical_language>this checked construction time. create object inconsistent state</technical_language>

Target:
private List<E> getFilteredList() { List<E> filteredValues = new ArrayList<>(); Collections.addAll(filteredValues, enumeration.getEnumConstants()); if (excludedValues != null) { for (E element : excludedValues) { filteredValues.remove(element); } } return filteredValues; }
Source:
<code><START> public boolean isTopicMute(Message message) { <END> return mutedTopics.contains(message.getStream().getId() + message.getSubject()); }</code><technical_language>this API cleaner</technical_language>

Target:
public boolean isTopicMute(Message message) { return mutedTopics.contains(message.concatStreamAndTopic()); }
Source:
<code>public boolean isPartitionedOn(Collection<Symbol> columns, Set<Symbol> knownConstants) { for (ArgumentBinding argument : arguments) { if (argument.isConstant()) { continue; } if (!argument.isVariable()) { <START> return false; <END> } if (!knownConstants.contains(argument.getColumn()) && !columns.contains(argument.getColumn())) { return false; } } return true; }</code><technical_language>(There is action required; thoughts reading code) I see. Previously, if variable, constant simply ignored. Now, if constant variable, a (coalesce) expression, return false for this method :)</technical_language>

Target:
public boolean isPartitionedOn(Collection<Symbol> columns, Set<Symbol> knownConstants) { for (ArgumentBinding argument : arguments) { if (argument.isConstant()) { continue; } if (!argument.isSymbolReference()) { return false; } if (!knownConstants.contains(argument.getSymbol()) && !columns.contains(argument.getSymbol())) { return false; } } return true; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { this.message = (SwrveMessage) extras.getSerializable("inAppMessage"); this.hideToolbar = extras.getBoolean("hideToolbar", true); this.minSampleSize = extras.getInt("minSampleSize", 1); this.messenger = (Messenger)extras.get("messenger"); <START> } <END> } SwrveOrientation deviceOrientation = getDeviceOrientation(); SwrveMessageFormat format = message.getFormat(deviceOrientation); if (format == null) { format = message.getFormats().get(0); if (format.getOrientation() != deviceOrientation) { if (format.getOrientation() == SwrveOrientation.Landscape) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } } if (message != null) { if (hideToolbar) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); } try { SwrveMessageView view = new SwrveMessageView(this, messenger, message, format, minSampleSize); setContentView(view); if(savedInstanceState == null) { view.notifyOfImpression(message, format); } } catch (SwrveMessageViewBuildException e) { e.printStackTrace(); } } else { finish(); } }</code><technical_language>else exit</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sdk = (SwrveBase)SwrveSDK.getInstance(); if (sdk == null) { finish(); return; } Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { int messageId = extras.getInt(MESSAGE_ID_KEY); message = sdk.getMessageForId(messageId); SwrveConfigBase config = sdk.getConfig(); this.hideToolbar = config.isHideToolbar(); this.minSampleSize = config.getMinSampleSize(); this.defaultBackgroundColor = config.getDefaultBackgroundColor(); } } if (message == null) { finish(); return; } SwrveOrientation deviceOrientation = getDeviceOrientation(); format = message.getFormat(deviceOrientation); if (format == null) { format = message.getFormats().get(0); } if (message.getFormats().size() == 1) { if (format.getOrientation() == SwrveOrientation.Landscape) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } if (!hideToolbar) { setTheme(R.style.Theme_InAppMessageWithToolbar); } try { SwrveMessageView view = new SwrveMessageView(this, message, format, minSampleSize, defaultBackgroundColor); setContentView(view); if(savedInstanceState == null) { notifyOfImpression(format); } } catch (SwrveMessageViewBuildException e) { SwrveLogger.e(LOG_TAG, "Error while creating the SwrveMessageView", e); } }
Source:
<code>public ConfigBuilder readFrom(View<?> view) { <START> if (view instanceof Dataset && view instanceof FileSystemDataset) { <END> FileSystemDataset dataset = (FileSystemDataset) view; conf.set(KITE_PARTITION_DIR, String.valueOf(dataset.getDescriptor().getLocation())); } withType(view.getType()); return readFrom(view.getUri()); }</code><technical_language>instanceof Dataset is redundant -- a single instanceof FilesystemDataset check</technical_language>

Target:
public ConfigBuilder readFrom(View<?> view) { if (view instanceof FileSystemDataset) { FileSystemDataset dataset = (FileSystemDataset) view; conf.set(KITE_PARTITION_DIR, String.valueOf(dataset.getDescriptor().getLocation())); } withType(view.getType()); return readFrom(view.getUri()); }
Source:
<code>public HadoopDruidIndexerConfig( final @JsonProperty("schema") HadoopIngestionSpec schema ) { this.columnConfig = columnConfig; this.schema = schema; this.pathSpec = jsonMapper.convertValue(schema.getIOConfig().getPathSpec(), PathSpec.class); for (Map.Entry<DateTime, List<HadoopyShardSpec>> entry : schema.getTuningConfig().getShardSpecs().entrySet()) { if (entry.getValue() == null || entry.getValue().isEmpty()) { continue; } <START> final ShardSpec actualSpec = entry.getValue().get(0).getActualSpec(); <END> shardSpecLookups.put( entry.getKey(), actualSpec.getLookup( Lists.transform( entry.getValue(), new Function<HadoopyShardSpec, ShardSpec>() { @Nullable @Override public ShardSpec apply(@Nullable HadoopyShardSpec input) { return input.getActualSpec(); } } ) ) ); for (HadoopyShardSpec hadoopyShardSpec : entry.getValue()) { hadoopShardSpecLookup.put(hadoopyShardSpec.getActualSpec(), hadoopyShardSpec); } } }</code><technical_language>multiple hadoopy shard specs</technical_language>

Target:
public HadoopDruidIndexerConfig( final @JsonProperty("schema") HadoopIngestionSpec schema ) { this.columnConfig = columnConfig; this.schema = schema; this.pathSpec = jsonMapper.convertValue(schema.getIOConfig().getPathSpec(), PathSpec.class); for (Map.Entry<DateTime, List<HadoopyShardSpec>> entry : schema.getTuningConfig().getShardSpecs().entrySet()) { if (entry.getValue() == null || entry.getValue().isEmpty()) { continue; } final ShardSpec actualSpec = entry.getValue().get(0).getActualSpec(); shardSpecLookups.put( entry.getKey(), actualSpec.getLookup( Lists.transform( entry.getValue(), new Function<HadoopyShardSpec, ShardSpec>() { @Override public ShardSpec apply(HadoopyShardSpec input) { return input.getActualSpec(); } } ) ) ); for (HadoopyShardSpec hadoopyShardSpec : entry.getValue()) { hadoopShardSpecLookup.put(hadoopyShardSpec.getActualSpec(), hadoopyShardSpec); } } }
Source:
<code>public void committed(long epoch, Layout layout, boolean force) throws WrongEpochException { CompletableFuture<Boolean>[] commitList = layout.getLayoutServers().stream() .map(x -> { CompletableFuture<Boolean> cf = new CompletableFuture<>(); try { if (force) { cf = getRuntimeLayout(layout).getLayoutClient(x).force(layout); } else { cf = getRuntimeLayout(layout).getLayoutClient(x).committed(epoch, layout); } } catch (NetworkException e) { cf.completeExceptionally(e); } return cf; }) .toArray(CompletableFuture[]::new); int responses = 0; for (CompletableFuture cf : commitList) { try { CFUtils.getUninterruptibly(cf, WrongEpochException.class, TimeoutException.class, NetworkException.class, NoBootstrapException.class); responses++; } catch (WrongEpochException e) { log.warn("committed: Error while force committing", e); <START> } catch (NoBootstrapException nbe) { <END> log.warn("committed: Error while force committing", nbe); } catch (TimeoutException | NetworkException e) { log.warn("committed: Error while committing", e); } } log.debug("committed: Successful responses={}, responses={}", commitList.length, responses); }</code><technical_language>Iog node information warning messages. I guessing useful for debugging in case of issues</technical_language>

Target:
public void committed(long epoch, Layout layout, boolean force) throws WrongEpochException { CompletableFuture<Boolean>[] commitList = layout.getLayoutServers().stream() .map(x -> { CompletableFuture<Boolean> cf = new CompletableFuture<>(); try { if (force) { cf = getRuntimeLayout(layout).getLayoutClient(x).force(layout); } else { cf = getRuntimeLayout(layout).getLayoutClient(x).committed(epoch, layout); } } catch (NetworkException e) { cf.completeExceptionally(e); } return cf; }) .toArray(CompletableFuture[]::new); int responses = 0; for (CompletableFuture cf : commitList) { try { CFUtils.getUninterruptibly(cf, WrongEpochException.class, TimeoutException.class, NetworkException.class, NoBootstrapException.class); responses++; } catch (WrongEpochException e) { if (!force) { throw e; } log.warn("committed: encountered exception", e); } catch (NoBootstrapException | TimeoutException | NetworkException e) { log.warn("committed: encountered exception", e); } } log.debug("committed: Successful requests={}, responses={}", commitList.length, responses); }
Source:
<code>public void cleanUp() throws Exception { if (container.isStarted()) { container.stop(); if(container.isStarted()){ throw new Exception("Could not stop container"); } } if(new File(COPY_PATH).isDirectory()){ if(new File(COPY_PATH+File.separatorChar+SERVER_CONFIG).exists()){ new File(COPY_PATH+File.separatorChar+SERVER_CONFIG).delete(); } <START> new File(COPY_PATH).delete(); <END> } }</code><technical_language>file calling File() constructors times (even lines), store in a variable</technical_language>

Target:
public void cleanUp() throws Exception { if (container.isStarted()) { container.stop(); if(container.isStarted()){ throw new Exception("Could not stop container"); } } if(targetDirectory != null){ if(copyConfigFile != null && copyConfigFile.exists()){ copyConfigFile.delete(); } targetDirectory.delete(); } }
Source:
<code>private <T> T constructWithConstructor( Class<T> clazz, Constructor<?> constructor, Set<Class<?>> autoConstructionCandidates) { Parameter[] parameters = constructor.getParameters(); Object[] values = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { values[i] = getValueForParameter(parameters[i]); if (values[i] == null) { Class<?> parameterType = parameters[i].getType(); if (canAutoConstruct(parameterType) && !autoConstructionCandidates.contains(parameterType)) { try { values[i] = construct(parameterType, autoConstructionCandidates); } catch (IllegalArgumentException | IllegalStateException e) { logger.debug("Could not build class as the following type could not be constructed {}", clazz, parameterType, e); return null; } } else { <START> logger.error("Could not build class as the following type was not found {}", clazz, parameterType); <END> return null; } } } return instantiate(clazz, constructor, values); }</code><technical_language>this, debug</technical_language>

Target:
private <T> T constructWithConstructor( Class<T> clazz, Constructor<?> constructor, Set<Class<?>> autoConstructionCandidates) { Parameter[] parameters = constructor.getParameters(); Object[] values = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { values[i] = getValueForParameter(parameters[i]); if (values[i] == null) { Class<?> parameterType = parameters[i].getType(); if (canAutoConstruct(parameterType) && !autoConstructionCandidates.contains(parameterType)) { try { values[i] = construct(parameterType, autoConstructionCandidates); } catch (IllegalArgumentException | IllegalStateException e) { logger.error("Could not build class as the following type could not be constructed {}", clazz, parameterType, e); return null; } } else { logger.error("Could not build class as the following type was not found {}", clazz, parameterType); return null; } } } return instantiate(clazz, constructor, values); }
Source:
<code>default Future<Long> write(ByteBuf src, Callback<Long> callback) { int numBuffers = src.nioBufferCount(); if (numBuffers == 1) { return write(src.nioBuffer(), (result, exception) -> { if (result != 0) { src.readerIndex(src.readerIndex() + (int) result.longValue()); } callback.onCompletion(result, exception); }); } else { ByteBuffer[] buffers = src.nioBuffers(); AtomicLong size = new AtomicLong(0); AtomicInteger index = new AtomicInteger(0); FutureResult<Long> futureResult = new FutureResult<Long>(); <START> Callback<Long> cb = new Callback<Long>() { <END> @Override public void onCompletion(Long result, Exception exception) { index.addAndGet(1); size.addAndGet(result); if (result != 0) { src.readerIndex(src.readerIndex() + (int) result.longValue()); } if (exception != null) { futureResult.done(size.get(), exception); if (callback != null) { callback.onCompletion(size.get(), exception); } } else { if (index.get() == buffers.length) { futureResult.done(size.get(), exception); if (callback != null) { callback.onCompletion(size.get(), exception); } } } } }; for (int i = 0; i < buffers.length; i++) { write(buffers[i], cb); } return futureResult; } }</code><technical_language>lambda syntax save some indentation</technical_language>

Target:
default Future<Long> write(ByteBuf src, Callback<Long> callback) { if (src == null) { throw new IllegalArgumentException("Source ByteBuf cannot be null"); } int numBuffers = src.nioBufferCount(); FutureResult<Long> futureResult = new FutureResult<>(); Callback<Long> singleBufferCallback = (result, exception) -> { if (result != 0) { src.readerIndex(src.readerIndex() + (int) result.longValue()); } futureResult.done(result.longValue(), exception); if (callback != null) { callback.onCompletion(result, exception); } }; if (numBuffers < 1) { ByteBuffer byteBuffer = ByteBuffer.allocate(src.readableBytes()); src.getBytes(src.readerIndex(), byteBuffer); write(byteBuffer, singleBufferCallback); } else if (numBuffers == 1) { write(src.nioBuffer(), singleBufferCallback); } else { ByteBuffer[] buffers = src.nioBuffers(); AtomicLong size = new AtomicLong(0); AtomicInteger index = new AtomicInteger(0); AtomicBoolean callbackInvoked = new AtomicBoolean(false); Callback<Long> cb = (result, exception) -> { index.addAndGet(1); size.addAndGet(result); if (result != 0) { src.readerIndex(src.readerIndex() + (int) result.longValue()); } if ((exception != null || index.get() == buffers.length) && callbackInvoked.compareAndSet(false, true)) { futureResult.done(size.get(), exception); if (callback != null) { callback.onCompletion(size.get(), exception); } } }; for (int i = 0; i < buffers.length; i++) { write(buffers[i], cb); } } return futureResult; }
Source:
<code>private static Tuple3<PriorityQueue<OptimizedEvaluator>, Double, Integer> getOptimizedEvaluators(final Cost cost) { final PriorityQueue<OptimizedEvaluator> optimizedEvaluatorQueue = new PriorityQueue<>(cost.getComputeTaskCosts().size(), COMP_UNIT_COST_INV_COMPARATOR); double compUnitCostSum = 0; int numUnitsTotal = 0; for (final Cost.ComputeTaskCost computeTaskCost : cost.getComputeTaskCosts()) { final int numBlocks = computeTaskCost.getDataInfo().getNumBlocks(); <START> final double compUnitCost = computeTaskCost.getComputeCost() / numBlocks; <END> final double compUnitCostInv = 1 / compUnitCost; compUnitCostSum += compUnitCost; numUnitsTotal += numBlocks; optimizedEvaluatorQueue.add(new OptimizedEvaluator( computeTaskCost.getId(), computeTaskCost.getDataInfo(), compUnitCostInv)); } return new Tuple3<>(optimizedEvaluatorQueue, compUnitCostSum, numUnitsTotal); }</code><technical_language>compUnitCost -> compBlockCost? blockCompCost</technical_language>

Target:
private static Tuple3<PriorityQueue<OptimizedEvaluator>, Double, Integer> getOptimizedEvaluators(final Cost cost) { final PriorityQueue<OptimizedEvaluator> optimizedEvaluatorQueue = new PriorityQueue<>(cost.getComputeTaskCosts().size(), COMP_COST_PER_BLOCK_INV_COMPARATOR); double compCostPerBlockSum = 0; int numTotalBlocks = 0; for (final Cost.ComputeTaskCost computeTaskCost : cost.getComputeTaskCosts()) { final int numBlocks = computeTaskCost.getDataInfo().getNumBlocks(); final double compCostPerBlock = computeTaskCost.getComputeCost() / numBlocks; final double compCostInv = 1 / compCostPerBlock; compCostPerBlockSum += compCostPerBlock; numTotalBlocks += numBlocks; optimizedEvaluatorQueue.add(new OptimizedEvaluator( computeTaskCost.getId(), computeTaskCost.getDataInfo(), compCostInv)); } return new Tuple3<>(optimizedEvaluatorQueue, compCostPerBlockSum, numTotalBlocks); }
Source:
<code>public boolean connect(String port) throws Exception { if (controller == null) { error("arduino is invalid"); return false; } <START> PortConnector arduino = (PortConnector) controller; <END> arduino.connect(port); if (!arduino.isConnected()) { error("torso arduino on port %s not connected", port); return false; } topStom.attach(controller, 27, topStom.getRest(), topStom.getVelocity()); midStom.attach(controller, 28, midStom.getRest(), midStom.getVelocity()); lowStom.attach(controller, 29, lowStom.getRest(), lowStom.getVelocity()); enableAutoEnable(true); broadcastState(); return true; }</code><technical_language>this unsafe type cast..</technical_language>

Target:
public boolean connect(String port) throws Exception { if (controller == null) { error("arduino is invalid"); return false; } if (controller instanceof PortConnector) { PortConnector arduino = (PortConnector) controller; arduino.connect(port); if (!arduino.isConnected()) { error("torso arduino on port %s not connected", port); return false; } } topStom.attach(controller, 27, topStom.getRest(), topStom.getVelocity()); midStom.attach(controller, 28, midStom.getRest(), midStom.getVelocity()); lowStom.attach(controller, 29, lowStom.getRest(), lowStom.getVelocity()); enableAutoEnable(true); broadcastState(); return true; }
Source:
<code>public static void initCOM() { HRESULT hres = null; if (!isComInitialized()) { hres = Ole32.INSTANCE.CoInitializeEx(null, Ole32.COINIT_MULTITHREADED); switch (hres.intValue()) { case COMUtils.S_OK: comInitialized = true; break; case COMUtils.S_FALSE: case WinError.RPC_E_CHANGED_MODE: break; default: throw new COMException("Failed to initialize COM library.", new HRESULT(-1)); } } if (!isSecurityInitialized()) { hres = Ole32.INSTANCE.CoInitializeSecurity(null, -1, null, null, Ole32.RPC_C_AUTHN_LEVEL_DEFAULT, Ole32.RPC_C_IMP_LEVEL_IMPERSONATE, null, Ole32.EOAC_NONE, null); if (COMUtils.FAILED(hres) && hres.intValue() != WinError.RPC_E_TOO_LATE) { Ole32.INSTANCE.CoUninitialize(); <START> throw new COMException("Failed to initialize security.", new HRESULT(-1)); <END> } securityInitialized = true; } }</code><technical_language>solution for OSHI, definitely, I trap null in other code. -1 a hres variable (already a HRESULT type us? correct fix (and 12 lines earlier) is include hres argument. :)</technical_language>

Target:
public static void initCOM() { HRESULT hres = null; if (!isComInitialized()) { hres = Ole32.INSTANCE.CoInitializeEx(null, Ole32.COINIT_MULTITHREADED); switch (hres.intValue()) { case COMUtils.S_OK: comInitialized = true; break; case COMUtils.S_FALSE: case WinError.RPC_E_CHANGED_MODE: break; default: throw new COMException("Failed to initialize COM library.", hres); } } if (!isSecurityInitialized()) { hres = Ole32.INSTANCE.CoInitializeSecurity(null, -1, null, null, Ole32.RPC_C_AUTHN_LEVEL_DEFAULT, Ole32.RPC_C_IMP_LEVEL_IMPERSONATE, null, Ole32.EOAC_NONE, null); if (COMUtils.FAILED(hres) && hres.intValue() != WinError.RPC_E_TOO_LATE) { Ole32.INSTANCE.CoUninitialize(); throw new COMException("Failed to initialize security.", hres); } securityInitialized = true; } }
Source:
<code><START> public AzureBlobFileSystemStore getAbfsStore() { <END> return abfsStore; }</code><technical_language>Making methods public for test purposes is a good idea, esp. for AzureBlobFileSystem class. Find alternative</technical_language>

Target:
AzureBlobFileSystemStore getAbfsStore() { return abfsStore; }
Source:
<code>public static <K, V> Block createMapBlock(MapType type, Map<K, V> map) { <START> BlockBuilder blockBuilder = type.createBlockBuilder(null, 1); <END> for (Map.Entry<K, V> entry : map.entrySet()) { BlockBuilder entryBuilder = blockBuilder.beginBlockEntry(); appendToBlockBuilder(BIGINT, entry.getKey(), entryBuilder); appendToBlockBuilder(BIGINT, entry.getValue(), entryBuilder); blockBuilder.closeEntry(); } return blockBuilder.build(); }</code><technical_language>nit: 1 -> map.size()</technical_language>

Target:
public static <K, V> Block createMapBlock(MapType type, Map<K, V> map) { BlockBuilder blockBuilder = type.createBlockBuilder(null, map.size()); for (Map.Entry<K, V> entry : map.entrySet()) { BlockBuilder entryBuilder = blockBuilder.beginBlockEntry(); appendToBlockBuilder(BIGINT, entry.getKey(), entryBuilder); appendToBlockBuilder(BIGINT, entry.getValue(), entryBuilder); blockBuilder.closeEntry(); } return blockBuilder.build(); }
Source:
<code>private void checkPrivateEndpointForExistingNetworkLink(ValidationResultBuilder resultBuilder, EnvironmentDto environmentDto, NetworkDto networkDto) { if (networkDto.getServiceEndpointCreation() == ServiceEndpointCreation.ENABLED_PRIVATE_ENDPOINT && ResourceGroupUsagePattern.USE_MULTIPLE != getResourceGroupUsagePattern(environmentDto)) { CloudCredential cloudCredential = credentialToCloudCredentialConverter.convert(environmentDto.getCredential()); <START> AzureClient azureClient = azureClientService.getClient(cloudCredential); <END> Optional<String> resourceGroupName = getAzureResourceGroupDto(environmentDto) .map(AzureResourceGroupDto::getName); ValidationResult validationResult; if (resourceGroupName.isPresent()) { validationResult = azureNetworkLinkService.validateExistingNetworkLink(azureClient, networkDto.getAzure().getNetworkId(), resourceGroupName.get()); NullUtil.doIfNotNull(validationResult, resultBuilder::merge); } else { resultBuilder.error("Resource group name is not specified in the environment request!"); } } }</code><technical_language>This line</technical_language>

Target:
private void checkPrivateEndpointForExistingNetworkLink(ValidationResultBuilder resultBuilder, EnvironmentDto environmentDto, NetworkDto networkDto) { if (networkDto.getServiceEndpointCreation() == ServiceEndpointCreation.ENABLED_PRIVATE_ENDPOINT && ResourceGroupUsagePattern.USE_MULTIPLE != getResourceGroupUsagePattern(environmentDto)) { CloudCredential cloudCredential = credentialToCloudCredentialConverter.convert(environmentDto.getCredential()); AzureClient azureClient = azureClientService.getClient(cloudCredential); Optional<String> resourceGroupName = getAzureResourceGroupDto(environmentDto) .map(AzureResourceGroupDto::getName); resourceGroupName.ifPresent(rgName -> NullUtil.doIfNotNull( azureNetworkLinkService.validateExistingNetworkLink(azureClient, networkDto.getAzure().getNetworkId(), rgName), resultBuilder::merge)); } }
Source:
<code>private List<ConstraintViolation> validateComplexTypeProperty(Schema schema, List<PathNode> path, Property prop, boolean dirtyOnly) { Field field = prop.getField(); assert field.getType().isComplexType(); List<ConstraintViolation> violations = new ArrayList<ConstraintViolation>(); boolean allChildrenPhantom = true; for (Property child : prop.getChildren()) { if (!child.isPhantom()) { allChildrenPhantom = false; break; } } Object value = prop.getValue(); if (prop.isPhantom() || value == null || allChildrenPhantom) { if (!field.isNillable()) { addNotNullViolation(violations, schema, path); } } else { if (value instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> castedValue = (Map<String, Object>) value; long nonNull = castedValue.values().stream().filter(Objects::nonNull).count(); <START> if (castedValue.isEmpty() || nonNull < 1) { <END> if (!field.isNillable()) { addNotNullViolation(violations, schema, path); } } else { for (Property child : prop.getChildren()) { List<PathNode> subPath = new ArrayList<PathNode>(path); subPath.add(new PathNode(child.getField())); violations.addAll(validateAnyTypeProperty(schema, subPath, child, dirtyOnly, true)); } } } } return violations; }</code><technical_language>== null is a real case ? rework condition it: castedValue.values().stream().allMatch(Objects::isNull)</technical_language>

Target:
private List<ConstraintViolation> validateComplexTypeProperty(Schema schema, List<PathNode> path, Property prop, boolean dirtyOnly) { Field field = prop.getField(); assert field.getType().isComplexType(); List<ConstraintViolation> violations = new ArrayList<ConstraintViolation>(); boolean allChildrenPhantom = true; for (Property child : prop.getChildren()) { if (!child.isPhantom()) { allChildrenPhantom = false; break; } } Object value = prop.getValue(); if (prop.isPhantom() || value == null || allChildrenPhantom) { if (!field.isNillable()) { addNotNullViolation(violations, schema, path); } } else { if (value instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> castedValue = (Map<String, Object>) value; if (castedValue.isEmpty() || castedValue.values().stream().allMatch(Objects::isNull)) { if (!field.isNillable()) { addNotNullViolation(violations, schema, path); } } else { for (Property child : prop.getChildren()) { List<PathNode> subPath = new ArrayList<PathNode>(path); subPath.add(new PathNode(child.getField())); violations.addAll(validateAnyTypeProperty(schema, subPath, child, dirtyOnly, true)); } } } } return violations; }
Source:
<code>private static void ingestTimeRangeDataForDuplicateDeletion( final Calendar cal, final Writer writer, final SimpleFeatureBuilder featureTimeRangeBuilder, final int min, final int max, final int field, final String name ) throws IOException { final GeometryFactory geomFactory = new GeometryFactory(); final int midPoint = (int) Math.floor((min + max) / 2.0); cal.set( field, min); featureTimeRangeBuilder.add(geomFactory.createPoint(new Coordinate( 0, 0))); featureTimeRangeBuilder.add(cal.getTime()); cal.set( field, max); featureTimeRangeBuilder.add(cal.getTime()); <START> SimpleFeature feature = featureTimeRangeBuilder.buildFeature(name + ":fullrange"); <END> writer.write(feature); }</code><technical_language>this repeating feature ID method ingestTimeRangeData() - if so, dangerous, feature IDs meant unique</technical_language>

Target:
private static void ingestTimeRangeDataForDuplicateDeletion( final Calendar cal, final Writer writer, final SimpleFeatureBuilder featureTimeRangeBuilder, final int min, final int max, final int field, final String name ) throws IOException { final GeometryFactory geomFactory = new GeometryFactory(); cal.set( field, min); featureTimeRangeBuilder.add(geomFactory.createPoint(new Coordinate( 0, 0))); featureTimeRangeBuilder.add(cal.getTime()); cal.set( field, max); featureTimeRangeBuilder.add(cal.getTime()); SimpleFeature feature = featureTimeRangeBuilder.buildFeature(name + ":fullrange"); writer.write(feature); }
Source:
<code>private HttpResponse sendToNodeServlet(Class<? extends HttpServlet> servlet, List<NameValuePair> nvps) { LOGGER.entering(); <START> final int TIME_OUT = 30 * 1000; <END> RequestConfig config = RequestConfig.custom().setConnectTimeout(TIME_OUT).setSocketTimeout(TIME_OUT).build(); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); String url = String.format("http://%s:%d/extra/%s", machine, this.getRemoteHost().getPort(), servlet.getSimpleName()); HttpResponse postResponse = null; try { HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(nvps)); postResponse = client.execute(post); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { try { client.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } LOGGER.exiting(postResponse); return postResponse; }</code><technical_language>move this variable class level, is more method</technical_language>

Target:
private HttpResponse sendToNodeServlet(Class<? extends HttpServlet> servlet, List<NameValuePair> nvps) { LOGGER.entering(); RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build(); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); String url = String.format("http://%s:%d/extra/%s", machine, this.getRemoteHost().getPort(), servlet.getSimpleName()); HttpResponse postResponse = null; try { HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(nvps)); postResponse = client.execute(post); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { try { client.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } LOGGER.exiting(postResponse); return postResponse; }
Source:
<code>void checkBlacklist(HttpRequest req, List<String> blacklist) { <START> if (blacklist.contains(req.headers().get(HttpHeaderNames.HOST).toLowerCase())) { <END> stripXFFHeaders(req); } }</code><technical_language>a normalized() method call avoids lowercase string allocation</technical_language>

Target:
void checkBlacklist(HttpRequest req, List<String> blacklist) { if (blacklist.stream().anyMatch(h -> h.equalsIgnoreCase(req.headers().get(HttpHeaderNames.HOST)))) { stripXFFHeaders(req); } }
Source:
<code><START> public Stream getStream(String streamId) { <END> for (Stream stream : this.getDeclaredOutputs()) { if (stream.getId().equals(streamId)) { return stream; } } throw new IllegalArgumentException("Invalid streamId " + streamId); }</code><technical_language>reason for calling super</technical_language>

Target:
public Stream getStream(String streamId) { for (Stream stream : this.getDeclaredOutputStreams()) { if (stream.getId().equals(streamId)) { return stream; } } throw new IllegalArgumentException("Invalid streamId " + streamId); }
Source:
<code>public Instance(@JsonProperty(value = "host", required = true) String host, @JsonProperty(value = "port", required = true) int port, @JsonProperty(value = "type", required = true) InstanceType type, @JsonProperty("tags") @Nullable List<String> tags, @JsonProperty("pools") @Nullable Map<String, Integer> pools, @JsonProperty("grpcPort") int grpcPort) { Preconditions.checkArgument(host != null, "'host' must be configured"); Preconditions.checkArgument(type != null, "'type' must be configured"); _host = host; _port = port; _type = type; _tags = tags; _pools = pools; <START> _grpcPort = grpcPort; <END> }</code><technical_language>This set 0 json if grpcPort is set. check for 0 put -1</technical_language>

Target:
public Instance(@JsonProperty(value = "host", required = true) String host, @JsonProperty(value = "port", required = true) int port, @JsonProperty(value = "type", required = true) InstanceType type, @JsonProperty("tags") @Nullable List<String> tags, @JsonProperty("pools") @Nullable Map<String, Integer> pools, @JsonProperty("grpcPort") int grpcPort) { Preconditions.checkArgument(host != null, "'host' must be configured"); Preconditions.checkArgument(type != null, "'type' must be configured"); _host = host; _port = port; _type = type; _tags = tags; _pools = pools; if (grpcPort == 0) { _grpcPort = NOT_SET_GRPC_PORT_VALUE; } else { _grpcPort = grpcPort; } }
Source:
<code>public boolean setTimeAddition(long newTimeIn) { <START> if (getWorld().getWorld().getDayTime() > newTimeIn) <END> return false; this.newTime = newTimeIn; return true; }</code><technical_language>getWorld().getWorld()? Also, pass in minTime compare here</technical_language>

Target:
public boolean setTimeAddition(long newTimeIn) { if (minTime > newTimeIn) return false; this.newTime = newTimeIn; return true; }
Source:
<code><START> public CosmosDataAccessor(AsyncDocumentClient asyncDocumentClient, String cosmosCollectionLink, <END> AzureMetrics azureMetrics) { this.asyncDocumentClient = asyncDocumentClient; this.cosmosCollectionLink = cosmosCollectionLink; this.azureMetrics = azureMetrics; }</code><technical_language>test constructor need public</technical_language>

Target:
CosmosDataAccessor(AsyncDocumentClient asyncDocumentClient, String cosmosCollectionLink, AzureMetrics azureMetrics) { this.asyncDocumentClient = asyncDocumentClient; this.cosmosCollectionLink = cosmosCollectionLink; this.azureMetrics = azureMetrics; }
Source:
<code>public List<String> get(Path path, FileSystem.Permission permission) { switch (permission) { case READ: return readers.getAllowed(path); case WRITE: return writers.getAllowed(path); default: throw new IllegalStateException("Unimplemented"); } <START> } <END></code><technical_language>careful of is write access implies read access in model</technical_language>

Target:
public List<String> get(Path path, FileSystem.Permission permission) { switch (permission) { case WRITE: return writers.getAllowed(path); case READ: List<String> allowed = readers.getAllowed(path); List<String> allowed2 = writers.getAllowed(path); return new ArrayList<>(Stream.of(allowed, allowed2).flatMap(e -> e.stream()).collect(Collectors.toSet())); default: throw new IllegalStateException("Unimplemented"); } }
Source:
<code>private boolean removeDelayedMessageFromMessageStore(Message<?> message) { if (this.messageStore instanceof SimpleMessageStore) { synchronized (this.messageGroupId) { Collection<Message<?>> messages = this.messageStore.getMessageGroup(this.messageGroupId).getMessages(); <START> if (messages.contains(message)) { <END> this.messageStore.removeMessageFromGroup(this.messageGroupId, message); return true; } else { return false; } } } else { return ((MessageStore) this.messageStore).removeMessage(message.getHeaders().getId()) != null; } }</code><technical_language>This is good - messages is unmodified collection wrapping a LinkedBlockingQueue. contains iterate contents is good for a large group. a similar problem in AcceptOnceFileListFilter solved (INT-3572) maintaining a Set parallel queue; technique here, though. SimpleMessageGroup - good for large groups - remove() requires iterating entire queue well. This explains Ryan's performance observation. a (synchronized) LinkedHashSet instead of BlockingQueue compare performance for small large groups. If a synchronized set is expensive, end 2 stores - for small groups for large</technical_language>

Target:
private boolean removeDelayedMessageFromMessageStore(Message<?> message) { if (this.messageStore instanceof SimpleMessageStore) { synchronized (this.messageGroupId) { Collection<Message<?>> messages = this.messageStore.getMessageGroup(this.messageGroupId).getMessages(); if (messages.contains(message)) { this.messageStore.removeMessagesFromGroup(this.messageGroupId, message); return true; } else { return false; } } } else { return ((MessageStore) this.messageStore).removeMessage(message.getHeaders().getId()) != null; } }
Source:
<code>public String updatePublishers(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, @PathVariable("appSlug") String slug, @RequestParam("enabled") String enabled, @RequestParam("disabled") String disabled) { Application app = null; for (String pubKey : CSV_SPLITTER.split(enabled)) { <START> Publisher publisher = Publisher.fromKey(pubKey).valueOrNull(); <END> if (publisher != null) { app = manager.enablePublisher(slug, publisher); } } for (String pubKey : CSV_SPLITTER.split(disabled)) { Publisher publisher = Publisher.fromKey(pubKey).valueOrNull(); if (publisher != null) { app = manager.disablePublisher(slug, publisher); } } model.put("application", modelBuilder.build(app)); return APPLICATION_TEMPLATE; }</code><technical_language>deliberately choosing do if publisher is found? is, is this expected happen for some requests? If not, suggest change this Publisher publisher = Publisher.fromKey(pubKey).requireValue() remove conditional. If exceptional case of publisher existing occurs, exception thrown</technical_language>

Target:
public String updatePublishers(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, @PathVariable("appSlug") String slug, @RequestParam("enabled") String enabled, @RequestParam("disabled") String disabled) { Application app = null; List<Publisher> enabledPubs = Publisher.fromCsv(enabled); for (Publisher publisher : enabledPubs) { app = manager.enablePublisher(slug, publisher); } List<Publisher> disabledPubs = Publisher.fromCsv(disabled); for (Publisher publisher : disabledPubs) { app = manager.disablePublisher(slug, publisher); } model.put("application", modelBuilder.build(app)); return APPLICATION_TEMPLATE; }
Source:
<code>public DimensionSelectorHavingSpec( @JsonProperty("dimension") String dimName, @JsonProperty("value") String value, @JsonProperty("extractionFn") ExtractionFn extractionFn ) { this.dimension = Preconditions.checkNotNull(dimName, "Must have attribute 'dimension'"); this.value = value; <START> this.extractionFn = extractionFn; <END> }</code><technical_language>IdentityExtractionFn is null reduce amount of if/else IMHO</technical_language>

Target:
public DimensionSelectorHavingSpec( @JsonProperty("dimension") String dimName, @JsonProperty("value") String value, @JsonProperty("extractionFn") ExtractionFn extractionFn ) { dimension = Preconditions.checkNotNull(dimName, "Must have attribute 'dimension'"); this.value = value; if (extractionFn != null) { this.extractionFn = extractionFn; } else { this.extractionFn = new IdentityExtractionFn(); } }
Source:
<code>public Builder setOldRevision(Revision revision) { switch (type) { case DIFF: case LOG: this.oldRevision = revision; break; default: checkState(revision == null, "cannot set old revision on %s view", type); <START> this.oldRevision = revision; <END> break; } return this; }</code><technical_language>nit: this return end of method</technical_language>

Target:
public Builder setOldRevision(Revision revision) { switch (type) { case DIFF: case LOG: this.oldRevision = revision; return this; default: throw new IllegalStateException( String.format("cannot set old revision on %s view", type)); } }