auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public Condition(final Field field, final Operator operator, final String object) { <END> this.field = field; this.operator = operator; this.object = object; }</code><technical_language>a thought, push expression parse logic this class. I Condition public static methods: * public static Condition fromExpression(final String conditionExpression); * public static Condition fromStrings(final String field, final String operator, final String object); * public static Condition fromEnums(final Field field, final Operator operator, final String object); lines</technical_language>

Target:
private Condition(final Field field, final Operator operator, final String object) { this.field = field; this.operator = operator; this.object = object; }
Source:
<code>public void setMaxValue(final BigDecimal maxValue) { BigDecimal currMax = getMaxValue(); if ((maxValue != null && currMax == null) <START> || currMax != null && (maxValue == null || !(maxValue.compareTo(currMax) == 0))) { <END> getOrCreateComponentModel().maxValue = maxValue; } }</code><technical_language>this Objects.equals</technical_language>

Target:
public void setMaxValue(final BigDecimal maxValue) { BigDecimal currMax = getMaxValue(); if (!Objects.equals(maxValue, currMax)) { getOrCreateComponentModel().maxValue = maxValue; } }
Source:
<code>private String replaceEntireString(final String value) { for (final Entry<String, String> entry : replacements.entrySet()) { final String replacementString = entry.getValue(); final String searchString = entry.getKey(); if (ignoreCaseSensitivity == true) { <START> if (value.toLowerCase().indexOf(searchString.toLowerCase()) != -1) { <END> return replacementString; } } else if (value.indexOf(searchString) != -1) { return replacementString; } } return value; }</code><technical_language>replaced contains()</technical_language>

Target:
private String replaceEntireString(final String value) { for (final Entry<String, String> entry : replacements.entrySet()) { final String replacementString = entry.getValue(); final String searchString = entry.getKey(); if (caseSensitive) { if (value.contains(searchString)) { return replacementString; } } else if (value.toLowerCase().contains(searchString.toLowerCase())) { return replacementString; } } return value; }
Source:
<code>public MsalToken(IAuthenticationResult msalResult, IdentityClientOptions options) { super(msalResult.accessToken(), OffsetDateTime.ofInstant( msalResult.expiresOnDate().toInstant().minus(options.getRefreshBeforeExpiry()), ZoneOffset.UTC) <START> .plusMinutes(2)); <END> this.account = msalResult.account(); }</code><technical_language>I feel spreading minute concept out code base. a private static final is referred everywhere</technical_language>

Target:
public MsalToken(IAuthenticationResult msalResult, IdentityClientOptions options) { super(msalResult.accessToken(), OffsetDateTime.ofInstant(msalResult.expiresOnDate().toInstant(), ZoneOffset.UTC), options); this.account = msalResult.account(); }
Source:
<code>static boolean assignPreemptedContainers(FSSchedulerNode node ) { boolean assignedAny = false; <START> node.cleanupPreemptionList(); <END> for (Entry<FSAppAttempt, Resource> entry : node.getPreemptionList().entrySet()) { FSAppAttempt app = entry.getKey(); Resource reserved = Resources.clone(entry.getValue()); while (!app.isStopped() && !Resources.isNone(reserved)) { Resource assigned = app.assignContainer(node); if (Resources.isNone(assigned)) { break; } assignedAny = true; Resources.subtractFromNonNegative(reserved, assigned); } } node.cleanupPreemptionList(); return assignedAny; }</code><technical_language>rely call getPreemptionList do cleanup instead</technical_language>

Target:
static boolean assignPreemptedContainers(FSSchedulerNode node ) { boolean assignedAny = false; for (Entry<FSAppAttempt, Resource> entry : node.getPreemptionList().entrySet()) { FSAppAttempt app = entry.getKey(); Resource preemptionPending = Resources.clone(entry.getValue()); while (!app.isStopped() && !Resources.isNone(preemptionPending)) { Resource assigned = app.assignContainer(node); if (Resources.isNone(assigned)) { break; } assignedAny = true; Resources.subtractFromNonNegative(preemptionPending, assigned); } } return assignedAny; }
Source:
<code>private void skip(int items) throws IOException { if (dataStream == null) { presentStream.skip(items); } else if (presentStream != null) { int dataToSkip = presentStream.countBitsSet(items); <START> long sum = lengthStream.sum(dataToSkip); <END> dataStream.skip(sum); } else { dataStream.skip(lengthStream.sum(items)); } }</code><technical_language>perhaps, lengthsToSkip dataToSkip; also, consider inlining dataToSkip in else branch: else if (presentStream != null) { int lengthsToSkip = presentStream.countBitsSet(items); dataStream.skip(lengthStream.sum(lengthsToSkip)); } else { dataStream.skip(lengthStream.sum(items)); }</technical_language>

Target:
private void skip(int items) throws IOException { if (dataStream == null) { presentStream.skip(items); } else if (presentStream != null) { int lengthToSkip = presentStream.countBitsSet(items); dataStream.skip(lengthStream.sum(lengthToSkip)); } else { dataStream.skip(lengthStream.sum(items)); } }
Source:
<code>public static void main(String[] args) { try { args = JVMPropertiesPreloader.overrideJVMProperties(args); CookieBasedProcessTreeKiller.registerKillChildProcessesOnShutdown("node"); RMNodeStarter passiveStarter = new RMNodeStarter(); String baseNodeName = passiveStarter.configure(args); <START> launchBackgorundKeyPairMaker(passiveStarter.workers); <END> passiveStarter.createNodesAndConnect(baseNodeName); } catch (Throwable t) { System.err.println("A major problem occurred when trying to start a node and register it into the Resource Manager, see the stacktrace below"); if (t instanceof java.lang.NoClassDefFoundError) { System.err.println("Unable to load a class definition, maybe the classpath is not accessible"); } t.printStackTrace(System.err); System.exit(-2); } }</code><technical_language>Small typo in word Backgorund</technical_language>

Target:
public static void main(String[] args) { try { args = JVMPropertiesPreloader.overrideJVMProperties(args); CookieBasedProcessTreeKiller.registerKillChildProcessesOnShutdown("node"); RMNodeStarter passiveStarter = new RMNodeStarter(); String baseNodeName = passiveStarter.configure(args); keyPairProducer = new KeyPairProducer(passiveStarter.workers); passiveStarter.createNodesAndConnect(baseNodeName); } catch (Throwable t) { System.err.println("A major problem occurred when trying to start a node and register it into the Resource Manager, see the stacktrace below"); if (t instanceof java.lang.NoClassDefFoundError) { System.err.println("Unable to load a class definition, maybe the classpath is not accessible"); } t.printStackTrace(System.err); System.exit(-2); } }
Source:
<code>public GitHubThread thread(final int number) { <START> throw new NotImplementedException("MkNotifications#thread"); <END> }</code><technical_language>~~Let's UnsupportedOperationException~~ Ignore that, I other places this exception</technical_language>

Target:
public GitHubThread thread(final int number) { throw new NotImplementedException("RtNotifications#thread"); }
Source:
<code>public void initialise() { infoArea = find("infoArea", UIText.class); updateInfoButton = find("updateInfoButton", UIButton.class); if (updateInfoButton != null) { updateInfoButton.subscribe(button -> { infoArea.setText(infoItems[infoIndex]); <START> if (infoIndex > infoItems.length() - 2) <END> infoIndex = 0; else infoIndex++; }); } }</code><technical_language>brackets, if if statement. for else clause below</technical_language>

Target:
public void initialise() { infoArea = find("infoArea", UIText.class); updateInfoButton = find("updateInfoButton", UIButton.class); if (updateInfoButton != null) { updateInfoButton.subscribe(button -> { infoArea.setText(infoItems[infoIndex]); if (infoIndex > infoItems.length() - 2) { infoIndex = 0; } else { infoIndex++; } }); } }
Source:
<code>public void emit(Event event) { if (!started.get()) { throw new ISE("WTF emit was called while service is not started yet"); } if (event instanceof ServiceMetricEvent) { final GraphiteEvent graphiteEvent = graphiteEventConverter.druidEventToGraphite((ServiceMetricEvent) event); if (graphiteEvent == null) { return; } try { <START> final boolean isSuccessful = eventsQueue.offer(graphiteEvent, graphiteEmitterConfig.getEmitWaitTime(), TimeUnit.MILLISECONDS); <END> if (!isSuccessful) { log.error( "Throwing event [%s] on the floor Graphite queue is full please increase the capacity or/and the consumer frequency", mapper.writeValueAsString(event) ); } } catch (InterruptedException e) { log.error(e, "got interrupted with message [%s]", e.getMessage()); Thread.currentThread().interrupt(); } catch (JsonProcessingException e) { log.error(e, e.getMessage()); } } else if (!emitterList.isEmpty() && event instanceof AlertEvent) { for (Emitter emitter : emitterList) { emitter.emit(event); } } else { throw new ISE("unknown event type [%s]", event.getClass()); } }</code><technical_language>log.error this is totally bonkers if queue fills up; print a log message X events (similar HttpPostEmitter)</technical_language>

Target:
public void emit(Event event) { if (!started.get()) { throw new ISE("WTF emit was called while service is not started yet"); } if (event instanceof ServiceMetricEvent) { final GraphiteEvent graphiteEvent = graphiteEventConverter.druidEventToGraphite((ServiceMetricEvent) event); if (graphiteEvent == null) { return; } try { final boolean isSuccessful = eventsQueue.offer( graphiteEvent, graphiteEmitterConfig.getEmitWaitTime(), TimeUnit.MILLISECONDS ); if (!isSuccessful) { if (countLostEvents.getAndIncrement() % 1000 == 0) { log.error( "Lost total of [%s] events because of emitter queue is full. Please increase the capacity or/and the consumer frequency", countLostEvents.get() ); } } } catch (InterruptedException e) { log.error(e, "got interrupted with message [%s]", e.getMessage()); Thread.currentThread().interrupt(); } } else if (!emitterList.isEmpty() && event instanceof AlertEvent) { for (Emitter emitter : emitterList) { emitter.emit(event); } } else { throw new ISE("unknown event type [%s]", event.getClass()); } }
Source:
<code>private void assertEqualsDeep(String expr0, String expr1, boolean expected) throws SqlParseException { SqlNode sqlNode0 = parseExpression(expr0); SqlNode sqlNode1 = parseExpression(expr1); <START> boolean actual = sqlNode0.equalsDeep(sqlNode1, Litmus.IGNORE); String reason = expr0 + " equals " + expr1; assertEquals(expected, actual, reason); <END> }</code><technical_language>suggestion assertEquals(expected, sqlNode0.equalsDeep(sqlNode1, Litmus.IGNORE), () -> expr0 + " equalsDeep " + expr1);</technical_language>

Target:
private void assertEqualsDeep(String expr0, String expr1, boolean expected) throws SqlParseException { SqlNode sqlNode0 = parseExpression(expr0); SqlNode sqlNode1 = parseExpression(expr1); assertEquals(expected, sqlNode0.equalsDeep(sqlNode1, Litmus.IGNORE), () -> expr0 + " equalsDeep " + expr1); }
Source:
<code>public Map<K, V> getEntries() { Set<Node> nodes = new HashSet<>(this.group.getNodes()); try (Batch batch = this.batcher.createBatch()) { <START> return nodes.stream() <END> .map(node -> this.cache.getAdvancedCache().get(node)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } }</code><technical_language>This need a set. stream List<Node></technical_language>

Target:
public Map<K, V> getEntries() { Set<Node> nodes = new HashSet<>(this.group.getMembership().getMembers()); try (Batch batch = this.batcher.createBatch()) { return this.cache.getAdvancedCache().getAll(nodes).values().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); } }
Source:
<code>private boolean isBundleReady(Bundle bundle) { String name = bundle.getHeaders().get(Constants.BUNDLE_NAME); BundleInfo info = bundleService.getInfo(bundle); BundleState state = info.getState(); boolean ready; if (info.isFragment()) { ready = BundleState.Resolved.equals(state); } else { if (BundleState.Failure.equals(state)) { printInactiveBundles(); LOGGER.error("The bundle " + name + " failed."); } ready = BundleState.Active.equals(state); } if (!ready) { <START> LOGGER.info("{} bundle not ready yet", name); <END> } return ready; }</code><technical_language>this is called in a wait loop flood logs a little, do want put a debug</technical_language>

Target:
private boolean isBundleReady(Bundle bundle) { String name = bundle.getHeaders().get(Constants.BUNDLE_NAME); BundleInfo info = bundleService.getInfo(bundle); BundleState state = info.getState(); boolean ready; if (info.isFragment()) { ready = BundleState.Resolved.equals(state); } else { if (BundleState.Failure.equals(state)) { printInactiveBundles(); LOGGER.error("The bundle " + name + " failed."); } ready = BundleState.Active.equals(state); } if (!ready) { LOGGER.debug("{} bundle not ready yet", name); } return ready; }
Source:
<code>public void replaceQualifierInCapabilities(IU iu, String qualifier) { List<Element> providedCapabilities = iu.getProvidedCapabilites(); if (providedCapabilities == null) return; for (Element capability : providedCapabilities) { String currentVersion = capability.getAttributeValue(IU.VERSION); if (hasQualifier(currentVersion) && <START> !iu.getId().equals(capability.getAttributeValue(IU.NAME))) <END> capability.setAttribute(IU.VERSION, currentVersion.replaceAll("qualifier", qualifier)); } }</code><technical_language>Is this prevent capability is processed here? If yes, namespace checked</technical_language>

Target:
public void replaceQualifierInCapabilities(IU iu, String qualifier) { List<Element> providedCapabilities = iu.getProvidedCapabilites(); if (providedCapabilities == null) return; for (Element capability : providedCapabilities) { String currentVersion = capability.getAttributeValue(IU.VERSION); if (hasQualifier(currentVersion) && !(iu.getId().equals(capability.getAttributeValue(IU.NAME)) && IU.P2_IU_NAMESPACE .equals(capability.getAttributeValue(IU.NAMESPACE)))) capability.setAttribute(IU.VERSION, currentVersion.replaceAll("qualifier", qualifier)); } }
Source:
<code>public void testDistributedSort() <START> { <END> ImmutableList<PlanMatchPattern.Ordering> orderBy = ImmutableList.of(sort("ORDERKEY", DESCENDING, LAST)); assertDistributedPlan( "SELECT orderkey FROM orders ORDER BY orderkey DESC", output( exchange(REMOTE, GATHER, orderBy, exchange(LOCAL, GATHER, orderBy, sort(orderBy, exchange(REMOTE, REPARTITION, tableScan("orders", ImmutableMap.of( "ORDERKEY", "orderkey")))))))); }</code><technical_language>update testJoinWithOrderBySameKey confirm plan nodes involved in distributed sort</technical_language>

Target:
public void testDistributedSort() { ImmutableList<PlanMatchPattern.Ordering> orderBy = ImmutableList.of(sort("ORDERKEY", DESCENDING, LAST)); assertDistributedPlan( "SELECT orderkey FROM orders ORDER BY orderkey DESC", output( exchange(REMOTE, GATHER, orderBy, exchange(LOCAL, GATHER, orderBy, sort(orderBy, exchange(REMOTE, REPARTITION, tableScan("orders", ImmutableMap.of( "ORDERKEY", "orderkey")))))))); assertDistributedPlan( "SELECT orderkey FROM orders ORDER BY orderkey DESC", Session.builder(this.getQueryRunner().getDefaultSession()) .setSystemProperty(DISTRIBUTED_SORT, Boolean.toString(false)) .build(), output( sort(orderBy, exchange(LOCAL, GATHER, exchange(REMOTE, GATHER, tableScan("orders", ImmutableMap.of( "ORDERKEY", "orderkey"))))))); }
Source:
<code>private static List<String> getSortedDirtyModules(@NotNull List<ErlangFileDescriptor> sortedFiles, @NotNull final Set<String> allDirtyFiles) { return ContainerUtil.mapNotNull(sortedFiles, new Function<ErlangFileDescriptor, String>() { @Nullable @Override public String fun(ErlangFileDescriptor node) { <START> return node.myPath.endsWith(".erl") && allDirtyFiles.contains(node.myPath) ? node.myPath : null; <END> } }); }</code><technical_language>Please, reuse extracted method for checking if a file is Erlang source file</technical_language>

Target:
private static List<String> getSortedDirtyModules(@NotNull List<ErlangFileDescriptor> sortedFiles, @NotNull final Set<String> allDirtyFiles) { return ContainerUtil.mapNotNull(sortedFiles, new Function<ErlangFileDescriptor, String>() { @Nullable @Override public String fun(ErlangFileDescriptor node) { return isSource(node.myPath) && allDirtyFiles.contains(node.myPath) ? node.myPath : null; } }); }
Source:
<code>boolean maybeTimeout() { <START> LOG.info("maybeTimeout"); <END> if (MathUtils.elapsedNanos(startTime) >= addEntryTimeoutNanos) { timeout(); return true; } else { return false; } }</code><technical_language>remove this logging</technical_language>

Target:
boolean maybeTimeout() { if (MathUtils.elapsedNanos(startTime) >= addEntryTimeoutNanos) { timeout(); return true; } else { return false; } }
Source:
<code>private Optional<KafkaDatastreamStatesResponse> getDatastreamStatesResponse(String streamName) { List<KafkaDatastreamStatesResponse> responses = _runningTasks.values() .stream() .filter(task -> task.hasDatastream(streamName)) .map(AbstractKafkaBasedConnectorTask::getKafkaDatastreamStatesResponse) .collect(Collectors.toList()); if (responses.size() > 0) { Map<TopicPartition, PausedSourcePartitionMetadata> autoPausedPartitions = new HashMap<>(); Map<String, Set<String>> manualPausedPartitions = new HashMap<>(); Set<TopicPartition> assignedTopicPartitions = new HashSet<>(); <START> responses.stream().forEach(t -> { <END> autoPausedPartitions.putAll(t.getAutoPausedPartitions()); manualPausedPartitions.putAll(t.getManualPausedPartitions()); assignedTopicPartitions.addAll(t.getAssignedTopicPartitions()); }); return Optional.of(new KafkaDatastreamStatesResponse(responses.get(0).getDatastream(), autoPausedPartitions, manualPausedPartitions, assignedTopicPartitions)); } return Optional.empty(); }</code><technical_language>This stream() extraneous</technical_language>

Target:
private Optional<KafkaDatastreamStatesResponse> getDatastreamStatesResponse(String streamName) { List<KafkaDatastreamStatesResponse> responses = _runningTasks.values() .stream() .filter(task -> task.hasDatastream(streamName)) .map(AbstractKafkaBasedConnectorTask::getKafkaDatastreamStatesResponse) .collect(Collectors.toList()); if (responses.size() > 0) { Map<TopicPartition, PausedSourcePartitionMetadata> autoPausedPartitions = new HashMap<>(); Map<String, Set<String>> manualPausedPartitions = new HashMap<>(); Set<TopicPartition> assignedTopicPartitions = new HashSet<>(); responses.forEach(t -> { autoPausedPartitions.putAll(t.getAutoPausedPartitions()); manualPausedPartitions.putAll(t.getManualPausedPartitions()); assignedTopicPartitions.addAll(t.getAssignedTopicPartitions()); }); return Optional.of(new KafkaDatastreamStatesResponse(responses.get(0).getDatastream(), autoPausedPartitions, manualPausedPartitions, assignedTopicPartitions)); } return Optional.empty(); }
Source:
<code>private void deactivateParticipants(IDebuggerConsole console) { if (console != null) { final ListenerList<IConsolePageParticipant> listeners = getParticipants(console); if (listeners != null) { for (IConsolePageParticipant iConsolePageParticipant : listeners) { <START> final IConsolePageParticipant participant = iConsolePageParticipant; <END> SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { participant.deactivated(); } @Override public void handleException(Throwable exception) { CDebugUIPlugin.log(exception); listeners.remove(participant); } }); } } } }</code><technical_language>Previous line removed</technical_language>

Target:
private void deactivateParticipants(IDebuggerConsole console) { if (console != null) { final ListenerList<IConsolePageParticipant> listeners = getParticipants(console); if (listeners != null) { for (IConsolePageParticipant participant : listeners) { SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { participant.deactivated(); } @Override public void handleException(Throwable exception) { CDebugUIPlugin.log(exception); listeners.remove(participant); } }); } } } }
Source:
<code>public boolean hasSchemaObjectNodeComponent(String absoluteFieldPath) { Boolean result = null; String selectedIndexName = null; ElasticsearchIndexSchemaObjectNode selectedObjectNode = null; for ( ElasticsearchIndexModel indexModel : indexModels ) { String indexName = indexModel.getHibernateSearchIndexName(); ElasticsearchIndexSchemaObjectNode objectNode = indexModel.getObjectNode( absoluteFieldPath ); Boolean hasObjectNode = ( objectNode != null ); if ( result == null ) { result = hasObjectNode; selectedIndexName = indexName; selectedObjectNode = objectNode; } <START> else if ( !result.equals( hasObjectNode ) ) { <END> throw log.conflictingObjectFieldModel( absoluteFieldPath, selectedObjectNode, objectNode, EventContexts.fromIndexNames( selectedIndexName, indexName ) ); } } return ( result != null ) ? result : false; }</code><technical_language>throwing exception in cases: 1. index A object field, index B a non-object field 2. index A object field, index B field this name (object non-object). I agree 1, 2 throw exception. need more tests</technical_language>

Target:
public boolean hasSchemaObjectNodeComponent(String absoluteFieldPath) { for ( ElasticsearchIndexModel indexModel : indexModels ) { ElasticsearchIndexSchemaObjectNode objectNode = indexModel.getObjectNode( absoluteFieldPath ); if ( objectNode != null ) { return true; } } return false; }
Source:
<code>public void setFont (Font font) { checkWidget(); if (((state & FONT) == 0) && font == null) return; this.font = font; long fontDesc; if (font == null) { fontDesc = defaultFont ().handle; } else { if (font.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); fontDesc = font.handle; } if (font == null) { state &= ~FONT; } else { state |= FONT; } <START> if (OS.GTK_VERSION<OS.VERSION(3, 21, 0)){ <END> setFontDescription (fontDesc); } else { if (provider == 0) { provider = OS.gtk_css_provider_new (); } long context = OS.gtk_widget_get_style_context (handle); long family = OS.pango_font_description_get_family(fontDesc); OS.gtk_style_context_add_provider (context, provider, OS.GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); int length = OS.strlen(family); byte[] buffer = new byte[length]; OS.memmove(buffer, family, length); String name = new String(Converter.mbcsToWcs(null, buffer)); String cssName = OS.GTK_VERSION >= OS.VERSION(3, 20, 0) ? display.gtk_widget_class_get_css_name(handle) : display.gtk_widget_get_name(handle); int height = OS.pango_font_description_get_size(fontDesc) / OS.PANGO_SCALE; String css = cssName + " { font: "+ name +" "+height+"; "+"}"; OS.gtk_css_provider_load_from_data (provider, Converter.wcsToMbcs (null, css, true), -1, null); } }</code><technical_language>Generally check for GTK dev versions. GTK3.21 is a development version, this call GTK3.22. Also, spaces "less than" operator</technical_language>

Target:
public void setFont (Font font) { checkWidget(); if (((state & FONT) == 0) && font == null) return; this.font = font; long fontDesc; if (font == null) { fontDesc = defaultFont ().handle; } else { if (font.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); fontDesc = font.handle; } if (font == null) { state &= ~FONT; } else { state |= FONT; } if (OS.GTK_VERSION<OS.VERSION(3, 22, 0)){ setFontDescription (fontDesc); } else { long context = OS.gtk_widget_get_style_context (handle); OS.gtk_style_context_add_provider (context, provider, OS.GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); long family = OS.pango_font_description_get_family(fontDesc); String name; if (family == 0) { name = "*"; } else { int length = OS.strlen (family); byte buffer = new byte [length]; OS.memmove (buffer, family, length); name = new String (Converter.mbcsToWcs (null, buffer)); } String cssName = OS.GTK_VERSION >= OS.VERSION(3, 20, 0) ? display.gtk_widget_class_get_css_name(handle) : display.gtk_widget_get_name(handle); int height = OS.pango_font_description_get_size(fontDesc) / OS.PANGO_SCALE; String css = cssName + " { font: "+ name +" "+height+"; "+"}"; gtk_css_provider_load_from_css(context,css); } }
Source:
<code>public void onDataLoaded(Displayer displayer) { <START> for (Displayer other : displayerList) { <END> if (other != displayer && !isNotificationVetoed(displayer, other)) { other.onDataLoaded(displayer); } } }</code><technical_language>Hey @dgutierr , I recommend Java8 functional interfaces Streams API soon try new stuff, for kind incremental replacement.</technical_language>

Target:
public void onDataLoaded(Displayer displayer) { displayerList.stream() .filter(other -> other != displayer && !isNotificationVetoed(displayer, other)) .forEach(other -> other.onDataLoaded(displayer)); }
Source:
<code>public List<Gpu> getGpus() { Collections.sort(gpus, new Comparator<Gpu>() { @Override public int compare(Gpu o1, Gpu o2) { return o1.getFreeMemory() > o2.getFreeMemory() ? -1 : 1; } <START> }); <END> return Collections.unmodifiableList(gpus); }</code><technical_language>Making getGpus() method non-deterministic is a scary. add load balancing Gpu pooling system instead</technical_language>

Target:
public List<Gpu> getGpus() { return Collections.unmodifiableList(gpus); }
Source:
<code>public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, <START> new RqWithDefaultHeader(req, "accept", "text/xml"), <END> new XeLink("save-email", "/acc/save") ); }</code><technical_language>@exper0 I header is Accept</technical_language>

Target:
public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); }
Source:
<code>void should_pass_assertions_on_values_extracted_from_given_extractors() { assertThat(map).extractingFromEntries() .contains(tuple(), tuple()); <START> assertThat(map).extractingFromEntries(Map.Entry::getKey) <END> .contains("name", "age"); assertThat(map).extractingFromEntries(e -> e.getKey().toString().toUpperCase(), Map.Entry::getValue) .contains(tuple("NAME", "bepson"), tuple("AGE", 10)); }</code><technical_language>move a test testing a method</technical_language>

Target:
void should_pass_assertions_on_values_extracted_from_given_extractors() { assertThat(map).extractingFromEntries(e -> e.getKey().toString().toUpperCase(), Map.Entry::getValue) .contains(tuple("NAME", "bepson"), tuple("AGE", 10)); }
Source:
<code>public static synchronized ConnectionModifier getModifier (String dbName, int major, int minor) { String exactMatch = null; String majorMatch = null; String driverMatch = null; Enumeration e = _modifiers.keys(); dbName = dbName.toLowerCase(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s.equalsIgnoreCase(dbName + "_" + major + "_" + minor)) exactMatch = s; if (s.equalsIgnoreCase(dbName + "_" + major + "_-1")) majorMatch = s; if (s.equalsIgnoreCase(dbName + "_-1_-1")) driverMatch = s; } ConnectionModifier modifier = defaultIsSameRMOverride ? isSameRMModifier : null; if (driverMatch != null) modifier = _modifiers.get(driverMatch); if (majorMatch != null) modifier = _modifiers.get(majorMatch); if (exactMatch != null) modifier = _modifiers.get(exactMatch); if (jdbcLogger.logger.isTraceEnabled()) { <START> jdbcLogger.logger.trace("ConnectionModifier for: " + modifier.getClass().getName() + " for " + dbName + " " + major + "/" + minor + " (defaultIsSameRMOverride was " + defaultIsSameRMOverride + ")"); <END> } return modifier; }</code><technical_language>I nicer method tracef tracev here</technical_language>

Target:
public static synchronized ConnectionModifier getModifier (String dbName, int major, int minor) { String exactMatch = null; String majorMatch = null; String driverMatch = null; Enumeration e = _modifiers.keys(); dbName = dbName.toLowerCase(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); if (s.equalsIgnoreCase(dbName + "_" + major + "_" + minor)) exactMatch = s; if (s.equalsIgnoreCase(dbName + "_" + major + "_-1")) majorMatch = s; if (s.equalsIgnoreCase(dbName + "_-1_-1")) driverMatch = s; } ConnectionModifier modifier = defaultIsSameRMOverride ? isSameRMModifier : null; if (driverMatch != null) modifier = _modifiers.get(driverMatch); if (majorMatch != null) modifier = _modifiers.get(majorMatch); if (exactMatch != null) modifier = _modifiers.get(exactMatch); if (jdbcLogger.logger.isTraceEnabled()) { jdbcLogger.logger.tracef("ConnectionModifier for: %s for %s %d/%d (defaultIsSameRMOverride was %b)", modifier == null? null : modifier.getClass().getName(), dbName, major, minor ,defaultIsSameRMOverride); } return modifier; }
Source:
<code>protected void configure() { <START> DynamicSet.setOf(binder(), RegisteredWebUiPlugin.class); <END> bind(ServerInformationImpl.class); bind(ServerInformation.class).to(ServerInformationImpl.class); bind(PluginCleanerTask.class); bind(PluginGuiceEnvironment.class); bind(PluginLoader.class); bind(CopyConfigModule.class); listener().to(PluginLoader.class); }</code><technical_language>This declared in another location, e.g. WebModule. need this set declared server binds PluginModule. In server powers gerit-review bind PluginModule. :-)</technical_language>

Target:
protected void configure() { install(new WebUiPluginModule()); bind(ServerInformationImpl.class); bind(ServerInformation.class).to(ServerInformationImpl.class); bind(PluginCleanerTask.class); bind(PluginGuiceEnvironment.class); bind(PluginLoader.class); bind(CopyConfigModule.class); listener().to(PluginLoader.class); }
Source:
<code>private static void addIfStartWith(final ArrayList<String> list, @NonNull final String base, final String str) { <START> if (str == null || str.isEmpty()) { <END> return; } final String lowerStr = str.toLowerCase(); if (lowerStr.startsWith(base)) { list.add(lowerStr); } }</code><technical_language>suggestion if (isNullOrEmpty(str)) {</technical_language>

Target:
private static void addIfStartWith(final ArrayList<String> list, @NonNull final String base, final String str) { if (isNullOrEmpty(str)) { return; } final String lowerStr = str.toLowerCase(); if (lowerStr.startsWith(base)) { list.add(lowerStr); } }
Source:
<code>public <T> Stream<T> getRanges( final TableReference tableRef, Iterable<RangeRequest> rangeRequests, int concurrencyLevel, BiFunction<RangeRequest, BatchingVisitable<RowResult<byte[]>>, T> visitableProcessor) { List<Pair<RangeRequest, BatchingVisitable<RowResult<byte[]>>>> requestAndVisitables = StreamSupport.stream(rangeRequests.spliterator(), false) .map(rangeRequest -> Pair.of(rangeRequest, getLazyRange(tableRef, rangeRequest))) .collect(Collectors.toList()); return MoreStreams.blockingStreamWithParallelism( <START> requestAndVisitables.stream(), <END> pair -> visitableProcessor.apply(pair.getLeft(), pair.getRight()), getRangesExecutor, concurrencyLevel); }</code><technical_language>Oo this takes a stream, remove collect above</technical_language>

Target:
public <T> Stream<T> getRanges( final TableReference tableRef, Iterable<RangeRequest> rangeRequests, int concurrencyLevel, BiFunction<RangeRequest, BatchingVisitable<RowResult<byte[]>>, T> visitableProcessor) { Stream<Pair<RangeRequest, BatchingVisitable<RowResult<byte[]>>>> requestAndVisitables = StreamSupport.stream(rangeRequests.spliterator(), false) .map(rangeRequest -> Pair.of(rangeRequest, getLazyRange(tableRef, rangeRequest))); if (concurrencyLevel == 1 || isSingleton(rangeRequests)) { return requestAndVisitables.map(pair -> visitableProcessor.apply(pair.getLeft(), pair.getRight())); } return MoreStreams.blockingStreamWithParallelism( requestAndVisitables, pair -> visitableProcessor.apply(pair.getLeft(), pair.getRight()), getRangesExecutor, concurrencyLevel); }
Source:
<code><START> public static long[] copyFromIntArray(int[] source) { <END> long[] dest = new long[source.length]; for (int i = 0; i < source.length; i++) { dest[i] = source[i]; } return dest; }</code><technical_language>@fchauveau is null handling of source, is this intended</technical_language>

Target:
public static long[] copyFromIntArray(int[] source) { if(source == null){ return new long[0]; } long[] dest = new long[source.length]; for (int i = 0; i < source.length; i++) { dest[i] = source[i]; } return dest; }
Source:
<code>public void cleanup() { try { <START> log.info("Start cleanup"); <END> DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.AuditLogAgingThreshold) * -1); auditLogDao.removeAllBeforeDate(latestTimeToKeep); log.info("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing audit log cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } }</code><technical_language>move debug in patch (or remove all), I for in INFO level</technical_language>

Target:
public void cleanup() { try { log.debug("Start cleanup"); DateTime latestTimeToKeep = DateTime.getNow().addDays( Config.<Integer>getValue(ConfigValues.AuditLogAgingThreshold) * -1); auditLogDao.removeAllBeforeDate(latestTimeToKeep); log.debug("Finished cleanup"); } catch (Throwable t) { log.error("Exception in performing audit log cleanup: {}", ExceptionUtils.getRootCauseMessage(t)); log.debug("Exception", t); } }
Source:
<code>public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { if (!isConfigured()) { return; } String selfSignedCertConfigMapName = identity.getWorkspaceId() + CHE_GIT_SELF_SIGNED_CERT_CONFIG_MAP_SUFFIX; k8sEnv .getConfigMaps() .put( selfSignedCertConfigMapName, new ConfigMapBuilder() .withNewMetadata() .withName(selfSignedCertConfigMapName) .endMetadata() .withData(singletonMap(CA_CERT_FILE, certificate)) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { <START> if (pod.getRole() != PodRole.INJECTABLE) { <END> Optional<Volume> certVolume = pod.getSpec() .getVolumes() .stream() .filter(v -> v.getName().equals(CHE_GIT_SELF_SIGNED_VOLUME)) .findAny(); if (!certVolume.isPresent()) { pod.getSpec().getVolumes().add(buildCertVolume(selfSignedCertConfigMapName)); } } for (Container container : pod.getSpec().getInitContainers()) { provisionCertVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionCertVolumeMountIfNeeded(container); } } }</code><technical_language>simplified stream().noneMatch()</technical_language>

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { if (!isConfigured()) { return; } String selfSignedCertConfigMapName = identity.getWorkspaceId() + CHE_GIT_SELF_SIGNED_CERT_CONFIG_MAP_SUFFIX; k8sEnv .getConfigMaps() .put( selfSignedCertConfigMapName, new ConfigMapBuilder() .withNewMetadata() .withName(selfSignedCertConfigMapName) .endMetadata() .withData(singletonMap(CA_CERT_FILE, certificate)) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { if (pod.getRole() != PodRole.INJECTABLE) { if (pod.getSpec() .getVolumes() .stream() .noneMatch(v -> v.getName().equals(CHE_GIT_SELF_SIGNED_VOLUME))) { pod.getSpec().getVolumes().add(buildCertVolume(selfSignedCertConfigMapName)); } } for (Container container : pod.getSpec().getInitContainers()) { provisionCertVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionCertVolumeMountIfNeeded(container); } } }
Source:
<code>public static int getPercentCompleteTotal(IAtsObject atsObject) throws OseeCoreException { if (!(atsObject instanceof IAtsWorkItem)) { return 0; } IAtsWorkItem workItem = (IAtsWorkItem) atsObject; if (AtsCore.getWorkDefService().isStateWeightingEnabled(workItem.getWorkDefinition())) { int percent = 0; for (IAtsStateDefinition stateDef : workItem.getWorkDefinition().getStates()) { if (!stateDef.getStateType().isCompletedState() && !stateDef.getStateType().isCancelledState()) { double stateWeightInt = stateDef.getStateWeight(); double weight = stateWeightInt / 100; int percentCompleteForState = getPercentCompleteSMAStateTotal(workItem, stateDef); percent += weight * percentCompleteForState; } } return percent; } else { int percent = getPercentCompleteSMASinglePercent(workItem); if (percent > 0) { return percent; } if (AtsCore.getWorkItemService().getWorkData(workItem).isCompletedOrCancelled()) { return 100; } if (isAnyStateHavePercentEntered(workItem)) { int numStates = 0; for (IAtsStateDefinition state : workItem.getWorkDefinition().getStates()) { if (!state.getStateType().isCompletedState() && !state.getStateType().isCancelledState()) { percent += getPercentCompleteSMAStateTotal(workItem, state); numStates++; } } if (numStates == 0) { return 0; } return percent / numStates; } } <START> return 0; <END> }</code><technical_language>method a "else" statements added reduce number of return statements</technical_language>

Target:
public static int getPercentCompleteTotal(IAtsObject atsObject) throws OseeCoreException { int percent = 0; if (atsObject instanceof IAtsWorkItem) { IAtsWorkItem workItem = (IAtsWorkItem) atsObject; if (AtsCore.getWorkDefService().isStateWeightingEnabled(workItem.getWorkDefinition())) { for (IAtsStateDefinition stateDef : workItem.getWorkDefinition().getStates()) { if (!stateDef.getStateType().isCompletedState() && !stateDef.getStateType().isCancelledState()) { double stateWeightInt = stateDef.getStateWeight(); double weight = stateWeightInt / 100; int percentCompleteForState = getPercentCompleteSMAStateTotal(workItem, stateDef); percent += weight * percentCompleteForState; } } } else { percent = getPercentCompleteSMASinglePercent(workItem); if (percent == 0) { if (AtsCore.getWorkItemService().getWorkData(workItem).isCompletedOrCancelled()) { percent = 100; } else if (isAnyStateHavePercentEntered(workItem)) { int numStates = 0; for (IAtsStateDefinition state : workItem.getWorkDefinition().getStates()) { if (!state.getStateType().isCompletedState() && !state.getStateType().isCancelledState()) { percent += getPercentCompleteSMAStateTotal(workItem, state); numStates++; } } if (numStates > 0) { percent = percent / numStates; } } } } } return percent; }
Source:
<code><START> private String getVersionInformation(PersistentEntity persistentEntity, Object domainObject){ <END> if(persistentEntity.hasVersionProperty()) { BeanWrapper<Object> beanWrapper = BeanWrapper.create(domainObject, conversionService); Object version = beanWrapper.getProperty(persistentEntity.getVersionProperty()); try { return "\"" + objectMapper.writeValueAsString(version) + "\""; } catch (JsonProcessingException e) { LOG.error("Creation of Etag header failed", e); } } return null; }</code><technical_language>reason invoke Jackson mapping here? a plain toString() sufficient</technical_language>

Target:
private String getVersionInformation(PersistentEntity persistentEntity, Object domainObject) { if (persistentEntity.hasVersionProperty()) { BeanWrapper<Object> beanWrapper = BeanWrapper.create(domainObject, conversionService); Object version = beanWrapper.getProperty(persistentEntity.getVersionProperty()); return "\"" + version.toString() + "\""; } return null; }
Source:
<code>public void handle(ExternalMessage value) { RequestForExternalMessages request = unpack(value.getOriginalMessage(), RequestForExternalMessages.class); BoundedContextName origin = value.getBoundedContextName(); addNewSubscriptions(request.getRequestedMessageTypeList(), origin); clearStaleSubscriptions(request.getRequestedMessageTypeList(), origin); if (!knownContexts.contains(origin)) { knownContexts.add(origin); <START> integrationBus.introduceSelf(); <END> } }</code><technical_language>This sound right. bus is introduced system. new context introduces itself. Or, if want bus do job method named differently</technical_language>

Target:
public void handle(ExternalMessage value) { RequestForExternalMessages request = unpack(value.getOriginalMessage(), RequestForExternalMessages.class); BoundedContextName origin = value.getBoundedContextName(); addNewSubscriptions(request.getRequestedMessageTypeList(), origin); clearStaleSubscriptions(request.getRequestedMessageTypeList(), origin); if (!knownContexts.contains(origin)) { knownContexts.add(origin); integrationBus.notifyOthers(); } }
Source:
<code>private static void loadExtensions(ModuleService moduleService, Map<String, Object> argMap) { ExtensionsManager extensionsManager = new ExtensionsManager(); moduleService.getContext().put(ModuleService.EXTENSION_MANAGER, extensionsManager); Map<String, ExtensionProxy> proxies = moduleService.getContext().get(ModuleService.EXTENSIONS_MAP); List<File> files = (List<File>)argMap.get("extension-file"); if(files == null) { files = listFiles( ((String) argMap.get("extensions-dir")).replace("@ENGINE_ETC@", ENGINE_ETC), "properties" ); } for(File f : files) { logger.debug("Loading extension file '{}'", f.getName()); try { proxies.put(extensionsManager.load(f), null); } catch (Exception ex) { logger.error("Can't load extension '{}', ignoring.", f.getName()); logger.debug("Exception:", ex); } } for(Map.Entry<String, ExtensionProxy> entry : proxies.entrySet()) { extensionsManager.initialize(entry.getKey()); entry.setValue(extensionsManager.getExtensionByName(entry.getKey())); logger.debug("Extension '{}' <START> initilized", <END> entry.getKey()); } }</code><technical_language>s/initilized/initialized</technical_language>

Target:
private static void loadExtensions(ModuleService moduleService, Map<String, Object> argMap) { ExtensionsManager extensionsManager = new ExtensionsManager(); moduleService.getContext().put(ModuleService.EXTENSION_MANAGER, extensionsManager); Map<String, ExtensionProxy> proxies = moduleService.getContext().get(ModuleService.EXTENSIONS_MAP); List<File> files = (List<File>)argMap.get("extension-file"); if(files == null) { files = listFiles( ((String) argMap.get("extensions-dir")).replace("@ENGINE_ETC@", ENGINE_ETC), "properties" ); } for(File f : files) { logger.debug("Loading extension file '{}'", f.getName()); try { proxies.put(extensionsManager.load(f), null); } catch (Exception ex) { logger.error("Can't load extension '{}', ignoring.", f.getName()); logger.debug("Exception:", ex); } } for(Map.Entry<String, ExtensionProxy> entry : proxies.entrySet()) { extensionsManager.initialize(entry.getKey()); entry.setValue(extensionsManager.getExtensionByName(entry.getKey())); logger.debug("Extension '{}' initialized", entry.getKey()); } }
Source:
<code>public void testAllResourceParametersMatch() { ServerStoreConfiguration serverConfiguration = new ServerStoreConfiguration(FIXED_POOL_ALLOCATION, STORED_KEY_TYPE, STORED_VALUE_TYPE, ACTUAL_KEY_TYPE, ACTUAL_VALUE_TYPE, KEY_SERIALIZER_TYPE, VALUE_SERIALIZER_TYPE, Consistency.EVENTUAL); ServerStoreConfiguration clientConfiguration = new ServerStoreConfiguration(FIXED_POOL_ALLOCATION, STORED_KEY_TYPE, STORED_VALUE_TYPE, ACTUAL_KEY_TYPE, ACTUAL_VALUE_TYPE, KEY_SERIALIZER_TYPE, VALUE_SERIALIZER_TYPE, Consistency.EVENTUAL); ServerStoreCompatibility serverStoreCompatibility = new ServerStoreCompatibility(); try { serverStoreCompatibility.verify(serverConfiguration, clientConfiguration); } catch(Exception e) { <START> fail("No Exception Expected!"); <END> } }</code><technical_language>declare test method throws Exception catching failing test knowing exception was</technical_language>

Target:
public void testAllResourceParametersMatch() throws Exception { ServerStoreConfiguration serverConfiguration = new ServerStoreConfiguration(FIXED_POOL_ALLOCATION, STORED_KEY_TYPE, STORED_VALUE_TYPE, ACTUAL_KEY_TYPE, ACTUAL_VALUE_TYPE, KEY_SERIALIZER_TYPE, VALUE_SERIALIZER_TYPE, Consistency.EVENTUAL); ServerStoreConfiguration clientConfiguration = new ServerStoreConfiguration(FIXED_POOL_ALLOCATION, STORED_KEY_TYPE, STORED_VALUE_TYPE, ACTUAL_KEY_TYPE, ACTUAL_VALUE_TYPE, KEY_SERIALIZER_TYPE, VALUE_SERIALIZER_TYPE, Consistency.EVENTUAL); ServerStoreCompatibility serverStoreCompatibility = new ServerStoreCompatibility(); serverStoreCompatibility.verify(serverConfiguration, clientConfiguration); }
Source:
<code>public static void PlayGameBot() { int direction = Number(); Direction <START> dir = <END> Direction.valueForBOT(direction); Game2048.gameManager.move(dir); }</code><technical_language>Bad name</technical_language>

Target:
public static void PlayGameBot() { int action = RandomNumber(); Direction direction = Direction.valueForBOT(action); Game2048.gameManager.move(direction); }
Source:
<code>JsonObject createPayload(ETConfiguration configuration) { JsonObject payload = new JsonObject(); payload.addProperty("client_id", configuration.get("clientId")); <START> if(configuration.get("applicationType").equals("web") || configuration.get("applicationType").equals("server")){ <END> payload.addProperty("client_secret", configuration.get("clientSecret")); } if(!isNullOrBlankOrEmpty(refreshToken)){ payload.addProperty("grant_type", "refresh_token"); payload.addProperty("refresh_token", refreshToken); } else if(configuration.get("applicationType").equals("public") || configuration.get("applicationType").equals("web")){ payload.addProperty("grant_type", "authorization_code"); payload.addProperty("code", configuration.get("authorizationCode")); payload.addProperty("redirect_uri", configuration.get("redirectURI")); } else{ payload.addProperty("grant_type", "client_credentials"); } if(!isNullOrBlankOrEmpty(configuration.get("accountId"))){ payload.addProperty("account_id", configuration.get("accountId")); } if(!isNullOrBlankOrEmpty(configuration.get("scope"))){ payload.addProperty("scope", configuration.get("scope")); } return payload; }</code><technical_language>Extract configuration.get("applicationType") a variable</technical_language>

Target:
JsonObject createPayload(ETConfiguration configuration) { JsonObject payload = new JsonObject(); payload.addProperty("client_id", configuration.get("clientId")); String applicationType = configuration.get("applicationType"); if(applicationType.equals("web") || applicationType.equals("server")){ payload.addProperty("client_secret", configuration.get("clientSecret")); } if(!isNullOrBlankOrEmpty(refreshToken)){ payload.addProperty("grant_type", "refresh_token"); payload.addProperty("refresh_token", refreshToken); } else if(applicationType.equals("public") || applicationType.equals("web")){ payload.addProperty("grant_type", "authorization_code"); payload.addProperty("code", configuration.get("authorizationCode")); payload.addProperty("redirect_uri", configuration.get("redirectURI")); } else{ payload.addProperty("grant_type", "client_credentials"); } if(!isNullOrBlankOrEmpty(configuration.get("accountId"))){ payload.addProperty("account_id", configuration.get("accountId")); } if(!isNullOrBlankOrEmpty(configuration.get("scope"))){ payload.addProperty("scope", configuration.get("scope")); } return payload; }
Source:
<code><START> public List<T> getVariants() <END> { return Collections.unmodifiableList(variants); }</code><technical_language>a NavigableSet instead if a TreeSet is used, I assume</technical_language>

Target:
public Collection<T> getVariants() { return Collections.unmodifiableSet(variants); }