auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void execute(Tuple tuple) { try { Thread.sleep(3000); } catch (Exception ex) { } String key = tuple.getString(0); <START> System.out.println(key); <END> if (myState.get(key) == null) { myState.put(key, 1); } else { Integer val = myState.get(key); myState.put(key, ++val); } }</code><technical_language>Leftover debugging changes</technical_language>

Target:
public void execute(Tuple tuple) { String key = tuple.getString(0); if (myState.get(key) == null) { myState.put(key, 1); } else { Integer val = myState.get(key); myState.put(key, ++val); } }
Source:
<code>public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.sp_field_officer: fieldOfficerId = mSavingProductsTemplateByProductId .getFieldOfficerOptions().get(position).getId(); break; case R.id.sp_product: productId = mProductSavings.get(position).getId(); <START> if (clientId != 0) { <END> mSavingsAccountPresenter. loadClientSavingAccountTemplateByProduct(clientId, productId); } else { mSavingsAccountPresenter. loadGroupSavingAccountTemplateByProduct(groupId, productId); } break; } }</code><technical_language>Do clientId, isGroupAccount. give create a GroupSavings ClientSavings Account</technical_language>

Target:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.sp_field_officer: fieldOfficerId = mSavingProductsTemplateByProductId .getFieldOfficerOptions().get(position).getId(); break; case R.id.sp_product: productId = mProductSavings.get(position).getId(); if (isGroupAccount) { mSavingsAccountPresenter. loadGroupSavingAccountTemplateByProduct(groupId, productId); } else { mSavingsAccountPresenter. loadClientSavingAccountTemplateByProduct(clientId, productId); } break; } }
Source:
<code>public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); <START> print(response); <END> checkStation1Exists(response); JSONObject station = getFeaturePropertiesById(response, "st.2"); assertThat(station, notNullValue()); JSONObject contact = station.getJSONObject("contact"); assertThat(contact.size(), is(3)); assertThat(contact.get("@mail"), is("st2@stations.org")); JSONObject phone = contact.getJSONObject("phone"); assertThat(phone.size(), is(1)); assertFalse(phone.has("value")); assertThat(phone.get("@timeZone"), is("")); }</code><technical_language>A leftover</technical_language>

Target:
public void testGetGeoJsonResponseWfs20() throws Exception { JSON response = getAsJSON( "wfs?request=GetFeature&version=2.0" + "&typenames=st_gml32:Station_gml32&outputFormat=application/json"); checkStation1Exists(response); JSONObject station = getFeaturePropertiesById(response, "st.2"); assertThat(station, notNullValue()); JSONObject contact = station.getJSONObject("contact"); assertThat(contact.size(), is(3)); assertThat(contact.get("@mail"), is("st2@stations.org")); JSONObject phone = contact.getJSONObject("phone"); assertThat(phone.size(), is(1)); assertFalse(phone.has("value")); assertThat(phone.get("@timeZone"), is("")); }
Source:
<code>void highlightView(View view) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams instanceof MarginLayoutParams) { MarginLayoutParams marginLayoutParams = (MarginLayoutParams) layoutParams; <START> mMargins = new Rect(marginLayoutParams.leftMargin, marginLayoutParams.topMargin, <END> marginLayoutParams.rightMargin, marginLayoutParams.bottomMargin); } mPaddings = new Rect(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom()); }</code><technical_language>a new rect. update it</technical_language>

Target:
void highlightView(View view) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams instanceof MarginLayoutParams) { MarginLayoutParams marginLayoutParams = (MarginLayoutParams) layoutParams; mMargins.left = marginLayoutParams.leftMargin; mMargins.top = marginLayoutParams.topMargin; mMargins.right = marginLayoutParams.rightMargin; mMargins.bottom = marginLayoutParams.bottomMargin; } else { mMargins.left = 0; mMargins.top = 0; mMargins.right = 0; mMargins.bottom = 0; } mPaddings.left = view.getPaddingLeft(); mPaddings.top = view.getPaddingTop(); mPaddings.right = view.getPaddingRight(); mPaddings.bottom = view.getPaddingBottom(); }
Source:
<code>public List<CustomAttributes> getAttributes() { <START> return attributes; <END> }</code><technical_language>return unmodifiable list</technical_language>

Target:
public List<CustomAttribute> getAttributes() { return Collections.unmodifiableList(attributes); }
Source:
<code>public static MessageBufferInput newBufferInput(InputStream in) { <START> if(in instanceof ByteArrayInputStream) { <END> ByteArrayInputStream b = (ByteArrayInputStream) in; try { byte[] buf = (byte[]) bufField.get(b); int pos = (Integer) bufPosField.get(b); int length = (Integer) bufCountField.get(b); return new ArrayBufferInput(buf, pos, length); } catch(Exception e) { } } else if (in instanceof FileInputStream) { return new ChannelBufferInput(((FileInputStream) in).getChannel()); } return new InputStreamBufferInput(in); }</code><technical_language>I instanceof ByteArrayInputStream is safe in instance of extended type of ByteArrayInputStream overrides read(byte[]) method. This is safe: ByteArrayInputStream.class.equals(in.getClass())</technical_language>

Target:
public static MessageBufferInput newBufferInput(InputStream in) { checkNotNull(in, "InputStream is null"); if(in.getClass() == ByteArrayInputStream.class) { ByteArrayInputStream b = (ByteArrayInputStream) in; try { byte[] buf = (byte[]) bufField.get(b); int pos = (Integer) bufPosField.get(b); int length = (Integer) bufCountField.get(b); return new ArrayBufferInput(buf, pos, length); } catch(Exception e) { } } else if (in instanceof FileInputStream) { return new ChannelBufferInput(((FileInputStream) in).getChannel()); } return new InputStreamBufferInput(in); }
Source:
<code><START> public ComponentBuilder append( BaseComponent[] components, FormatRetention retention ) <END> { Preconditions.checkArgument( components.length != 0, "No components to append" ); parts.add( current ); Collections.addAll( parts, components ); current = components[ components.length - 1 ]; retain( retention ); return this; }</code><technical_language>spaces arguments</technical_language>

Target:
public ComponentBuilder append(BaseComponent[] components, FormatRetention retention) { Preconditions.checkArgument( components.length != 0, "No components to append" ); for ( BaseComponent component : components ) { parts.add( current ); current = component.duplicate(); retain( retention ); } return this; }
Source:
<code>public void updateStats() { <START> physics.setTopSpeed((int) (SPEED + (_score * 1))); <END> weapon.setBulletSpeed((int) (BULLET_SPEED + (_score * 1))); weapon.setFireRate((int) (FIRE_RATE + (_score * 1))); weapon.setDamage((int) (DAMAGE + (_score * 1))); weapon.setMagazineMaxSize((int) (MAGAZINE_MAX_SIZE + (_score * 1))); weapon.setReloadSpeed((int) (RELOAD_SPEED + (_score * 1))); }</code><technical_language>cast adding SPEED, for cases size</technical_language>

Target:
public void updateStats() { physics.setTopSpeed( SPEED + (int) (_score * 1)); weapon.setBulletSpeed( BULLET_SPEED + (int) (_score * 1)); weapon.setFireRate( FIRE_RATE + (int) (_score * 1)); weapon.setDamage( DAMAGE + (int) (_score * 1)); weapon.setMagazineMaxSize( MAGAZINE_MAX_SIZE + (int) (_score * 1)); weapon.setReloadSpeed( RELOAD_SPEED + (int) (_score * 1)); }
Source:
<code><START> public void onServoEvent(Integer eventType, double currentPos) { <END> currentPosInput = mapper.calcInput(currentPos); if (isIKEventEnabled) { ServoEventData data = new ServoEventData(); data.name = getName(); data.pos = currentPosInput; data.state = eventType; data.velocity = velocity; data.targetPos = this.targetPos; invoke("publishIKServoEvent", data); } if (eventType == SERVO_EVENT_STOPPED) { moving = false; } else { moving = true; } if (isEventsEnabled) { invoke("publishServoEvent", currentPosInput); } }</code><technical_language>this a ServoEvent object</technical_language>

Target:
public void onServoEvent(Integer eventType, double currentPos) { log.info("On servo event called with a current pos {}", currentPos); currentPosInput = mapper.calcInput(currentPos); if (isIKEventEnabled) { ServoEventData data = new ServoEventData(); data.name = getName(); data.pos = currentPosInput; data.state = eventType; data.velocity = velocity; data.targetPos = this.targetPos; invoke("publishIKServoEvent", data); } if (eventType == SERVO_EVENT_STOPPED) { moving = false; } else { moving = true; } if (isEventsEnabled) { invoke("publishServoEvent", currentPosInput); } }
Source:
<code>public void testOperations() { MathOperation multiplication = (int a, int b) -> { return a * b; }; Optional<String> description = getDescriptionForIntCallable(() -> {return this.operate(5, 3, multiplication);});; assertTrue(description.isPresent()); <START> assertNameMatch("operate(_,_,_).Integer.valueOf(_)", "testOperations", CLASSNAME, description.get().toString()); <END> }</code><technical_language>This description weird: operate(_,_,_).Integer.valueOf(_) methods operate(_,_,_) Integer.valueOf(_) connected .. detect autoboxing truncate description? I reasonable truncate Integer.valueOf(int) if return type of a lambda is Integer. This description operate(_,_,_). Similar for other primitives e.g. truncate Long.valueOf(long) if return type of a lambda is Long. for toString() return type is String</technical_language>

Target:
public void testOperations() { MathOperation multiplication = (int a, int b) -> { return a * b; }; Optional<String> description = getDescriptionForIntCallable(() -> {return this.operate(5, 3, multiplication);});; assertTrue(description.isPresent()); assertNameMatch("operate(_,_,_)", "testOperations", CLASSNAME, description.get()); }
Source:
<code>public void restartFrom(RecordsRetrieved recordsRetrieved) { if (!(recordsRetrieved instanceof PrefetchRecordsRetrieved)) { throw new IllegalArgumentException( "Provided RecordsRetrieved was not produced by the PrefetchRecordsPublisher"); } PrefetchRecordsRetrieved prefetchRecordsRetrieved = (PrefetchRecordsRetrieved) recordsRetrieved; resetLock.writeLock().lock(); try { <START> requestedResponses.set(0); <END> getRecordsResultQueue.clear(); giveDrainingControlToPublisherOrDemandNotifier(); prefetchCounters.reset(); highestSequenceNumber = prefetchRecordsRetrieved.lastBatchSequenceNumber(); dataFetcher.resetIterator(prefetchRecordsRetrieved.shardIterator(), highestSequenceNumber, initialPositionInStreamExtended); wasReset = true; } finally { resetLock.writeLock().unlock(); } }</code><technical_language>this class track of state, need reset restartFrom call. wondering if pulling out state tracking variable in common place, call reset start clean state helps longer term maintainability of this class. do think</technical_language>

Target:
public void restartFrom(RecordsRetrieved recordsRetrieved) { if (!(recordsRetrieved instanceof PrefetchRecordsRetrieved)) { throw new IllegalArgumentException( "Provided RecordsRetrieved was not produced by the PrefetchRecordsPublisher"); } resetLock.writeLock().lock(); try { publisherSession.reset((PrefetchRecordsRetrieved)recordsRetrieved); wasReset = true; } finally { resetLock.writeLock().unlock(); } }
Source:
<code>static Optional<String> getClientName(Principal principal) { X500Name name = new X500Name(principal.getName()); RDN[] rdns = name.getRDNs(BCStyle.CN); if (rdns.length == 0) { <START> logger.warn("Certificate does not contain CN=xxx,...: {}", principal.getName()); <END> return Optional.empty(); } return Optional.of(IETFUtils.valueToString(rdns[0].getFirst().getValue())); }</code><technical_language>Nit: Certificate's Subject contain..</technical_language>

Target:
static Optional<String> getClientName(Principal principal) { X500Name name = new X500Name(principal.getName()); RDN[] rdns = name.getRDNs(BCStyle.CN); if (rdns.length == 0) { logger.warn("Certificate's subject does not contain CN=xxx,...: {}", principal.getName()); return Optional.empty(); } return Optional.of(IETFUtils.valueToString(rdns[0].getFirst().getValue())); }
Source:
<code>public List<MetricFamilySamples> collect() { GaugeMetricFamily availablePermissionsFamily = new GaugeMetricFamily( names.getAvailablePermissionsMetricName(), <START> "The number of rate limiter available permissions", <END> LabelNames.NAME ); GaugeMetricFamily waitingThreadsFamily = new GaugeMetricFamily( names.getWaitingThreadsMetricName(), "The number of rate limiter waiting threads", LabelNames.NAME ); for (RateLimiter rateLimiter : supplier.get()) { List<String> nameLabel = singletonList(rateLimiter.getName()); availablePermissionsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getAvailablePermissions()); waitingThreadsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getNumberOfWaitingThreads()); } return Arrays.asList(availablePermissionsFamily, waitingThreadsFamily); }</code><technical_language>better: number of permissions</technical_language>

Target:
public List<MetricFamilySamples> collect() { GaugeMetricFamily availablePermissionsFamily = new GaugeMetricFamily( names.getAvailablePermissionsMetricName(), "The number of available permissions", LabelNames.NAME ); GaugeMetricFamily waitingThreadsFamily = new GaugeMetricFamily( names.getWaitingThreadsMetricName(), "The number of waiting threads", LabelNames.NAME ); for (RateLimiter rateLimiter : supplier.get()) { List<String> nameLabel = singletonList(rateLimiter.getName()); availablePermissionsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getAvailablePermissions()); waitingThreadsFamily.addMetric(nameLabel, rateLimiter.getMetrics().getNumberOfWaitingThreads()); } return Arrays.asList(availablePermissionsFamily, waitingThreadsFamily); }
Source:
<code>public void sampleBoardAutoCreationTest() { assertEquals(panelControl.getNumberOfSavedBoards(), 0); clickMenu("Boards", "Auto-create", SAMPLE_BOARD); waitUntilNodeAppears(SAMPLE_BOARD_DIALOG); click("OK"); assertEquals(panelControl.getPanelCount(), BoardAutoCreator.getSamplePanelDetails().size()); assertEquals(panelControl.getCurrentlySelectedPanel(), Optional.of(0)); assertEquals(panelControl.getNumberOfSavedBoards(), 1); List<PanelInfo> panelInfos = panelControl.getCurrentPanelInfos(); int i = 0; for (String panelName : BoardAutoCreator.getSamplePanelDetails().keySet()) { assertEquals(panelInfos.get(i).getPanelName(), panelName); i++; } int j = 0; for (String panelFilter : BoardAutoCreator.getSamplePanelDetails().values()) { assertEquals(panelInfos.get(j).getPanelFilter(), panelFilter); <START> j++; <END> } }</code><technical_language>I need loops iterate a map. a related note, I need classes represent information of a board (BoardInfo?), a panel (PanelInfo?) current code is messy due lack of right abstractions</technical_language>

Target:
public void sampleBoardAutoCreationTest() { assertEquals(panelControl.getNumberOfSavedBoards(), 0); clickMenu("Boards", "Auto-create", SAMPLE_BOARD); waitUntilNodeAppears(SAMPLE_BOARD_DIALOG); click("OK"); verifyBoard(panelControl, BoardAutoCreator.getSamplePanelDetails()); }
Source:
<code>public Collection<Event> search(final Optional<RyaURI> subject, final Optional<Collection<IndexingExpr>> geoFilters, final Optional<Collection<IndexingExpr>> temporalFilters) throws EventStorageException { requireNonNull(subject); try { final Collection<IndexingExpr> geos = (geoFilters.isPresent() ? geoFilters.get() : new ArrayList<>()); final Collection<IndexingExpr> tempos = (temporalFilters.isPresent() ? temporalFilters.get() : new ArrayList<>()); final DBObject filterObj = queryAdapter.getFilterQuery(geos, tempos); final BasicDBObjectBuilder builder = BasicDBObjectBuilder .start(filterObj.toMap()); if(subject.isPresent()) { builder.append(EventDocumentConverter.SUBJECT, subject.get().getData()); } final MongoCursor<Document> results = mongo.getDatabase(ryaInstanceName) .getCollection(COLLECTION_NAME) .find( BsonDocument.parse(builder.get().toString()) ) .iterator(); final List<Event> events = new ArrayList<>(); <START> final EventDocumentConverter adapter = new EventDocumentConverter(); <END> while(results.hasNext()) { events.add(adapter.fromDocument(results.next())); } return events; } catch(final MongoException | DocumentConverterException | GeoTemporalIndexException e) { throw new EventStorageException("Could not get the Event.", e); } }</code><technical_language>static final instance of EVENT_CONVERTER</technical_language>

Target:
public Collection<Event> search(final Optional<RyaURI> subject, final Optional<Collection<IndexingExpr>> geoFilters, final Optional<Collection<IndexingExpr>> temporalFilters) throws EventStorageException { requireNonNull(subject); try { final Collection<IndexingExpr> geos = (geoFilters.isPresent() ? geoFilters.get() : new ArrayList<>()); final Collection<IndexingExpr> tempos = (temporalFilters.isPresent() ? temporalFilters.get() : new ArrayList<>()); final DBObject filterObj = queryAdapter.getFilterQuery(geos, tempos); final BasicDBObjectBuilder builder = BasicDBObjectBuilder .start(filterObj.toMap()); if(subject.isPresent()) { builder.append(EventDocumentConverter.SUBJECT, subject.get().getData()); } final MongoCursor<Document> results = mongo.getDatabase(ryaInstanceName) .getCollection(COLLECTION_NAME) .find( BsonDocument.parse(builder.get().toString()) ) .iterator(); final List<Event> events = new ArrayList<>(); while(results.hasNext()) { events.add(EVENT_CONVERTER.fromDocument(results.next())); } return events; } catch(final MongoException | DocumentConverterException | GeoTemporalIndexException e) { throw new EventStorageException("Could not get the Event.", e); } }
Source:
<code>private String getDefaultVersion(Set<String> keys, String appName) { String aut = null; SortedSet<String> listOfApps = new TreeSet<String>(); if (keys.size() > 0) { for (String key : keys) { if (key.split(":")[0].contentEquals(appName)) { listOfApps.add(key); } } } if (listOfApps.size() > 0) { aut = listOfApps.last(); } <START> return aut; <END> }</code><technical_language>return listOpApps.size() > 0 ? listOfApps.last() : null; listOfApps.pollLast() if TreeSet line 354. I this communicates intend of code, removes relevant variable declaration line 353</technical_language>

Target:
private String getDefaultVersion(Set<String> keys, String appName) { SortedSet<String> listOfApps = new TreeSet<String>(); for (String key : keys) { if (key.split(":")[0].contentEquals(appName)) { listOfApps.add(key); } } return listOfApps.size() > 0 ? listOfApps.last() : null; }
Source:
<code>public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) { String githubClientId = propertyManager.getProperty(SocialProperties.GITHUB_CLIENT_ID); String githubSecret = propertyManager.getProperty(SocialProperties.GITHUB_SECRET); AdjustableGithubConnectionFactory githubFactory = new AdjustableGithubConnectionFactory(githubClientId, githubSecret); cfConfig.addConnectionFactory(githubFactory); reloadService.addFactory(IReloadService.GITHUB, githubFactory); identityProviderRegistry.addProvider(githubFactory.getProviderId()); <START> identityProviderRegistry.addProviderTokenChecker(githubFactory.getProviderId(), GitHubChecker.ID); <END> }</code><technical_language>token checker, there? this is needed</technical_language>

Target:
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) { String githubClientId = propertyManager.getProperty(SocialProperties.GITHUB_CLIENT_ID); String githubSecret = propertyManager.getProperty(SocialProperties.GITHUB_SECRET); AdjustableGithubConnectionFactory githubFactory = new AdjustableGithubConnectionFactory(githubClientId, githubSecret); cfConfig.addConnectionFactory(githubFactory); reloadService.addFactory(IReloadService.GITHUB, githubFactory); }
Source:
<code>protected NotificationChannel getNotificationChannel(Context context, Intent intent) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel notificationChannel = new NotificationChannel("parse_push", "Push notifications", NotificationManager.IMPORTANCE_DEFAULT); <START> nm.createNotificationChannel(notificationChannel); <END> return notificationChannel; }</code><technical_language>move channel creation outside, in getNotification(), right call getNotificationChannel() ? If overrides this method, creation happen</technical_language>

Target:
protected NotificationChannel getNotificationChannel(Context context, Intent intent) { return new NotificationChannel("parse_push", "Push notifications", NotificationManager.IMPORTANCE_DEFAULT); }
Source:
<code>public int compareTo( PointValue other ) { <START> return unsafeCompareTo(other); <END> }</code><technical_language>above, invert calls compareTo unsafeCompareTo</technical_language>

Target:
public int compareTo( PointValue other ) { int cmpCRS = this.crs.getCode() - other.crs.getCode(); if ( cmpCRS != 0 ) { return cmpCRS; } if ( this.coordinate.length > other.coordinate.length ) { return 1; } else if ( this.coordinate.length < other.coordinate.length ) { return -1; } for ( int i = 0; i < coordinate.length; i++ ) { int cmpVal = Double.compare( this.coordinate[i], other.coordinate[i] ); if ( cmpVal != 0 ) { return cmpVal; } } return 0; }
Source:
<code>public void run() { while (!shutdown) { synchronized (this) { try { if (isActive) { processQueuedFlows(activeExecutorRefreshWindowInMilisec, activeExecutorRefreshWindowInFlows); } wait(QUEUE_PROCESSOR_WAIT_IN_MS); } catch (Exception e) { <START> logger.info( <END> "QueueProcessorThread Interrupted. Probably to shut down.", e); } } } }</code><technical_language>logger.error()</technical_language>

Target:
public void run() { while (!shutdown) { synchronized (this) { try { if (isActive) { processQueuedFlows(activeExecutorRefreshWindowInMilisec, activeExecutorRefreshWindowInFlows); } wait(QUEUE_PROCESSOR_WAIT_IN_MS); } catch (Exception e) { logger.error( "QueueProcessorThread Interrupted. Probably to shut down.", e); } } } }
Source:
<code>static HeadRules creaeHeadRules(TrainerToolParams params) throws IOException { ArtifactSerializer headRulesSerializer; if (params.getHeadRulesSerializerImpl() != null) { headRulesSerializer = ExtensionLoader.instantiateExtension(ArtifactSerializer.class, params.getHeadRulesSerializerImpl()); } else { <START> if ("en".equals(params.getLang()) || "eng".equals(params.getLang())) { <END> headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } else if ("es".equals(params.getLang()) || "spa".equals(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.es.AncoraSpanishHeadRules.HeadRulesSerializer(); } else { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } } Object headRulesObject = headRulesSerializer.create(new FileInputStream(params.getHeadRules())); if (headRulesObject instanceof HeadRules) { return (HeadRules) headRulesObject; } else { throw new TerminateToolException(-1, "HeadRules Artifact Serializer must create an object of type HeadRules!"); } }</code><technical_language>equalsIgnoreCase() ??</technical_language>

Target:
static HeadRules creaeHeadRules(TrainerToolParams params) throws IOException { ArtifactSerializer headRulesSerializer; if (params.getHeadRulesSerializerImpl() != null) { headRulesSerializer = ExtensionLoader.instantiateExtension(ArtifactSerializer.class, params.getHeadRulesSerializerImpl()); } else { if ("en".equalsIgnoreCase(params.getLang()) || "eng".equalsIgnoreCase(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } else if ("es".equalsIgnoreCase(params.getLang()) || "spa".equalsIgnoreCase(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.es.AncoraSpanishHeadRules.HeadRulesSerializer(); } else { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } } Object headRulesObject = headRulesSerializer.create(new FileInputStream(params.getHeadRules())); if (headRulesObject instanceof HeadRules) { return (HeadRules) headRulesObject; } else { throw new TerminateToolException(-1, "HeadRules Artifact Serializer must create an object of type HeadRules!"); } }
Source:
<code>public void listWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listWithMultipleKeysRunner(key, key2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().keys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); <START> return new IterableResponse<>(Flux.fromStream(selected.stream())); <END> }); }</code><technical_language>Flux.fromIterable(selected)</technical_language>

Target:
public void listWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listWithMultipleKeysRunner(key, key2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().keys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); }
Source:
<code>public Spliterator<T> spliterator() { class SpliteratorProxy implements Spliterator<T> { private final Spliterator<Tuple2<Integer, T>> spliterator; private SpliteratorProxy(Spliterator<Tuple2<Integer, T>> spliterator) { this.spliterator = spliterator; } @Override public boolean tryAdvance(Consumer<? super T> action) { return spliterator.tryAdvance(a -> action.accept(a._2)); } @Override public Spliterator<T> trySplit() { return new SpliteratorProxy(spliterator.trySplit()); } @Override public long estimateSize() { return spliterator.estimateSize(); } @Override public int characteristics() { return spliterator.characteristics(); } @Override public Comparator<? super T> getComparator() { return null; <START> } <END> } return new SpliteratorProxy(original.spliterator()); }</code><technical_language>super impl Spliterator.getComparator() throws IllegalStateException default. Is necessary return null? If null is throw a NPE, is roughly throwing IllegalStateException. curious - is a reason</technical_language>

Target:
public Spliterator<T> spliterator() { class SpliteratorProxy implements Spliterator<T> { private final Spliterator<Tuple2<Integer, T>> spliterator; private SpliteratorProxy(Spliterator<Tuple2<Integer, T>> spliterator) { this.spliterator = spliterator; } @Override public boolean tryAdvance(Consumer<? super T> action) { return spliterator.tryAdvance(a -> action.accept(a._2)); } @Override public Spliterator<T> trySplit() { return new SpliteratorProxy(spliterator.trySplit()); } @Override public long estimateSize() { return spliterator.estimateSize(); } @Override public int characteristics() { return spliterator.characteristics(); } @Override public Comparator<? super T> getComparator() { if (hasCharacteristics(Spliterator.SORTED)) { return null; } throw new IllegalStateException(); } } return new SpliteratorProxy(original.spliterator()); }
Source:
<code>private boolean hasRegistrationFormSelected() { SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions(); boolean registrationFormSelected = false; for (int i = 0; i < checkedItemPositions.size(); i++) { if (checkedItemPositions.valueAt(i)) { AvailableForm selectedForm = (AvailableForm) listView.getItemAtPosition(checkedItemPositions.keyAt(i)); <START> if (selectedForm.hasDescriminator(Constants.FORM_DISCRIMINATOR_REGISTRATION)) { <END> registrationFormSelected = true; } } } return registrationFormSelected; }</code><technical_language>redefine logic for determining a registration form isRegistrationForm() method? reason is, method in places need remain consistent</technical_language>

Target:
private boolean hasRegistrationFormSelected() { SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions(); boolean registrationFormSelected = false; for (int i = 0; i < checkedItemPositions.size(); i++) { if (checkedItemPositions.valueAt(i)) { AvailableForm selectedForm = (AvailableForm) listView.getItemAtPosition(checkedItemPositions.keyAt(i)); if (selectedForm.isRegistrationForm()) { registrationFormSelected = true; } } } return registrationFormSelected; }
Source:
<code><START> public ExecutionPlan plan(ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc) { <END> validateConfig(); JobGraph jobGraph = createJobGraph(config, appDesc, new JobGraphJsonGenerator(), new JobNodeConfigureGenerator()); fetchInputAndOutputStreamPartitions(jobGraph, streamManager); new IntermediateStreamPartitionPlanner(config, appDesc).calculatePartitions(jobGraph); return jobGraph; }</code><technical_language>Minor: remove type bound if used</technical_language>

Target:
public ExecutionPlan plan(ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc) { validateConfig(); JobGraph jobGraph = createJobGraph(config, appDesc); setInputAndOutputStreamPartitionCount(jobGraph, streamManager); new IntermediateStreamManager(config, appDesc).calculatePartitions(jobGraph); return jobGraph; }
Source:
<code>public static SortOrder toSortOrder(SortItem sortItem) { if (sortItem.getOrdering() == SortItem.Ordering.ASCENDING) { if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.ASC_NULLS_FIRST; } <START> else { <END> return SortOrder.ASC_NULLS_LAST; } } else { if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.DESC_NULLS_FIRST; } else { return SortOrder.DESC_NULLS_LAST; } } }</code><technical_language>else if redundant</technical_language>

Target:
public static SortOrder toSortOrder(SortItem sortItem) { if (sortItem.getOrdering() == SortItem.Ordering.ASCENDING) { if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.ASC_NULLS_FIRST; } return SortOrder.ASC_NULLS_LAST; } if (sortItem.getNullOrdering() == SortItem.NullOrdering.FIRST) { return SortOrder.DESC_NULLS_FIRST; } return SortOrder.DESC_NULLS_LAST; }
Source:
<code>public void prepare() throws NotDeliciousException { <START> this.addCondiments("sour cream", "chives", "butter", "crumbled bacon", "grated cheese", "ketchup", "salt", "tabasco", "pepporoni", "sausage"); <END> this.listCondiments(); if(!this.isDelicious()) throw new NotDeliciousException(); }</code><technical_language>spell check</technical_language>

Target:
public void prepare() throws NotDeliciousException { this.addCondiments("sour cream", "chives", "butter", "crumbled bacon", "grated cheese", "ketchup", "salt", "tabasco", "pepperoni", "sausage"); this.listCondiments(); if(!this.isDelicious()) throw new NotDeliciousException(); }
Source:
<code>public ConsumptionMap getByTicketIdIfValid(Long ticketId) { if(!ticketService.getTicketById(ticketId).isValid()){ <START> throw new InvalidTicketException("Ticket is invalid; can't reset consumptions"); <END> } Collection<ConsumptionMap> consumptionMaps = consumptionMapsRepository.findAll(); Optional<ConsumptionMap> mapOptional = consumptionMapsRepository.findByTicketId(ticketId); if(mapOptional.isPresent()){ return mapOptional.get(); }else{ return InitializeConsumptionMap(ticketId); } }</code><technical_language>Wrong error message</technical_language>

Target:
public ConsumptionMap getByTicketIdIfValid(Long ticketId) { if(!ticketService.getTicketById(ticketId).isValid()){ throw new InvalidTicketException("Ticket is invalid; It can not be used for consumptions."); } Optional<ConsumptionMap> mapOptional = consumptionMapsRepository.findByTicketId(ticketId); if(mapOptional.isPresent()){ return mapOptional.get(); }else{ return initializeConsumptionMap(ticketId); } }
Source:
<code>private void clickOnElement(WebElement element) { <START> Actions action = new Actions(seleniumWebDriver); <END> action.moveToElement(element).click().perform(); }</code><technical_language>ActionManager</technical_language>

Target:
private void clickOnElement(WebElement element) { actionsFactory.createAction(seleniumWebDriver).moveToElement(element).click().perform(); }
Source:
<code>public void testLoadAndSaveAggregate() { String identifier = UUID.randomUUID().toString(); DomainEventMessage event1 = new GenericDomainEventMessage<>("type", identifier, (long) 1, "Mock contents", emptyInstance()); <START> DomainEventMessage event2 = <END> new GenericDomainEventMessage<>("type", identifier, (long) 2, "Mock contents", emptyInstance()); DomainEventMessage event3 = new GenericDomainEventMessage<>("otherType", identifier, (long) 1, "Other contents", emptyInstance()); when(mockEventStore.readEvents(identifier)).thenReturn(DomainEventStream.of(event1, event2, event3)); Aggregate<TestAggregate> aggregate = testSubject.load(identifier, null); assertEquals(2, aggregate.invoke(TestAggregate::getHandledEvents).size()); assertSame(event1, aggregate.invoke(TestAggregate::getHandledEvents).get(0)); assertSame(event2, aggregate.invoke(TestAggregate::getHandledEvents).get(1)); assertEquals(0, aggregate.invoke(TestAggregate::getLiveEvents).size()); StubDomainEvent event4 = new StubDomainEvent(); aggregate.execute(r -> r.apply(event4)); CurrentUnitOfWork.commit(); verify(mockEventStore, times(1)).publish((EventMessage) anyVararg()); assertEquals(1, aggregate.invoke(TestAggregate::getLiveEvents).size()); assertSame(event4, aggregate.invoke(TestAggregate::getLiveEvents).get(0).getPayload()); }</code><technical_language>I a bit cleaner introduce a new test verifies if filtering Aggregate Type is performed instead of adjusting existing one</technical_language>

Target:
public void testLoadAndSaveAggregate() { String identifier = UUID.randomUUID().toString(); DomainEventMessage event1 = new GenericDomainEventMessage<>("type", identifier, (long) 1, "Mock contents", emptyInstance()); DomainEventMessage event2 = new GenericDomainEventMessage<>("type", identifier, (long) 2, "Mock contents", emptyInstance()); when(mockEventStore.readEvents(identifier)).thenReturn(DomainEventStream.of(event1, event2)); Aggregate<TestAggregate> aggregate = testSubject.load(identifier, null); assertEquals(2, aggregate.invoke(TestAggregate::getHandledEvents).size()); assertSame(event1, aggregate.invoke(TestAggregate::getHandledEvents).get(0)); assertSame(event2, aggregate.invoke(TestAggregate::getHandledEvents).get(1)); assertEquals(0, aggregate.invoke(TestAggregate::getLiveEvents).size()); StubDomainEvent event3 = new StubDomainEvent(); aggregate.execute(r -> r.apply(event3)); CurrentUnitOfWork.commit(); verify(mockEventStore, times(1)).publish((EventMessage) anyVararg()); assertEquals(1, aggregate.invoke(TestAggregate::getLiveEvents).size()); assertSame(event3, aggregate.invoke(TestAggregate::getLiveEvents).get(0).getPayload()); }
Source:
<code>private static Configuration readTestConfiguration() { String testConfigurationUris = System.getProperty(TEST_CONFIGURATION_URI_KEY, DEFAULT_TEST_CONFIGURATION_LOCATION); Configuration configuration = emptyConfiguration(); for (String testConfigurationUri : Splitter.on(",").split(testConfigurationUris)) { Optional<InputStream> testConfigurationStream = getConfigurationInputStream(testConfigurationUri); if (!testConfigurationStream.isPresent()) { throw new IllegalArgumentException("Unable find to configuration: " + testConfigurationUri); } Configuration parsedConfiguration = parseConfiguration(testConfigurationStream.get()); <START> configuration = new HierarchicalConfiguration(parsedConfiguration, configuration); <END> } return configuration; }</code><technical_language>reverse params order</technical_language>

Target:
private static Configuration readTestConfiguration() { String testConfigurationUris = System.getProperty(TEST_CONFIGURATION_URIS_KEY, DEFAULT_TEST_CONFIGURATION_LOCATION); Configuration configuration = emptyConfiguration(); for (String testConfigurationUri : Splitter.on(",").split(testConfigurationUris)) { Optional<InputStream> testConfigurationStream = getConfigurationInputStream(testConfigurationUri); if (!testConfigurationStream.isPresent()) { throw new IllegalArgumentException("Unable find to configuration: " + testConfigurationUri); } Configuration parsedConfiguration = parseConfiguration(testConfigurationStream.get()); configuration = new HierarchicalConfiguration(configuration, parsedConfiguration); } return configuration; }
Source:
<code>public void setValue(final String value) { <START> final Moment moment = moment(value, "HH:mm:ss"); <END> if (moment.isValid()) { view.setDate(moment); } }</code><technical_language>Please TIME_FORMAT instead of "HH:mm:ss"</technical_language>

Target:
public void setValue(final String value) { final Moment moment = moment(value, TIME_FORMAT); if (moment.isValid()) { view.setDate(moment); } }
Source:
<code>void testInitializeFromAggregateSnapshot() { StubAggregate aggregate = new StubAggregate("stubId"); <START> DomainEventMessage<StubAggregate> snapshotMessage = new GenericDomainEventMessage<>("StubAggregate", aggregate.getIdentifier(), <END> 2, aggregate); GenericAggregateFactory<StubAggregate> factory = new GenericAggregateFactory<>(StubAggregate.class); assertSame(aggregate, factory.createAggregateRoot(aggregate.getIdentifier(), snapshotMessage)); }</code><technical_language>Ideally, this test require change pass. aggregateType in past, polymorphism is used, type matter</technical_language>

Target:
void testInitializeFromAggregateSnapshot() { StubAggregate aggregate = new StubAggregate("stubId"); DomainEventMessage<StubAggregate> snapshotMessage = new GenericDomainEventMessage<>("type", aggregate.getIdentifier(), 2, aggregate); GenericAggregateFactory<StubAggregate> factory = new GenericAggregateFactory<>(StubAggregate.class); assertSame(aggregate, factory.createAggregateRoot(aggregate.getIdentifier(), snapshotMessage)); }
Source:
<code>public void testProlongDueDate() { String responsible = "john"; long caseId = wcs.createWork("Integrate module X into project Y", "Module X working in the project Y by ...", responsible); wcs.prolongTimeoutTo(caseId, 15); try { <START> Thread.sleep(11000); <END> } catch (InterruptedException e) { e.printStackTrace(); } ProcessInstanceLog pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_ACTIVE); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_COMPLETED); }</code><technical_language>Is sleeps shorter? (max 2 seconds?) is thread waiting for</technical_language>

Target:
public void testProlongDueDate() { String responsible = "john"; long caseId = wcs.createWork("Integrate module X into project Y", "Module X working in the project Y by ...", responsible, 1); wcs.prolongTimeoutTo(caseId, 3); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } ProcessInstanceLog pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_ACTIVE); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } pil = auditService.findProcessInstance(caseId); Assertions.assertThat(pil.getStatus()).isEqualTo(ProcessInstance.STATE_COMPLETED); }
Source:
<code><START> protected void createAndDispatchGDBFocusChangedEvent() { <END> fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); }</code><technical_language>Lets reduce API this private, assert fCurrentThreadCtx != null</technical_language>

Target:
private void createAndDispatchGDBFocusChangedEvent() { assert fCurrentThreadCtx != null; fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); }
Source:
<code>public boolean isActive(IJavaProject project) { boolean enabled = Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, Activator.PREF_ENABLED, false, new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE, DefaultScope.INSTANCE }); if (!enabled) return false; IProject iproject = project.getProject(); <START> if (iproject.isOpen() && !PDE.hasPluginNature(iproject)) <END> return false; if (WorkspaceModelManager.isBinaryProject(project.getProject())) return false; try { IType annotationType = project.findType(COMPONENT_ANNOTATION); return annotationType != null && annotationType.isAnnotation(); } catch (JavaModelException e) { Activator.log(e); } return false; }</code><technical_language>This participant active for Java Plugin projects -- return false if verify (because project is closed?) if (!iproject.isOpen() || !PDE.hasPluginNature(iproject)) return false; FWIW I this method called for closed projects</technical_language>

Target:
public boolean isActive(IJavaProject project) { boolean enabled = Platform.getPreferencesService().getBoolean(Activator.PLUGIN_ID, Activator.PREF_ENABLED, false, new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE, DefaultScope.INSTANCE }); if (!enabled) return false; IProject iproject = project.getProject(); if (!iproject.isOpen() || !PDE.hasPluginNature(iproject)) return false; if (WorkspaceModelManager.isBinaryProject(project.getProject())) return false; try { IType annotationType = project.findType(COMPONENT_ANNOTATION); return annotationType != null && annotationType.isAnnotation(); } catch (JavaModelException e) { Activator.log(e); } return false; }
Source:
<code>public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { final int sqlType; if (type == LocalDate.class) { sqlType = Types.DATE; } else if (type == LocalTime.class) { sqlType = Types.TIME; } else if (type == LocalDateTime.class) { sqlType = Types.TIMESTAMP; } else if (type == OffsetDateTime.class) { sqlType = Types.TIMESTAMP_WITH_TIMEZONE; } else { return Optional.empty(); } <START> return Optional.of(ObjectArgument.of(value, sqlType)); <END> }</code><technical_language>This structure smells delegate a Map<Class, Integer> instead of a code tree if gonna refactor</technical_language>

Target:
public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { return Optional.ofNullable(TYPES.get(type)) .map(sqlType -> ObjectArgument.of(value, sqlType)); }
Source:
<code>public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { String txnMgr = context.hiveConf.getVar(HiveConf.ConfVars.HIVE_TXN_MANAGER); <START> boolean concurrency = context.hiveConf.getBoolVar(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY); <END> String dbTxnMgr = "org.apache.hadoop.hive.ql.lockmgr.DbTxnManager"; if (!txnMgr.equals(dbTxnMgr) || !concurrency) { context.log.error("Cannot load transaction events as acid is not enabled"); throw new SemanticException("Cannot load transaction events as acid is not enabled"); } AbortTxnMessage msg = deserializer.getAbortTxnMessage(context.dmd.getPayload()); Task<ReplTxnWork> abortTxnTask = TaskFactory.get( new ReplTxnWork(context.dbName, context.tableName, msg.getTxnId(), ReplTxnWork.OperationType.REPL_ABORT_TXN), context.hiveConf ); updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); context.log.debug("Added Abort txn task : {}", abortTxnTask.getId()); return Collections.singletonList(abortTxnTask); }</code><technical_language>acid check is duplicated in txn events, add static method in TxnUtils AcidUtils appropriate</technical_language>

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { if (!AcidUtils.isAcidEnabled(context.hiveConf)) { context.log.error("Cannot load transaction events as acid is not enabled"); throw new SemanticException("Cannot load transaction events as acid is not enabled"); } AbortTxnMessage msg = deserializer.getAbortTxnMessage(context.dmd.getPayload()); Task<ReplTxnWork> abortTxnTask = TaskFactory.get( new ReplTxnWork(context.dbName, context.tableName, msg.getTxnId(), ReplTxnWork.OperationType.REPL_ABORT_TXN), context.hiveConf ); updatedMetadata.set(context.dmd.getEventTo().toString(), context.dbName, context.tableName, null); context.log.debug("Added Abort txn task : {}", abortTxnTask.getId()); return Collections.singletonList(abortTxnTask); }
Source:
<code>private void validateGateway(VdsNetworkInterface iface) { if (!FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) <START> && StringUtils.isNotEmpty(iface.getGateway())) { <END> addViolation(VdcBllMessages.NETWORK_ATTACH_ILLEGAL_GATEWAY, iface.getNetworkName()); } }</code><technical_language>please revert order of conditions static validation validation requires fetching DB: private void validateGateway(VdsNetworkInterface iface) {if (StringUtils.isNotEmpty(iface.getGateway()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && !FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion()) ) { ... }</technical_language>

Target:
private void validateGateway(VdsNetworkInterface iface) { if (StringUtils.isNotEmpty(iface.getGateway()) && !NetworkUtils.isManagementNetwork(iface.getNetworkName()) && !FeatureSupported.multipleGatewaysSupported(vds.getVdsGroupCompatibilityVersion())) { addViolation(VdcBllMessages.NETWORK_ATTACH_ILLEGAL_GATEWAY, iface.getNetworkName()); } }
Source:
<code>public Optional<BackupMetadata> getLatestBackupMetaData(List<BackupMetadata> metadata) { metadata = metadata.stream() .filter(backupMetadata -> backupMetadata.getStatus() == Status.FINISHED) .collect(Collectors.toList()); <START> metadata.sort((o1, o2) -> o2.getStart().compareTo(o1.getStart())); <END> return metadata.stream().findFirst(); }</code><technical_language>include this in stream above. this metadata.stream() .filter(backupMetadata -> backupMetadata.getStatus() == Status.FINISHED) .sorted((o1, o2) -> o2.getStart().compareTo(o1.getStart())) .collect(Collectors.toList());</technical_language>

Target:
public Optional<BackupMetadata> getLatestBackupMetaData(List<BackupMetadata> metadata) { return metadata.stream() .filter(backupMetadata -> backupMetadata.getStatus() == Status.FINISHED) .sorted(Comparator.comparing(BackupMetadata::getStart).reversed()) .findFirst(); }