auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; <START> for (int i = 0; i < 2; i++) { <END> if (lock.getSemaphoreLocks() != null) { for (Entry<String, Guid> entry : lock.getSemaphoreLocks().entrySet()) { if (!insertSemaphoreLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of semaphore lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } if (lock.getExclusiveLocks() != null) { for (Entry<String, Guid> entry : lock.getExclusiveLocks().entrySet()) { if (!insertExclusiveLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of exclusive lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } checkOnly = false; } log.debug("Successed to acquire a lock"); return true; }</code><technical_language>I agree Kolesnik , a method is more readable in this case ...</technical_language>

Target:
private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; for (int i = 0; i < 2; i++) { if (lock.getSharedLocks() != null) { for (Entry<String, Guid> entry : lock.getSharedLocks().entrySet()) { if (!insertSharedLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of shared lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } if (lock.getExclusiveLocks() != null) { for (Entry<String, Guid> entry : lock.getExclusiveLocks().entrySet()) { if (!insertExclusiveLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of exclusive lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } checkOnly = false; } log.debug("Successed to acquire a lock"); return true; }
Source:
<code>private Reader getPemReader() throws IOException { String privateKey = tokenClientConfiguration.getPrivateKey(); <START> if (privateKey.startsWith("-----BEGIN PRIVATE KEY-----") && privateKey.contains("-----END PRIVATE KEY-----")) { <END> return new StringReader(tokenClientConfiguration.getPrivateKey()); } else { Path privateKeyPemFilePath = Paths.get(tokenClientConfiguration.getPrivateKey()); return Files.newBufferedReader(privateKeyPemFilePath, Charset.defaultCharset()); } }</code><technical_language>duplicate code DefaultClientBuilder.java above</technical_language>

Target:
private Reader getPemReader() throws IOException { String privateKey = tokenClientConfiguration.getPrivateKey(); if (ConfigUtil.hasPrivateKeyContentWrapper(privateKey)) { return new StringReader(privateKey); } else { return Files.newBufferedReader(Paths.get(privateKey), Charset.defaultCharset()); } }
Source:
<code>public void listNetworkPartitions() throws CommandException { try { Type listType = new TypeToken<ArrayList<NetworkPartitionBean>>() { }.getType(); List<NetworkPartitionBean> networkPartitionsList = (List<NetworkPartitionBean>) restClient.listEntity(ENDPOINT_LIST_NETWORK_PARTITIONS, listType, "network-partitions"); if ((networkPartitionsList == null) || (networkPartitionsList.size() == 0)) { System.out.println("No network partitions found"); return; } RowMapper<NetworkPartitionBean> networkPartitionMapper = new RowMapper<NetworkPartitionBean>() { public String[] getData(NetworkPartitionBean partition) { String[] data = new String[3]; data[0] = partition.getId(); data[1] = (partition.getKubernetesClusterId() != null) ? partition.getKubernetesClusterId() : ""; data[2] = String.valueOf(partition.getPartitions().size());; return data; } }; NetworkPartitionBean[] partitions = new NetworkPartitionBean[networkPartitionsList.size()]; partitions = networkPartitionsList.toArray(partitions); System.out.println("Network partitions found:"); CliUtils.printTable(partitions, networkPartitionMapper, "PartitionId", "Kubernetes Cluster Id", "Partitions"); } catch (Exception e) { <START> String message = "Error in listing network partitions" + e; <END> printError(message, e); } }</code><technical_language>need append exception message. message. Thanks</technical_language>

Target:
public void listNetworkPartitions() throws CommandException { try { Type listType = new TypeToken<ArrayList<NetworkPartitionBean>>() { }.getType(); List<NetworkPartitionBean> networkPartitionsList = (List<NetworkPartitionBean>) restClient.listEntity(ENDPOINT_LIST_NETWORK_PARTITIONS, listType, "network-partitions"); if ((networkPartitionsList == null) || (networkPartitionsList.size() == 0)) { System.out.println("No network partitions found"); return; } RowMapper<NetworkPartitionBean> networkPartitionMapper = new RowMapper<NetworkPartitionBean>() { public String[] getData(NetworkPartitionBean partition) { String[] data = new String[3]; data[0] = partition.getId(); data[1] = (partition.getKubernetesClusterId() != null) ? partition.getKubernetesClusterId() : ""; data[2] = String.valueOf(partition.getPartitions().size());; return data; } }; NetworkPartitionBean[] partitions = new NetworkPartitionBean[networkPartitionsList.size()]; partitions = networkPartitionsList.toArray(partitions); System.out.println("Network partitions found:"); CliUtils.printTable(partitions, networkPartitionMapper, "PartitionId", "Kubernetes Cluster Id", "Partitions"); } catch (Exception e) { String message = "Error in listing network partitions"; printError(message, e); } }
Source:
<code>private BucketShards compute() throws SQLException { if (!resultSet.next()) { return endOfData(); } UUID shardUuid = uuidFromBytes(resultSet.getBytes("shard_uuid")); <START> Optional<UUID> deltaShardUuid = Optional.empty(); <END> if (tableSupportsDeltaDelete && resultSet.getBytes("delta_shard_uuid") != null) { deltaShardUuid = Optional.of(uuidFromBytes(resultSet.getBytes("delta_shard_uuid"))); } Set<String> nodeIdentifiers; OptionalInt bucketNumber = OptionalInt.empty(); if (bucketToNode != null) { int bucket = resultSet.getInt("bucket_number"); bucketNumber = OptionalInt.of(bucket); nodeIdentifiers = ImmutableSet.of(getBucketNode(bucket)); } else { List<Integer> nodeIds = intArrayFromBytes(resultSet.getBytes("node_ids")); nodeIdentifiers = getNodeIdentifiers(nodeIds, shardUuid); } ShardNodes shard = new ShardNodes(shardUuid, deltaShardUuid, nodeIdentifiers); return new BucketShards(bucketNumber, ImmutableSet.of(shard)); }</code><technical_language>this code block a helper is twice</technical_language>

Target:
private BucketShards compute() throws SQLException { if (!resultSet.next()) { return endOfData(); } UUID shardUuid = uuidFromBytes(resultSet.getBytes("shard_uuid")); Optional<UUID> deltaShardUuid = getDeltaShardUuidFromResultSet(); Set<String> nodeIdentifiers; OptionalInt bucketNumber = OptionalInt.empty(); if (bucketToNode != null) { int bucket = resultSet.getInt("bucket_number"); bucketNumber = OptionalInt.of(bucket); nodeIdentifiers = ImmutableSet.of(getBucketNode(bucket)); } else { List<Integer> nodeIds = intArrayFromBytes(resultSet.getBytes("node_ids")); nodeIdentifiers = getNodeIdentifiers(nodeIds, shardUuid); } ShardNodes shard = new ShardNodes(shardUuid, deltaShardUuid, nodeIdentifiers); return new BucketShards(bucketNumber, ImmutableSet.of(shard)); }
Source:
<code>private void save(CompilationUnit cu, Path path) throws IOException { Files.createDirectories(path.getParent()); final String code = new PrettyPrinter().print(cu); <START> Files.write(path, code.getBytes()); <END> }</code><technical_language>Oops, pass a character set getBytes() please</technical_language>

Target:
private void save(CompilationUnit cu, Path path) throws IOException { Files.createDirectories(path.getParent()); final String code = new PrettyPrinter().print(cu); Files.write(path, code.getBytes(UTF8)); }
Source:
<code>EitherOf3<CatchUpCompleted, ShardProcessingRequested, Nothing> handle(ShardProcessed event) { if (builder().getStatus() == COMPLETED) { return EitherOf3.withC(nothing()); } CatchUpId id = builder().getId(); Optional<CatchUp> stateVisibleToDelivery = findJob(id, event.getRunInfo()); if (stateVisibleToDelivery.isPresent()) { CatchUp observedJob = stateVisibleToDelivery.get(); if (observedJob.getStatus() == FINALIZING) { int indexOfFinalized = event.getIndex() .getIndex(); if (!builder().getFinalizedShardList() .contains(indexOfFinalized)) { <START> builder().addFinalizedShard(indexOfFinalized); <END> } List<Integer> affectedShards = builder().getAffectedShardList(); List<Integer> finalizedShards = builder().getFinalizedShardList(); if (finalizedShards.containsAll(affectedShards)) { CatchUpCompleted completed = completeProcess(builder().getId()); return EitherOf3.withA(completed); } return EitherOf3.withC(nothing()); } } ShardProcessingRequested stillRequested = shardProcessingRequested(id, event.getIndex()); return EitherOf3.withB(stillRequested); }</code><technical_language>Please extract builder() a variable</technical_language>

Target:
EitherOf3<CatchUpCompleted, ShardProcessingRequested, Nothing> handle(ShardProcessed event) { CatchUp.Builder builder = builder(); if (builder.getStatus() == COMPLETED) { return EitherOf3.withC(nothing()); } CatchUpId id = builder.getId(); Optional<CatchUp> stateVisibleToDelivery = findJob(id, event.getRunInfo()); if (stateVisibleToDelivery.isPresent()) { CatchUp observedJob = stateVisibleToDelivery.get(); if (observedJob.getStatus() == FINALIZING) { int indexOfFinalized = event.getIndex() .getIndex(); if (!builder.getFinalizedShardList().contains(indexOfFinalized)) { builder.addFinalizedShard(indexOfFinalized); } List<Integer> affectedShards = builder.getAffectedShardList(); if (builder.getFinalizedShardList().containsAll(affectedShards)) { CatchUpCompleted completed = completeProcess(builder.getId()); return EitherOf3.withA(completed); } return EitherOf3.withC(nothing()); } } ShardProcessingRequested stillRequested = shardProcessingRequested(id, event.getIndex()); return EitherOf3.withB(stillRequested); }
Source:
<code>if (mx.equals("true") || mx.equals("t") || mx.equals("")) { try { <START> Class c = Class.forName("PointerBufferPoolMXBean"); <END> Method method = c.getDeclaredMethod("register"); method.invoke(null); } catch (Throwable t) { logger.warn("Could not load PointerBufferPoolMXBean: " + t); } }</code><technical_language>Yes, work otherwise</technical_language>

Target:
if (mx.equals("true") || mx.equals("t") || mx.equals("")) { try { Class c = Class.forName("org.bytedeco.javacpp.tools.PointerBufferPoolMXBean"); Method method = c.getDeclaredMethod("register"); method.invoke(null); } catch (ReflectiveOperationException e) { logger.warn("Could not register PointerBufferPoolMXBean: " + e); } }
Source:
<code>public Class<?> getCellClass(int column) { EditedStyleItem item = myAttributes.get(myRowIndex); String value = item.getValue(); String name = item.getName(); AttributeDefinition attrDefinition = myAttributeDefinitions.getAttrDefByName(name); if (ThemeEditorUtils.acceptsFormat(attrDefinition, AttributeFormat.Color)) { return Color.class; } ResourceUrl url = ResourceUrl.parse(value); if (item.isAttr()) { item.setValue(value); ItemResourceValue resourceValue = (ItemResourceValue) mySelectedStyle.getConfiguration().getResourceResolver().findResValue(value, false); if (resourceValue == null ) { LOG.error("Unable to resolve " + value); return null; } item = new EditedStyleItem(resourceValue, mySelectedStyle); value = item.getValue(); url = ResourceUrl.parse(value); } <START> <END> if ((url != null && url.type == ResourceType.COLOR) || value.startsWith("#")) { return Color.class; } if (url != null && url.type == ResourceType.DRAWABLE) { return DrawableDomElement.class; } if (column == 1) { if (url != null && url.type == ResourceType.STYLE) { return ThemeEditorStyle.class; } if ((url != null && url.type == ResourceType.INTEGER) || ThemeEditorUtils.acceptsFormat(attrDefinition, AttributeFormat.Integer)) { return Integer.class; } if ((url != null && url.type == ResourceType.BOOL) || value.equals("true") || value.equals("false")) { return Boolean.class; } } return String.class; }</code><technical_language>Add if (url == null) { return String.class; } remove other null checks</technical_language>

Target:
public Class<?> getCellClass(int column) { EditedStyleItem item = myAttributes.get(myRowIndex); String value = item.getValue(); String name = item.getName(); AttributeDefinition attrDefinition = myAttributeDefinitions.getAttrDefByName(name); if (ThemeEditorUtils.acceptsFormat(attrDefinition, AttributeFormat.Color)) { return Color.class; } ResourceUrl url = ResourceUrl.parse(value); if (item.isAttr()) { item.setValue(value); ItemResourceValue resourceValue = (ItemResourceValue) mySelectedStyle.getConfiguration().getResourceResolver().findResValue(value, false); if (resourceValue == null ) { LOG.error("Unable to resolve " + value); return null; } item = new EditedStyleItem(resourceValue, mySelectedStyle); value = item.getValue(); url = ResourceUrl.parse(value); } ResourceType urlType = null; if (url != null) { urlType = url.type; } if (urlType == ResourceType.COLOR || (value.startsWith("#") && ThemeEditorUtils.acceptsFormat(attrDefinition, AttributeFormat.Color))) { return Color.class; } if (urlType == ResourceType.DRAWABLE) { return DrawableDomElement.class; } if (column == 1) { if (urlType == ResourceType.STYLE) { return ThemeEditorStyle.class; } if (urlType == ResourceType.INTEGER || ThemeEditorUtils.acceptsFormat(attrDefinition, AttributeFormat.Integer)) { return Integer.class; } if (urlType == ResourceType.BOOL || ((value.equals("true") || value.equals("false")) && ThemeEditorUtils.acceptsFormat(attrDefinition, AttributeFormat.Boolean))) { return Boolean.class; } } return String.class; }
Source:
<code>public String render(String template, StatementContext ctx) { final ExtensionMethod extensionMethod = ctx.getExtensionMethod(); final String originalResult = originalEngine.render(template, ctx); <START> if ((extensionMethod != null) <END> && (extensionMethod.getType() != null) && (extensionMethod.getMethod() != null)) { final StringBuilder query = new StringBuilder(originalResult.length() + 100); query.append(" "); query.append(originalResult); return query.toString(); } return originalResult; }</code><technical_language>I more clear a check extension method _doesn't_ exist exit early. java if (extensionMethod == null || extensionMethod.getType() == null || extensionMethod.getMethod() == null) { return originalResult; }</technical_language>

Target:
public String render(String template, StatementContext ctx) { final ExtensionMethod extensionMethod = ctx.getExtensionMethod(); final String originalResult = originalEngine.render(template, ctx); if (extensionMethod == null) { return originalResult; } final StringBuilder query = new StringBuilder(originalResult.length() + 100); query.append(" "); query.append(originalResult); return query.toString(); }
Source:
<code>protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { if (!isEnabled(CleanUpConstants.NUMBER_SUFFIX)) { return null; } final List<CompilationUnitRewriteOperation> rewriteOperations= new ArrayList<>(); unit.accept(new ASTVisitor() { @Override public boolean visit(NumberLiteral node) { final String token= node.getToken(); <START> if (token.endsWith("l") || token.endsWith("f")) { END> rewriteOperations.add(new NumberSuffixOperation(node, token)); return false; } return true; } }); if (rewriteOperations.isEmpty()) { return null; } return new CompilationUnitRewriteOperationsFix(MultiFixMessages.CodeStyleCleanUp_numberSuffix_description, unit, rewriteOperations.toArray(new CompilationUnitRewriteOperation[rewriteOperations.size()])); }</code><technical_language>doubles? Is reason covered well</technical_language>

Target:
protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { if (!isEnabled(CleanUpConstants.NUMBER_SUFFIX)) { return null; } final List<CompilationUnitRewriteOperation> rewriteOperations= new ArrayList<>(); unit.accept(new ASTVisitor() { @Override public boolean visit(NumberLiteral node) { final String token= node.getToken(); if (token.endsWith("l") || token.endsWith("d") || token.endsWith("f")) { rewriteOperations.add(new NumberSuffixOperation(node, token)); return false; } return true; } }); if (rewriteOperations.isEmpty()) { return null; } return new CompilationUnitRewriteOperationsFix(MultiFixMessages.CodeStyleCleanUp_numberSuffix_description, unit, rewriteOperations.toArray(new CompilationUnitRewriteOperation[rewriteOperations.size()])); }
Source:
<code>public void setJsonPathTo(String path, String value){ String jsonStr = getResponse().getResponse(); String jsonPath = getPathExpr(path); <START> getResponse().setResponse(pathHelper.updateJsonPathWithValue(jsonStr, jsonPath, value)); <END> }</code><technical_language>Please a local variable new response, setting it. debugging easier..</technical_language>

Target:
public void setJsonPathTo(String path, String value){ String jsonStr = getResponse().getResponse(); String jsonPath = getPathExpr(path); String newResponse = pathHelper.updateJsonPathWithValue(jsonStr, jsonPath, value); getResponse().setResponse(newResponse); }
Source:
<code>public void unzipFlatFileEntryZip() throws IOException { <START> File singleFile = this.resourceLoader.getResource("classpath:testzipdata/single.txt").getFile(); <END> File zip = new File(singleFile.getParentFile(), "flatfileentry.zip"); ZipUtil.packEntry(singleFile, zip, "subfolder/single.txt"); final Resource zipResource = this.resourceLoader.getResource("classpath:testzipdata/flatfileentry.zip"); final InputStream is = zipResource.getInputStream(); final Message<InputStream> message = MessageBuilder.withPayload(is).build(); final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.afterPropertiesSet(); final Message<?> resultMessage = unZipTransformer.transform(message); Assert.assertNotNull(resultMessage); @SuppressWarnings("unchecked") Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload(); Assert.assertNotNull(unzippedData); Assert.assertTrue(unzippedData.size() == 1); }</code><technical_language>I review test restore other changes in this class</technical_language>

Target:
public void unzipFlatFileEntryZip() throws IOException { final Resource zipResource = this.resourceLoader.getResource("classpath:testzipdata/flatfileentry.zip"); final InputStream is = zipResource.getInputStream(); final Message<InputStream> message = MessageBuilder.withPayload(is).build(); final UnZipTransformer unZipTransformer = new UnZipTransformer(); unZipTransformer.setZipResultType(ZipResultType.FILE); unZipTransformer.afterPropertiesSet(); final Message<?> resultMessage = unZipTransformer.transform(message); Assert.assertNotNull(resultMessage); @SuppressWarnings("unchecked") Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload(); Assert.assertNotNull(unzippedData); Assert.assertTrue(unzippedData.size() == 1); }
Source:
<code>public Response add(Template template) { validateParameters(template, "name", "vm.id|name"); validateEnums(Template.class, template); Guid clusterId = null; VDSGroup cluster = null; if (namedCluster(template)) { clusterId = getClusterId(template); cluster = lookupCluster(clusterId); } VmStatic staticVm = getMapper(Template.class, VmStatic.class).map(template, getVm(cluster, template)); if (namedCluster(template)) { staticVm.setVdsGroupId(clusterId); } staticVm.setUsbPolicy(VmMapper.getUsbPolicyOnCreate(template.getUsb(), cluster != null ? cluster : lookupCluster(staticVm.getVdsGroupId()))); AddVmTemplateParameters params = new AddVmTemplateParameters(staticVm, template.getName(), template.getDescription()); <START> params.setConsoleEnabled(!getConsoleDevicesForEntity(staticVm.getId()).isEmpty()); <END> boolean isDomainSet = false; if (template.isSetStorageDomain() && template.getStorageDomain().isSetId()) { params.setDestinationStorageDomainId(asGuid(template.getStorageDomain().getId())); isDomainSet = true; } params.setDiskInfoDestinationMap(getDiskToDestinationMap(template.getVm(), params.getDestinationStorageDomainId(), isDomainSet)); return performCreate(VdcActionType.AddVmTemplate, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmTemplate, GetVmTemplateParameters.class)); }</code><technical_language>set user, e.g template.isConsoleEnabled() if set vm's config</technical_language>

Target:
public Response add(Template template) { validateParameters(template, "name", "vm.id|name"); validateEnums(Template.class, template); Guid clusterId = null; VDSGroup cluster = null; if (namedCluster(template)) { clusterId = getClusterId(template); cluster = lookupCluster(clusterId); } VmStatic staticVm = getMapper(Template.class, VmStatic.class).map(template, getVm(cluster, template)); if (namedCluster(template)) { staticVm.setVdsGroupId(clusterId); } staticVm.setUsbPolicy(VmMapper.getUsbPolicyOnCreate(template.getUsb(), cluster != null ? cluster : lookupCluster(staticVm.getVdsGroupId()))); AddVmTemplateParameters params = new AddVmTemplateParameters(staticVm, template.getName(), template.getDescription()); params.setConsoleEnabled(template.getConsole() != null && template.getConsole().isSetEnabled() ? template.getConsole().isEnabled() : !getConsoleDevicesForEntity(staticVm.getId()).isEmpty()); boolean isDomainSet = false; if (template.isSetStorageDomain() && template.getStorageDomain().isSetId()) { params.setDestinationStorageDomainId(asGuid(template.getStorageDomain().getId())); isDomainSet = true; } params.setDiskInfoDestinationMap(getDiskToDestinationMap(template.getVm(), params.getDestinationStorageDomainId(), isDomainSet)); return performCreate(VdcActionType.AddVmTemplate, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmTemplate, GetVmTemplateParameters.class)); }
Source:
<code>public Map<String, String[]> asMap() { Map<String, String[]> map = new HashMap<>(); if (loc != null) { <START> map.put("loc", new String[]{ loc.toString() }); <END> } if (caption != null) { map.put("caption", new String[]{ caption }); } if (geoLocation != null) { map.put("geo_location", new String[]{ geoLocation }); } if (title != null) { map.put("title", new String[]{ title }); } if (license != null) { map.put("license", new String[]{ license.toString() }); } return Collections.unmodifiableMap(map); }</code><technical_language>For this, other xxxAttributes classes, defined map key name constants use? If not, I in favor of adding public constants xxxAttribute classes, avoid raw string constant usage in consumer code</technical_language>

Target:
public Map<String, String[]> asMap() { Map<String, String[]> map = new HashMap<>(); if (loc != null) { map.put(LOC, new String[]{ loc.toString() }); } if (caption != null) { map.put(CAPTION, new String[]{ caption }); } if (geoLocation != null) { map.put(GEO_LOCATION, new String[]{ geoLocation }); } if (title != null) { map.put(TITLE, new String[]{ title }); } if (license != null) { map.put(LICENSE, new String[]{ license.toString() }); } return Collections.unmodifiableMap(map); }
Source:
<code>public VmNetworkInterface get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("id", id); VmNetworkInterface entity = getCallsHandler().executeRead("Getvm_interfaceById", mapper, parameterSource); <START> entity.setVmInterfaceDynamic(DbFacade.getInstance().getVmInterfaceDynamic().get(id)); <END> return entity; }</code><technical_language>This done part of mapper logic, fields added vm_interface_view, need double query</technical_language>

Target:
public VmNetworkInterface get(Guid id) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("id", id); VmNetworkInterface entity = getCallsHandler().executeRead("Getvm_interfaceById", mapper, parameterSource); return entity; }
Source:
<code>private ThriftPlugin(ThriftPluginInfo info) { <START> this(info.getName(), info.getLocationModule(), info.getPluginSessionProperties()); <END> }</code><technical_language>rename locationModule module. bind SessionPropertyProvider module. (The name is bad, longer for location. I missed converting Drift.)</technical_language>

Target:
private ThriftPlugin(ThriftPluginInfo info) { this(info.getName(), info.getModule()); }
Source:
<code>private void toggleAfk(User sender, User user, String message) throws Exception { if (message != null && sender != null) { if (sender.isMuted()) { <START> if (sender.getMuteReason ().equals ("")) { <END> throw new Exception(tl("voiceSilenced")); } else { throw new Exception(tl("voiceSilenced") + tl("muteFormat", sender.getMuteReason ())); } } if (!sender.isAuthorized("essentials.afk.message")) { throw new Exception(tl("noPermToAFKMessage")); } } user.setDisplayNick(); String msg = ""; if (!user.toggleAfk()) { if (!user.isHidden()) { msg = tl("userIsNotAway", user.getDisplayName()); } user.updateActivity(false); } else { if (!user.isHidden()) { if (message != null) { msg = tl("userIsAwayWithMessage", user.getDisplayName(), message); } else { msg = tl("userIsAway", user.getDisplayName()); } } user.setAfkMessage(message); } if (!msg.isEmpty()) { ess.broadcastMessage(user, msg); } }</code><technical_language>I feel is a format adding if/else statements concatenating string blocks. Personally, I would: * Add a hasMuteReason method UserData getMuteReason().equals(""); * a ternary operator concatenating strings instead of if/else blocks: java throw new Exception(tl("voiceSilenced") + (sender.hasMuteReason() ? tl("muteReason", sender.getMuteReason())));</technical_language>

Target:
private void toggleAfk(User sender, User user, String message) throws Exception { if (message != null && sender != null) { if (sender.isMuted()) { throw new Exception(sender.hasMuteReason() ? tl("voiceSilencedReason", sender.getMuteReason()) : tl("voiceSilenced")); } if (!sender.isAuthorized("essentials.afk.message")) { throw new Exception(tl("noPermToAFKMessage")); } } user.setDisplayNick(); String msg = ""; if (!user.toggleAfk()) { if (!user.isHidden()) { msg = tl("userIsNotAway", user.getDisplayName()); } user.updateActivity(false); } else { if (!user.isHidden()) { if (message != null) { msg = tl("userIsAwayWithMessage", user.getDisplayName(), message); } else { msg = tl("userIsAway", user.getDisplayName()); } } user.setAfkMessage(message); } if (!msg.isEmpty()) { ess.broadcastMessage(user, msg); } }
Source:
<code>public void shouldGenerateNewspaperProcesses() throws Exception { Process completeEdition = ServiceManager.getProcessService().getById(10); Course course = NewspaperCourse.getCourse(); course.splitInto(Granularity.DAYS); NewspaperProcessesGenerator underTest = new NewspaperProcessesGenerator(completeEdition, course); while (underTest.getProgress() < underTest.getNumberOfSteps()) { underTest.nextStep(); } cleanUp(); <START> } <END></code><technical_language>is Assert in Test :(</technical_language>

Target:
public void shouldGenerateNewspaperProcesses() throws Exception { Process completeEdition = ServiceManager.getProcessService().getById(10); Course course = NewspaperCourse.getCourse(); course.splitInto(Granularity.DAYS); NewspaperProcessesGenerator underTest = new NewspaperProcessesGenerator(completeEdition, course); while (underTest.getProgress() < underTest.getNumberOfSteps()) { underTest.nextStep(); } Assert.assertEquals("The newspaper processes generator has not been completed!", underTest.getNumberOfSteps(), underTest.getProgress()); cleanUp(); }
Source:
<code>public VisitQueryResult evaluate(VisitQuery definition, EvaluationContext context) throws EvaluationException { context = ObjectUtil.nvl(context, new EvaluationContext()); BasicVisitQuery query = (BasicVisitQuery) definition; VisitQueryResult result = new VisitQueryResult(query, context); if (context.getBaseCohort() != null && context.getBaseCohort().isEmpty()) { return result; } if (context instanceof VisitEvaluationContext) { VisitIdSet baseVisits = ((VisitEvaluationContext) context).getBaseVisits(); if (baseVisits != null && baseVisits.getMemberIds().isEmpty()) { return result; } } HqlQueryBuilder q = new HqlQueryBuilder(); q.select("v.visitId"); q.from(Visit.class, "v"); q.whereIn("v.visitType", query.getVisitTypes()); q.whereGreaterOrEqualTo("v.startDatetime", query.getStartedOnOrAfter()); q.whereLessOrEqualTo("v.startDatetime", query.getStartedOnOrBefore()); q.whereGreaterOrEqualTo("v.stopDatetime", query.getEndedOnOrAfter()); q.whereLessOrEqualTo("v.stopDatetime", query.getEndedOnOrBefore()); q.whereIn("v.location", query.getLocationList()); <START> q.whereEncounterIn("v.visitId", context); <END> for (Object[] row : evaluationService.evaluateToList(q, context)) { result.add((Integer)row[0]); } return result; }</code><technical_language>@rbuisson - This q.whereEncounterIn(...), q.whereVisitIn(...). this good</technical_language>

Target:
public VisitQueryResult evaluate(VisitQuery definition, EvaluationContext context) throws EvaluationException { context = ObjectUtil.nvl(context, new EvaluationContext()); BasicVisitQuery query = (BasicVisitQuery) definition; VisitQueryResult result = new VisitQueryResult(query, context); if (context.getBaseCohort() != null && context.getBaseCohort().isEmpty()) { return result; } if (context instanceof VisitEvaluationContext) { VisitIdSet baseVisits = ((VisitEvaluationContext) context).getBaseVisits(); if (baseVisits != null && baseVisits.getMemberIds().isEmpty()) { return result; } } HqlQueryBuilder q = new HqlQueryBuilder(); q.select("v.visitId"); q.from(Visit.class, "v"); q.whereIn("v.visitType", query.getVisitTypes()); q.whereGreaterOrEqualTo("v.startDatetime", query.getStartedOnOrAfter()); q.whereLessOrEqualTo("v.startDatetime", query.getStartedOnOrBefore()); q.whereGreaterOrEqualTo("v.stopDatetime", query.getEndedOnOrAfter()); q.whereLessOrEqualTo("v.stopDatetime", query.getEndedOnOrBefore()); q.whereIn("v.location", query.getLocationList()); q.whereVisitIn("v.visitId", context); for (Object[] row : evaluationService.evaluateToList(q, context)) { result.add((Integer)row[0]); } return result; }
Source:
<code>public void alterPartition(String databaseName, String tableName, PartitionWithStatistics partitionWithStatistics) { Partition oldPartition = getPartition(databaseName, tableName, partitionWithStatistics.getPartition().getValues()) .orElseThrow(() -> new PartitionNotFoundException(new SchemaTableName(databaseName, tableName), partitionWithStatistics.getPartition().getValues())); Table table = getTable(databaseName, tableName) .orElseThrow(() -> new TableNotFoundException(new SchemaTableName(databaseName, tableName))); List<String> partitionColumns = table.getPartitionKeys().stream() .map(FieldSchema::getName) .collect(toImmutableList()); String partitionName = makePartName(partitionColumns, oldPartition.getValues()); List<String> dataColumns = table.getSd().getCols().stream() .map(FieldSchema::getName) .collect(toImmutableList()); List<ColumnStatisticsObj> oldStatistics = getMetastorePartitionColumnStatistics(table.getDbName(), table.getTableName(), ImmutableSet.of(partitionName), dataColumns) .getOrDefault(partitionName, ImmutableList.of()); alterMetastorePartition(databaseName, tableName, toMetastoreApiPartition(partitionWithStatistics)); try { Set<String> columnStatisticsForRemoval = oldStatistics.stream() .map(ColumnStatisticsObj::getColName) .collect(toSet()); columnStatisticsForRemoval.removeAll(partitionWithStatistics.getStatistics().getColumnStatistics().keySet()); for (String columnName : columnStatisticsForRemoval) { deletePartitionColumnStatistics(databaseName, tableName, partitionName, columnName); } storePartitionColumnStatistics(databaseName, tableName, partitionName, partitionWithStatistics); } catch (Throwable t) { try { alterMetastorePartition(databaseName, tableName, oldPartition); } catch (Throwable suppressed) { if (t != suppressed) { t.addSuppressed(suppressed); } } throw t; <START> } <END> }</code><technical_language>is acceptable O(#partition * #column) calls. alternatives</technical_language>

Target:
public void alterPartition(String databaseName, String tableName, PartitionWithStatistics partitionWithStatistics) { alterPartitionWithoutStatistics(databaseName, tableName, toMetastoreApiPartition(partitionWithStatistics)); storePartitionColumnStatistics(databaseName, tableName, partitionWithStatistics.getPartitionName(), partitionWithStatistics); dropExtraColumnStatisticsAfterAlterPartition(databaseName, tableName, partitionWithStatistics); }
Source:
<code>public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; J2EContext context = new J2EContext(httpServletRequest, httpServletResponse, sessionStore); if (Pac4jCallbackResource.SELF_URL.equals(httpServletRequest.getRequestURI())) { callbackLogic.perform( context, pac4jConfig, <START> (int code, J2EContext ctx) -> null, <END> "/", true, false, false, null); } else { String uid = securityLogic.perform( context, pac4jConfig, (J2EContext ctx, Collection<CommonProfile> profiles, Object... parameters) -> { if (profiles.isEmpty()) { LOGGER.warn("No profiles found after OIDC auth."); return null; } else { return profiles.iterator().next().getId(); } }, (int code, J2EContext ctx) -> null, null, null, null, null); if (uid != null) { AuthenticationResult authenticationResult = new AuthenticationResult(uid, authorizerName, name, null); servletRequest.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, authenticationResult); filterChain.doFilter(servletRequest, servletResponse); } } }</code><technical_language>J2ENopHttpActionAdapter.INSTANCE</technical_language>

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; J2EContext context = new J2EContext(httpServletRequest, httpServletResponse, sessionStore); if (Pac4jCallbackResource.SELF_URL.equals(httpServletRequest.getRequestURI())) { callbackLogic.perform( context, pac4jConfig, NOOP_HTTP_ACTION_ADAPTER, "/", true, false, false, null); } else { String uid = securityLogic.perform( context, pac4jConfig, (J2EContext ctx, Collection<CommonProfile> profiles, Object... parameters) -> { if (profiles.isEmpty()) { LOGGER.warn("No profiles found after OIDC auth."); return null; } else { return profiles.iterator().next().getId(); } }, NOOP_HTTP_ACTION_ADAPTER, null, null, null, null); if (uid != null) { AuthenticationResult authenticationResult = new AuthenticationResult(uid, authorizerName, name, null); servletRequest.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, authenticationResult); filterChain.doFilter(servletRequest, servletResponse); } } }
Source:
<code><START> public void weightedSampleTest() throws Exception <END> { System.getProperties().setProperty("pigunit.randseed", "1"); PigTest test = createPigTest("test/pig/datafu/test/pig/bags/weightedSampleTest.pig"); writeLinesToFile("input", "({(a, 100),(b, 1),(c, 5),(d, 2)})"); test.runScript(); assertOutput(test, "data2", "({(c,5),(a,100),(b,1),(d,2)})"); }</code><technical_language>need this</technical_language>

Target:
public void weightedSampleTest() throws Exception { PigTest test = createPigTest("test/pig/datafu/test/pig/bags/weightedSampleTest.pig"); writeLinesToFile("input", "({(a, 100),(b, 1),(c, 5),(d, 2)})"); test.runScript(); assertOutput(test, "data2", "({(a,100),(c,5),(b,1),(d,2)})"); }
Source:
<code>public void close() throws IOException, CopycatException, InterruptedException { <START> timedRotateThread.shutdown(); <END> for (TopicPartition topicPart : writers.keySet()) { rotate(topicPart); } writers.clear(); for (WAL wal : wals.values()) { wal.close(); } wals.clear(); tempFileNames.clear(); recordCounters.clear(); offsets.clear(); tasks.clear(); if (fs != null) { fs.close(); } }</code><technical_language>Do need awaitTermination here? in-flight background file rotation completed? If in progress matter lock, if start, a race code calls rotate() cleans WAL</technical_language>

Target:
public void close() throws CopycatException { List<Exception> exceptions = new ArrayList<>(); for (TopicPartition topicPart : assignment) { try { if (writers.containsKey(topicPart)) { closeTempfile(topicPart); appendToWAL(topicPart); commitFile(topicPart); } } catch (IOException e) { log.error("Error rotating when closing task.", tempFileNames.get(topicPart)); exceptions.add(e); } } writers.clear(); for (WAL wal : wals.values()) { try { wal.close(); } catch (CopycatException e) { log.error("Error closing {}.", wal.getLogFile()); exceptions.add(e); } } wals.clear(); tempFileNames.clear(); recordCounters.clear(); offsets.clear(); lastAssignment.clear(); failureTime.clear(); try { storage.close(); } catch (IOException e) { log.error("Error closing storage {}.", storage.url()); exceptions.add(e); } if (exceptions.size() != 0) { StringBuilder sb = new StringBuilder(); for (Exception exception: exceptions) { sb.append(exception.getMessage()); sb.append("\n"); } throw new CopycatException("Error closing writer: " + sb.toString()); } }
Source:
<code><START> private void validateStreamId(final List<NakadiCursor> cursors, final String streamId, <END> final String subscriptionId) throws ServiceUnavailableException, InvalidCursorException, InvalidStreamIdException, NoSuchEventTypeException, InternalNakadiException { if (!isActiveSession(subscriptionId, streamId)) { throw new InvalidStreamIdException("Session with stream id " + streamId + " not found"); } final HashMap<EventTypePartition, String> partitionSessions = new HashMap<>(); for (final NakadiCursor cursor : cursors) { final EventType eventType = eventTypeRepository.findByName(cursor.getTimeline().getEventType()); final EventTypePartition etPartition = new EventTypePartition(eventType.getName(), cursor.getPartition()); String partitionSession = partitionSessions.get(etPartition); if (partitionSession == null) { partitionSession = getPartitionSession(subscriptionId, eventType.getTopic(), cursor); partitionSessions.put(etPartition, partitionSession); } if (!streamId.equals(partitionSession)) { throw new InvalidStreamIdException("Cursor " + cursor + " cannot be committed with stream id " + streamId); } } }</code><technical_language>line 133: partitionSession = getPartitionSession(subscriptionId, eventType.getTopic(), cursor); topic event type. I sense</technical_language>

Target:
private void validateStreamId(final List<NakadiCursor> cursors, final String streamId, final String subscriptionId) throws ServiceUnavailableException, InvalidCursorException, InvalidStreamIdException, NoSuchEventTypeException, InternalNakadiException { if (!isActiveSession(subscriptionId, streamId)) { throw new InvalidStreamIdException("Session with stream id " + streamId + " not found"); } final HashMap<EventTypePartition, String> partitionSessions = new HashMap<>(); for (final NakadiCursor cursor : cursors) { final EventTypePartition etPartition = new EventTypePartition( cursor.getTimeline().getEventType(), cursor.getPartition()); String partitionSession = partitionSessions.get(etPartition); if (partitionSession == null) { partitionSession = getPartitionSession(subscriptionId, cursor.getTopic(), cursor); partitionSessions.put(etPartition, partitionSession); } if (!streamId.equals(partitionSession)) { throw new InvalidStreamIdException("Cursor " + cursor + " cannot be committed with stream id " + streamId); } } }
Source:
<code>public void run(final ApplicationArguments args) throws Exception { final Optional<Storage> storageOpt = storageDbRepository.getStorage(DEFAULT_STORAGE); if (!storageOpt.isPresent()) { final Storage storage = new Storage(); storage.setId(DEFAULT_STORAGE); storage.setType(Storage.Type.KAFKA); storage.setConfiguration(new Storage.KafkaConfiguration( environment.getProperty("nakadi.zookeeper.exhibitor.brokers"), Integer.valueOf(environment.getProperty("nakadi.zookeeper.exhibitor.port", "0")), environment.getProperty("nakadi.zookeeper.brokers"), environment.getProperty("nakadi.zookeeper.kafkaNamespace", ""))); <START> storageDbRepository.createStorage(storage); <END> } }</code><technical_language>Is problem if exception is launched here</technical_language>

Target:
public void run(final ApplicationArguments args) throws InternalNakadiException { final Storage storage = new Storage(); storage.setId(DEFAULT_STORAGE); storage.setType(Storage.Type.KAFKA); storage.setConfiguration(new Storage.KafkaConfiguration( environment.getProperty("nakadi.zookeeper.exhibitor.brokers"), Integer.valueOf(environment.getProperty("nakadi.zookeeper.exhibitor.port", "0")), environment.getProperty("nakadi.zookeeper.brokers"), environment.getProperty("nakadi.zookeeper.kafkaNamespace", ""))); try { storageDbRepository.createStorage(storage); } catch (final DuplicatedStorageIdException e) { LOG.info("Creation of default storage failed: {}", e.getMessage()); } }
Source:
<code>public boolean test() { WidgetHandler.getInstance().setFocus(ib.getSWTWidget()); Display.syncExec(new ResultRunnable<Boolean>() { @Override public Boolean run() { boolean ret = ib.getSWTWidget().forceFocus(); <START> return ret; <END> } }); return ib.getText().contains(text); }</code><technical_language>This returned variable is anywhere. overlook</technical_language>

Target:
public boolean test() { WidgetHandler.getInstance().setFocus(ib.getSWTWidget()); Display.syncExec(new Runnable() { @Override public void run() { ib.getSWTWidget().forceFocus(); } }); return ib.getText().contains(text); }
Source:
<code>public static MessageType getSubfieldType(GroupType baseType, Subfield subfield) { checkArgument(subfield.getPath().size() >= 1, "subfield size is less than 1"); ImmutableList.Builder<org.apache.parquet.schema.Type> typeBuilder = ImmutableList.builder(); org.apache.parquet.schema.Type parentType = getParquetTypeByName(subfield.getRootName(), baseType); String rootName = parentType.getName(); for (PathElement field : subfield.getPath()) { if (field instanceof NestedField) { NestedField nestedField = (NestedField) field; org.apache.parquet.schema.Type childType = getParquetTypeByName(nestedField.getName(), parentType.asGroupType()); if (childType != null) { typeBuilder.add(childType); parentType = childType; } <START> else { <END> return new MessageType(rootName, ImmutableList.of()); } } else { typeBuilder.add(parentType.asGroupType().getFields().get(0)); break; } } List<org.apache.parquet.schema.Type> subfieldTypes = typeBuilder.build(); org.apache.parquet.schema.Type type = subfieldTypes.get(subfieldTypes.size() - 1); for (int i = subfieldTypes.size() - 2; i >= 0; --i) { GroupType groupType = subfieldTypes.get(i).asGroupType(); type = new MessageType(groupType.getName(), ImmutableList.of(type)); } return new MessageType(rootName, ImmutableList.of(type)); }</code><technical_language>simplify logic as: if (childType == null) { return new MessageType(rootName, ImmutableList.of()); } typeBuilder.add(childType); parentType = childType;</technical_language>

Target:
public static MessageType getSubfieldType(GroupType baseType, Subfield subfield) { checkArgument(subfield.getPath().size() >= 1, "subfield size is less than 1"); ImmutableList.Builder<org.apache.parquet.schema.Type> typeBuilder = ImmutableList.builder(); org.apache.parquet.schema.Type parentType = getParquetTypeByName(subfield.getRootName(), baseType); String rootName = parentType.getName(); for (PathElement field : subfield.getPath()) { if (field instanceof NestedField) { NestedField nestedField = (NestedField) field; org.apache.parquet.schema.Type childType = getParquetTypeByName(nestedField.getName(), parentType.asGroupType()); if (childType == null) { return new MessageType(rootName, ImmutableList.of()); } typeBuilder.add(childType); parentType = childType; } else { typeBuilder.add(parentType.asGroupType().getFields().get(0)); break; } } List<org.apache.parquet.schema.Type> subfieldTypes = typeBuilder.build(); org.apache.parquet.schema.Type type = subfieldTypes.get(subfieldTypes.size() - 1); for (int i = subfieldTypes.size() - 2; i >= 0; --i) { GroupType groupType = subfieldTypes.get(i).asGroupType(); type = new MessageType(groupType.getName(), ImmutableList.of(type)); } return new MessageType(rootName, ImmutableList.of(type)); }
Source:
<code>public void getTriggers(@NonNull Callback<List<Trigger>> callback) { TriggerService service = retrofit.create(TriggerService.class); <START> Map<String, String> map = new HashMap<>(); <END> String cred = new String(Base64.encode(("jdoe:password").getBytes(), Base64.NO_WRAP)); map.put("Authorization", "Basic "+cred); map.put("Hawkular-Tenant", "hawkular"); Call call = service.get(map); call.enqueue(callback); }</code><technical_language>setup for application need set for call</technical_language>

Target:
public void getTriggers(@NonNull Callback<List<Trigger>> callback) { TriggerService service = retrofit.create(TriggerService.class); Call call = service.get(); call.enqueue(callback); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String postType = getArguments().getString(ARG_POST_TYPE); boolean isNewPost = getArguments() != null && getArguments().getBoolean(ARG_IS_NEW_POST); String localeString = getArguments().getString(ARG_LOCALE); Bundle translations = getArguments().getBundle(ARG_TRANSLATIONS); mWPAndroidGlueCode = new WPAndroidGlueCode(); mWPAndroidGlueCode.onCreate(getContext()); mWPAndroidGlueCode.onCreateView( getContext(), mHtmlModeEnabled, getActivity().getApplication(), BuildConfig.DEBUG, BuildConfig.BUILD_GUTENBERG_FROM_SOURCE, postType, isNewPost, localeString, translations, <START> getContext().getResources().getColor(R.color.background_color)); <END> mHasReceivedAnyContent = false; }</code><technical_language>defined background color in styles.xml for light dark mode, I existing color attribute here, this: ContextExtensionsKt.getColorFromAttribute(getContext(), R.attr.backgroundColor)</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String postType = getArguments().getString(ARG_POST_TYPE); boolean isNewPost = getArguments() != null && getArguments().getBoolean(ARG_IS_NEW_POST); String localeString = getArguments().getString(ARG_LOCALE); Bundle translations = getArguments().getBundle(ARG_TRANSLATIONS); boolean isDarkMode = getArguments().getBoolean(ARG_PREFERRED_COLOR_SCHEME); mWPAndroidGlueCode = new WPAndroidGlueCode(); mWPAndroidGlueCode.onCreate(getContext()); mWPAndroidGlueCode.onCreateView( getContext(), mHtmlModeEnabled, getActivity().getApplication(), BuildConfig.DEBUG, BuildConfig.BUILD_GUTENBERG_FROM_SOURCE, postType, isNewPost, localeString, translations, getContext().getResources().getColor(R.color.background_color), isDarkMode); mHasReceivedAnyContent = false; }
Source:
<code>public Lock lock(String resourceId, Long ttl) throws LightblueException { <START> acquire(resourceId, ttl); <END> return new Lock(resourceId); }</code><technical_language>This right. return a lock if acquire returns false</technical_language>

Target:
public Lock lock(String resourceId, Long ttl) throws LightblueException { if (acquire(resourceId, ttl)) { return new Lock(resourceId); } return null; }