auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setReplyChannel(MessageChannel replyChannel) { <START> this.setOutputChannel(replyChannel); <END> }</code><technical_language>this. method calls? I guess moved existing setter for class structure. fix this. in a change</technical_language>

Target:
public void setReplyChannel(MessageChannel replyChannel) { setOutputChannel(replyChannel); }
Source:
<code>private ObjectWriter getObjectWriter(List<String> fieldsToReturn) { if (fieldsToReturn.isEmpty()) { <START> FilterProvider filter = new SimpleFilterProvider().addFilter("filter properties by name", SimpleBeanPropertyFilter.serializeAll()); <END> return mapper.writer(filter); } HashSet<String> givenFields = new HashSet<>(); givenFields.add("schemas"); givenFields.addAll(fieldsToReturn); String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]); FilterProvider filters = new SimpleFilterProvider() .addFilter("filter properties by name", SimpleBeanPropertyFilter.filterOutAllExcept( finalFieldsToReturn)); return mapper.writer(filters); }</code><technical_language>Do need another no-op filter? defined in global ObjectMapper enough</technical_language>

Target:
private ObjectWriter getObjectWriter(List<String> fieldsToReturn) { if (fieldsToReturn.isEmpty()) { return mapper.writer(); } HashSet<String> givenFields = new HashSet<>(); givenFields.add("schemas"); givenFields.addAll(fieldsToReturn); String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]); FilterProvider filters = new SimpleFilterProvider() .addFilter("propertiesFilter", SimpleBeanPropertyFilter.filterOutAllExcept( finalFieldsToReturn)); return mapper.writer(filters); }
Source:
<code>protected void doOperation() { List<StudentProfileAttributes> allStudentProfiles = profilesLogic.getAllStudentProfiles(); int numberOfAffectedProfiles = 0; int numberOfUpdatedProfiles = 0; LoopHelper loopHelper = new LoopHelper(100, "student profiles processed."); println("Running data migration for sanitization on student profiles..."); println("Preview: " + isPreview); for (StudentProfileAttributes profile : allStudentProfiles) { loopHelper.recordLoop(); boolean isProfileSanitized = isProfileSanitized(profile); <START> if (!isProfileSanitized) { <END> continue; } numberOfAffectedProfiles++; try { desanitizeAndUpdateProfile(profile); numberOfUpdatedProfiles++; } catch (InvalidParametersException | EntityDoesNotExistException e) { println("Problem sanitizing profile with google id " + profile.googleId); println(e.getMessage()); } } println("Total number of profiles: " + loopHelper.getCount()); println("Number of affected profiles: " + numberOfAffectedProfiles); println("Number of updated profiles: " + numberOfUpdatedProfiles); }</code><technical_language>I prefer isProfileUnsanitized this is place isProfileSanitized is used</technical_language>

Target:
protected void doOperation() { List<StudentProfileAttributes> allStudentProfiles = profilesLogic.getAllStudentProfiles(); int numberOfAffectedProfiles = 0; int numberOfUpdatedProfiles = 0; LoopHelper loopHelper = new LoopHelper(100, "student profiles processed."); println("Running data migration for sanitization on student profiles..."); println("Preview: " + isPreview); for (StudentProfileAttributes profile : allStudentProfiles) { loopHelper.recordLoop(); boolean hasAllUnsanitizedFields = !hasAnySanitizedField(profile); if (hasAllUnsanitizedFields) { continue; } numberOfAffectedProfiles++; try { desanitizeAndUpdateProfile(profile); numberOfUpdatedProfiles++; } catch (InvalidParametersException | EntityDoesNotExistException e) { println("Problem sanitizing profile with google id " + profile.googleId); println(e.getMessage()); } } println("Total number of profiles: " + loopHelper.getCount()); println("Number of affected profiles: " + numberOfAffectedProfiles); println("Number of updated profiles: " + numberOfUpdatedProfiles); }
Source:
<code>protected void setup(Binder binder) { Set<String> eventClientTypes = buildConfigObject(BenchmarkRunnerConfig.class).getEventClients(); Sets.SetView<String> unsupportedEventClients = difference(eventClientTypes, supportedEventClientTypes); checkArgument(unsupportedEventClients.isEmpty(), "Unsupported EventClient: %s", unsupportedEventClients); Multibinder<EventClient> eventClientBinder = newSetBinder(binder, EventClient.class); <START> for (Map.Entry<String, Class<? extends EventClient>> entry : DEFAULT_EVENT_CLIENTS.entrySet()) { <END> if (eventClientTypes.contains(entry.getKey())) { eventClientBinder.addBinding().to(entry.getValue()).in(SINGLETON); } } }</code><technical_language>import Map.Entry</technical_language>

Target:
protected void setup(Binder binder) { Set<String> eventClientTypes = buildConfigObject(BenchmarkRunnerConfig.class).getEventClients(); Sets.SetView<String> unsupportedEventClients = difference(eventClientTypes, supportedEventClientTypes); checkArgument(unsupportedEventClients.isEmpty(), "Unsupported EventClient: %s", unsupportedEventClients); Multibinder<EventClient> eventClientBinder = newSetBinder(binder, EventClient.class); for (Entry<String, Class<? extends EventClient>> entry : DEFAULT_EVENT_CLIENTS.entrySet()) { if (eventClientTypes.contains(entry.getKey())) { eventClientBinder.addBinding().to(entry.getValue()).in(SINGLETON); } } }
Source:
<code>private Map<String, DbParameterAccessor> readIntoParams(String[] queryParameters, String query) throws SQLException { PreparedStatement dc = currentConnection.prepareStatement(query); <START> try { <END> for (int i = 0; i < queryParameters.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(queryParameters[i])); } ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); while (rs.next()) { String paramName = rs.getString(1); if (paramName == null) paramName = ""; String dataType = rs.getString(2); String direction = rs.getString(3); int position = rs.getInt(4); Direction paramDirection = getParameterDirection(direction); DbParameterAccessor dbp = new DbParameterAccessor(paramName, paramDirection, getSqlType(dataType), getJavaClass(dataType), paramDirection == RETURN_VALUE ? -1 : position); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; } finally { dc.close(); } }</code><technical_language>Similarly other discussion: cleaner try-with-resources syntax too</technical_language>

Target:
private Map<String, DbParameterAccessor> readIntoParams(String[] queryParameters, String query) throws SQLException { try (PreparedStatement dc = currentConnection.prepareStatement(query)) { for (int i = 0; i < queryParameters.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(queryParameters[i])); } ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); while (rs.next()) { String paramName = defaultIfNull(rs.getString(1), ""); String dataType = rs.getString(2); String direction = rs.getString(3); int position = rs.getInt(4); Direction paramDirection = getParameterDirection(direction); if (paramDirection != RETURN_VALUE && paramName.isEmpty()) { throw new SQLException("Missing column or procedure parameter name"); } DbParameterAccessor dbp = createDbParameterAccessor( paramName, paramDirection, getSqlType(dataType), getJavaClass(dataType), paramDirection == RETURN_VALUE ? -1 : position); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } rs.close(); return allParams; } }
Source:
<code>public void destroy(final String identifier) throws EhcacheEntityNotFoundException, EntityBusyException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier's maintenance lease held"); } boolean finished = false; try { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { if (!ref.destroy()) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier in use by other clients"); } finished = true; } catch (EntityNotProvidedException e) { LOGGER.error("Unable to delete clustered tier manager for id {}", identifier, e); throw new AssertionError(e); } catch (EntityNotFoundException e) { throw new EhcacheEntityNotFoundException(e); } catch (PermanentEntityException e) { <START> LOGGER.error("Unable to destroy entity - server says it is permanent"); <END> throw new AssertionError(e); } } finally { if (localMaintenance != null) { if (finished) { localMaintenance.unlock(); } else { silentlyUnlock(localMaintenance, identifier); } } } }</code><technical_language>exception logged here</technical_language>

Target:
public void destroy(final String identifier) throws EhcacheEntityNotFoundException, EntityBusyException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier's maintenance lease held"); } boolean finished = false; try { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { if (!ref.destroy()) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier in use by other clients"); } finished = true; } catch (EntityNotProvidedException e) { LOGGER.error("Unable to delete clustered tier manager for id {}", identifier, e); throw new AssertionError(e); } catch (EntityNotFoundException e) { throw new EhcacheEntityNotFoundException(e); } catch (PermanentEntityException e) { LOGGER.error("Unable to destroy entity - server says it is permanent", e); throw new AssertionError(e); } } finally { if (localMaintenance != null) { if (finished) { localMaintenance.unlock(); } else { silentlyUnlock(localMaintenance, identifier); } } } }
Source:
<code>public void deleteSuccess() throws Exception { context.turnOffAuthorisationSystem(); MetadataField metadataField = MetadataFieldBuilder.createMetadataField(context, ELEMENT, QUALIFIER, SCOPE_NOTE) <START> .build(); <END> getClient().perform(get("/api/core/metadatafields/" + metadataField.getID())) .andExpect(status().isOk()); getClient(getAuthToken(admin.getEmail(), password)) .perform(delete("/api/core/metadatafields/" + metadataField.getID())) .andExpect(status().isNoContent()); getClient().perform(get("/api/core/metadatafields/" + metadataField.getID())) .andExpect(status().isNotFound()); }</code><technical_language>turn auth system creating test data</technical_language>

Target:
public void deleteSuccess() throws Exception { context.turnOffAuthorisationSystem(); MetadataField metadataField = MetadataFieldBuilder.createMetadataField(context, ELEMENT, QUALIFIER, SCOPE_NOTE) .build(); context.restoreAuthSystemState(); getClient().perform(get("/api/core/metadatafields/" + metadataField.getID())) .andExpect(status().isOk()); getClient(getAuthToken(admin.getEmail(), password)) .perform(delete("/api/core/metadatafields/" + metadataField.getID())) .andExpect(status().isNoContent()); getClient().perform(get("/api/core/metadatafields/" + metadataField.getID())) .andExpect(status().isNotFound()); }
Source:
<code>public void queueLogout(Player player) { if (player.getState() == EntityState.ACTIVE && !logouts.contains(player)) { <START> logouts.offer(player); <END> } }</code><technical_language>add/offer issue</technical_language>

Target:
public void queueLogout(Player player) { if (player.getState() == EntityState.ACTIVE && !logouts.contains(player)) { logouts.add(player); } }
Source:
<code>private NewsIterator(String dataDirectory, WordVectors wordVectors, int batchSize, int truncateLength, boolean train, TokenizerFactory tokenizerFactory) { <START> this.dataDirectory = dataDirectory; <END> this.batchSize = batchSize; this.vectorSize = wordVectors.getWordVector(wordVectors.vocab().wordAtIndex(0)).length; this.wordVectors = wordVectors; this.truncateLength = truncateLength; this.tokenizerFactory = tokenizerFactory; this.populateData(train); this.labels = new ArrayList<String>(); for (int i = 0; i < this.categoryData.size(); i++) { this.labels.add(this.categoryData.get(i).getKey().split(",")[1]); } }</code><technical_language>Try truncate some of constructors. Add a \n break parameters</technical_language>

Target:
private NewsIterator(String dataDirectory, WordVectors wordVectors, int batchSize, int truncateLength, boolean train, TokenizerFactory tokenizerFactory) { this.dataDirectory = dataDirectory; this.batchSize = batchSize; this.vectorSize = wordVectors.getWordVector(wordVectors.vocab().wordAtIndex(0)).length; this.wordVectors = wordVectors; this.truncateLength = truncateLength; this.tokenizerFactory = tokenizerFactory; this.populateData(train); this.labels = new ArrayList<>(); for (int i = 0; i < this.categoryData.size(); i++) { this.labels.add(this.categoryData.get(i).getKey().split(",")[1]); } }
Source:
<code>public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } if (response == null) { urlopen = login(); } try { Matcher matcher; matcher = reBalance.matcher(response); matcher = reBalance.matcher(response); if(matcher.find()) { accounts.add(new Account("Kvar att utnyttja" , Helpers.parseBalance(matcher.group(1)), "1")); balance = balance.add(Helpers.parseBalance(matcher.group(1))); } if(matcher.find()) { accounts.add(new Account("Saldo" , Helpers.parseBalance(matcher.group(1)), "2")); accounts.add(new Account("Saldo" , Helpers.parseBalance(matcher.group(1)).negate(), "4")); } if(matcher.find()) { accounts.add(new Account("Köpgräns" , Helpers.parseBalance(matcher.group(1)), "3")); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } response = urlopen.open("<LINK_0>"); matcher = reTransactions.matcher(response); ArrayList<Transaction> transactions = new ArrayList<Transaction>(); while (matcher.find()) { transactions.add(new Transaction(matcher.group(1).trim(), Html.fromHtml(matcher.group(2)).toString().trim(), Helpers.parseBalance(matcher.group(3)).negate())); } accounts.get(0).setTransactions(transactions); <START> } finally { <END> super.updateComplete(); } }</code><technical_language>remove finally {</technical_language>

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } if (response == null) { urlopen = login(); } Matcher matcher = reBalance.matcher(response); if(matcher.find()) { accounts.add(new Account("Kvar att utnyttja" , Helpers.parseBalance(matcher.group(1)), "1")); balance = balance.add(Helpers.parseBalance(matcher.group(1))); } if(matcher.find()) { accounts.add(new Account("Saldo" , Helpers.parseBalance(matcher.group(1)), "2")); accounts.add(new Account("Saldo" , Helpers.parseBalance(matcher.group(1)).negate(), "4")); } if(matcher.find()) { accounts.add(new Account("Köpgräns" , Helpers.parseBalance(matcher.group(1)), "3")); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } response = urlopen.open("<LINK_0>"); matcher = reTransactions.matcher(response); ArrayList<Transaction> transactions = new ArrayList<Transaction>(); while (matcher.find()) { transactions.add(new Transaction(matcher.group(1).trim(), Html.fromHtml(matcher.group(2)).toString().trim(), Helpers.parseBalance(matcher.group(3)).negate())); } accounts.get(0).setTransactions(transactions); super.updateComplete(); }
Source:
<code>public CorfuServerNode(@Nonnull ServerContext serverContext) { LogUnitServerConfig config = LogUnitServerConfig.parse(serverContext.getServerConfig()); <START> StreamLog streamLog; <END> if (config.isMemoryMode()) { log.warn("Log unit opened in-memory mode (Maximum size={}). " + "This should be run for testing purposes only. " + "If you exceed the maximum size of the unit, old entries will be " + "AUTOMATICALLY trimmed. " + "The unit WILL LOSE ALL DATA if it exits.", Utils .convertToByteStringRepresentation(config.getMaxCacheSize())); streamLog = new InMemoryStreamLog(); } else{ streamLog = new StreamLogFiles(serverContext, config.isNoVerify()); } ImmutableMap<Class, AbstractServer> servers = ImmutableMap.<Class, AbstractServer>builder() .put(BaseServer.class, new BaseServer(serverContext)) .put(SequencerServer.class, new SequencerServer(serverContext)) .put(LayoutServer.class, new LayoutServer(serverContext)) .put(LogUnitServer.class, new LogUnitServer(serverContext, streamLog)) .put(ManagementServer.class, new ManagementServer(serverContext, streamLog)) .build(); this.serverContext = serverContext; this.serverMap = servers; router = new NettyServerRouter(new ArrayList<>(serverMap.values())); this.serverContext.setServerRouter(router); this.close = new AtomicBoolean(false); }</code><technical_language>This a leaky abstraction, leaking streamLogFiles CorfuServerNode. If this needs shared multiple components needs done ServerContext</technical_language>

Target:
public CorfuServerNode(@Nonnull ServerContext serverContext) { this(serverContext, ImmutableMap.<Class, AbstractServer>builder() .put(BaseServer.class, new BaseServer(serverContext)) .put(SequencerServer.class, new SequencerServer(serverContext)) .put(LayoutServer.class, new LayoutServer(serverContext)) .put(LogUnitServer.class, new LogUnitServer(serverContext)) .put(ManagementServer.class, new ManagementServer(serverContext)) .build() ); }
Source:
<code>static Class<? extends Widget> getMobileNativeWidgetClass(Class<? extends Widget> declaredClass, AnnotatedElement annotatedElement, String platform, String automation) { String transformedPlatform = String.valueOf(platform).toUpperCase().trim(); String transformedAutomation = String.valueOf(automation).toUpperCase().trim(); if (ANDROID.equalsIgnoreCase(transformedPlatform) && AutomationName.SELENDROID .equalsIgnoreCase(transformedAutomation)) { return getConvenientClass(declaredClass, annotatedElement, SELENDROID); } if (ANDROID.equalsIgnoreCase(transformedPlatform)) { return getConvenientClass(declaredClass, annotatedElement, ANDROID_UI_AUTOMATOR); } <START> if (IOS.equalsIgnoreCase(transformedPlatform) && AutomationName.IOS_XCUI_TEST <END> .equalsIgnoreCase(transformedAutomation)) { return getConvenientClass(declaredClass, annotatedElement, IOS_XCUIT_AUTOMATION); } if (IOS.equalsIgnoreCase(transformedPlatform)) { return getConvenientClass(declaredClass, annotatedElement, IOS_UI_AUTOMATION); } if (WINDOWS.equalsIgnoreCase(transformedPlatform)) { return getConvenientClass(declaredClass, annotatedElement, WINDOWS_AUTOMATION); } return getDefaultOrHTMLWidgetClass(declaredClass, annotatedElement); }</code><technical_language>added this condition single IOS.equalsIgnoreCase(transformedPlatform) condition. forget fact, conditions order matters here, current implementation</technical_language>

Target:
static Class<? extends Widget> getMobileNativeWidgetClass(Class<? extends Widget> declaredClass, AnnotatedElement annotatedElement, String platform, String automation) { String transformedPlatform = String.valueOf(platform).toUpperCase().trim(); String transformedAutomation = String.valueOf(automation).toUpperCase().trim(); if (ANDROID.equalsIgnoreCase(transformedPlatform)) { if (AutomationName.SELENDROID.equalsIgnoreCase(transformedAutomation)) { return getConvenientClass(declaredClass, annotatedElement, SELENDROID); } return getConvenientClass(declaredClass, annotatedElement, ANDROID_UI_AUTOMATOR); } if (IOS.equalsIgnoreCase(transformedPlatform)) { if (AutomationName.IOS_XCUI_TEST.equalsIgnoreCase(transformedAutomation)) { return getConvenientClass(declaredClass, annotatedElement, IOS_XCUIT_AUTOMATION); } return getConvenientClass(declaredClass, annotatedElement, IOS_UI_AUTOMATION); } if (WINDOWS.equalsIgnoreCase(transformedPlatform)) { return getConvenientClass(declaredClass, annotatedElement, WINDOWS_AUTOMATION); } return getDefaultOrHTMLWidgetClass(declaredClass, annotatedElement); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TreeNode)) { return false; } TreeNode node = (TreeNode) obj; if (docRef.equals(node.docRef)) { return (((position == null) && (node.position == null)) || ((position != null) <START> && position.equals(node.position))); <END> } return false; }</code><technical_language>is a neat method java.util.Objects.equals(a, b) (since Java 7) handles null checks well</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TreeNode)) { return false; } TreeNode node = (TreeNode) obj; return Objects.equal(docRef, node.docRef) && Objects.equal(position, node.position); }
Source:
<code>public WindowedQueryBolt(StreamSelector type, String streamId, String key) { <START> if (type!=StreamSelector.STREAM && type!=StreamSelector.SOURCE) <END> throw new IllegalArgumentException(type.name()); streamSelectorType = type; streamJoinOrder.add(streamId); joinCriteria.put(streamId, new JoinInfo(key) ); }</code><technical_language>This check redundant values for enum supported based code</technical_language>

Target:
public WindowedQueryBolt(StreamSelector type, String streamId, String key) { streamSelectorType = type; joinCriteria.put(streamId, new JoinInfo(key) ); }
Source:
<code>protected void log(Site site, Object... params) { if (!prefs.getBoolean(PrefKeys.getEventLoggingEnabled(), true)) { return; } JSONObject eventData = new JSONObject(); try { Log.d(ANALYTICS_TAG, this.getClass().getSimpleName() + ": Building event to transmit"); for (int i = 0; i < params.length; i += 2) { eventData.put(params[i].toString(), params[i + 1]); <START> Log.d(ANALYTICS_TAG, this.getClass().getSimpleName() + ": event_" + params[i] + " = " + params[i + 1]); <END> } } catch (JSONException e) { throw new RuntimeException(e); } new EventLoggingEvent( schemaName, revision, Utils.getDBNameForSite(site), app.getUserAgent(), preprocessData(eventData) ).log(); }</code><technical_language>of log messages necessary all, "hitting" message in EventLoggingEvent contains of parameters line</technical_language>

Target:
protected void log(Site site, Object... params) { if (!prefs.getBoolean(PrefKeys.getEventLoggingEnabled(), true)) { return; } JSONObject eventData = new JSONObject(); String logString = this.getClass().getSimpleName() + ": Sending event"; try { for (int i = 0; i < params.length; i += 2) { eventData.put(params[i].toString(), params[i + 1]); logString += ", event_" + params[i] + " = " + params[i + 1]; } Log.d(ANALYTICS_TAG, logString); } catch (JSONException e) { throw new RuntimeException(e); } new EventLoggingEvent( schemaName, revision, Utils.getDBNameForSite(site), app.getUserAgent(), preprocessData(eventData) ).log(); }
Source:
<code>public Object getReplacementValue(Object initialValue) { Object replacementValue = ""; if (initialValue != null) { if (initialValue instanceof Cohort) { replacementValue = new Integer(((Cohort) initialValue).size()); } else if (initialValue instanceof IndicatorResult) { <START> replacementValue = new Integer((Integer) ((IndicatorResult) initialValue).getValue()); <END> } else { replacementValue = initialValue; } } return replacementValue; }</code><technical_language>@solemabrothers do for values decimal points in some indicators</technical_language>

Target:
public Object getReplacementValue(Object initialValue) { Object replacementValue = ""; if (initialValue != null) { if (initialValue instanceof Cohort) { replacementValue = new Integer(((Cohort) initialValue).size()); } else if (initialValue instanceof IndicatorResult) { replacementValue = new Double(((IndicatorResult) initialValue).getValue().doubleValue()); } else { replacementValue = initialValue; } } return replacementValue; }
Source:
<code>public void onClickTypeButton(final ClickEvent clickEvent) { <START> dataTypePageNavTab.active(); <END> }</code><technical_language>wondering.... MultiPageEditor void selectPage(final int index);... this raise event show tab DMNDiagramEditor (and SessionDiagramEditorScreen) observe event call kieView.selectPage( index )? problem I is correct index (as for DMNDiagramEditor 2 for SessionDiagramEditorScreen 1).. hard-coded (as I _nice_ of index)... a thought</technical_language>

Target:
public void onClickTypeButton(final ClickEvent clickEvent) { dataTypePageActiveEvent.fire(new DataTypePageTabActiveEvent()); }
Source:
<code>protected BasicDataSource getDatasource() { MetadataStorageConnectorConfig connectorConfig = getConfig(); BasicDataSource dataSource = null; try { Properties dbcpProperties = connectorConfig.getProperties(); if (dbcpProperties != null) { dataSource = BasicDataSourceFactory.createDataSource(dbcpProperties); } else { dataSource = new BasicDataSource(); } } catch (Exception e) { log.error(e, "Failed to create data source using dbcp properties file"); throw new RuntimeException(e); } <START> <END> dataSource.setUsername(connectorConfig.getUser()); dataSource.setPassword(connectorConfig.getPassword()); String uri = connectorConfig.getConnectURI(); dataSource.setUrl(uri); dataSource.setValidationQuery(getValidationQuery()); dataSource.setTestOnBorrow(true); return dataSource; }</code><technical_language>if user provides username, password connectionURL in dbcp config file in runtime properties, values dbcp config file ignored. Is expected behavior</technical_language>

Target:
protected BasicDataSource getDatasource() { MetadataStorageConnectorConfig connectorConfig = getConfig(); BasicDataSource dataSource = null; try { Properties dbcpProperties = connectorConfig.getDbcpProperties(); if (dbcpProperties != null) { dataSource = BasicDataSourceFactory.createDataSource(dbcpProperties); } else { dataSource = new BasicDataSource(); } } catch (Exception e) { throw new RuntimeException(e); } dataSource.setUsername(connectorConfig.getUser()); dataSource.setPassword(connectorConfig.getPassword()); String uri = connectorConfig.getConnectURI(); dataSource.setUrl(uri); dataSource.setValidationQuery(getValidationQuery()); dataSource.setTestOnBorrow(true); return dataSource; }
Source:
<code>public boolean canBeAdded(IPlayer player) { if (player == null) return false; <START> else if (lightTrail) <END> return false; else if (this.player != null) return false; else return true; }</code><technical_language>Getter please? If needed externally, a private one</technical_language>

Target:
public boolean canBeAdded(IPlayer player) { if (player == null) return false; else if (this.hasLightTrail()) return false; else if (this.player != null) return false; else return true; }
Source:
<code>public void testTransformNativeRserveSingleExpressionInPlaceTrue() throws DDFException { Boolean inPlace = Boolean.TRUE; DDF newDdf = ddf.copy(); DDF newDdf2 = newDdf.Transform.transformNativeRserve("newcol = deptime / arrtime", inPlace); List<String> res = newDdf2.VIEWS.head(10); Assert.assertNotNull(newDdf2); <START> Assert.assertNotNull(newDdf); <END> Assert.assertTrue("With inPlace being true, two DDF should have the same UUID", newDdf.getUUID().equals(newDdf2.getUUID())); Assert.assertEquals("newcol", newDdf.getColumnName(8)); Assert.assertEquals(10, res.size()); }</code><technical_language>run this previous one??</technical_language>

Target:
public void testTransformNativeRserveSingleExpressionInPlaceTrue() throws DDFException { Boolean inPlace = Boolean.TRUE; DDF newDdf = ddf.copy(); DDF newDdf2 = newDdf.Transform.transformNativeRserve("newcol = deptime / arrtime", inPlace); List<String> res = newDdf2.VIEWS.head(10); Assert.assertNotNull(newDdf); Assert.assertNotNull(newDdf2); Assert.assertTrue("With inPlace being true, two DDF should have the same UUID", newDdf.getUUID().equals(newDdf2.getUUID())); Assert.assertEquals("With inPlace being true, original DDF should have newcol added", "newcol", newDdf.getColumnName(8)); Assert.assertEquals("transformed DDF newDdf2 should have newcol added", "newcol", newDdf2.getColumnName(8)); Assert.assertEquals(10, res.size()); }
Source:
<code>public DiscreteRangeCondition<E> subCondition(E from, E to) { if (from.compareTo(to) > 0) { throw new IllegalArgumentException(from.toString() + " is greater than " + to.toString()); } <START> return new DiscreteRangeCondition<>(fSet.subSet(from, true, to, true)); <END> }</code><technical_language>.. this subset empty, throw exception. actually. I full branch a kernel memory view trace "bug446190". allow empty sets, require min() max() @Nullable, if subset is empty, return a singleton empty condition. do think</technical_language>

Target:
public @Nullable DiscreteRangeCondition<E> subCondition(E from, E to) { if (from.compareTo(to) > 0) { throw new IllegalArgumentException(from.toString() + " is greater than " + to.toString()); } NavigableSet<@NonNull E> subSet = fSet.subSet(from, true, to, true); if (subSet.isEmpty()) { return null; } return new DiscreteRangeCondition<>(subSet); }
Source:
<code>private String getIndexManagementWaitTimeout(Properties properties) { String timeout = properties.getProperty( ElasticsearchEnvironment.INDEX_MANAGEMENT_WAIT_TIMEOUT ); <START> return timeout != null ? Integer.valueOf( timeout ) + "ms" : DEFAULT_INDEX_MANAGEMENT_WAIT_TIMEOUT; <END> }</code><technical_language>Do need validation, i.e. a positive number a reasonable range</technical_language>

Target:
private String getIndexManagementWaitTimeout(Properties properties) { int timeout = ConfigurationParseHelper.getIntValue( properties, ElasticsearchEnvironment.INDEX_MANAGEMENT_WAIT_TIMEOUT, ElasticsearchEnvironment.Defaults.INDEX_MANAGEMENT_WAIT_TIMEOUT ); if ( timeout < 0 ) { throw new SearchException( "Positive timeout value expected, but it was: " + timeout ); } return timeout + "ms"; }
Source:
<code><START> public boolean registerInterceptor(Object theInterceptor) { <END> synchronized (myRegistryMutex) { boolean retVal = false; for (Object next : myGlobalInterceptors) { if (next == theInterceptor) { return false; } } int typeOrder = DEFAULT_ORDER; Order typeOrderAnnotation = AnnotationUtils.findAnnotation(theInterceptor.getClass(), Order.class); if (typeOrderAnnotation != null) { typeOrder = typeOrderAnnotation.value(); } for (Method nextMethod : theInterceptor.getClass().getDeclaredMethods()) { Hook hook = AnnotationUtils.findAnnotation(nextMethod, Hook.class); if (hook != null) { int methodOrder = typeOrder; Order methodOrderAnnotation = AnnotationUtils.findAnnotation(nextMethod, Order.class); if (methodOrderAnnotation != null) { methodOrder = methodOrderAnnotation.value(); } HookInvoker invoker = new HookInvoker(hook, theInterceptor, nextMethod, methodOrder); for (Pointcut nextPointcut : hook.value()) { myInvokers.put(nextPointcut, invoker); } retVal = true; } } myGlobalInterceptors.add(theInterceptor); sortByOrderAnnotation(myGlobalInterceptors); for (Pointcut nextPointcut : myInvokers.keys()) { List<BaseInvoker> nextInvokerList = myInvokers.get(nextPointcut); nextInvokerList.sort(Comparator.naturalOrder()); } return retVal; } }</code><technical_language>This method is long deeply nested. Consider breaking smaller methods names describe happening</technical_language>

Target:
public boolean registerInterceptor(Object theInterceptor) { synchronized (myRegistryMutex) { if (isInterceptorAlreadyRegistered(theInterceptor)) { return false; } Class<?> interceptorClass = theInterceptor.getClass(); int typeOrder = determineOrder(interceptorClass); if (!scanInterceptorForHookMethodsAndAddThem(theInterceptor, typeOrder)) { return false; } myInterceptors.add(theInterceptor); sortByOrderAnnotation(myInterceptors); for (Pointcut nextPointcut : myInvokers.keys()) { List<BaseInvoker> nextInvokerList = myInvokers.get(nextPointcut); nextInvokerList.sort(Comparator.naturalOrder()); } return true; } }
Source:
<code>public StatementsMatcher(List<Statement> statements) { <START> Collections.copy(statements, unmatched); <END> }</code><technical_language>_Matcher_ reused multiple times - list doesn't</technical_language>

Target:
public StatementsMatcher(List<Statement> statements) { unmatched = new ArrayList<>(); Collections.copy(statements, unmatched); }
Source:
<code>private void removeOldJobs(final Path prefixDirectory) throws ExecutionException, InterruptedException, IOException { final File[] files = prefixDirectory.toFile().listFiles(); if (files == null || files.length == 0) { return; } log.info("Removing old temporary jobs"); final Map<JobId, Job> jobs = client.jobs().get(); for (File file : files) { if (file.getName().endsWith(".tmp") || file.isDirectory()) { continue; } try ( JobPrefixFile prefixFile = JobPrefixFile.tryFromExistingFile(file.toPath()) ) { if (prefixFile == null) { log.debug("Unable to create JobPrefixFile for {}", file.getPath()); continue; } boolean jobRemovalFailed = false; for (Map.Entry<JobId, Job> entry : jobs.entrySet()) { final JobId jobId = entry.getKey(); if (!jobId.getName().startsWith(prefixFile.prefix())) { continue; } final JobStatus status = client.jobStatus(entry.getKey()).get(); final List<String> hosts = ImmutableList.copyOf(status.getDeployments().keySet()); final List<AssertionError> errors = undeploy(client, entry.getValue(), hosts, new ArrayList<AssertionError>()); if (!errors.isEmpty()) { jobRemovalFailed = true; } } if (!jobRemovalFailed) { prefixFile.delete(); } } catch (NoSuchFileException e) { <START> log.info("File already gone. Cool", file.getPath()); <END> } catch (Exception e) { log.warn("Exception processing file {}", file.getPath(), e); } } }</code><technical_language>making this a debug message? match this log message earlier in function, caused a file deleted a test running in parallel. log.debug("Unable create JobPrefixFile for {}", file.getPath());</technical_language>

Target:
private void removeOldJobs(final Path prefixDirectory) throws ExecutionException, InterruptedException, IOException { final File[] files = prefixDirectory.toFile().listFiles(); if (files == null || files.length == 0) { return; } log.info("Removing old temporary jobs"); final Map<JobId, Job> jobs = client.jobs().get(); for (File file : files) { if (file.getName().endsWith(".tmp") || file.isDirectory()) { continue; } try ( JobPrefixFile prefixFile = JobPrefixFile.tryFromExistingFile(file.toPath()) ) { if (prefixFile == null) { log.debug("Unable to create JobPrefixFile for {}", file.getPath()); continue; } boolean jobRemovalFailed = false; for (Map.Entry<JobId, Job> entry : jobs.entrySet()) { final JobId jobId = entry.getKey(); if (!jobId.getName().startsWith(prefixFile.prefix())) { continue; } final JobStatus status = client.jobStatus(entry.getKey()).get(); final List<String> hosts = ImmutableList.copyOf(status.getDeployments().keySet()); final List<AssertionError> errors = undeploy(client, entry.getValue(), hosts, new ArrayList<AssertionError>()); if (!errors.isEmpty()) { jobRemovalFailed = true; } } if (!jobRemovalFailed) { prefixFile.delete(); } } catch (NoSuchFileException e) { log.debug("File already processed by somebody else.", file.getPath()); } catch (Exception e) { log.warn("Exception processing file {}", file.getPath(), e); } } }
Source:
<code>public void testAddValue() { final HTMLOptionElement optionElement = mock(HTMLOptionElement.class); <START> final KieAssetsDropdownItem entry = new KieAssetsDropdownItem("text", "value", new HashMap<String, String>() {{ <END> put("foo", "bar"); }}); doReturn(optionElement).when(view).makeHTMLOptionElement(); view.addValue(entry); assertEquals("text", optionElement.text); assertEquals("value", optionElement.value); verify(optionElement).setAttribute("data-foo", "bar"); verify(nativeSelect).appendChild(optionElement); }</code><technical_language>Please this map initialization: java new Maps.Builder() .put("foo", "bar") .build();</technical_language>

Target:
public void testAddValue() { final HTMLOptionElement optionElement = mock(HTMLOptionElement.class); final KieAssetsDropdownItem entry = new KieAssetsDropdownItem("text", "subtext", "value", getMetaData()); doReturn(optionElement).when(view).makeHTMLOptionElement(); view.addValue(entry); assertEquals("text", optionElement.text); assertEquals("value", optionElement.value); verify(optionElement).setAttribute(SELECT_PICKER_SUBTEXT_ATTRIBUTE, "subtext"); verify(nativeSelect).appendChild(optionElement); }
Source:
<code>public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { Stopwatch stopwatch = Stopwatch.createStarted(); <START> HttpServletRequest httpRequest = (HttpServletRequest)servletRequest; <END> String requestURL = httpRequest.getRequestURI(); String requestMethod = httpRequest.getMethod(); String requestIdHeader = httpRequest.getHeader(HEADER_REQUEST_ID); String requestId = requestIdHeader == null ? "" : requestIdHeader; MDC.put(HEADER_REQUEST_ID, requestId); logger.info("[{}] - to began", requestId, requestMethod, requestURL); try { filterChain.doFilter(servletRequest, servletResponse); } catch (Throwable throwable) { logger.error("[{}] - Exception - {}", requestId, throwable.getMessage(), throwable); } finally { logger.info("[{}] - to ended - total time {}ms", requestId, requestMethod, requestURL, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS)); } }</code><technical_language>Space (HttpServletRequest) servletRequest please</technical_language>

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { Stopwatch stopwatch = Stopwatch.createStarted(); HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; String requestURL = httpRequest.getRequestURI(); String requestMethod = httpRequest.getMethod(); String requestIdHeader = httpRequest.getHeader(HEADER_REQUEST_ID); String requestId = requestIdHeader == null ? "" : requestIdHeader; MDC.put(HEADER_REQUEST_ID, requestId); logger.info("[{}] - to began", requestId, requestMethod, requestURL); try { filterChain.doFilter(servletRequest, servletResponse); } catch (Throwable throwable) { logger.error("[{}] - Exception - {}", requestId, throwable.getMessage(), throwable); } finally { stopwatch.stop(); logger.info("[{}] - to ended - total time {}ms", requestId, requestMethod, requestURL, stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }
Source:
<code>public InputStream getStream() { <START> if (objects == null || objects.isEmpty()) { <END> return null; } final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.objects); final String xmlOutput = XmlOutput.toXml(objects, false); final byte[] stringBytes = xmlOutput.getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }</code><technical_language>I added a guard class sdk do this exact check</technical_language>

Target:
public InputStream getStream() { if (Guard.isNullOrEmpty(objects)) { return null; } final Ds3ObjectList objects = new Ds3ObjectList(); objects.setObjects(this.objects); final String xmlOutput = XmlOutput.toXml(objects, false); final byte[] stringBytes = xmlOutput.getBytes(); this.size = stringBytes.length; return new ByteArrayInputStream(stringBytes); }
Source:
<code>void isoOffsetTimeFormat() { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().timeFormat("isooffset")); <START> OffsetDateTime offsetdate =OffsetDateTime.of(LocalDate.of(2020, 4, 26), LocalTime.of(12, 45, 23), ZoneOffset.ofHoursMinutes(1, 30)); <END> assertThat(conversionService.convert(offsetdate, String.class)) .isEqualTo(DateTimeFormatter.ISO_OFFSET_TIME.format(offsetdate)); }</code><technical_language>close. Thank you. This needs OffsetTime OffsetDateTime: java OffsetTime offsetdate = OffsetTime.of(LocalTime.of(12, 45, 23), ZoneOffset.ofHoursMinutes(1, 30)); this change in place I test pass</technical_language>

Target:
void isoOffsetTimeFormat() { WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().timeFormat("isooffset")); OffsetTime offsetTime =OffsetTime.of(LocalTime.of(12, 45, 23), ZoneOffset.ofHoursMinutes(1, 30)); assertThat(conversionService.convert(offsetTime, String.class)) .isEqualTo(DateTimeFormatter.ISO_OFFSET_TIME.format(offsetTime)); }
Source:
<code>public void testRenamedFiles() throws Exception { String[][] tests = new String[][]{ <START> {"moved/renamed2.c", "67dfbe26", "moved/renamed2.c"}, <END> {"moved/renamed2.c", "1086eaf5", "moved/renamed.c"}, {"moved/renamed2.c", "b6413947", "moved/renamed.c"}, {"moved/renamed2.c", "ce4c98ec", "renamed.c"}, {"moved/renamed2.c", "bb74b7e8", "renamed.c"},}; setUpTestRepository(); File root = new File(repository.getSourceRoot(), "git"); GitRepository gitrepo = (GitRepository) RepositoryFactory.getRepository(root); int i = 0; for (String[] test : tests) { String file = root.getAbsolutePath() + File.separator + test[0]; String changeset = test[1]; String expected = root.getAbsolutePath() + File.separator + test[2]; try { Assert.assertEquals(expected, gitrepo.findOriginalName(file, changeset)); } catch (IOException ex) { Assert.fail(String.format("Looking for original name of in shouldn't fail", file, changeset)); } i++; } }</code><technical_language>testing renames distinct directories</technical_language>

Target:
public void testRenamedFiles() throws Exception { String[][] tests = new String[][]{ {"moved2/renamed2.c", "84599b3c", "moved2/renamed2.c"}, {"moved2/renamed2.c", "67dfbe26", "moved/renamed2.c"}, {"moved2/renamed2.c", "67dfbe26", "moved/renamed2.c"}, {"moved2/renamed2.c", "1086eaf5", "moved/renamed.c"}, {"moved2/renamed2.c", "b6413947", "moved/renamed.c"}, {"moved2/renamed2.c", "ce4c98ec", "renamed.c"}, {"moved2/renamed2.c", "bb74b7e8", "renamed.c"} }; setUpTestRepository(); File root = new File(repository.getSourceRoot(), "git"); GitRepository gitrepo = (GitRepository) RepositoryFactory.getRepository(root); int i = 0; for (String[] test : tests) { String file = root.getAbsolutePath() + File.separator + test[0]; String changeset = test[1]; String expected = root.getAbsolutePath() + File.separator + test[2]; try { Assert.assertEquals(expected, gitrepo.findOriginalName(file, changeset)); } catch (IOException ex) { Assert.fail(String.format("Looking for original name of in shouldn't fail", file, changeset)); } i++; } }
Source:
<code>public boolean configure() throws TargetException { try { if( this.vmwareServiceInstance == null ) this.vmwareServiceInstance = VmwareIaasHandler.getServiceInstance( this.targetProperties ); VirtualMachine vm = VmwareIaasHandler.getVirtualMachine( this.vmwareServiceInstance, this.rootInstanceName ); if( vm == null ) { this.logger.warning( "No VM named '" + this.rootInstanceName + "' could be found. The VM might not yet be ready." ); return false; } GuestOperationsManager gom = this.vmwareServiceInstance.getGuestOperationsManager(); NamePasswordAuthentication npa = new NamePasswordAuthentication(); npa.username = this.targetProperties.get( VmwareIaasHandler.VM_USER ); npa.password = this.targetProperties.get( VmwareIaasHandler.VM_PASSWORD ); GuestProgramSpec spec = new GuestProgramSpec(); spec.programPath = "/bin/echo"; spec.arguments = "$\'" + this.userData + "\' > /tmp/roboconf.properties"; this.logger.fine(spec.programPath + " " + spec.arguments); GuestProcessManager gpm = gom.getProcessManager( vm ); gpm.startProgramInGuest(npa, spec); return true; } catch( Exception e ) { if(++ this.vmwareToolsCheckCount < 20) { this.logger.fine("VMWare tools not yet started... check #" + this.vmwareToolsCheckCount + " failed"); return false; } <START> else throw new TargetException( e ); <END> } }</code><technical_language>"else" is useless here</technical_language>

Target:
public boolean configure() throws TargetException { try { if( this.vmwareServiceInstance == null ) this.vmwareServiceInstance = VmwareIaasHandler.getServiceInstance( this.targetProperties ); VirtualMachine vm = VmwareIaasHandler.getVirtualMachine( this.vmwareServiceInstance, this.rootInstanceName ); if( vm == null ) { this.logger.warning( "No VM named '" + this.rootInstanceName + "' could be found. The VM might not yet be ready." ); return false; } GuestOperationsManager gom = this.vmwareServiceInstance.getGuestOperationsManager(); NamePasswordAuthentication npa = new NamePasswordAuthentication(); npa.username = this.targetProperties.get( VmwareIaasHandler.VM_USER ); npa.password = this.targetProperties.get( VmwareIaasHandler.VM_PASSWORD ); GuestProgramSpec spec = new GuestProgramSpec(); spec.programPath = "/bin/echo"; spec.arguments = "$\'" + this.userData + "\' > /tmp/roboconf.properties"; this.logger.fine(spec.programPath + " " + spec.arguments); GuestProcessManager gpm = gom.getProcessManager( vm ); gpm.startProgramInGuest(npa, spec); return true; } catch( Exception e ) { if(++ this.vmwareToolsCheckCount < 20) { this.logger.fine("VMWare tools not yet started... check #" + this.vmwareToolsCheckCount + " failed"); return false; } throw new TargetException( e ); } }
Source:
<code>public void setContentType(String contentType) { <START> Assert.notNull(contentType, "'contentType' cannot be null"); <END> this.contentType = contentType; }</code><technical_language>contentType empty String</technical_language>

Target:
public void setContentType(String contentType) { Assert.notNull(contentType, "'contentType' cannot be null"); try { MimeType.valueOf(contentType); } catch (InvalidMimeTypeException e) { throw new IllegalArgumentException("'contentType' could not be parsed", e); } this.contentType = contentType; }
Source:
<code>public static String removeHTMLTags(@NonNull String text) { return <START> Jsoup.parse(text).text(); <END> }</code><technical_language>This done more efficiently (and jsoup) returning fromHtml(text).toString()</technical_language>

Target:
public static String removeHTMLTags(@NonNull String text) { return fromHtml(text).toString(); }
Source:
<code>public QResyncParameter(final long uidValidity, final long modSeq, @Nullable final MessageNumberSet[] knownUids, @Nullable final QResyncSeqMatchData seqMatchData) { this.uidValidity = uidValidity; this.modSeq = modSeq; <START> if (knownUids != null) { <END> this.knownUids = knownUids; } this.seqMatchData = seqMatchData; }</code><technical_language>is difference if statement</technical_language>

Target:
public QResyncParameter(final long uidValidity, final long modSeq, @Nullable final MessageNumberSet[] knownUids, @Nullable final QResyncSeqMatchData seqMatchData) { this.uidValidity = uidValidity; this.modSeq = modSeq; this.knownUids = knownUids; this.seqMatchData = seqMatchData; }