auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void writeMetrics() { if (metrics.size() > 0) { try { String payload = pickleMetrics(metrics); int length = payload.length(); byte[] header = ByteBuffer.allocate(4).putInt(length).array(); socket.getOutputStream().write(header); writer.write(payload); writer.flush(); } catch (Exception e) { <START> if (LOGGER.isDebugEnabled()) { <END> LOGGER.debug("Error writing to Graphite", e); } else { LOGGER.warn("Error writing to Graphite: {}", e.getMessage()); } } LOGGER.debug("Wrote metrics", metrics.size()); metrics.clear(); } }</code><technical_language>Update this.failures</technical_language>

Target:
private void writeMetrics() throws IOException { if (metrics.size() > 0) { try { String payload = pickleMetrics(metrics); int length = payload.length(); byte[] header = ByteBuffer.allocate(4).putInt(length).array(); socket.getOutputStream().write(header); writer.write(payload); writer.flush(); LOGGER.debug("Wrote metrics", metrics.size()); } catch (IOException e) { this.failures++; throw e; } finally { metrics.clear(); } } }
Source:
<code>public TileEntity createNewTileEntity(World worldIn, int meta) { <START> if (Loader.isModLoaded("ic2") && PowerSystem.EnergySystem.EU.enabled.get()) { <END> return new TileCableEU(getStateFromMeta(meta).getValue(TYPE)); } else return new TileCable(getStateFromMeta(meta).getValue(TYPE)); }</code><technical_language>a bad idea add a config option for this, change behavour of cables in existing worlds. Right people cables transfer RF power IC2 is installed. I do out of scope a good idea a cable works EU FE, a config force FE cables amiss</technical_language>

Target:
public TileEntity createNewTileEntity(World worldIn, int meta) { if (useEUCables && Loader.isModLoaded("ic2") && PowerSystem.EnergySystem.EU.enabled.get()) { return new TileCableEU(getStateFromMeta(meta).getValue(TYPE)); } else return new TileCable(getStateFromMeta(meta).getValue(TYPE)); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); uri = Uri.parse(getString(R.string.website) + "cgi/user.pl"); <START> uri2 = Uri.parse(getString(R.string.website) + "cgi/reset_password.pl"); <END> customTabActivityHelper = new CustomTabActivityHelper(); customTabActivityHelper.setConnectionCallback(this); customTabActivityHelper.mayLaunchUrl(uri, null, null); signup.setEnabled(false); final SharedPreferences settings = getSharedPreferences("login", 0); String loginS = settings.getString("user", getResources().getString(R.string.txt_anonymous)); if(!loginS.equals(getResources().getString(R.string.txt_anonymous))) { new MaterialDialog.Builder(this) .title("Login") .content("Already logged in!") .neutralText(R.string.ok_button) .show(); } apiClient = new Retrofit.Builder() .baseUrl(BuildConfig.HOST) .build() .create(OpenFoodAPIService.class); }</code><technical_language>For code maintainability, change uri's reflect for? for example, uri -> userLoginUri uri2 -> resetPasswordUri similar? This get confusing in future, fixing this improve readability. :)</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); userLoginUri = Uri.parse(getString(R.string.website) + "cgi/user.pl"); resetPasswordUri = Uri.parse(getString(R.string.website) + "cgi/reset_password.pl"); customTabActivityHelper = new CustomTabActivityHelper(); customTabActivityHelper.setConnectionCallback(this); customTabActivityHelper.mayLaunchUrl(userLoginUri, null, null); signup.setEnabled(false); final SharedPreferences settings = getSharedPreferences("login", 0); String loginS = settings.getString("user", getResources().getString(R.string.txt_anonymous)); if(!loginS.equals(getResources().getString(R.string.txt_anonymous))) { new MaterialDialog.Builder(this) .title("Login") .content("Already logged in!") .neutralText(R.string.ok_button) .show(); } apiClient = new Retrofit.Builder() .baseUrl(BuildConfig.HOST) .build() .create(OpenFoodAPIService.class); }
Source:
<code>public ChartRange(BigDecimal minimum, BigDecimal maximum) { <START> BigDecimal subtract = maximum.subtract(minimum); if (BigDecimal.ZERO.equals(subtract)) { fMinimum = minimum; fMaximum = minimum.add(BigDecimal.ONE); fRange = BigDecimal.ONE; } else { fMinimum = minimum; fMaximum = maximum; fRange = checkNotNull(subtract); } <END> }</code><technical_language>this logic needs applied too</technical_language>

Target:
public ChartRange(BigDecimal minimum, BigDecimal maximum) { BigDecimal subtract = maximum.subtract(minimum); if (minimum.compareTo(maximum) > 0) { throw new IllegalArgumentException("ChartRange: minimum should be lower than or equal to the maximum (min: " + minimum + ", max: " + maximum + ')'); } if (BigDecimal.ZERO.equals(subtract)) { fMinimum = minimum; fMaximum = minimum.add(BigDecimal.ONE); fRange = BigDecimal.ONE; } else { fMinimum = minimum; fMaximum = maximum; fRange = checkNotNull(subtract); } }
Source:
<code>private String rowToString() { String fields = arguments.stream() .map(ClientTypeSignatureParameter::getNamedTypeSignature) .map(parameter -> { if (parameter.getName().isPresent()) { <START> format("%s %s", parameter.getName().get(), parameter.getTypeSignature().toString()); <END> } return parameter.getTypeSignature().toString(); }) .collect(Collectors.joining(",")); return format("row(%s)", fields); }</code><technical_language>return</technical_language>

Target:
private String rowToString() { String fields = arguments.stream() .map(ClientTypeSignatureParameter::getNamedTypeSignature) .map(parameter -> { if (parameter.getName().isPresent()) { return format("%s %s", parameter.getName().get(), parameter.getTypeSignature().toString()); } return parameter.getTypeSignature().toString(); }) .collect(Collectors.joining(",")); return format("row(%s)", fields); }
Source:
<code>public boolean isWebSocketProxyDefined() { String wsConfig = (String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.WebSocketProxy); <START> return wsConfig != null && !"".equals(wsConfig) && !"Off".equals(wsConfig); END> }</code><technical_language>"Off" capital? need do a case insensitive compare</technical_language>

Target:
public boolean isWebSocketProxyDefined() { String wsConfig = (String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.WebSocketProxy); return wsConfig != null && !"".equals(wsConfig) && !"Off".equalsIgnoreCase(wsConfig); }
Source:
<code><START> MethodInvocationTree getTree() { <END> return tree; }</code><technical_language>visibility this method have</technical_language>

Target:
public MethodInvocationTree getTree() { return tree; }
Source:
<code>public String getAsCommaSeparatedList(final List<String> headers) { Assert.requireNonNull(headers, "headers"); StringBuilder values = new StringBuilder(""); <START> if (null != headers && headers.size() > 0) { <END> for (int i = 0; i < headers.size(); i++) { values.append(headers.get(i)); if (i < headers.size() - 1) { values.append(","); } } } return values.toString(); }</code><technical_language>check for null twice. assert is good enough</technical_language>

Target:
public String getAsCommaSeparatedList(final List<String> headers) { Assert.requireNonNull(headers, "headers"); StringBuilder values = new StringBuilder(""); if (headers.size() > 0) { for (int i = 0; i < headers.size(); i++) { values.append(headers.get(i)); if (i < headers.size() - 1) { values.append(","); } } } return values.toString(); }
Source:
<code>public void readerOpened(BlockReader reader, BlockStoreLocation location) { Preconditions.checkState(locationValid(location)); mStreamsPerLocation.compute(location, (k, v) -> { Set<Object> streamList = v; if (streamList == null) { streamList = new ConcurrentHashSet<>(); } streamList.add(reader); return streamList; <START> }); <END> }</code><technical_language>logic of *Opened *Closed same, abstract another method</technical_language>

Target:
public void readerOpened(BlockReader reader, BlockStoreLocation location) { streamOpened(reader, location); }
Source:
<code><START> public File newFolder(String folder) throws IOException, IllegalArgumentException { <END> return newFolder(new String[]{folder}); }</code><technical_language>Please remove IllegalArgumentException throws clause</technical_language>

Target:
public File newFolder(String folder) throws IOException { return newFolder(new String[]{folder}); }
Source:
<code><START> public JsonNode getSavedSearch(Mediator m, <END> ClientIdentification clid, String searchName, String entity, String version) { LOGGER.debug("Loading {}:{}:{}",searchName,entity,version); ObjectNode doc=null; String loadVersion; if(version==null) { LOGGER.debug("{} version is null, attempting to find default version for entity",entity); EntityMetadata md=m.metadata.getEntityMetadata(entity,null); if(md==null) throw Error.get(CrudConstants.ERR_UNKNOWN_ENTITY,entity+":"+version); loadVersion=md.getVersion().getValue(); LOGGER.debug("Loading {}:{}:{}",searchName,entity,loadVersion); } else { loadVersion=version; } Key key=new Key(searchName,entity,loadVersion); LOGGER.debug("Lookup {}",key); doc=cache.getIfPresent(key); if(doc==null) { key=new Key(searchName,entity,null); LOGGER.debug("Lookup {}",key); doc=cache.getIfPresent(key); } if(doc==null) { LOGGER.debug("Loading from DB",searchName); JsonNode node=retrieveFromDB(m,clid,searchName,entity,loadVersion); if(node instanceof ObjectNode) { LOGGER.debug("Loaded a single search"); doc=(ObjectNode)node; store(doc); } else if(node instanceof ArrayNode) { LOGGER.debug("Loaded an array of searches"); store((ArrayNode)node); doc=findDocForVersion((ArrayNode)node,loadVersion); } if(doc!=null) { store(doc); } } return doc; }</code><technical_language>name a more intuitively? getSavedSearch getSavedSearchFromDb that</technical_language>

Target:
public JsonNode getSavedSearch(Mediator m, ClientIdentification clid, String searchName, String entity, String version) { LOGGER.debug("Loading {}:{}:{}",searchName,entity,version); ObjectNode doc=null; String loadVersion; if(version==null) { LOGGER.debug("{} version is null, attempting to find default version for entity",entity); EntityMetadata md=m.metadata.getEntityMetadata(entity,null); if(md==null) throw Error.get(CrudConstants.ERR_UNKNOWN_ENTITY,entity+":"+version); loadVersion=md.getVersion().getValue(); LOGGER.debug("Loading {}:{}:{}",searchName,entity,loadVersion); } else { loadVersion=version; } Key key=new Key(searchName,entity,loadVersion); LOGGER.debug("Lookup {}",key); doc=cache.getIfPresent(key); if(doc==null) { key=new Key(searchName,entity,null); LOGGER.debug("Lookup {}",key); doc=cache.getIfPresent(key); } if(doc==null) { LOGGER.debug("Loading from DB",searchName); JsonNode node=getSavedSearchFromDB(m,clid,searchName,entity,loadVersion); if(node instanceof ObjectNode) { LOGGER.debug("Loaded a single search"); doc=(ObjectNode)node; store(doc); } else if(node instanceof ArrayNode) { LOGGER.debug("Loaded an array of searches"); store((ArrayNode)node); doc=findDocForVersion((ArrayNode)node,loadVersion); } if(doc!=null) { store(doc); } } return doc; }
Source:
<code>private StorageManager getCacheBackedDao(IotasConfiguration iotasConfiguration) { StorageProviderConfiguration storageProviderConfiguration = iotasConfiguration.getStorageProviderConfiguration(); final String providerType = storageProviderConfiguration.getType(); <START> final StorageManager dao = providerType.equalsIgnoreCase("jdbc") ? <END> JdbcStorageManager.createStorageManager(storageProviderConfiguration.getProperties()) : new InMemoryStorageManager(); final CacheBuilder cacheBuilder = getGuavaCacheBuilder(); final Cache<StorableKey, Storable> cache = getCache(dao, cacheBuilder); final StorageWriter storageWriter = getStorageWriter(dao); return doGetCacheBackedDao(cache, storageWriter); }</code><technical_language>this "jdbc" a constant</technical_language>

Target:
private StorageManager getCacheBackedDao(IotasConfiguration iotasConfiguration) { StorageProviderConfiguration storageProviderConfiguration = iotasConfiguration.getStorageProviderConfiguration(); final String providerType = storageProviderConfiguration.getType(); final StorageManager dao = providerType.equalsIgnoreCase(JDBC) ? JdbcStorageManager.createStorageManager(storageProviderConfiguration.getProperties()) : new InMemoryStorageManager(); final CacheBuilder cacheBuilder = getGuavaCacheBuilder(); final Cache<StorableKey, Storable> cache = getCache(dao, cacheBuilder); final StorageWriter storageWriter = getStorageWriter(dao); return doGetCacheBackedDao(cache, storageWriter); }
Source:
<code>public void set(TypedHistogram value) { if (value instanceof GroupedTypedHistogram) { if (typedHistogram != null) { size -= typedHistogram.getEstimatedSize(); } typedHistogram = value; } else { <START> throw new IllegalArgumentException(String.format("only class %s supported, passed %s", GroupedTypedHistogram.class, typedHistogram.getClass())); <END> } size += typedHistogram.getEstimatedSize(); }</code><technical_language>a checkArgument top of method</technical_language>

Target:
public void set(TypedHistogram value) { checkArgument(value instanceof GroupedTypedHistogram, "only class %s supported, passed %s", GroupedTypedHistogram.class, typedHistogram.getClass()); requireNonNull(typedHistogram != null, "this.typedHistogram should always be non-null"); size -= typedHistogram.getEstimatedSize(); size += value.getEstimatedSize(); typedHistogram = value; }
Source:
<code>public void updatePeriodicBinResults(TransactionBase tx, VisibilityBindingSet bs, PeriodicQueryMetadata metadata) throws Exception { Set<Long> binIds = getBinEndTimes(metadata, bs); for(Long id: binIds) { QueryBindingSet binnedBs = new QueryBindingSet(bs); binnedBs.addBinding(IncrementalUpdateConstants.PERIODIC_BIN_ID, vf.createLiteral(id)); VisibilityBindingSet visibilityBindingSet = new VisibilityBindingSet(binnedBs, bs.getVisibility()); Bytes periodicBsBytes = BS_SERDE.serialize(visibilityBindingSet); <START> final Bytes resultRow = getRowKey(metadata.getNodeId(), metadata.getVariableOrder(), visibilityBindingSet); <END> Column col = FluoQueryColumns.PERIODIC_QUERY_BINDING_SET; tx.set(resultRow, col, periodicBsBytes); } }</code><technical_language>create get doc</technical_language>

Target:
public void updatePeriodicBinResults(TransactionBase tx, VisibilityBindingSet bs, PeriodicQueryMetadata metadata) throws Exception { Set<Long> binIds = getBinEndTimes(metadata, bs); for(Long id: binIds) { QueryBindingSet binnedBs = new QueryBindingSet(bs); binnedBs.addBinding(IncrementalUpdateConstants.PERIODIC_BIN_ID, vf.createLiteral(id)); VisibilityBindingSet visibilityBindingSet = new VisibilityBindingSet(binnedBs, bs.getVisibility()); Bytes periodicBsBytes = BS_SERDE.serialize(visibilityBindingSet); final Bytes resultRow = makeRowKey(metadata.getNodeId(), metadata.getVariableOrder(), visibilityBindingSet); Column col = FluoQueryColumns.PERIODIC_QUERY_BINDING_SET; tx.set(resultRow, col, periodicBsBytes); } }
Source:
<code><START> public ArrayList<PixelWeight> getPixelWeights (Geometry geometry) { <END> return getPixelWeights(geometry, false, null); }</code><technical_language>Field return types interface type (List) implementation type (ArrayList)</technical_language>

Target:
public List<PixelWeight> getPixelWeights (Geometry geometry) { return getPixelWeights(geometry, false); }
Source:
<code>protected MapSqlParameterSource createFullParametersMapper(Provider<?> entity) { MapSqlParameterSource mapper = createBaseProviderParametersMapper(entity); String tenantName = null; String pluginType = null; if (entity.getAdditionalProperties() != null) { switch (entity.getType()) { case OPENSTACK_NETWORK: OpenstackNetworkProviderProperties networkProperties = (OpenstackNetworkProviderProperties) entity.getAdditionalProperties(); tenantName = networkProperties.getTenantName(); pluginType = networkProperties.getPluginType().name(); break; case OPENSTACK_IMAGE: <START> OpenstackImageProviderProperties imageProperties = <END> (OpenstackImageProviderProperties) entity.getAdditionalProperties(); tenantName = imageProperties.getTenantName(); break; default: break; } } mapper.addValue("tenant_name", tenantName); mapper.addValue("plugin_type", pluginType); return mapper; }</code><technical_language>if OpenstackNetworkProviderProperties OpenstackImageProviderProperties property tenantName - create a base class contains this property. more clean set in mapAdditionalProperties method below</technical_language>

Target:
protected MapSqlParameterSource createFullParametersMapper(Provider<?> entity) { MapSqlParameterSource mapper = createBaseProviderParametersMapper(entity); String tenantName = null; String pluginType = null; if (entity.getAdditionalProperties() != null) { switch (entity.getType()) { case OPENSTACK_NETWORK: OpenstackNetworkProviderProperties networkProperties = (OpenstackNetworkProviderProperties) entity.getAdditionalProperties(); tenantName = networkProperties.getTenantName(); pluginType = networkProperties.getPluginType(); break; case OPENSTACK_IMAGE: OpenstackImageProviderProperties imageProperties = (OpenstackImageProviderProperties) entity.getAdditionalProperties(); tenantName = imageProperties.getTenantName(); break; default: break; } } mapper.addValue("tenant_name", tenantName); mapper.addValue("plugin_type", pluginType); return mapper; }
Source:
<code>public SourceRoot parse(String startPackage, JavaParser javaParser, Callback callback) throws IOException { assertNotNull(startPackage); assertNotNull(javaParser); assertNotNull(callback); Log.info("Parsing package \"%s\"", startPackage); final Path path = packageAbsolutePath(root, startPackage); class AsynchronousParse extends RecursiveAction { private static final long serialVersionUID = 1L; private final Path path; public AsynchronousParse(Path path) { this.path = path; } @Override protected void compute() { final List<AsynchronousParse> walks = new ArrayList<>(); try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (!dir.equals(AsynchronousParse.this.path)) { AsynchronousParse w = new AsynchronousParse(dir); w.fork(); <START> walks.add(w); <END> return FileVisitResult.SKIP_SUBTREE; } else { return FileVisitResult.CONTINUE; } } @Override public FileVisitResult visitFile(Path absolutePath, BasicFileAttributes attrs) throws IOException { if (!attrs.isDirectory() && absolutePath.toString().endsWith(".java")) { Path localPath = root.relativize(absolutePath); Log.trace("Parsing %s", localPath); final ParseResult<CompilationUnit> result = new JavaParser( SourceRoot.this.javaParser.getParserConfiguration()).parse(COMPILATION_UNIT, provider(absolutePath)); result.getResult().ifPresent(cu -> cu.setStorage(absolutePath)); if (callback.process(localPath, absolutePath, result) == SAVE) { if (result.getResult().isPresent()) { save(result.getResult().get(), path); } } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { Log.error(e); } for (AsynchronousParse w : walks) { w.join(); } } } AsynchronousParse w = new AsynchronousParse(path); ForkJoinPool p = new ForkJoinPool(); p.invoke(w); return this; }</code><technical_language>completely unfamiliar this API, I judge if this is written. Works for code generation parts of JP though. @ftomassetti ? @jimshowalter</technical_language>

Target:
public SourceRoot parse(String startPackage, JavaParser javaParser, Callback callback) throws IOException { assertNotNull(startPackage); assertNotNull(javaParser); assertNotNull(callback); Log.info("Parsing package \"%s\"", startPackage); final Path path = packageAbsolutePath(root, startPackage); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path absolutePath, BasicFileAttributes attrs) throws IOException { if (!attrs.isDirectory() && absolutePath.toString().endsWith(".java")) { Path localPath = root.relativize(absolutePath); Log.trace("Parsing %s", localPath); final ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(absolutePath)); result.getResult().ifPresent(cu -> cu.setStorage(absolutePath)); if (callback.process(localPath, absolutePath, result) == SAVE) { if (result.getResult().isPresent()) { save(result.getResult().get(), path); } } } return FileVisitResult.CONTINUE; } }); return this; }
Source:
<code><START> public Integer getLimit() { <END> return _limit; }</code><technical_language>Based @Nullable in builder, convention Optional here. above, if KairosDb model this impossible</technical_language>

Target:
public Optional<Integer> getLimit() { return _limit; }
Source:
<code>private void copyFileInJarToOutput( JarFile jar, ZipEntry fileInJar ) throws MojoFailureException { String fullPath = fileInJar.getName(); String relativePath = fullPath .substring(fullPath.toLowerCase(Locale.ENGLISH) .indexOf(sourceDirectory.toLowerCase(Locale.ENGLISH)) + sourceDirectory.length()); <START> File target = new File(outputDirectory, relativePath); try { if (target.exists()) { if (clobber) { getLog().info(String.format( "File %s already exists and clobber is set; overwriting.", target.getName() )); File tempFile = File.createTempFile(fullPath, null); FileUtils.copyInputStreamToFile( jar.getInputStream(fileInJar), tempFile ); if (!FileUtils.contentEquals(tempFile, target)) { FileUtils.forceDelete(target); FileUtils.moveFile(tempFile, target); } else { tempFile.delete(); } } else { getLog().info(String.format( "File %s already exists and clobber is not set; skipping.", target.getName() )); } } else { FileUtils.copyInputStreamToFile( jar.getInputStream(fileInJar), target ); } <END> } catch (IOException e) { throw new MojoFailureException( "Failed to copy file " + fileInJar.getName() ); } }</code><technical_language>I prefer break this functions layers of branching</technical_language>

Target:
private void copyFileInJarToOutput( JarFile jar, ZipEntry fileInJar ) throws MojoFailureException { String fullPath = fileInJar.getName(); String relativePath = fullPath .substring(fullPath.toLowerCase(Locale.ENGLISH) .indexOf(sourceDirectory.toLowerCase(Locale.ENGLISH)) + sourceDirectory.length()); File target = new File(outputDirectory, relativePath); try { copyRespectingClobber(jar.getInputStream(fileInJar), target); } catch (IOException e) { throw new MojoFailureException( "Failed to copy file " + fileInJar.getName() ); } }
Source:
<code><START> public NGuid getStorageDomainId() { <END> List<DiskImage> images = getDiskImageDao().getAllSnapshotsForVmSnapshot(sourceSnapshotId); return (!images.isEmpty()) ? ImagesHandler.getStorageDomainId(images.get(0)) : Guid.Empty; }</code><technical_language>time a method called, running a new query</technical_language>

Target:
public NGuid getStorageDomainId() { if (storageDomainId == null) { List<DiskImage> images = getDiskImageDao().getAllSnapshotsForVmSnapshot(sourceSnapshotId); storageDomainId = (!images.isEmpty()) ? ImagesHandler.getStorageDomainId(images.get(0)) : Guid.Empty; } return storageDomainId; }
Source:
<code>private void collectPluginCapabilities(Map<String, CapabilityInfo> output) { for (String pluginName : pluginCapabilities.plugins()) { for (Map.Entry<String, Provider<CapabilityDefinition>> entry : pluginCapabilities.byPlugin(pluginName).entrySet()) { if (isPluginNameSane(pluginName)) { String id = String.format("%s-%s", pluginName, entry.getKey()); output.put(id, new CapabilityInfo( id, entry.getValue().get().getDescription())); } else { log.warn(String.format("Plugin name is not sane: <%s> " + "dropping plugin owned capability %s; " <START> + "consider to change the plugin file name.", <END> pluginName, entry.getKey())); } } } }</code><technical_language>"consider changing plugin filename"</technical_language>

Target:
private void collectPluginCapabilities(Map<String, CapabilityInfo> output) { for (String pluginName : pluginCapabilities.plugins()) { for (Map.Entry<String, Provider<CapabilityDefinition>> entry : pluginCapabilities.byPlugin(pluginName).entrySet()) { if (isPluginNameSane(pluginName)) { String id = String.format("%s-%s", pluginName, entry.getKey()); output.put(id, new CapabilityInfo( id, entry.getValue().get().getDescription())); } else { log.warn(String.format("Plugin name is not sane: <%s> " + "dropping plugin owned capability %s; " + "consider changing the plugin filename.", pluginName, entry.getKey())); } } } }
Source:
<code>private LogicalNode createCartesianProduct(PlanContext context, LogicalNode left, LogicalNode right) throws TajoException { LogicalPlan plan = context.plan; QueryBlock block = context.queryBlock; Schema merged = SchemaUtil.merge(left.getOutSchema(), right.getOutSchema()); JoinNode join = plan.createNode(JoinNode.class); join.init(JoinType.CROSS, left, right); join.setInSchema(merged); block.addJoinType(join.getJoinType()); EvalNode evalNode; List<String> newlyEvaluatedExprs = new ArrayList<>(); for (Iterator<NamedExpr> it = block.namedExprsMgr.getIteratorForUnevaluatedExprs(); it.hasNext();) { NamedExpr namedExpr = it.next(); try { evalNode = exprAnnotator.createEvalNode(context, namedExpr.getExpr(), NameResolvingMode.LEGACY); if (EvalTreeUtil.findDistinctAggFunction(evalNode).size() == 0 && EvalTreeUtil.findWindowFunction(evalNode).size() == 0) { block.namedExprsMgr.markAsEvaluated(namedExpr.getAlias(), evalNode); newlyEvaluatedExprs.add(namedExpr.getAlias()); } } catch (UndefinedColumnException ve) } List<Target> targets = new ArrayList<>(); <START> targets.addAll(PlannerUtil.schemaToTargets(merged)); <END> for (String newAddedExpr : newlyEvaluatedExprs) { targets.add(block.namedExprsMgr.getTarget(newAddedExpr, true)); } join.setTargets(targets); return join; }</code><technical_language>rewritten a single constructor call</technical_language>

Target:
private LogicalNode createCartesianProduct(PlanContext context, LogicalNode left, LogicalNode right) throws TajoException { LogicalPlan plan = context.plan; QueryBlock block = context.queryBlock; Schema merged = SchemaUtil.merge(left.getOutSchema(), right.getOutSchema()); JoinNode join = plan.createNode(JoinNode.class); join.init(JoinType.CROSS, left, right); join.setInSchema(merged); block.addJoinType(join.getJoinType()); EvalNode evalNode; List<String> newlyEvaluatedExprs = new ArrayList<>(); for (Iterator<NamedExpr> it = block.namedExprsMgr.getIteratorForUnevaluatedExprs(); it.hasNext();) { NamedExpr namedExpr = it.next(); try { evalNode = exprAnnotator.createEvalNode(context, namedExpr.getExpr(), NameResolvingMode.LEGACY); if (EvalTreeUtil.findDistinctAggFunction(evalNode).size() == 0 && EvalTreeUtil.findWindowFunction(evalNode).size() == 0) { block.namedExprsMgr.markAsEvaluated(namedExpr.getAlias(), evalNode); newlyEvaluatedExprs.add(namedExpr.getAlias()); } } catch (UndefinedColumnException ve) } List<Target> targets = new ArrayList<>(PlannerUtil.schemaToTargets(merged)); for (String newAddedExpr : newlyEvaluatedExprs) { targets.add(block.namedExprsMgr.getTarget(newAddedExpr, true)); } join.setTargets(targets); return join; }
Source:
<code>private Obs saveObsNotDirty(Obs obs, String changeMessage) { if(!obs.isObsGrouping()){ return obs; } ObsService os = Context.getObsService(); for (Obs o : obs.getGroupMembers(true)) { if (o.getId() == null) { os.saveObs(o, null); } else { os.saveObs(o, changeMessage); } } <START> Context.refreshEntity(obs); <END> return obs; }</code><technical_language>imagine need this if clause refresh parent is a replaced child</technical_language>

Target:
private Obs saveObsNotDirty(Obs obs, String changeMessage) { if(!obs.isObsGrouping()){ return obs; } ObsService os = Context.getObsService(); boolean refreshNeeded = false; for (Obs o : obs.getGroupMembers(true)) { if (o.getId() == null) { os.saveObs(o, null); } else { Obs newObs = os.saveObs(o, changeMessage); refreshNeeded = !newObs.equals(o) || refreshNeeded; } } if(refreshNeeded) { Context.refreshEntity(obs); } return obs; }
Source:
<code>private void processZoneFile(IngestJobContext context, Content dataSource, AbstractFile zoneFile, Collection<BlackboardArtifact> sourceArtifacts, Collection<BlackboardArtifact> downloadArtifacts, Set<Long> knownPathIDs) throws TskCoreException { ZoneIdentifierInfo zoneInfo = null; try { zoneInfo = new ZoneIdentifierInfo(zoneFile); } catch (IOException ex) { String message = String.format("Unable to parse temporary File for %s", zoneFile.getName()); LOG.log(Level.WARNING, message, ex); } if (zoneInfo == null) { return; } AbstractFile downloadFile = getDownloadFile(dataSource, zoneFile); if (downloadFile != null) { if (!knownPathIDs.contains(downloadFile.getDataSourceObjectId())) { <START> BlackboardArtifact downloadbba = createDownloadArtifact(zoneFile, zoneInfo); <END> if (downloadbba != null) { downloadArtifacts.add(downloadbba); } } if (downloadFile.getArtifactsCount(TSK_DOWNLOAD_SOURCE) == 0) { BlackboardArtifact sourcebba = createDownloadSourceArtifact(downloadFile, zoneInfo); if (sourcebba != null) { sourceArtifacts.add(sourcebba); } } } }</code><technical_language>CamelCase naming a easier read</technical_language>

Target:
private void processZoneFile(IngestJobContext context, Content dataSource, AbstractFile zoneFile, Collection<BlackboardArtifact> sourceArtifacts, Collection<BlackboardArtifact> downloadArtifacts, Set<Long> knownPathIDs) throws TskCoreException { ZoneIdentifierInfo zoneInfo = null; try { zoneInfo = new ZoneIdentifierInfo(zoneFile); } catch (IOException ex) { String message = String.format("Unable to parse temporary File for %s", zoneFile.getName()); LOG.log(Level.WARNING, message, ex); } if (zoneInfo == null) { return; } AbstractFile downloadFile = getDownloadFile(dataSource, zoneFile); if (downloadFile != null) { if (!knownPathIDs.contains(downloadFile.getDataSourceObjectId())) { BlackboardArtifact downloadBba = createDownloadArtifact(zoneFile, zoneInfo); if (downloadBba != null) { downloadArtifacts.add(downloadBba); } } if (downloadFile.getArtifactsCount(TSK_DOWNLOAD_SOURCE) == 0) { BlackboardArtifact sourceBba = createDownloadSourceArtifact(downloadFile, zoneInfo); if (sourceBba != null) { sourceArtifacts.add(sourceBba); } } } }
Source:
<code>public String[] getTypeNames() { <START> return typeNames; <END> }</code><technical_language>sure, want return a copy of array prevent mutation (e.g getIndexNames()[0] = "foo")</technical_language>

Target:
public String[] getTypeNames() { return Arrays.copyOf(typeNames, typeNames.length); }
Source:
<code>public void givenServerHeaderWithVulnerableAndSafeOpenSSLVersionsThenAlertRaised() throws IOException { String firstVersion = "openssl/1.0.1"; <START> HttpMessage msg = createMsg(String.format("Apache-Coyote/1.1 (%s)", firstVersion)); <END> setServerHeader(msg, String.format("Apache-Coyote/1.1 (%s)", SAFE_OPENSSL_VERSION)); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), is(1)); assertAlertAttributes(alertsRaised.get(0), firstVersion); }</code><technical_language>if order is switched? :)</technical_language>

Target:
public void givenServerHeaderWithVulnerableAndSafeOpenSSLVersionsThenAlertRaised() throws IOException { String vulnerableVersion = "openssl/1.0.1"; HttpMessage msg = createMsg(String.format("Apache-Coyote/1.1 (%s)", vulnerableVersion)); addServerHeader(msg, String.format("Apache-Coyote/1.1 (%s)", SAFE_OPENSSL_VERSION)); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), is(1)); assertAlertAttributes(alertsRaised.get(0), vulnerableVersion); }
Source:
<code>public void clear() { for (Counter counter : arrays) { <START> int[] array = counter.array; <END> Arrays.fill(array, 0); } offset = 0; }</code><technical_language>final</technical_language>

Target:
public void clear() { for (Counter counter : arrays) { final int[] array = counter.array; Arrays.fill(array, 0); } offset = 0; }
Source:
<code>public static void destroy(Entity e) { if (isManaged(e)) { <START> if (e instanceof Startable) Entities.invokeEffector((EntityLocal)e, e, Startable.STOP); <END> if (e instanceof AbstractEntity) ((AbstractEntity)e).destroy(); unmanage(e); } }</code><technical_language>this call stop asynchronously, previously a blocking call? do a .getUnchecked() well? return task</technical_language>

Target:
public static void destroy(Entity e) { if (isManaged(e)) { if (e instanceof Startable) Entities.invokeEffector((EntityLocal)e, e, Startable.STOP).getUnchecked(); if (e instanceof AbstractEntity) ((AbstractEntity)e).destroy(); unmanage(e); } }
Source:
<code><START> public static ColumnValueSelector makeColumnValueSelectorWithDoubleDefault( <END> final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, final String fieldName, final String fieldExpression, final double nullValue ) { if (fieldName != null && fieldExpression == null) { return metricFactory.makeColumnValueSelector(fieldName); } if (fieldName == null && fieldExpression != null) { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionDoubleColumnSelector implements DoubleColumnSelector { @Override public double getDouble() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNumericNull() ? nullValue : exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { final ExprEval exprEval = baseSelector.getObject(); return exprEval == null || exprEval.isNumericNull(); } } return new ExpressionDoubleColumnSelector(); } throw new IllegalArgumentException("Must have a valid, non-null fieldName or expression"); }</code><technical_language>question</technical_language>

Target:
public static BaseDoubleColumnValueSelector makeColumnValueSelectorWithDoubleDefault( final ColumnSelectorFactory metricFactory, final ExprMacroTable macroTable, final String fieldName, final String fieldExpression, final double nullValue ) { if (fieldName != null && fieldExpression == null) { return metricFactory.makeColumnValueSelector(fieldName); } if (fieldName == null && fieldExpression != null) { final Expr expr = Parser.parse(fieldExpression, macroTable); final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr); class ExpressionDoubleColumnSelector implements DoubleColumnSelector { @Override public double getDouble() { final ExprEval exprEval = baseSelector.getObject(); return exprEval.isNumericNull() ? nullValue : exprEval.asDouble(); } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } @Override public boolean isNull() { final ExprEval exprEval = baseSelector.getObject(); return exprEval == null || exprEval.isNumericNull(); } } return new ExpressionDoubleColumnSelector(); } throw new IllegalArgumentException("Must have a valid, non-null fieldName or expression"); }
Source:
<code>public <T> List<T> getServices(Class<T> clazz) { checkNonNullArgument(clazz, "Service Class instance cannot be null"); try { <START> ServiceReference<?>[] refs = getBundleContext().getServiceReferences(clazz.getName(), null); <END> return Stream.of(refs) .map(r -> getBundleContext().getService(r)) .filter(clazz::isInstance) .map(clazz::cast) .collect(Collectors.toList()); } catch (InvalidSyntaxException e) { throw Exceptions.duck(e); } }</code><technical_language>Please do this. If I do streams is a reason ..</technical_language>

Target:
public <T> List<T> getServices(Class<T> clazz) { requireNonNull(clazz, "Service Class instance cannot be null"); try { ServiceReference[] refs = getBundleContext().getAllServiceReferences(clazz.getName(), null); if (refs == null) { return Collections.emptyList(); } return Stream.of(refs) .map(r -> getBundleContext().getService(r)) .filter(clazz::isInstance) .map(clazz::cast) .collect(Collectors.toList()); } catch (InvalidSyntaxException e) { throw Exceptions.duck(e); } }
Source:
<code>public void registerRequirements(Set<CapabilityReferenceRecorder> requirements) { writeLock.lock(); try { if (requirements == null) { <START> this.requirements = null; <END> } else if (requirements.isEmpty()) { this.requirements = Collections.emptySet(); } else { for (CapabilityReferenceRecorder requirement : requirements) { requirement.setRegistrationAddress(getPathAddress()); } this.requirements = Collections.unmodifiableSet(new HashSet<>(requirements)); } } finally { writeLock.unlock(); } }</code><technical_language>is a difference a null requirments empty set</technical_language>

Target:
public void registerRequirements(Set<CapabilityReferenceRecorder> requirements) { writeLock.lock(); try { if (requirements == null || requirements.isEmpty()) { this.requirements = Collections.emptySet(); } else { this.requirements = Collections.unmodifiableSet(new HashSet<>(requirements)); } } finally { writeLock.unlock(); } }
Source:
<code>public void testBuild() { System.out.println("build"); ClassicOptionBuilder builder = OptionBuilder.classic(chart); builder.title("My first Chart"); ChartOptions expResult = new ChartOptions(); expResult.put("title", "My first Chart"); ChartOptions result = builder.build(); assertNotEquals(expResult, result); assertEquals(expResult.toJSON().toString(), result.toJSON().toString()); builder.axis("TEMP", "Temps (Celsius)").axis("DAYLIGHT", "Daylight"); builder.modifyAxis("TEMP", new OptionModifier() { @Override public void modify(ChartOptions options) { ChartOptions textStyle = new ChartOptions(); textStyle.put("color", "red"); options.put("textStyle", textStyle); } }); builder.mapSeries("TEMP").mapSeries("DAYLIGHT", new OptionModifier() { @Override public void modify(ChartOptions options) { options.put("color", "yellow"); } }); result = builder.build(); <START> System.out.println(result.toJSON().toString()); <END> assertEquals("{\"vAxes\":{\"0\":{\"textStyle\":{\"color\":\"red\"},\"title\":\"Temps (Celsius)\"},\"1\":{\"title\":\"Daylight\"}},\"series\":{\"0\":{\"targetAxisIndex\":0},\"1\":{\"color\":\"yellow\",\"targetAxisIndex\":1}},\"title\":\"My first Chart\"}", result.toJSON().toString()); }</code><technical_language>Please remove System.out replace LOG.debug() switched default</technical_language>

Target:
public void testBuild() { ClassicOptionBuilder builder = OptionBuilder.classic(chart); builder.title("My first Chart"); ChartOptions expResult = new ChartOptions(); expResult.put("title", "My first Chart"); ChartOptions result = builder.build(); assertNotEquals(expResult, result); assertEquals(expResult.toJSON().toString(), result.toJSON().toString()); builder.axis("TEMP", "Temps (Celsius)").axis("DAYLIGHT", "Daylight"); builder.modifyAxis("TEMP", new OptionModifier() { @Override public void modify(ChartOptions options) { ChartOptions textStyle = new ChartOptions(); textStyle.put("color", "red"); options.put("textStyle", textStyle); } }); builder.mapSeries("TEMP").mapSeries("DAYLIGHT", new OptionModifier() { @Override public void modify(ChartOptions options) { options.put("color", "yellow"); } }); result = builder.build(); assertEquals("{\"vAxes\":{\"0\":{\"textStyle\":{\"color\":\"red\"},\"title\":\"Temps (Celsius)\"},\"1\":{\"title\":\"Daylight\"}},\"series\":{\"0\":{\"targetAxisIndex\":0},\"1\":{\"color\":\"yellow\",\"targetAxisIndex\":1}},\"title\":\"My first Chart\"}", result.toJSON().toString()); }
Source:
<code>public Response postServiceListeners(MultipartBody inputDataMap) throws ApiException { Map<String, Object> result = new HashMap<String, Object>(); String message = null, serviceName = null, dispatchResult = null; InputStream file = null; try { if(inputDataMap.getAttachmentObject("message", String.class) != null) message = inputDataMap.getAttachmentObject("message", String.class); <START> if(inputDataMap.getAttachmentObject("service", String.class) != null) { <END> serviceName = inputDataMap.getAttachmentObject("service", String.class); } Attachment attFile = inputDataMap.getAttachment( "file" ); if(attFile != null) { file = inputDataMap.getAttachmentObject("file", InputStream.class); String fileEncoding = Misc.DEFAULT_INPUT_STREAM_ENCODING; message = Misc.streamToString(file, "\n", fileEncoding, false); message = XmlUtils.readXml(IOUtils.toByteArray(file), fileEncoding,false); } else { message = new String(message.getBytes(), Misc.DEFAULT_INPUT_STREAM_ENCODING); } if(!ServiceDispatcher.getInstance().isRegisteredServiceListener(serviceName)) { return Response.status(Response.Status.BAD_REQUEST).build(); } try { @SuppressWarnings("rawtypes") Map context = new HashMap(); dispatchResult = ServiceDispatcher.getInstance().dispatchRequest(serviceName, null, message, context); } catch (ListenerException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } result.put("state", "success"); result.put("result", dispatchResult); } catch (IOException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } return Response.status(Response.Status.CREATED).entity(result).build(); }</code><technical_language>resolveStringFromMap(inputDataMap, "service");</technical_language>

Target:
public Response postServiceListeners(MultipartBody inputDataMap) throws ApiException { Map<String, Object> result = new HashMap<String, Object>(); String dispatchResult = null; InputStream file = null; try { this.checkMessageAndFile(inputDataMap); String message = resolveStringFromMap(inputDataMap, "message").orElse(null); String serviceName = resolveStringFromMap(inputDataMap, "service").orElse(null); file = resolveTypeFromMap(inputDataMap, "file", InputStream.class).orElse(null); if(file != null) { String fileEncoding = Misc.DEFAULT_INPUT_STREAM_ENCODING; message = Misc.streamToString(file, "\n", fileEncoding, false); message = XmlUtils.readXml(IOUtils.toByteArray(file), fileEncoding,false); } else { message = new String(message.getBytes(), Misc.DEFAULT_INPUT_STREAM_ENCODING); } if(!ServiceDispatcher.getInstance().isRegisteredServiceListener(serviceName)) { return Response.status(Response.Status.BAD_REQUEST).build(); } try { @SuppressWarnings("rawtypes") Map context = new HashMap(); dispatchResult = ServiceDispatcher.getInstance().dispatchRequest(serviceName, null, message, context); } catch (ListenerException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } result.put("state", "success"); result.put("result", dispatchResult); } catch (IOException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } return Response.status(Response.Status.CREATED).entity(result).build(); }
Source:
<code>public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) { Map<Host, HostEvent> hosts = new HashMap<Host, HostEvent>(); for (NodeRefreshRequest req : events) { hosts.put(req.host, req.eventType); } List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size()); for (final Entry<Host, HostEvent> entry : hosts.entrySet()) { final Host host = entry.getKey(); HostEvent eventType = entry.getValue(); switch (eventType) { case UP: <START> schedule(hostUp(host)); <END> break; case ADDED: schedule(hostAdded(host)); break; case DOWN: execute(hostDown(host)); break; case REMOVED: execute(hostRemoved(host)); break; } } return Futures.allAsList(futures); }</code><technical_language>hostUp executed right away? previously 'schedule' for added</technical_language>

Target:
public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) { Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>(); for (NodeRefreshRequest req : events) { hosts.put(req.address, req.eventType); } List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size()); for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) { InetSocketAddress address = entry.getKey(); HostEvent eventType = entry.getValue(); switch (eventType) { case UP: Host upHost = metadata.getHost(address); if (upHost == null) { upHost = metadata.add(address); if (upHost == null) continue; futures.add(schedule(hostAdded(upHost))); } else { futures.add(schedule(hostUp(upHost))); } break; case ADDED: Host newHost = metadata.add(address); if (newHost != null) futures.add(schedule(hostAdded(newHost))); break; case DOWN: Host downHost = metadata.getHost(address); if (downHost != null) futures.add(execute(hostDown(downHost))); break; case REMOVED: Host removedHost = metadata.getHost(address); if (removedHost != null) futures.add(execute(hostRemoved(removedHost))); break; } } return Futures.allAsList(futures); }
Source:
<code>private Promise<List<File>> collectChildren(Container root, Path relativeFilePath) { return root.getTree(-1).then(new Function<Resource[], List<File>>() { @Override public List<File> apply(Resource[] children) throws FunctionException { final List<File> result = newArrayList(); <START> for (Resource child : children) { <END> if (child.isFile()) { File file = child.asFile(); if (endsWith(file.getLocation(), relativeFilePath)) { result.add(file); } } } return result; } }); }</code><technical_language>simpler read streams / filter/ Collectors.toList()</technical_language>

Target:
private Promise<List<File>> collectChildren(Container root, Path relativeFilePath) { return root.getTree(-1).then(new Function<Resource[], List<File>>() { @Override public List<File> apply(Resource[] children) throws FunctionException { return Stream.of(children).filter( child -> child.isFile() && endsWith(child.asFile().getLocation(), relativeFilePath)) .map(Resource::asFile).collect(Collectors.toList()); } }); }
Source:
<code>private static List<String> extracStringtList(Map<String, Object> xmlRpcStruct, String propertyName) { if (!xmlRpcStruct.containsKey(propertyName)){ return null; } Object[] items = (Object[]) xmlRpcStruct.get(propertyName); if (items.length == 0) { return null; } List<String> list = new ArrayList<>(); <START> Arrays.stream(items).forEach(item -> list.add((String) item)); <END> return list; }</code><technical_language>I Java 8 is below: List<String> list = Arrays.stream(items).map(item -> (String)item).collect(Collectors.toList());</technical_language>

Target:
private static List<String> extracStringtList(Map<String, Object> xmlRpcStruct, String propertyName) { if (!xmlRpcStruct.containsKey(propertyName)){ return null; } Object[] items = (Object[]) xmlRpcStruct.get(propertyName); if (items.length == 0) { return null; } return Arrays.stream(items).map(item -> (String) item).collect(Collectors.toList()); }
Source:
<code>public void stop() { DynamicCluster slaves = getSlaves(); RedisStore master = getMaster(); <START> if (slaves != null) slaves.invoke(DynamicCluster.STOP, ImmutableMap.<String, Object>of()).blockUntilEnded(); <END> if (master != null) master.invoke(RedisStore.STOP, ImmutableMap.<String, Object>of()).blockUntilEnded(); setAttribute(Startable.SERVICE_UP, false); }</code><technical_language>here, invoke effectors check for return value</technical_language>

Target:
public void stop() { ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING); try { doStop(); ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED); } catch (Exception e) { ServiceProblemsLogic.updateProblemsIndicator(this, STOP, "Stop failed with error: "+e); ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE); throw Exceptions.propagate(e); } }