auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private IRequirement getRequirement(SiteIU iu) { String id = iu.getID(); String range = iu.getRange(); String type = iu.getQueryType(); String expression = iu.getQueryExpression(); String[] params = iu.getQueryParams(); if (id != null) { VersionRange vRange = new VersionRange(range); return MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, id, vRange, null, false, false); } else if ("match".equals(type)) { String[] allArgs = new String[(params == null ? 0 : params.length) + 1]; allArgs[0] = id; if (params != null) System.arraycopy(params, 0, allArgs, 1, params.length); IMatchExpression<IInstallableUnit> iuMatcher = ExpressionUtil.getFactory() .<IInstallableUnit> matchExpression(ExpressionUtil.parse(expression), params); return MetadataFactory.createRequirement(iuMatcher, null, 0, 1, true); } else if ("context".equals(type)) { <START> throw new IllegalStateException( "Context iu queries are not supported in Tycho. Faulty expression is " + expression); <END> } return null; }</code><technical_language>Is this work in principle, implemented/tested</technical_language>

Target:
private IRequirement getRequirement(SiteIU iu) { String id = iu.getID(); String range = iu.getRange(); String type = iu.getQueryType(); String expression = iu.getQueryExpression(); String[] params = iu.getQueryParams(); if (id != null) { VersionRange vRange = new VersionRange(range); return MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, id, vRange, null, false, false); } else if ("match".equals(type)) { IMatchExpression<IInstallableUnit> iuMatcher = ExpressionUtil.getFactory() .<IInstallableUnit> matchExpression(ExpressionUtil.parse(expression), params); return MetadataFactory.createRequirement(iuMatcher, null, 0, 1, true); } else if ("context".equals(type)) { throw new IllegalStateException( "Context iu queries are not supported in Tycho. Faulty expression is " + expression); } return null; }
Source:
<code>public static String[] getDefaultErrorParserIds() { <START> if (fDefaultErrorParserIds==null) { <END> return fAvailableErrorParsers.keySet().toArray(new String[0]); } return fDefaultErrorParserIds.toArray(new String[0]); }</code><technical_language>Restore spaces</technical_language>

Target:
public static String[] getDefaultErrorParserIds() { if (fDefaultErrorParserIds == null) { return fAvailableErrorParsers.keySet().toArray(new String[fAvailableErrorParsers.size()]); } return fDefaultErrorParserIds.toArray(new String[fDefaultErrorParserIds.size()]); }
Source:
<code>public static String parse(String inField) throws IllegalArgumentException { Objects.requireNonNull(inField); String toFormat = UNDERSCORE_MATCHER.matcher(inField).replaceAll(REPLACEMENT_CHAR); try { var parsingResult = LaTeX2Unicode.parse(toFormat); if (parsingResult instanceof Parsed.Success) { String text = parsingResult.get().value(); toFormat = Normalizer.normalize(text, Normalizer.Form.NFC); return UNDERSCORE_PLACEHOLDER_MATCHER.matcher(toFormat).replaceAll("_"); } else { throw new IllegalArgumentException("Parsing of latex failed."); } <START> } catch (Throwable throwable) { <END> throw new IllegalArgumentException("An error occurred while attempting to parse latex."); } }</code><technical_language>I more sense Optional<String> instead of exception handling for control flows (that is a bad idea)</technical_language>

Target:
public static Optional<String> parse(String inField) { Objects.requireNonNull(inField); String toFormat = UNDERSCORE_MATCHER.matcher(inField).replaceAll(REPLACEMENT_CHAR); var parsingResult = LaTeX2Unicode.parse(toFormat); if (parsingResult instanceof Parsed.Success) { String text = parsingResult.get().value(); toFormat = Normalizer.normalize(text, Normalizer.Form.NFC); return Optional.of(UNDERSCORE_PLACEHOLDER_MATCHER.matcher(toFormat).replaceAll("_")); } return Optional.empty(); }
Source:
<code><START> public Map<Symbol, Object> getMessageAnnotationsMap(boolean createIfAbsent) { <END> Map<Symbol, Object> map = null; if (messageAnnotations != null) { map = messageAnnotations.getValue(); } if (map == null) { if (createIfAbsent) { map = new HashMap<>(); this.messageAnnotations = new MessageAnnotations(map); } else { map = Collections.EMPTY_MAP; } } return map; }</code><technical_language>This wasnt public prevent people screwing map knowledge of message object, screw up. Exposing unwise</technical_language>

Target:
protected Map<Symbol, Object> getMessageAnnotationsMap(boolean createIfAbsent) { Map<Symbol, Object> map = null; if (messageAnnotations != null) { map = messageAnnotations.getValue(); } if (map == null) { if (createIfAbsent) { map = new HashMap<>(); this.messageAnnotations = new MessageAnnotations(map); } else { map = Collections.EMPTY_MAP; } } return map; }
Source:
<code>public UniqueRandomFunction(int minValue, int maxValue) { this.dataset = this.initIntegerDataset(minValue, maxValue); this.shuffleDataset(); <START> this.nextValueIndex = 0; <END> }</code><technical_language>I set initial nextValueIndex right attribute declaration, avoid repeating in constructors. do think</technical_language>

Target:
public UniqueRandomFunction(int minValue, int maxValue) { if(minValue >= maxValue) { throw new IllegalArgumentException("maxValue cannot be greater than minValue."); } this.dataset = this.initIntegerDataset(minValue, maxValue); this.shuffleDataset(); }
Source:
<code>public Object decodeBytes(byte[] b, Object object) throws SerializationException { if (!(object instanceof Schema)) { throw logger.logExceptionAsError( <START> new SerializationException("Attempted to decode with non-Avro schema object in AvroByteDecoder")); <END> } Schema schema = (Schema) object; if (schema.getType().equals(Schema.Type.BYTES)) { return b; } DatumReader<?> reader = getDatumReader(schema); try { Object result = reader.read(null, decoderFactory.binaryDecoder(b, null)); if (schema.getType().equals(Schema.Type.STRING)) { return result.toString(); } return result; } catch (IOException | RuntimeException e) { throw logger.logExceptionAsError(new SerializationException("Error deserializing Avro message.", e)); } }</code><technical_language>Do if phrase exception in "why this happened" instead of "what happened"? Attempted decode non-Avro schema object in AvroByteDecoder. object Avro Schema</technical_language>

Target:
public Object decodeBytes(byte[] b, Object object) { Objects.requireNonNull(object, "Schema must not be null."); if (!(object instanceof Schema)) { throw logger.logExceptionAsError( new SerializationException("Object must be an Avro schema.")); } Schema schema = (Schema) object; if (schema.getType().equals(Schema.Type.BYTES)) { return b; } DatumReader<?> reader = getDatumReader(schema); try { Object result = reader.read(null, DECODER_FACTORY.binaryDecoder(b, null)); if (schema.getType().equals(Schema.Type.STRING)) { return result.toString(); } return result; } catch (IOException | RuntimeException e) { throw logger.logExceptionAsError(new SerializationException("Error deserializing Avro message.", e)); } }
Source:
<code>private void updateDestinationVds(final Guid dstVdsId, final VM vm) { <START> TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { <END> @Override public Void runInTransaction() { DbFacade.getInstance() .getVdsDynamicDao() .updatePartialVdsDynamicCalc(dstVdsId, 1, vm.getNumOfCpus(), vm.getMinAllocatedMem(), 0, 0); return null; } }); log.debugFormat( "IncreasePendingVms::MigrateVm Increasing vds {0} pending vcpu count, in {1}, and pending vmem size, in {2}. Vm: {3}", dstVdsId, vm.getNumOfCpus(), vm.getMinAllocatedMem(), vm.getName()); }</code><technical_language>new transaction? this information is updated in other transaction db lock? (maintenance/non operational/rerun flows)</technical_language>

Target:
private void updateDestinationVds(final Guid dstVdsId, final VM vm) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { DbFacade.getInstance() .getVdsDynamicDao() .updatePartialVdsDynamicCalc(dstVdsId, 1, vm.getNumOfCpus(), vm.getMinAllocatedMem(), 0, 0); log.debugFormat( "IncreasePendingVms::MigrateVm Increasing vds {0} pending vcpu count, in {1}, and pending vmem size, in {2}. Vm: {3}", dstVdsId, vm.getNumOfCpus(), vm.getMinAllocatedMem(), vm.getName()); } }); }
Source:
<code>public boolean has(final String name) { if (parsed == null) { throw new IllegalStateException("parse() wasn't called"); <START> } <END> return parsed.containsKey(name); }</code><technical_language>Lets options check please, find issues this bug</technical_language>

Target:
public boolean has(final String name) { if (!options.containsKey(name)) { throw new IllegalArgumentException("Unknown option " + name); } else if (parsed == null) { throw new IllegalStateException("parse() wasn't called"); } return parsed.containsKey(name); }
Source:
<code>private Stream<String> attributeIdsFromResponseAsStream(Response response) { return response .getAssertions() .stream() .flatMap(assertion -> assertion.getAttributeStatements().stream()) .flatMap(statement -> statement.getAttributes().stream()) .flatMap(attribute -> attribute.getAttributeValues().stream()) <START> .filter(attributeValue -> attributeValue instanceof XSString) <END> .map(attributeValue -> (XSString) attributeValue) .map(XSString::getValue) .filter(StringUtils::isNotBlank); }</code><technical_language>filter(XSString::isInstance)</technical_language>

Target:
private Stream<String> attributeIdsFromResponseAsStream(Response response) { return response .getAssertions() .stream() .flatMap(assertion -> assertion.getAttributeStatements().stream()) .flatMap(statement -> statement.getAttributes().stream()) .flatMap(attribute -> attribute.getAttributeValues().stream()) .filter(XSString.class::isInstance) .map(XSString.class::cast) .map(XSString::getValue) .filter(StringUtils::isNotBlank); }
Source:
<code>static public String filenameNoCompression(String filename) { for ( String ext : extensions ) { if ( filename.endsWith(ext) ) return filename.substring(0, filename.length()-ext.length()); } return filename; <START> } <END></code><technical_language>instead java /** filename compression extension, original filename. * tests for compression types handled {@link #openFileEx}. */ static public String filenameNoCompression(String filename) { if ( FilenameUtils.isExtension(filename, extensions) ) { return FilenameUtils.removeExtension(filename); } return filename; } I commons-io in dependencies list. some extra check for null bytes in extension check... important. simpler I think</technical_language>

Target:
static public String filenameNoCompression(String filename) { if ( FilenameUtils.isExtension(filename, extensions) ) { return FilenameUtils.removeExtension(filename); } return filename; }
Source:
<code>public void elideSecurityEnabled() { Elide elide = new Elide(new ElideSettingsBuilder(dataStore) .withEntityDictionary(new EntityDictionary(TestCheckMappings.MAPPINGS)) .withAuditLogger(new TestAuditLogger()) .build()); <START> com.yahoo.elide.security.User user = new com.yahoo.elide.security.User(new Principal() { @Override public String getName() { return "-1"; } }); <END> ElideResponse response = elide.get("parent/1/children", new MultivaluedHashMap<>(), user); assertEquals(response.getResponseCode(), HttpStatus.SC_OK); assertEquals(response.getBody(), "{\"data\":[]}"); }</code><technical_language>suggestion com.yahoo.elide.security.User user = new com.yahoo.elide.security.User(() -> "-1");</technical_language>

Target:
public void elideSecurityEnabled() { Elide elide = new Elide(new ElideSettingsBuilder(dataStore) .withEntityDictionary(new EntityDictionary(TestCheckMappings.MAPPINGS)) .withAuditLogger(new TestAuditLogger()) .build()); com.yahoo.elide.security.User user = new com.yahoo.elide.security.User(() -> "-1"); ElideResponse response = elide.get("parent/1/children", new MultivaluedHashMap<>(), user); assertEquals(response.getResponseCode(), HttpStatus.SC_OK); assertEquals(response.getBody(), "{\"data\":[]}"); }
Source:
<code>public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) throws IOException { Compute compute = GcpStackUtil.buildCompute(cloudCredential); String projectId = GcpStackUtil.getProjectId(cloudCredential); Map<String, Set<CloudSecurityGroup>> result = new HashMap<>(); FirewallList firewallList = compute.firewalls().list(projectId).execute(); for (Firewall firewall : firewallList.getItems()) { Map<String, Object> properties = new HashMap<>(); properties.put("network", getNetworkName(firewall)); CloudSecurityGroup cloudSecurityGroup = new CloudSecurityGroup(firewall.getName(), firewall.getName(), properties); result.computeIfAbsent(region.value(), k -> new HashSet<>()).add(cloudSecurityGroup); } if (filters != null) { String sharedProjectId = filters.get(SHARED_PROJECT_ID); if (!Strings.isNullOrEmpty(sharedProjectId)) { try { FirewallList sharedProjectFirewalls = compute.firewalls().list(sharedProjectId).execute(); for (Firewall firewall : sharedProjectFirewalls.getItems()) { Map<String, Object> properties = new HashMap<>(); properties.put("network", getNetworkName(firewall)); CloudSecurityGroup cloudSecurityGroup = new CloudSecurityGroup(firewall.getName(), firewall.getName(), properties); result.computeIfAbsent(region.value(), k -> new HashSet<>()).add(cloudSecurityGroup); } } catch (Exception ex) { <START> LOGGER.warn(String.format("We can not read the host project which id %s", sharedProjectId)); <END> } } } return new CloudSecurityGroups(result); }</code><technical_language>-> "We read host project id"</technical_language>

Target:
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) throws IOException { Compute compute = GcpStackUtil.buildCompute(cloudCredential); String projectId = GcpStackUtil.getProjectId(cloudCredential); Map<String, Set<CloudSecurityGroup>> result = new HashMap<>(); FirewallList firewallList = compute.firewalls().list(projectId).execute(); for (Firewall firewall : firewallList.getItems()) { Map<String, Object> properties = new HashMap<>(); properties.put("network", getNetworkName(firewall)); CloudSecurityGroup cloudSecurityGroup = new CloudSecurityGroup(firewall.getName(), firewall.getName(), properties); result.computeIfAbsent(region.value(), k -> new HashSet<>()).add(cloudSecurityGroup); } if (filters != null) { String sharedProjectId = filters.get(SHARED_PROJECT_ID); if (!Strings.isNullOrEmpty(sharedProjectId)) { try { FirewallList sharedProjectFirewalls = compute.firewalls().list(sharedProjectId).execute(); for (Firewall firewall : sharedProjectFirewalls.getItems()) { Map<String, Object> properties = new HashMap<>(); properties.put("network", getNetworkName(firewall)); CloudSecurityGroup cloudSecurityGroup = new CloudSecurityGroup(firewall.getName(), firewall.getName(), properties); result.computeIfAbsent(region.value(), k -> new HashSet<>()).add(cloudSecurityGroup); } } catch (Exception ex) { LOGGER.warn(String.format("We can not read the host project with id %s", sharedProjectId)); } } } return new CloudSecurityGroups(result); }
Source:
<code>public void start() { isPessimisticCache = cacheConfiguration.transaction().lockingMode() == LockingMode.PESSIMISTIC; useClusteredWriteSkewCheck = Configurations.isVersioningEnabled(cacheConfiguration); rollbackRpcOptions = createRpcOptionsFor2ndPhase(cacheConfiguration.transaction().syncRollbackPhase() <START> ); <END> commitRpcOptions = createRpcOptionsFor2ndPhase(cacheConfiguration.transaction().syncCommitPhase() ); }</code><technical_language>Line wrap is a bit weird</technical_language>

Target:
public void start() { isPessimisticCache = cacheConfiguration.transaction().lockingMode() == LockingMode.PESSIMISTIC; useClusteredWriteSkewCheck = Configurations.isVersioningEnabled(cacheConfiguration); }
Source:
<code>protected Builder() { super(); id("azurecompute-arm") .name("Azure Resource Management ") .apiMetadata(new AzureManagementApiMetadata()) .endpoint("<LINK_0>") .homepage(URI.create("<LINK_1>")) .console(URI.create("<LINK_2>")) <START> .linkedServices("azureblob", "azurequeue", "azuretable") <END> .defaultProperties(AzureComputeProviderMetadata.defaultProperties()); }</code><technical_language>This reference _existing_ providers accessed account</technical_language>

Target:
protected Builder() { super(); id("azurecompute-arm") .name("Azure Resource Management ") .apiMetadata(new AzureManagementApiMetadata()) .endpoint("<LINK_0>") .homepage(URI.create("<LINK_1>")) .console(URI.create("<LINK_2>")) .linkedServices("azureblob") .defaultProperties(AzureComputeProviderMetadata.defaultProperties()); }
Source:
<code>public Object evaluate(Object feature) { Object arg0; Object arg1; MatchAction matchAction = null; try { arg0 = (Object) getExpression(0).evaluate(feature); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function equalTo argument #0 - expected type Object"); } try { arg1 = (Object) getExpression(1).evaluate(feature); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function equalTo argument #1 - expected type Object"); } if (getParameters().size() > 2) { try { <START> matchAction = MatchAction.valueOf((String) getExpression(2).evaluate(feature)); <END> } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function equalTo argument #2 - expected one of ANY, ONE or ALL"); } } return Boolean.valueOf(StaticGeometry.equalTo(arg0, arg1, matchAction)); }</code><technical_language>getExpression(2).evaualte( feature, MatchAction.class ) work (there a converter convert a string enum required)</technical_language>

Target:
public Object evaluate(Object feature) { Expression arg0 = getExpression(0); Expression arg1 = getExpression(1); MatchAction matchAction = null; if (getParameters().size() > 2) { try { matchAction = (MatchAction) getExpression(2).evaluate(feature, MatchAction.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function equalTo argument #2 - expected one of ANY, ONE or ALL"); } } Filter equalTo = matchAction == null ? getFilterFactory2().equal(arg0, arg1, false) : getFilterFactory2().equal(arg0, arg1, false, matchAction); return equalTo.evaluate(feature); }
Source:
<code>public void act(float delta) { super.act(delta); getCurrentFrame().act(delta); if (getCurrentFrame().isDone()) { getCurrentFrame().reset(); <START> currentFrame = function.getNextFrameIndex(currentFrame, <END> frames.size()); } }</code><technical_language>create a setCurrentFrame method set this attribute, do range check is done in get (if (currentFrame >= 0 && currentFrame < frames.size()) {), log error if valid, getCurrentFrame return frames.get(currentFrame);</technical_language>

Target:
public void act(float delta) { super.act(delta); while (delta > 0) { getCurrentFrame().act(delta); delta = getCurrentFrame().surplusTime(); if (delta >= 0) { getCurrentFrame().reset(); setCurrentFrame(function.getNextFrameIndex(currentFrame, frames.size())); } } }
Source:
<code>private <T extends AbstractEntity> boolean isAuditable(final T entity) { <START> if(entity.getClass().isAnnotationPresent(Auditable.class)) { <END> return true; } return false; }</code><technical_language>Add not-null check here</technical_language>

Target:
private <T extends AbstractEntity> boolean isAuditable(final T entity) { Assert.requireNonNull(entity , "entity"); if(entity.getClass().isAnnotationPresent(Auditable.class)) { return true; } return false; }
Source:
<code>public void testGetForValidId() throws JsonProcessingException { final UUID uuid = UUID.randomUUID(); Assert.assertFalse(alertRepo.get(uuid).isPresent()); final Transaction transaction = Ebean.beginTransaction(); try { final models.ebean.Alert ebeanAlert = new models.ebean.Alert(); ebeanAlert.setNagiosExtension(TEST_NAGIOS_EXTENSIONS); ebeanAlert.setName(TEST_NAME); ebeanAlert.setOperator(TEST_OPERATOR); ebeanAlert.setPeriod(TEST_PERIOD_IN_SECONDS); ebeanAlert.setStatistic(TEST_STATISTIC); ebeanAlert.setQuantityValue(TEST_QUANTITY_VALUE); ebeanAlert.setQuantityUnit(TEST_QUANTITY_UNIT); ebeanAlert.setCluster(TEST_CLUSTER); ebeanAlert.setUuid(uuid); ebeanAlert.setMetric(TEST_METRIC); ebeanAlert.setContext(TEST_CONTEXT); ebeanAlert.setService(TEST_SERVICE); Ebean.save(ebeanAlert); transaction.commit(); } finally { transaction.end(); } final Optional<Alert> expected = alertRepo.get(uuid); Assert.assertTrue(expected.isPresent()); Assert.assertEquals(uuid, expected.get().getId()); Assert.assertEquals(TEST_CLUSTER, expected.get().getCluster()); Assert.assertEquals(TEST_METRIC, expected.get().getMetric()); Assert.assertEquals(TEST_EXTENSIONS, expected.get().getExtensions()); Assert.assertEquals(TEST_SERVICE, expected.get().getService()); Assert.assertEquals(TEST_NAME, expected.get().getName()); Assert.assertEquals(TEST_OPERATOR, expected.get().getOperator()); Assert.assertEquals(Period.seconds(TEST_PERIOD_IN_SECONDS), expected.get().getPeriod()); Assert.assertEquals(TEST_STATISTIC, expected.get().getStatistic()); Assert.assertEquals(TEST_QUANTITY, expected.get().getValue()); <START> Assert.assertEquals(TEST_CONTEXT, expected.get().getContext()); <END> }</code><technical_language>instances instead of field constants externalized equality method. External if write equals bean orm I want (at yet)</technical_language>

Target:
public void testGetForValidId() throws IOException { final UUID uuid = UUID.randomUUID(); Assert.assertFalse(alertRepo.get(uuid).isPresent()); final models.ebean.Alert ebeanAlert = TestBeanFactory.createEbeanAlert(); ebeanAlert.setUuid(uuid); try (Transaction transaction = Ebean.beginTransaction()) { Ebean.save(ebeanAlert); transaction.commit(); } final Optional<Alert> expected = alertRepo.get(uuid); Assert.assertTrue(expected.isPresent()); Assert.assertTrue(isAlertEbeanEquivalent(expected.get(), ebeanAlert)); }
Source:
<code>private static void initializeAppsLocation(File serverXML, File configDir, File bootstrapFile, Map<String, String> bootstrapProp, File serverEnvFile) { try { serverFile = serverXML; configDirectory = configDir; locations = new HashSet<String>(); props = new Properties(); Document doc = parseDocument(new FileInputStream(serverFile)); if (serverEnvFile.exists()) { Properties propServerEnv = new Properties(); propServerEnv.load(new FileInputStream(serverEnvFile)); props.putAll(propServerEnv); } <START> if (bootstrapProp != null && !bootstrapProp.isEmpty()) { <END> props.putAll(bootstrapProp); } else if (bootstrapFile.exists()) { Properties propBootStrap = new Properties(); propBootStrap.load(new FileInputStream(bootstrapFile)); props.putAll(propBootStrap); } parseIncludeVariables(doc); parseConfigDropinsDirVariables("defaults"); parseVariables(doc); parseConfigDropinsDirVariables("overrides"); parseApplication(doc, "/server/application"); parseApplication(doc, "/server/webApplication"); parseApplication(doc, "/server/enterpriseApplication"); parseInclude(doc); parseConfigDropinsDir(); } catch (Exception e) { e.printStackTrace(); } }</code><technical_language>respect server parameters precedence? is, bootstrip.properties in ${configDirectory} first, <bootstrapProperties> in pom.xml, ${bootstrapPropertiesFile} last. I condition involving ${configDirectory}</technical_language>

Target:
private static void initializeAppsLocation(File serverXML, File configDir, File bootstrapFile, Map<String, String> bootstrapProp, File serverEnvFile) { try { serverFile = serverXML; configDirectory = configDir; locations = new HashSet<String>(); props = new Properties(); Document doc = parseDocument(new FileInputStream(serverFile)); Properties fProps; File cfgDirFile = getFileFromConfigDirectory("server.env"); if (cfgDirFile != null) { fProps = parseProperties(new FileInputStream(cfgDirFile)); props.putAll(fProps); } else if (serverEnvFile.exists()) { fProps = parseProperties(new FileInputStream(serverEnvFile)); props.putAll(fProps); } cfgDirFile = getFileFromConfigDirectory("bootstrap.properties"); if (cfgDirFile != null) { fProps = parseProperties(new FileInputStream(cfgDirFile)); props.putAll(fProps); } else if (bootstrapProp != null && !bootstrapProp.isEmpty()) { props.putAll(bootstrapProp); } else if (bootstrapFile.exists()) { fProps = parseProperties(new FileInputStream(bootstrapFile)); props.putAll(fProps); } parseIncludeVariables(doc); parseConfigDropinsDirVariables("defaults"); parseVariables(doc); parseConfigDropinsDirVariables("overrides"); parseApplication(doc, "/server/application"); parseApplication(doc, "/server/webApplication"); parseApplication(doc, "/server/enterpriseApplication"); parseInclude(doc); parseConfigDropinsDir(); } catch (Exception e) { e.printStackTrace(); } }
Source:
<code>private CredentialsProvider getCredentialsProvider() { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( <START> System.getProperty("solr.username"), System.getProperty("solr.credentials")); <END> provider.setCredentials(AuthScope.ANY, credentials); return provider; }</code><technical_language>Retrieve properties privileged actions</technical_language>

Target:
private CredentialsProvider getCredentialsProvider() { String username = getUsername(); String password = getPassword(); CredentialsProvider provider = new BasicCredentialsProvider(); org.apache.http.auth.UsernamePasswordCredentials credentials = new org.apache.http.auth.UsernamePasswordCredentials(username, password); provider.setCredentials(AuthScope.ANY, credentials); return provider; }
Source:
<code>public void removeWorkspace(String workspaceId) throws ConflictException, ServerException { TracingTags.WORKSPACE_ID.set(workspaceId); TracingTags.USER_ID.set(() -> EnvironmentContext.getCurrent().getSubject().getUserId()); try { <START> TracingTags.STACK_ID.set( <END> workspaceDao.get(workspaceId).getAttributes().getOrDefault("stackId", "no stack")); } catch (NotFoundException e) { LOG.warn("Unable to provide stack id for tracing"); } requireNonNull(workspaceId, "Required non-null workspace id"); if (runtimes.hasRuntime(workspaceId)) { throw new ConflictException( format("The workspace '%s' is currently running and cannot be removed.", workspaceId)); } workspaceDao.remove(workspaceId); LOG.info("Workspace '{}' removed by user '{}'", workspaceId, sessionUserNameOrUndefined()); }</code><technical_language>ThisSTACK_ID code overweight. remove all? @sleshchenko @mshaposhnik @metlos wdyt</technical_language>

Target:
public void removeWorkspace(String workspaceId) throws ConflictException, ServerException { TracingTags.WORKSPACE_ID.set(workspaceId); requireNonNull(workspaceId, "Required non-null workspace id"); if (runtimes.hasRuntime(workspaceId)) { throw new ConflictException( format("The workspace '%s' is currently running and cannot be removed.", workspaceId)); } Optional<WorkspaceImpl> workspaceOpt = workspaceDao.remove(workspaceId); workspaceOpt.ifPresent( workspace -> TracingTags.STACK_ID.set( workspace.getAttributes().getOrDefault("stackId", "no stack"))); LOG.info("Workspace '{}' removed by user '{}'", workspaceId, sessionUserNameOrUndefined()); }
Source:
<code><START> public void doVisitRandomArticle() { <END> final Bus bus = app.getBus(); Handler randomHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { RandomArticleIdTask randomTask = new RandomArticleIdTask(app.getAPIForSite(app.getPrimarySite()), app.getPrimarySite(), app) { @Override public void onBeforeExecute() { setState(true); } @Override public void onFinish(PageTitle title) { if (isClosed) { return; } setState(false); Log.d("Wikipedia", "Random article title pulled: " + title); if (title != null) { randomListener.onRandomPageReceived(title); } else { Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } } @Override public void onCatch(Throwable caught) { if (isClosed) { return; } setState(false); Log.d("Wikipedia", "Random article ID retrieval failed"); curRandomArticleIdTask = null; Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } }; if (curRandomArticleIdTask != null) { curRandomArticleIdTask.cancel(); } curRandomArticleIdTask = randomTask; curRandomArticleIdTask.execute(); return true; } }); randomHandler.removeMessages(MESSAGE_RND); Message randomMessage = Message.obtain(); randomMessage.what = MESSAGE_RND; randomMessage.obj = "random"; randomHandler.sendMessage(randomMessage); }</code><technical_language>needed anymore</technical_language>

Target:
public void doVisitRandomArticle() { Handler randomHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { RandomArticleIdTask randomTask = new RandomArticleIdTask(app.getAPIForSite(app.getPrimarySite()), app.getPrimarySite(), app) { @Override public void onBeforeExecute() { setState(true); } @Override public void onFinish(PageTitle title) { if (isClosed) { return; } setState(false); Log.d("Wikipedia", "Random article title pulled: " + title); if (title != null) { randomListener.onRandomPageReceived(title); } else { Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } } @Override public void onCatch(Throwable caught) { if (isClosed) { return; } setState(false); Log.d("Wikipedia", "Random article ID retrieval failed"); curRandomArticleIdTask = null; Toast.makeText(app, app.getString(R.string.error_network_error), Toast.LENGTH_LONG).show(); } }; if (curRandomArticleIdTask != null) { curRandomArticleIdTask.cancel(); } curRandomArticleIdTask = randomTask; curRandomArticleIdTask.execute(); return true; } }); randomHandler.removeMessages(MESSAGE_RND); Message randomMessage = Message.obtain(); randomMessage.what = MESSAGE_RND; randomMessage.obj = "random"; randomHandler.sendMessage(randomMessage); }
Source:
<code>public QueryableGridDialect<?> initiateService(Map configurationValues, ServiceRegistryImplementor registry) { <START> return asQueryableGridDialectOrNull( registry.getService( GridDialect.class ) ); <END> }</code><technical_language>I guess reuse method in ForwardingGridDialect</technical_language>

Target:
public QueryableGridDialect<?> initiateService(Map configurationValues, ServiceRegistryImplementor registry) { return GridDialects.getDialectFacetOrNull( registry.getService( GridDialect.class ), QueryableGridDialect.class ); }
Source:
<code>private void updateAllocation() { long totalAllocations = 0; double scale; for (Long allocation : writerList.values()) { totalAllocations += allocation; } if (totalAllocations <= totalMemoryPool) { scale = 1.0; } else { scale = (double) totalMemoryPool / totalAllocations; LOG.warn(String.format( "Total allocation exceeds %.2f%% (%,d bytes) of heap memory\n" + "Scaling row group sizes to %.2f%% for %d writers", 100*memoryPoolRatio, totalMemoryPool, 100*scale, writerList.size())); } int maxColCount = 0; for (InternalParquetRecordWriter w : writerList.keySet()) { maxColCount = Math.max(w.getSchema().getColumns().size(), maxColCount); } for (Map.Entry<InternalParquetRecordWriter, Long> entry : writerList.entrySet()) { long newSize = (long) Math.floor(entry.getValue() * scale); if(scale < 1.0 && minMemoryAllocation > 0 && newSize < minMemoryAllocation) { <START> throw new ParquetRuntimeException(String.format("New Memory allocation %d" + <END> " is smaller than the minimum allocation size of %d", newSize, minMemoryAllocation)){}; } entry.getKey().setRowGroupSizeThreshold(newSize); LOG.debug(String.format("Adjust block size from %,d to %,d for writer: %s", entry.getValue(), newSize, entry.getKey())); } }</code><technical_language>Nit: include units in error message</technical_language>

Target:
private void updateAllocation() { long totalAllocations = 0; double scale; for (Long allocation : writerList.values()) { totalAllocations += allocation; } if (totalAllocations <= totalMemoryPool) { scale = 1.0; } else { scale = (double) totalMemoryPool / totalAllocations; LOG.warn(String.format( "Total allocation exceeds %.2f%% (%,d bytes) of heap memory\n" + "Scaling row group sizes to %.2f%% for %d writers", 100*memoryPoolRatio, totalMemoryPool, 100*scale, writerList.size())); } int maxColCount = 0; for (InternalParquetRecordWriter w : writerList.keySet()) { maxColCount = Math.max(w.getSchema().getColumns().size(), maxColCount); } for (Map.Entry<InternalParquetRecordWriter, Long> entry : writerList.entrySet()) { long newSize = (long) Math.floor(entry.getValue() * scale); if(scale < 1.0 && minMemoryAllocation > 0 && newSize < minMemoryAllocation) { throw new ParquetRuntimeException(String.format("New Memory allocation %d bytes" + " is smaller than the minimum allocation size of %d bytes.", newSize, minMemoryAllocation)){}; } entry.getKey().setRowGroupSizeThreshold(newSize); LOG.debug(String.format("Adjust block size from %,d to %,d for writer: %s", entry.getValue(), newSize, entry.getKey())); } }
Source:
<code>public Object getMember(String memberName) { if (memberName == MEMBER_ARTIFACT_KEY) return key; if (memberName == MEMBER_PROPERTIES) { if (properties == null) { <START> properties = new OrderedProperties(); <END> } return properties; } if (memberName == MEMBER_PROCESSING_STEPS) return processingSteps; if (memberName == MEMBER_REPOSITORY) return repository; throw new IllegalArgumentException("No such member: " + memberName); }</code><technical_language>threading considerations this happen time multiple threads</technical_language>

Target:
public Object getMember(String memberName) { if (memberName == MEMBER_ARTIFACT_KEY) return key; if (memberName == MEMBER_PROPERTIES) { synchronized (this) { if (properties == null) { properties = new OrderedProperties(); } } return properties; } if (memberName == MEMBER_PROCESSING_STEPS) return processingSteps; if (memberName == MEMBER_REPOSITORY) return repository; throw new IllegalArgumentException("No such member: " + memberName); }
Source:
<code>public ProjectToOrganizationConverter(ResultApprover resultApprover, byte[] relationColumnFamilyBytes) { super(resultApprover); <START> this.relationColumnFamilyBytes = OafHelper.copyArrayWhenNotNull(relationColumnFamilyBytes); <END> }</code><technical_language>resultApprover null? sense? I guess not, is a general solution a specific class in specific circumstances. relationColumnFamilyBytes null? if is null</technical_language>

Target:
public ProjectToOrganizationConverter(ResultApprover resultApprover, byte[] relationColumnFamilyBytes) { super(resultApprover); Preconditions.checkNotNull(resultApprover); Preconditions.checkNotNull(relationColumnFamilyBytes); this.relationColumnFamilyBytes = OafHelper.copyArrayWhenNotNull(relationColumnFamilyBytes); }
Source:
<code>public void trimDocument() { int len = 0; len = getDocument().getLength(); if (len > maxChars) { int n = len - maxChars; <START> System.out.println("trimDocument: remove " + n + " chars"); <END> try { getDocument().remove(0, n); } catch (BadLocationException ble) { } } }</code><technical_language>Left</technical_language>

Target:
public void trimDocument() { int len = 0; len = getDocument().getLength(); if (len > trimMaxChars) { int n = len - trimMaxChars; try { getDocument().remove(0, n); } catch (BadLocationException ble) { } } }
Source:
<code>protected String[] getBodyArray( HttpResponse response ) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy( response.getEntity().getContent(), sw ); <START> IOUtils.closeQuietly( response.getEntity().getContent() ); <END> return sw.toString().split( System.lineSeparator() ); }</code><technical_language>do closeQuietly in a finally block</technical_language>

Target:
protected String[] getBodyArray( HttpResponse response ) throws IOException { try { StringWriter sw = new StringWriter(); IOUtils.copy( response.getEntity().getContent(), sw ); return sw.toString().split( System.lineSeparator() ); } finally { IOUtils.closeQuietly( response.getEntity().getContent() ); } }
Source:
<code>public void should_know_the_url_of_the_last_build() { view = JobView.of( a(job().whereTheLast(build().numberIs(22))), <START> config, locatedAt("job/project-name") <END> ); assertThat(view.lastBuildUrl(), is("job/project-name/22/")); }</code><technical_language>Similarly here, if wanted inject config object explicitly, a helper akin locatedAt, ie. JobView.of(a(job().whereTheLast(build().finishedWith(FAILURE)), configuredTo(showCulprits())))</technical_language>

Target:
public void should_know_the_url_of_the_last_build() { view = a(jobView().of( a(job().whereTheLast(build().hasNumber(22)))) .with(locatedAt("job/project-name"))); assertThat(view.lastBuildUrl(), is("job/project-name/22/")); }
Source:
<code>public boolean supports(MediaType delimiter) { <START> if (this.mediaTypes == null) { <END> return true; } else { for (MediaType mediaType : this.mediaTypes) { if (mediaType.isCompatibleWith(delimiter)) { return true; } } return false; } }</code><technical_language>This definition happen, I check for empty collection here</technical_language>

Target:
public boolean supports(MediaType delimiter) { if (this.mediaTypes.isEmpty()) { return true; } else { for (MediaType mediaType : this.mediaTypes) { if (mediaType.isCompatibleWith(delimiter)) { return true; } } return false; } }
Source:
<code>public static void freeDirectBuffer(ByteBuffer buffer) { <START> if (!ALLOW_CUSTOM_CLEANER || customerCleaner == null) { <END> PlatformDependent.freeDirectBuffer(buffer); } else { customerCleaner.freeDirectMemory(buffer); } }</code><technical_language>a big deal read in a local variable customCleaner is null while accessing time</technical_language>

Target:
public static void freeDirectBuffer(ByteBuffer buffer) { CustomCleaner localCustomCleaner; if (!ALLOW_CUSTOM_CLEANER || (localCustomCleaner = DirectCleaner.customCleaner) == null) { PlatformDependent.freeDirectBuffer(buffer); } else { localCustomCleaner.freeDirectMemory(buffer); } }
Source:
<code><START> public void addComponent(JComponent component, String orientation){ <END> workspaceBar.add(component, orientation); }</code><technical_language>this protected if want</technical_language>

Target:
protected void addComponent(JComponent component, String orientation){ workspaceBar.add(component, orientation); }
Source:
<code>private boolean rewrite() { match(subject); if (success) { List<ExtendedSubstitution> normalizedExtSubsts = getCNFExtendedSubstitutions( fExtSubst, fMultiExtSubsts); Profiler.startTimer(Profiler.EVALUATE_SIDE_CONDITIONS_TIMER); ExtendedSubstitution solution = null; for (ExtendedSubstitution extSubst : normalizedExtSubsts) { Map<Variable, Term> updatedSubst = evaluateConditions(extSubst.substitution()); if (updatedSubst != null) { extSubst.setSubst(updatedSubst); solution = extSubst; break; } } Profiler.stopTimer(Profiler.EVALUATE_SIDE_CONDITIONS_TIMER); if (solution != null) { Profiler.startTimer(Profiler.LOCAL_REWRITE_BUILD_RHS_TIMER); Transformer substAndEvalTransformer = new CopyOnShareSubstAndEvalTransformer( solution.substitution(), rule.reusableLhsVariables().elementSet(), context); for (Cell cell : solution.writeCells()) { String cellLabel = cell.getLabel(); Term rightHandSide = getWriteCellRHS(cellLabel); if (rule.cellsToCopy().contains(cellLabel)) { rightHandSide = DeepCloner.clone(rightHandSide); } <START> cell.unsafeSetContent((Term) rightHandSide.accept(substAndEvalTransformer)); <END> } Profiler.stopTimer(Profiler.LOCAL_REWRITE_BUILD_RHS_TIMER); } else { success = false; } } return success; }</code><technical_language>do need reset computed hash code do this</technical_language>

Target:
private boolean rewrite() { match(subject); if (success) { List<ExtendedSubstitution> normalizedExtSubsts = getCNFExtendedSubstitutions( fExtSubst, fMultiExtSubsts); Profiler.startTimer(Profiler.EVALUATE_SIDE_CONDITIONS_TIMER); ExtendedSubstitution solution = null; for (ExtendedSubstitution extSubst : normalizedExtSubsts) { Map<Variable, Term> updatedSubst = evaluateConditions(extSubst.substitution()); if (updatedSubst != null) { extSubst.setSubst(updatedSubst); solution = extSubst; break; } } Profiler.stopTimer(Profiler.EVALUATE_SIDE_CONDITIONS_TIMER); if (solution != null) { Profiler.startTimer(Profiler.LOCAL_REWRITE_BUILD_RHS_TIMER); Transformer substAndEvalTransformer = new CopyOnShareSubstAndEvalTransformer( solution.substitution(), rule.reusableVariables().elementSet(), context); for (Cell cell : solution.writeCells()) { String cellLabel = cell.getLabel(); Term rightHandSide = getWriteCellRHS(cellLabel); if (rule.cellsToCopy().contains(cellLabel)) { rightHandSide = DeepCloner.clone(rightHandSide); } cell.unsafeSetContent((Term) rightHandSide.accept(substAndEvalTransformer)); } Profiler.stopTimer(Profiler.LOCAL_REWRITE_BUILD_RHS_TIMER); } else { success = false; } } return success; }
Source:
<code><START> public static Expr[] toConjunctiveNormalFormArray(Expr expr) { <END> List<Expr> list = new ArrayList<Expr>(); toConjunctiveNormalFormArrayRecursive(expr, list); return list.toArray(new Expr[list.size()]); }</code><technical_language>Unnecessary change</technical_language>

Target:
public static Expr[] toConjunctiveNormalFormArray(Expr expr) { List<Expr> list = TUtil.newList(); toConjunctiveNormalFormArrayRecursive(expr, list); return list.toArray(new Expr[list.size()]); }
Source:
<code><START> public static Map<String, Partitioner> getPartitioners() { <END> return partitionersByTopic; }</code><technical_language>this method return map values collection values set</technical_language>

Target:
public static Set<Partitioner> getPartitioners() { return new HashSet<Partitioner>(partitionersByTopic.values()); }
Source:
<code>public String getElementAxisName(final IAxis axis) { String returnedValue = null; if (axis instanceof FeatureIdAxis) { String elementId = ((FeatureIdAxis) axis).getElement(); final Object resolvedElement = resolvedPath(elementId); if (resolvedElement instanceof NamedElement) { returnedValue = UMLLabelInternationalization.getInstance().getLabel((NamedElement) resolvedElement); } else { elementId = <START> elementId.replace("property_of_stereotype:/", <END> ""); final String[] splitedElementId = elementId.split("::"); returnedValue = splitedElementId[splitedElementId.length - 1]; } } return null != returnedValue ? returnedValue : super.getElementAxisName(axis); }</code><technical_language>duplicate string</technical_language>

Target:
public String getElementAxisName(final IAxis axis) { String returnedValue = null; if (axis instanceof FeatureIdAxis) { String elementId = ((FeatureIdAxis) axis).getElement(); final Object resolvedElement = resolvedPath(elementId); if (resolvedElement instanceof NamedElement) { returnedValue = UMLLabelInternationalization.getInstance().getLabel((NamedElement) resolvedElement); } else { elementId = elementId.replace(Constants.PROPERTY_OF_STEREOTYPE_PREFIX, ""); final String[] splitedElementId = elementId.split("::"); returnedValue = splitedElementId[splitedElementId.length - 1]; } } return null != returnedValue ? returnedValue : super.getElementAxisName(axis); }
Source:
<code>private @NonNull InneractiveAdSpot.RequestListener createFyberBannerAdListener() { return new InneractiveAdSpot.RequestListener() { @Override public void onInneractiveSuccessfulAdRequest(InneractiveAdSpot inneractiveAdSpot) { if (!(mBannerSpot.getSelectedUnitController() instanceof InneractiveAdViewUnitController)) { <START> mMediationBannerListener.onAdFailedToLoad(FyberMediationAdapter.this, <END> AdRequest.ERROR_CODE_INTERNAL_ERROR); } InneractiveAdViewUnitController controller = (InneractiveAdViewUnitController) mBannerSpot.getSelectedUnitController(); InneractiveAdViewEventsListener listener = createFyberAdViewListener(); controller.setEventsListener(listener); mMediationBannerListener.onAdLoaded(FyberMediationAdapter.this); } @Override public void onInneractiveFailedAdRequest(InneractiveAdSpot inneractiveAdSpot, InneractiveErrorCode inneractiveErrorCode) { int adMobErrorCode = AdRequest.ERROR_CODE_INTERNAL_ERROR; if (inneractiveErrorCode == InneractiveErrorCode.CONNECTION_ERROR || inneractiveErrorCode == InneractiveErrorCode.CONNECTION_TIMEOUT) { adMobErrorCode = AdRequest.ERROR_CODE_NETWORK_ERROR; } else if (inneractiveErrorCode == InneractiveErrorCode.NO_FILL) { adMobErrorCode = AdRequest.ERROR_CODE_NO_FILL; } mMediationBannerListener.onAdFailedToLoad(FyberMediationAdapter.this, adMobErrorCode); } }; }</code><technical_language>clean invoke 'spot''s destroy()</technical_language>

Target:
private @NonNull InneractiveAdSpot.RequestListener createFyberBannerAdListener() { return new InneractiveAdSpot.RequestListener() { @Override public void onInneractiveSuccessfulAdRequest(InneractiveAdSpot inneractiveAdSpot) { if (!(mBannerSpot.getSelectedUnitController() instanceof InneractiveAdViewUnitController)) { mMediationBannerListener.onAdFailedToLoad(FyberMediationAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); mBannerSpot.destroy(); } InneractiveAdViewUnitController controller = (InneractiveAdViewUnitController) mBannerSpot.getSelectedUnitController(); InneractiveAdViewEventsListener listener = createFyberAdViewListener(); controller.setEventsListener(listener); mMediationBannerListener.onAdLoaded(FyberMediationAdapter.this); } @Override public void onInneractiveFailedAdRequest(InneractiveAdSpot inneractiveAdSpot, InneractiveErrorCode inneractiveErrorCode) { int adMobErrorCode = AdRequest.ERROR_CODE_INTERNAL_ERROR; if (inneractiveErrorCode == InneractiveErrorCode.CONNECTION_ERROR || inneractiveErrorCode == InneractiveErrorCode.CONNECTION_TIMEOUT) { adMobErrorCode = AdRequest.ERROR_CODE_NETWORK_ERROR; } else if (inneractiveErrorCode == InneractiveErrorCode.NO_FILL) { adMobErrorCode = AdRequest.ERROR_CODE_NO_FILL; } mMediationBannerListener.onAdFailedToLoad(FyberMediationAdapter.this, adMobErrorCode); } }; }
Source:
<code>protected Session getSession(URI sessionModelURI) { <START> Session sessionFromURI = null; <END> try { sessionFromURI = SessionManager.INSTANCE.getSession(sessionModelURI); if (sessionFromURI != null) { if (!sessionFromURI.isOpen()) { sessionFromURI.open(new NullProgressMonitor()); } IEditingSession uiSession = SessionUIManager.INSTANCE.getOrCreateUISession(sessionFromURI); uiSession.open(); } } catch (IllegalStateException e) { } return sessionFromURI; }</code><technical_language>combination of a default null a silent catch (which relies earlier initialization set correct value) confusing. this: final Session sessionFromURI; try { sessionFromURI = ...; ... } catch (IllegalStateException e) { sessionFromURI = null; // log error? } This clearer "when error occurs return null" (IMHO)</technical_language>

Target:
protected Session getSession(URI sessionModelURI) { Session sessionFromURI; try { sessionFromURI = SessionManager.INSTANCE.getSession(sessionModelURI); if (sessionFromURI != null) { if (!sessionFromURI.isOpen()) { sessionFromURI.open(new NullProgressMonitor()); } IEditingSession uiSession = SessionUIManager.INSTANCE.getOrCreateUISession(sessionFromURI); uiSession.open(); } } catch (IllegalStateException e) { sessionFromURI = null; } return sessionFromURI; }