auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static <T> CompletionStage<T> onExecutor(CompletionStage<T> future, Executor executor) { if (executor == null) { return future; } <START> return future.thenApplyAsync(Function.identity(), executor); <END> }</code><technical_language>Docs a quick empirical test executor supplied thenApplyAsync is for exceptions. handleAsync method normal values exceptions run supplied executor. E.g. java return future.handleAsync((v, e) -> { if (v != null) { return v; } else { throw new CompletionException(e); } }, executor);</technical_language>

Target:
private static <T> CompletionStage<T> onExecutor(CompletionStage<T> future, Executor executor) { if (executor == null) { return future; } return future.whenCompleteAsync((result, t) -> { }, executor); }
Source:
<code>public static void init() { <START> EsteemedInnovation.logger.info("[EI] Getting some fields through reflection."); <END> lastBuyingPlayerField = getField("lastBuyingPlayer", "field_82189_bL", EntityVillager.class); timeUntilResetField = getField("timeUntilReset", "field_70961_j", EntityVillager.class); buyingListField = getField("buyingList", "field_70963_i", EntityVillager.class); isJumpingField = getField("isJumping", "field_70703_bu", EntityLivingBase.class); createStackedBlockMethod = getMethod("getSilkTouchDrop", "func_180643_i", Block.class, IBlockState.class); setAccessible(lastBuyingPlayerField); setAccessible(timeUntilResetField); setAccessible(buyingListField); setAccessible(isJumpingField); setAccessible(createStackedBlockMethod); try { merchantField = getField("merchant", "field_147037_w", GuiMerchant.class); setAccessible(merchantField); } catch (NoClassDefFoundError ignore) { EsteemedInnovation.logger.warn("[EI] GuiMerchant class not found. You are probably a server."); } }</code><technical_language>[EI] removed this, [esteemedinnovation] in log entry</technical_language>

Target:
public static void init() { EsteemedInnovation.logger.info("Getting some fields through reflection."); lastBuyingPlayerField = getField("lastBuyingPlayer", "field_82189_bL", EntityVillager.class); timeUntilResetField = getField("timeUntilReset", "field_70961_j", EntityVillager.class); buyingListField = getField("buyingList", "field_70963_i", EntityVillager.class); isJumpingField = getField("isJumping", "field_70703_bu", EntityLivingBase.class); createStackedBlockMethod = getMethod("getSilkTouchDrop", "func_180643_i", Block.class, IBlockState.class); setAccessible(lastBuyingPlayerField); setAccessible(timeUntilResetField); setAccessible(buyingListField); setAccessible(isJumpingField); setAccessible(createStackedBlockMethod); try { merchantField = getField("merchant", "field_147037_w", GuiMerchant.class); setAccessible(merchantField); } catch (NoClassDefFoundError ignore) { EsteemedInnovation.logger.warn("GuiMerchant class not found. You are probably a server."); } }
Source:
<code>protected void addProvider(Provider<E> provider) { final Collection<E> elementsOfAddedProvider = provider.getAll(); final Collection<E> elementsAdded = new HashSet<>(elementsOfAddedProvider.size()); elementWriteLock.lock(); try { if (providerToElements.get(provider) != null) { <START> logger.warn("Cannot add provider because it already exists."); <END> return; } provider.addProviderChangeListener(this); final HashSet<E> providerElements = new HashSet<>(); providerToElements.put(provider, providerElements); for (E element : elementsOfAddedProvider) { if (added(provider, element, providerElements)) { elementsAdded.add(element); } } } finally { elementWriteLock.unlock(); } elementsAdded.forEach(this::notifyListenersAboutAddedElement); logger.debug("Provider '{}' has been added.", provider.getClass().getName()); }</code><technical_language>suggestion logger.warn("Cannot add provider '{}' exists.", provider.getClass().getSimpleName());</technical_language>

Target:
protected void addProvider(Provider<E> provider) { final Collection<E> elementsOfAddedProvider = provider.getAll(); final Collection<E> elementsAdded = new HashSet<>(elementsOfAddedProvider.size()); elementWriteLock.lock(); try { if (providerToElements.get(provider) != null) { logger.warn("Cannot add provider \"{}\" because it already exists.", provider.getClass().getSimpleName()); return; } provider.addProviderChangeListener(this); final HashSet<E> providerElements = new HashSet<>(); providerToElements.put(provider, providerElements); for (E element : elementsOfAddedProvider) { if (added(provider, element, providerElements)) { elementsAdded.add(element); } } } finally { elementWriteLock.unlock(); } elementsAdded.forEach(this::notifyListenersAboutAddedElement); logger.debug("Provider \"{}\" has been added.", provider.getClass().getName()); }
Source:
<code>public void close() throws IOException { for ( IndexAccessor accessor : accessors.values() ) { accessor.close(); } accessors.clear(); <START> onlineIndexRules.clear(); <END> }</code><technical_language>if do clear need clear notOnlineIndexRules</technical_language>

Target:
public void close() throws IOException { for ( IndexAccessor accessor : accessors.values() ) { accessor.close(); } accessors.clear(); onlineIndexRules.clear(); notOnlineIndexRules.clear(); }
Source:
<code>public SolrRecordWriter(TaskAttemptContext context) { conf = context.getConfiguration(); <START> config = new SolrSearchSinkConfig(null, conf.get(SERVER_MODE), conf.get(SERVER_URL), conf.get(COLLECTION_NAME), <END> conf.get(KEY_FIELD), conf.get(FIELD_MAPPINGS)); solrClient = config.getSolrConnection(); }</code><technical_language>referenceName is null ? this issue @albertshau ? is issue reference name config</technical_language>

Target:
public SolrRecordWriter(TaskAttemptContext context) { conf = context.getConfiguration(); config = new SolrSearchSinkConfig(null, conf.get(SERVER_MODE), conf.get(SERVER_URL), conf.get(COLLECTION_NAME), conf.get(KEY_FIELD), conf.get(FIELD_MAPPINGS)); solrClient = config.getSolrConnection(); batchSize = Integer.parseInt(conf.get(BATCH_SIZE)); if (outputFieldMap == null) { outputFieldMap = config.createOutputFieldMap(); } }
Source:
<code>public void getNameWhenTokenHasUsernameThenReturnsUsernameAttribute() { OAuth2IntrospectionAuthenticationToken authenticated = new OAuth2IntrospectionAuthenticationToken(this.token, this.attributes, Collections.emptyList()); <START> assertThat(authenticated.getName()).isEqualTo(this.attributes.getAttributes().get(SUBJECT)); <END> }</code><technical_language>I call this.attributes.getAttribute(SUBJECT), right</technical_language>

Target:
public void getNameWhenTokenHasUsernameThenReturnsUsernameAttribute() { OAuth2IntrospectionAuthenticationToken authenticated = new OAuth2IntrospectionAuthenticationToken(this.token, this.attributes, Collections.emptyList()); assertThat(authenticated.getName()).isEqualTo(this.attributes.getAttribute(SUBJECT)); }
Source:
<code>public static LocationListener createLocationListener(final ILinkHandler handler) { return new LocationAdapter() { @Override public void changing(LocationEvent event) { String loc= event.location; if ("about:blank".equals(loc)) { handler.handleTextSet(); return; } event.doit= false; if (loc.startsWith("about:")) { return; } URI uri= null; try { uri= new URI(loc); } catch (URISyntaxException e) { JavaPlugin.log(e); } String scheme= uri == null ? null : uri.getScheme(); <START> if (null == scheme) { <END> try { if (handler.handleExternalLink(new URL(loc), event.display)) return; event.doit= true; } catch (MalformedURLException e) { JavaPlugin.log(e); } } else switch (scheme) { case JavaElementLinks.JAVADOC_VIEW_SCHEME: { IJavaElement linkTarget= JavaElementLinks.parseURI(uri); if (linkTarget == null) return; handler.handleJavadocViewLink(linkTarget); break; } case JavaElementLinks.JAVADOC_SCHEME: { IJavaElement linkTarget= JavaElementLinks.parseURI(uri); if (linkTarget == null) return; handler.handleInlineJavadocLink(linkTarget); break; } case JavaElementLinks.OPEN_LINK_SCHEME: { IJavaElement linkTarget= JavaElementLinks.parseURI(uri); if (linkTarget == null) return; handler.handleDeclarationLink(linkTarget); break; } default: try { if (handler.handleExternalLink(new URL(loc), event.display)) return; event.doit= true; } catch (MalformedURLException e) { JavaPlugin.log(e); } break; } } }; }</code><technical_language>code boolean nomatch= false; if (scheme != null) switch(xxxx) { ... default: nomatch= true; break; } if (nomatch) { try { if (handler...... This template applied a other places previously well. This prevents perform duplicate code maintenance null condition default case</technical_language>

Target:
public static LocationListener createLocationListener(final ILinkHandler handler) { return new LocationAdapter() { @Override public void changing(LocationEvent event) { String loc= event.location; if ("about:blank".equals(loc)) { handler.handleTextSet(); return; } event.doit= false; if (loc.startsWith("about:")) { return; } URI uri= null; try { uri= new URI(loc); } catch (URISyntaxException e) { JavaPlugin.log(e); } String scheme= uri == null ? null : uri.getScheme(); boolean nomatch= false; if (scheme != null) switch (scheme) { case JavaElementLinks.JAVADOC_VIEW_SCHEME: { IJavaElement linkTarget= JavaElementLinks.parseURI(uri); if (linkTarget == null) return; handler.handleJavadocViewLink(linkTarget); break; } case JavaElementLinks.JAVADOC_SCHEME: { IJavaElement linkTarget= JavaElementLinks.parseURI(uri); if (linkTarget == null) return; handler.handleInlineJavadocLink(linkTarget); break; } case JavaElementLinks.OPEN_LINK_SCHEME: { IJavaElement linkTarget= JavaElementLinks.parseURI(uri); if (linkTarget == null) return; handler.handleDeclarationLink(linkTarget); break; } default: nomatch= true; break; } if (nomatch) { try { if (handler.handleExternalLink(new URL(loc), event.display)) return; event.doit= true; } catch (MalformedURLException e) { JavaPlugin.log(e); } } } }; }
Source:
<code>public synchronized void renameRSGroup(String oldName, String newName) throws IOException { if (oldName.equals(RSGroupInfo.DEFAULT_GROUP)) { throw new ConstraintException(RSGroupInfo.DEFAULT_GROUP + " can't be rename"); } checkGroupName(newName); RSGroupInfo oldRSG = getRSGroupInfo(oldName); Map<String, RSGroupInfo> rsGroupMap = holder.groupName2Group; Map<String, RSGroupInfo> newGroupMap = Maps.newHashMap(rsGroupMap); newGroupMap.remove(oldRSG.getName()); RSGroupInfo newRSG = new RSGroupInfo(newName, oldRSG.getServers()); <START> newGroupMap.put(newRSG.getName(), newRSG); <END> flushConfig(newGroupMap); TableDescriptors tableDescriptors = masterServices.getTableDescriptors(); Set<TableName> updateTables = new HashSet<>(); for (Map.Entry<String, TableDescriptor> table : tableDescriptors.getAll().entrySet()) { Optional<String> rsgroup = table.getValue().getRegionServerGroup(); if (!rsgroup.isPresent()) { continue; } if (rsgroup.get().equals(oldName)) { updateTables.add(table.getValue().getTableName()); } } setRSGroup(updateTables, newName); }</code><technical_language>nit: simplify newGroupMap.put(newName, newRSG);</technical_language>

Target:
public synchronized void renameRSGroup(String oldName, String newName) throws IOException { if (oldName.equals(RSGroupInfo.DEFAULT_GROUP)) { throw new ConstraintException(RSGroupInfo.DEFAULT_GROUP + " can't be rename"); } checkGroupName(newName); RSGroupInfo oldRSG = getRSGroupInfo(oldName); Map<String, RSGroupInfo> rsGroupMap = holder.groupName2Group; Map<String, RSGroupInfo> newGroupMap = Maps.newHashMap(rsGroupMap); newGroupMap.remove(oldRSG.getName()); RSGroupInfo newRSG = new RSGroupInfo(newName, oldRSG.getServers()); newGroupMap.put(newName, newRSG); flushConfig(newGroupMap); Set<TableName> updateTables = masterServices.getTableDescriptors().getAll().values() .stream() .filter(t -> oldName.equals(t.getRegionServerGroup().orElse(null))) .map(TableDescriptor::getTableName) .collect(Collectors.toSet()); setRSGroup(updateTables, newName); }
Source:
<code>public boolean isBackwardCompatibleWith(Schema oldSchema) { for (Map.Entry<String, FieldSpec> entry : oldSchema.getFieldSpecMap().entrySet()) { <START> if (!getColumnNames().contains(entry.getKey())) { <END> return false; } if (!getFieldSpecFor(entry.getKey()).equals(entry.getValue())) { return false; } } return true; }</code><technical_language>Move getColumnNames() out of loop</technical_language>

Target:
public boolean isBackwardCompatibleWith(Schema oldSchema) { Set<String> columnNames = getColumnNames(); for (Map.Entry<String, FieldSpec> entry : oldSchema.getFieldSpecMap().entrySet()) { String oldSchemaColumnName = entry.getKey(); if (!columnNames.contains(oldSchemaColumnName)) { return false; } FieldSpec oldSchemaFieldSpec = entry.getValue(); FieldSpec fieldSpec = getFieldSpecFor(oldSchemaColumnName); if (!fieldSpec.equals(oldSchemaFieldSpec)) { return false; } } return true; }
Source:
<code>private static String getProcessPiece() { Integer pid = null; String pidProperty = System.getProperty(PID_SYSTEM_PROPERTY); if (pidProperty != null) { try { pid = Integer.parseInt(pidProperty); <START> LOGGER.debug("PID obtained from System property {}: {}", PID_SYSTEM_PROPERTY, pid); <END> } catch (NumberFormatException e) { LOGGER.warn("Incorrect integer specified for PID in System property {}: {}", PID_SYSTEM_PROPERTY, pidProperty); } } if (pid == null && Native.isGetpidAvailable()) { try { pid = Native.processId(); LOGGER.debug("PID obtained through native call to getpid(): {}", pid); } catch (Exception e) { LOGGER.warn("Call to getpid() failed", e); } } if (pid == null) { try { String pidJmx = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; pid = Integer.parseInt(pidJmx); LOGGER.debug("PID obtained through JMX: {}", pid); } catch (Exception e) { LOGGER.warn("Failed to obtain PID from JMX", e); } } if (pid == null) { pid = new java.util.Random().nextInt(); LOGGER.warn("Could not determine PID, falling back to a random integer: {}", pid); } ClassLoader loader = UUIDs.class.getClassLoader(); int loaderId = loader != null ? System.identityHashCode(loader) : 0; return Integer.toHexString(pid) + Integer.toHexString(loaderId); }</code><technical_language>I log level INFO, lines 155 164</technical_language>

Target:
private static String getProcessPiece() { Integer pid = null; String pidProperty = System.getProperty(PID_SYSTEM_PROPERTY); if (pidProperty != null) { try { pid = Integer.parseInt(pidProperty); LOGGER.info("PID obtained from System property {}: {}", PID_SYSTEM_PROPERTY, pid); } catch (NumberFormatException e) { LOGGER.warn("Incorrect integer specified for PID in System property {}: {}", PID_SYSTEM_PROPERTY, pidProperty); } } if (pid == null && Native.isGetpidAvailable()) { try { pid = Native.processId(); LOGGER.info("PID obtained through native call to getpid(): {}", pid); } catch (Exception e) { LOGGER.warn("Native call to getpid() failed", e); } } if (pid == null) { try { String pidJmx = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; pid = Integer.parseInt(pidJmx); LOGGER.info("PID obtained through JMX: {}", pid); } catch (Exception e) { LOGGER.warn("Failed to obtain PID from JMX", e); } } if (pid == null) { pid = new java.util.Random().nextInt(); LOGGER.warn("Could not determine PID, falling back to a random integer: {}", pid); } ClassLoader loader = UUIDs.class.getClassLoader(); int loaderId = loader != null ? System.identityHashCode(loader) : 0; return Integer.toHexString(pid) + Integer.toHexString(loaderId); }
Source:
<code>public XGyro getGyro(ImuType imuType) { try { <START> if (imuType == ImuType.nav6) { <END> return new Nav6Gyro(); } if (imuType == ImuType.navX) { return new InertialMeasurementUnitAdapter(Port.kMXP); } else { log.error("Could not find " + imuType.name() + "! Returning a \"broken\" MockGyro instead."); return getBrokenGyro(); } } catch (Exception e) { log.error("Could not create gyro! Returning a \"broken\" MockGyro instead."); return getBrokenGyro(); } }</code><technical_language>A cleaner a case statement maybe? if want if's, subsequent else ifs explicit</technical_language>

Target:
public XGyro getGyro(ImuType imuType) { try { switch (imuType) { case nav6: return new Nav6Gyro(); case navX: return new InertialMeasurementUnitAdapter(Port.kMXP); default: log.error("Could not find " + imuType.name() + "! Returning a \"broken\" MockGyro instead."); return getBrokenGyro(); } } catch (Exception e) { log.error("Could not create gyro! Returning a \"broken\" MockGyro instead."); return getBrokenGyro(); } }
Source:
<code>public void testUpdateSettingsWithStringValue() throws Exception { <START> Map<Symbol, List<Symbol>> settings = new HashMap<>() {{ <END> put(Literal.of("cluster.graceful_stop.min_availability"), ImmutableList.of(Literal.of("full"))); }}; Settings expected = Settings.builder() .put("cluster.graceful_stop.min_availability", "full") .build(); assertThat(buildSettingsFrom(settings, symbolEvaluator(Row.EMPTY)), is(expected)); }</code><technical_language>avoid this double-brace initialization, factory static methods</technical_language>

Target:
public void testUpdateSettingsWithStringValue() throws Exception { List<Assignment<Symbol>> settings = List.of( new Assignment<>(Literal.of("cluster.graceful_stop.min_availability"), List.of(Literal.of("full")))); Settings expected = Settings.builder() .put("cluster.graceful_stop.min_availability", "full") .build(); assertThat(buildSettingsFrom(settings, symbolEvaluator(Row.EMPTY)), is(expected)); }
Source:
<code>private Collection<Contributor> extractContributors(final ConfigGroup configGroup) { final List<Contributor> contributors = new ArrayList<>(); boolean oldConfigGroup = false; final String oldOwner = configGroup.getConfigItemValue("owner"); if (oldOwner != null) { oldConfigGroup = true; contributors.add(new Contributor(oldOwner, ContributorType.OWNER)); } <START> ConfigItem<List<String>> oldContributors = configGroup.getConfigItem("contributors"); <END> if (oldContributors != null) { oldConfigGroup = true; for (String userName : oldContributors.getValue()) { if (!userName.equals(oldOwner)) { contributors.add(new Contributor(userName, ContributorType.CONTRIBUTOR)); } } } if (!oldConfigGroup) { ConfigItem<List<Contributor>> newContributorsConfigItem = configGroup.getConfigItem("space-contributors"); contributors.addAll(newContributorsConfigItem.getValue()); } return contributors; }</code><technical_language>"contributors"</technical_language>

Target:
private Collection<Contributor> extractContributors(final ConfigGroup configGroup) { final List<Contributor> contributors = new ArrayList<>(); boolean oldConfigGroup = false; final String oldOwner = configGroup.getConfigItemValue(OWNER); if (oldOwner != null) { oldConfigGroup = true; contributors.add(new Contributor(oldOwner, ContributorType.OWNER)); } ConfigItem<List<String>> oldContributors = configGroup.getConfigItem(CONTRIBUTORS); if (oldContributors != null) { oldConfigGroup = true; for (String userName : oldContributors.getValue()) { if (!userName.equals(oldOwner)) { contributors.add(new Contributor(userName, ContributorType.CONTRIBUTOR)); } } } if (!oldConfigGroup) { ConfigItem<List<Contributor>> newContributorsConfigItem = configGroup.getConfigItem(SPACE_CONTRIBUTORS); contributors.addAll(newContributorsConfigItem.getValue()); } return contributors; }
Source:
<code>public Node getNode() { Label label = new Label((canDisplayFullName ? getFullName() : getShortName())); label.getStyleClass().add("labels"); if (isRemoved) label.getStyleClass().add("labels-removed"); String style = getStyle() + (isHighlighted ? " -fx-border-color: black; -fx-border-width: 2px;" : ""); style += (isFaded ? " -fx-opacity: 40%;" : ""); <START> label.setStyle(style); <END> label.setText(label.getText() + (!canDisplayFullName && isSelected ? " ✓" : "")); FontLoader fontLoader = Toolkit.getToolkit().getFontLoader(); double width = fontLoader.computeStringWidth(label.getText(), label.getFont()); label.setPrefWidth(width + 30); if (isInGroup()) { Tooltip groupTooltip = new Tooltip(getGroupName()); label.setTooltip(groupTooltip); } setupEvents(label); return label; }</code><technical_language>This style part extracted another method</technical_language>

Target:
public Node getNode() { Label label = new Label((canDisplayFullName ? getFullName() : getShortName())); setLabelStyle(label); label.setText(label.getText() + (!canDisplayFullName && isSelected ? " ✓" : "")); FontLoader fontLoader = Toolkit.getToolkit().getFontLoader(); double width = fontLoader.computeStringWidth(label.getText(), label.getFont()); label.setPrefWidth(width + 30); if (isInGroup()) { Tooltip groupTooltip = new Tooltip(getGroupName()); label.setTooltip(groupTooltip); } setupEvents(label); return label; }
Source:
<code>private void chooseCamera() { if(_mCameraId == null){ for (int i = 0, count = Camera.getNumberOfCameras(); i < count; i++) { Camera.getCameraInfo(i, mCameraInfo); if (mCameraInfo.facing == mFacing) { mCameraId = i; return; } } <START> mCameraId = 0; END> } else{ try{ mCameraId = Integer.parseInt(_mCameraId); Camera.getCameraInfo(mCameraId, mCameraInfo); } catch(Exception e){ mCameraId = INVALID_CAMERA_ID; } } }</code><technical_language>hard find a device cameras happen throw? user get this error ErrorBoundary? 0 is camera? break current behavior</technical_language>

Target:
private void chooseCamera() { if(_mCameraId == null){ int count = Camera.getNumberOfCameras(); if(count == 0){ throw new RuntimeException("No camera available."); } for (int i = 0; i < count; i++) { Camera.getCameraInfo(i, mCameraInfo); if (mCameraInfo.facing == mFacing) { mCameraId = i; return; } } mCameraId = 0; Camera.getCameraInfo(mCameraId, mCameraInfo); } else{ try{ mCameraId = Integer.parseInt(_mCameraId); Camera.getCameraInfo(mCameraId, mCameraInfo); } catch(Exception e){ mCameraId = INVALID_CAMERA_ID; } } }
Source:
<code>private AlertExecution findOrCreateAlertExecution( final UUID jobId, final Organization organization, final Instant scheduled ) { final Optional<models.ebean.Organization> org = models.ebean.Organization.findByOrganization(_ebeanServer, organization); if (!org.isPresent()) { final String message = String.format( "Could not find org with organization.uuid=%s", organization.getId() ); throw new EntityNotFoundException(message); } final Optional<AlertExecution> existingExecution = org.flatMap(r -> _ebeanServer.createQuery(AlertExecution.class) .where() .eq("organization", org.get()) .eq("scheduled", scheduled) .findOneOrEmpty() ); <START> final AlertExecution newOrUpdatedExecution = existingExecution.orElse(new AlertExecution()); <END> newOrUpdatedExecution.setAlertId(jobId); newOrUpdatedExecution.setOrganization(org.get()); newOrUpdatedExecution.setScheduled(scheduled); return newOrUpdatedExecution; }</code><technical_language>nit: orElseGet pass a reference default constructor avoid creating new instance, if need it</technical_language>

Target:
private AlertExecution findOrCreateAlertExecution( final UUID jobId, final Organization organization, final Instant scheduled ) { final Optional<models.ebean.Organization> org = models.ebean.Organization.findByOrganization(_ebeanServer, organization); if (!org.isPresent()) { final String message = String.format( "Could not find org with organization.uuid=%s", organization.getId() ); throw new EntityNotFoundException(message); } final Optional<AlertExecution> existingExecution = org.flatMap(r -> _ebeanServer.createQuery(AlertExecution.class) .where() .eq("organization.uuid", org.get().getUuid()) .eq("scheduled", scheduled) .findOneOrEmpty() ); final AlertExecution newOrUpdatedExecution = existingExecution.orElseGet(AlertExecution::new); newOrUpdatedExecution.setAlertId(jobId); newOrUpdatedExecution.setOrganization(org.get()); newOrUpdatedExecution.setScheduled(scheduled); return newOrUpdatedExecution; }
Source:
<code>private void execute(LdapProviderType ldapProviderType, String domain) { Hashtable<String, String> env = new Hashtable<String, String>(); int timeLimit = Config.<Integer> GetValue(ConfigValues.LDAPQueryTimeout) * 1000; env.put("com.sun.jndi.ldap.connect.timeout", Long.toString(timeLimit)); <START> initContextVariables(env); <END> Attributes results = null; DirContext ctx = null; try { ctx = createContext(env); LdapQueryData ldapQueryData = new LdapQueryDataImpl(); ldapQueryData.setLdapQueryType(LdapQueryType.rootDSE); ldapQueryData.setDomain(domain); LdapQueryExecution queryExecution = LdapQueryExecutionBuilderImpl.getInstance().build(ldapProviderType, ldapQueryData); SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(queryExecution.getReturningAttributes()); searchControls.setSearchScope(queryExecution.getSearchScope()); searchControls.setReturningObjFlag(true); searchControls.setTimeLimit(timeLimit); NamingEnumeration<SearchResult> search = ctx.search(queryExecution.getBaseDN(), queryExecution.getFilter(), searchControls); try { results = search.next().getAttributes(); } finally { search.close(); } } catch (NamingException e) { log.errorFormat("Failed to query rootDSE for LDAP server {0} due to {1}", ldapURI, e.getMessage()); } finally { closeContext(ctx); } attributes = results; }</code><technical_language>Nice! wonder, is needed in other locations of code well</technical_language>

Target:
private void execute(LdapProviderType ldapProviderType, String domain) { Hashtable<String, String> env = new Hashtable<String, String>(); LdapBrokerUtils.addLdapConfigValues(env); initContextVariables(env); Attributes results = null; DirContext ctx = null; try { ctx = createContext(env); LdapQueryData ldapQueryData = new LdapQueryDataImpl(); ldapQueryData.setLdapQueryType(LdapQueryType.rootDSE); ldapQueryData.setDomain(domain); LdapQueryExecution queryExecution = LdapQueryExecutionBuilderImpl.getInstance().build(ldapProviderType, ldapQueryData); SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(queryExecution.getReturningAttributes()); searchControls.setSearchScope(queryExecution.getSearchScope()); searchControls.setReturningObjFlag(true); searchControls.setTimeLimit(Config.<Integer> GetValue(ConfigValues.LDAPOperationTimeout) * 1000); NamingEnumeration<SearchResult> search = ctx.search(queryExecution.getBaseDN(), queryExecution.getFilter(), searchControls); try { results = search.next().getAttributes(); } finally { search.close(); } } catch (NamingException e) { log.errorFormat("Failed to query rootDSE for LDAP server {0} due to {1}", ldapURI, e.getMessage()); } finally { closeContext(ctx); } attributes = results; }
Source:
<code>public DownloadHistoryDTO convert(DownloadHistory downloadHistory) { final AthenaUser athenaUser = userService.get(downloadHistory.getUserId()); DownloadHistoryDTO dto = new DownloadHistoryDTO(); <START> dto.setUserName(athenaUser.getFirstName()+", "+athenaUser.getLastName()); <END> dto.setVocabularyName(downloadHistory.getVocabularyBundle().getName()); return dto; }</code><technical_language>String.format</technical_language>

Target:
public DownloadHistoryDTO convert(DownloadHistory downloadHistory) { final AthenaUser athenaUser = userService.get(downloadHistory.getUserId()); DownloadHistoryDTO dto = new DownloadHistoryDTO(); dto.setUserName(String.format("%s %s", athenaUser.getFirstName(), athenaUser.getLastName())); dto.setVocabularyName(downloadHistory.getVocabularyBundle().getName()); return dto; }
Source:
<code>public boolean canSatisfyRequirements(CapabilityContext dependentContext) { <START> return true; <END> }</code><technical_language>This be: return dependentContext == CapabilityContext.GLOBAL || dependentContext instanceof HostCapabilityContext; capabilities domain level profile socket-binding-group resources able find requirements host context</technical_language>

Target:
public boolean canSatisfyRequirements(CapabilityContext dependentContext) { return dependentContext == CapabilityContext.GLOBAL || dependentContext instanceof HostCapabilityContext; }
Source:
<code>public TimestampedMessageParser(SecorConfig config) { super(config); outputPattern = mConfig.getOutputPattern(); if (outputPattern == null) { mFormatter = new SimpleDateFormat("yyyy-MM-dd"); mFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); } else { mFormatter = new SimpleDateFormat(outputPattern.toString()); <START> mFormatter.setTimeZone(TimeZone.getTimeZone("EST")); <END> } }</code><technical_language>timezone set EST a date format is</technical_language>

Target:
public TimestampedMessageParser(SecorConfig config) { super(config); Object outputPatternObj = mConfig.getOutputPattern(); if (outputPatternObj != null) { outputPattern = outputPatternObj.toString(); } if (outputPattern == null) { mFormatter = new SimpleDateFormat("yyyy-MM-dd"); mFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); } else { mFormatter = new SimpleDateFormat(outputPattern); } }
Source:
<code>static Map<ArtifactMode, RealMatrix> countOrientationBiasMetricsOverContext(final List<SequencingArtifactMetrics.PreAdapterDetailMetrics> metrics) { Utils.nonNull(metrics, "Input metrics cannot be null"); final Map<ArtifactMode, RealMatrix> result = new HashMap<>(); for (SequencingArtifactMetrics.PreAdapterDetailMetrics metric : metrics) { final ArtifactMode key = ArtifactMode.of(metric.REF_BASE, metric.ALT_BASE); <START> result.putIfAbsent(key, new Array2DRowRealMatrix(2, 2)); <END> result.get(key).addToEntry(PreAdapterOrientationScorer.PRO, PreAdapterOrientationScorer.ALT, metric.PRO_ALT_BASES); result.get(key).addToEntry(PreAdapterOrientationScorer.CON, PreAdapterOrientationScorer.ALT, metric.CON_ALT_BASES); result.get(key).addToEntry(PreAdapterOrientationScorer.PRO, PreAdapterOrientationScorer.REF, metric.PRO_REF_BASES); result.get(key).addToEntry(PreAdapterOrientationScorer.CON, PreAdapterOrientationScorer.REF, metric.CON_REF_BASES); } return result; }</code><technical_language>Instead of matrix time update it, build matrix entry-by-entry *then* put it</technical_language>

Target:
static Map<Transition, RealMatrix> countOrientationBiasMetricsOverContext(final List<SequencingArtifactMetrics.PreAdapterDetailMetrics> metrics) { Utils.nonNull(metrics, "Input metrics cannot be null"); final Map<Transition, RealMatrix> result = new HashMap<>(); for (SequencingArtifactMetrics.PreAdapterDetailMetrics metric : metrics) { final Transition key = Transition.transitionOf(metric.REF_BASE, metric.ALT_BASE); result.putIfAbsent(key, new Array2DRowRealMatrix(2, 2)); final RealMatrix preAdapterCountMatrix = result.get(key); preAdapterCountMatrix.addToEntry(PreAdapterOrientationScorer.PRO, PreAdapterOrientationScorer.ALT, metric.PRO_ALT_BASES); preAdapterCountMatrix.addToEntry(PreAdapterOrientationScorer.CON, PreAdapterOrientationScorer.ALT, metric.CON_ALT_BASES); preAdapterCountMatrix.addToEntry(PreAdapterOrientationScorer.PRO, PreAdapterOrientationScorer.REF, metric.PRO_REF_BASES); preAdapterCountMatrix.addToEntry(PreAdapterOrientationScorer.CON, PreAdapterOrientationScorer.REF, metric.CON_REF_BASES); } return result; }
Source:
<code><START> CompactionLog(String dir, String name, Time time, CompactionDetails compactionDetails) throws IOException { <END> this.time = time; file = new File(dir, name + COMPACTION_LOG_SUFFIX); if (file.exists() || !file.createNewFile()) { throw new IllegalArgumentException(file.getAbsolutePath() + " already exists or could not be created"); } startTime = time.milliseconds(); cycleLogs = new ArrayList<>(); cycleLogs.add(new CycleLog(compactionDetails)); flush(); }</code><technical_language>I need understand this is changed list a single item</technical_language>

Target:
CompactionLog(String dir, String name, Time time, CompactionDetails compactionDetails) throws IOException { this.time = time; file = new File(dir, name + COMPACTION_LOG_SUFFIX); if (!file.createNewFile()) { throw new IllegalArgumentException(file.getAbsolutePath() + " already exists"); } startTime = time.milliseconds(); cycleLogs = new ArrayList<>(); cycleLogs.add(new CycleLog(compactionDetails)); flush(); }
Source:
<code><START> private static Genesis createBlockForJson(GenesisJson genesisJson) throws Exception { <END> byte[] nonce = prepareNonce(ByteUtil.hexStringToBytes(genesisJson.nonce)); byte[] difficulty = ByteUtil.hexStringToBytes(genesisJson.difficulty); byte[] mixHash = ByteUtil.hexStringToBytes(genesisJson.mixhash); byte[] coinbase = ByteUtil.hexStringToBytes(genesisJson.coinbase); byte[] timestampBytes = ByteUtil.hexStringToBytes(genesisJson.timestamp); long timestamp = ByteUtil.byteArrayToLong(timestampBytes); byte[] parentHash = ByteUtil.hexStringToBytes(genesisJson.parentHash); byte[] extraData = ByteUtil.hexStringToBytes(genesisJson.extraData); byte[] gasLimitBytes = ByteUtil.hexStringToBytes(genesisJson.gasLimit); long gasLimit = ByteUtil.byteArrayToLong(gasLimitBytes); return new Genesis(parentHash, EMPTY_LIST_HASH, coinbase, ZERO_HASH_2048, difficulty, 0, gasLimit, 0, timestamp, extraData, mixHash, nonce); }</code><technical_language>Do need this checked exception here</technical_language>

Target:
private static Genesis createBlockForJson(GenesisJson genesisJson) { byte[] nonce = prepareNonce(ByteUtil.hexStringToBytes(genesisJson.nonce)); byte[] difficulty = ByteUtil.hexStringToBytes(genesisJson.difficulty); byte[] mixHash = ByteUtil.hexStringToBytes(genesisJson.mixhash); byte[] coinbase = ByteUtil.hexStringToBytes(genesisJson.coinbase); byte[] timestampBytes = ByteUtil.hexStringToBytes(genesisJson.timestamp); long timestamp = ByteUtil.byteArrayToLong(timestampBytes); byte[] parentHash = ByteUtil.hexStringToBytes(genesisJson.parentHash); byte[] extraData = ByteUtil.hexStringToBytes(genesisJson.extraData); byte[] gasLimitBytes = ByteUtil.hexStringToBytes(genesisJson.gasLimit); long gasLimit = ByteUtil.byteArrayToLong(gasLimitBytes); return new Genesis(parentHash, EMPTY_LIST_HASH, coinbase, ZERO_HASH_2048, difficulty, 0, gasLimit, 0, timestamp, extraData, mixHash, nonce); }
Source:
<code>private void setupSourceLocationControls(@Nullable VirtualFile importSource) { if (importSource == null) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor(); descriptor.setTitle("Select Source Location"); <START> descriptor.setDescription("Select location of your existing "); <END> mySourceLocation.addBrowseFolderListener(new TextBrowseFolderListener(descriptor)); mySourceLocation.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { invalidate(); } }); } else { mySourceLocation.setVisible(false); myLocationLabel.setVisible(false); mySourceLocation.setText(importSource.getPath()); } applyBackgroundOperationResult(checkPath(mySourceLocation.getText())); }</code><technical_language>is missing end of this sentence</technical_language>

Target:
private void setupSourceLocationControls(@Nullable VirtualFile importSource) { if (importSource == null) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor(); descriptor.setTitle("Select Source Location"); descriptor.setDescription("Select existing ADT or Gradle project to import as a new subproject"); mySourceLocation.addBrowseFolderListener(new TextBrowseFolderListener(descriptor)); mySourceLocation.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { invalidate(); } }); } else { mySourceLocation.setVisible(false); myLocationLabel.setVisible(false); mySourceLocation.setText(importSource.getPath()); } applyBackgroundOperationResult(checkPath(mySourceLocation.getText())); }
Source:
<code>private Repository getRepositoryForPath(String containerPath) { IContainer mappedContainer = ResourcesPlugin.getWorkspace().getRoot() .getContainerForLocation(new Path(containerPath)); GitProjectData projectData = GitProjectData.get((IProject) mappedContainer); <START> return projectData.getRepositoryMapping(mappedContainer).getRepository(); <END> }</code><technical_language>check for null return of getRepositoryMapping here</technical_language>

Target:
private Repository getRepositoryForPath(String containerPath) { IPath path = Path.fromPortableString(containerPath); IContainer mappedContainer = ResourcesPlugin.getWorkspace().getRoot() .getContainerForLocation(path); GitProjectData projectData = GitProjectData.get((IProject) mappedContainer); RepositoryMapping mapping = projectData.getRepositoryMapping(mappedContainer); if (mapping != null) return mapping.getRepository(); return null; }
Source:
<code>ChannelBinding.IndexedMessageChannel createChannel(Object plugin, String channel) throws ChannelRegistrationException; ChannelBinding.RawDataChannel createRawChannel(Object plugin, String channel) throws ChannelRegistrationException; Optional<ChannelBinding> getChannel(String channel); <START> default Optional<ChannelBinding.IndexedMessageChannel> getOrCreate(Object plugin, String channel) throws ChannelRegistrationException { <END> Optional<ChannelBinding> existing = getChannel(channel); if (existing.isPresent()) { if (existing.get() instanceof ChannelBinding.IndexedMessageChannel) { return Optional.of((ChannelBinding.IndexedMessageChannel) existing.get()); } return Optional.empty(); } return Optional.of(createChannel(plugin, channel)); }</code><technical_language>In case this return Optional.empty()? creating if present</technical_language>

Target:
ChannelBinding.IndexedMessageChannel createChannel(Object plugin, String channel) throws ChannelRegistrationException; ChannelBinding.RawDataChannel createRawChannel(Object plugin, String channel) throws ChannelRegistrationException; Optional<ChannelBinding> getChannel(String channel); default ChannelBinding.IndexedMessageChannel getOrCreate(Object plugin, String channel) throws ChannelRegistrationException { Optional<ChannelBinding> existing = getChannel(channel); if (existing.isPresent()) { if (existing.get() instanceof ChannelBinding.IndexedMessageChannel) { return (ChannelBinding.IndexedMessageChannel) existing.get(); } throw new IllegalStateException("Tried to get existing channel " + channel + " as an IndexedMessageChannel but found it was a RawDataChannel"); } return createChannel(plugin, channel); }
Source:
<code>public void updateDependency(PluginWrapper depender, PluginWrapper dependee) { DependencyClassLoader classLoader = findAncestorDependencyClassLoader(depender.classLoader); if (classLoader != null) { classLoader.updateTransientDependencies(); <START> LOGGER.log(Level.FINEST, "Updated dependency of {0}", depender.getShortName()); <END> } }</code><technical_language>No</technical_language>

Target:
public void updateDependency(PluginWrapper depender, PluginWrapper dependee) { DependencyClassLoader classLoader = findAncestorDependencyClassLoader(depender.classLoader); if (classLoader != null) { classLoader.updateTransientDependencies(); LOGGER.log(Level.INFO, "Updated dependency of {0}", depender.getShortName()); } }
Source:
<code>public boolean equals(Object obj) { boolean ret = (this == obj); <START> if (!ret && (obj instanceof BitVector)) { <END> BitVector other = (BitVector) obj; ret = (this.size == other.size()); if (ret) { long comparisonFirstPos = 0; if (other instanceof BitVectorImpl) { BitVectorImpl otherBitVectorImpl = (BitVectorImpl) other; int arraySize = (int) (this.size >> LG_WORD_SIZE); for (int i = 0; ret && (i < arraySize); i++) { ret = ret && (this.array[i] == otherBitVectorImpl.array[i]); } comparisonFirstPos = ((long) arraySize << LG_WORD_SIZE); } for (long i = comparisonFirstPos; ret && (i < this.size); i++) { ret = ret && (getBit(i) == other.getBit(i)); } } } return ret; }</code><technical_language>control flow simpler if checks (ignoring style ;-): if (this == obj) return true; if (! obj instanceof BitVector) return false code for rest of checks, size comparison replaced a flat if (immediate return false); ret needed (all ret assignments replaced return statements). This lead code nested if-clauses. More readable. This is auto-generated default equals in Eclipse constructed</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BitVector)) { return false; } BitVector other = (BitVector) obj; if (this.size != other.size()) { return false; } long comparisonFirstPos = 0; if (other instanceof BitVectorImpl) { BitVectorImpl otherBitVectorImpl = (BitVectorImpl) other; int arraySize = (int) (this.size >> LG_WORD_SIZE); for (int i = 0; i < arraySize; i++) { if (this.arrayOfBits[i] != otherBitVectorImpl.arrayOfBits[i]) { return false; } } comparisonFirstPos = ((long) arraySize << LG_WORD_SIZE); } for (long i = comparisonFirstPos; i < this.size; i++) { if (getBit(i) != other.getBit(i)) { return false; } } return true; }
Source:
<code>public static BundleGroupDocAdapter create(BundleGroup bundleGroup, CoreSession session, String containerPath) { DocumentModel doc = session.createDocumentModel(TYPE_NAME); String name = computeDocumentName("bg-" + bundleGroup.getId()); String targetPath = new Path(containerPath).append(name).toString(); boolean exist = false; if (session.exists(new PathRef(targetPath))) { exist = true; doc = session.getDocument(new PathRef(targetPath)); } doc.setPathInfo(containerPath, name); doc.setPropertyValue(NuxeoArtifact.TITLE_PROPERTY_PATH, bundleGroup.getName()); doc.setPropertyValue(PROP_GROUP_NAME, bundleGroup.getName()); doc.setPropertyValue(PROP_KEY, bundleGroup.getId()); var files = new ArrayList<Map<String, Serializable>>(); for (Blob blob : bundleGroup.getReadmes()) { Map<String, Serializable> item = new HashMap<>(); item.put("file", (Serializable) blob); files.add(item); } doc.setPropertyValue(PROP_READMES, files); <START> doc.getContextData().put(ThumbnailConstants.DISABLE_THUMBNAIL_COMPUTATION, true); <END> if (exist) { doc = session.saveDocument(doc); } else { doc = session.createDocument(doc); } return new BundleGroupDocAdapter(doc); }</code><technical_language>doc.putContextData() directly</technical_language>

Target:
public static BundleGroupDocAdapter create(BundleGroup bundleGroup, CoreSession session, String containerPath) { DocumentModel doc = session.createDocumentModel(TYPE_NAME); String name = computeDocumentName("bg-" + bundleGroup.getId()); String targetPath = new Path(containerPath).append(name).toString(); boolean exist = false; if (session.exists(new PathRef(targetPath))) { exist = true; doc = session.getDocument(new PathRef(targetPath)); } doc.setPathInfo(containerPath, name); doc.setPropertyValue(NuxeoArtifact.TITLE_PROPERTY_PATH, bundleGroup.getName()); doc.setPropertyValue(PROP_GROUP_NAME, bundleGroup.getName()); doc.setPropertyValue(PROP_KEY, bundleGroup.getId()); var files = new ArrayList<Map<String, Serializable>>(); for (Blob blob : bundleGroup.getReadmes()) { Map<String, Serializable> item = new HashMap<>(); item.put("file", (Serializable) blob); files.add(item); } doc.setPropertyValue(PROP_READMES, files); doc.putContextData(ThumbnailConstants.DISABLE_THUMBNAIL_COMPUTATION, true); if (exist) { doc = session.saveDocument(doc); } else { doc = session.createDocument(doc); } return new BundleGroupDocAdapter(doc); }
Source:
<code>public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_analysisJob == null) ? 0 : _analysisJob.hashCode()); result = prime * result + ((_table == null) ? 0 : _table.hashCode()); <START> return result; <END> }</code><technical_language>Objects.hash(...)</technical_language>

Target:
public int hashCode() { return Objects.hash(_analysisJob, _table); }
Source:
<code>public static NetworkAccess build(NetworkAccess source) { NonWriteThroughStorage storage = new NonWriteThroughStorage(source.dhtClient); NonWriteThroughMutablePointers mutable = new NonWriteThroughMutablePointers(source.mutable, storage); return new NetworkAccess( new NonWriteThroughCoreNode(source.coreNode, storage), new NonWriteThroughSocialNetwork(source.social, storage), storage, mutable, new MutableTreeImpl(mutable, storage), <START> null, <END> source.usernames, false); }</code><technical_language>nan</technical_language>

Target:
public static NetworkAccess build(NetworkAccess source) { NonWriteThroughStorage storage = new NonWriteThroughStorage(source.dhtClient); NonWriteThroughMutablePointers mutable = new NonWriteThroughMutablePointers(source.mutable, storage); return new NetworkAccess( new NonWriteThroughCoreNode(source.coreNode, storage), new NonWriteThroughSocialNetwork(source.social, storage), storage, mutable, new MutableTreeImpl(mutable, storage), source.instanceAdmin, source.usernames, false); }
Source:
<code>private File createTestVmRuntime() throws MojoExecutionException { IvyTestRuntime testRuntime = new IvyTestRuntime(); testRuntime.setProductDir(identifyAndGetEngineDirectory()); try { File target = new File(project.getBuild().getOutputDirectory()).getParentFile(); <START> File tstVmDir = new File(target, "ivyTestVm"); <END> tstVmDir.mkdir(); testRuntime.store(tstVmDir); return tstVmDir; } catch (IOException ex) { throw new MojoExecutionException("Failed to write ivy test vm settings.", ex); } }</code><technical_language>I move this code store method store method return file needs set classpath. In this is more similar in core</technical_language>

Target:
private File createTestVmRuntime() throws MojoExecutionException { IvyTestRuntime testRuntime = new IvyTestRuntime(); testRuntime.setProductDir(identifyAndGetEngineDirectory()); try { return testRuntime.store(project); } catch (IOException ex) { throw new MojoExecutionException("Failed to write ivy test vm settings.", ex); } }
Source:
<code>protected BufferedImage readImage(String path) { try { <START> return readImage(new FileInputStream(FileUtils.getResourceFileFromContext(path))); <END> } catch (FileNotFoundException e) { throw new UncheckedIOException(e); } }</code><technical_language>FileInputStream closed right</technical_language>

Target:
protected BufferedImage readImage(String path) { try (InputStream is = new FileInputStream(FileUtils.getResourceFileFromContext(path))) { return readImage(is); } catch (IOException e) { throw new UncheckedIOException(e); } }