auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldFindUserSubscribingForAnyPipelineAndThatHasPermission() { User foo = new User("foo", Arrays.asList("fOO", "Foo"), "foo@cruise.com", false); foo.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); User bar = new User("bar", Arrays.asList("bAR", "Bar"), "bar@go.com", true); bar.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); <START> User quux = new User("quux", Arrays.asList("qUUX", "Quux"), "quux@cruise.go", false); <END> quux.addNotificationFilter(new NotificationFilter("p2", "s2", StageEvent.Passes, true)); when(userDao.findNotificationSubscribingUsers()).thenReturn(new Users(Arrays.asList(foo, bar))); when(securityService.hasViewPermissionForPipeline(foo.getName(), "p1")).thenReturn(true); when(securityService.hasViewPermissionForPipeline(bar.getName(), "p1")).thenReturn(false); assertThat(userService.findValidSubscribers(new StageConfigIdentifier("p1", "s1")), contains(foo)); }</code><technical_language>Small note: User quux is in this test removed</technical_language>

Target:
public void shouldFindUserSubscribingForAnyPipelineAndThatHasPermission() { User foo = new User("foo", Arrays.asList("fOO", "Foo"), "foo@cruise.com", false); foo.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); User bar = new User("bar", Arrays.asList("bAR", "Bar"), "bar@go.com", true); bar.addNotificationFilter(new NotificationFilter(GoConstants.ANY_PIPELINE, GoConstants.ANY_STAGE, StageEvent.Passes, true)); when(userDao.findNotificationSubscribingUsers()).thenReturn(new Users(Arrays.asList(foo, bar))); when(securityService.hasViewPermissionForPipeline(foo.getName(), "p1")).thenReturn(true); when(securityService.hasViewPermissionForPipeline(bar.getName(), "p1")).thenReturn(false); assertThat(userService.findValidSubscribers(new StageConfigIdentifier("p1", "s1")), contains(foo)); }
Source:
<code>public void testSubstitutionEqualsAndHashCodeAreConsistent() { final List<Substitution> substitutions = new ArrayList<>(); for (int position : new int[] {0, 1}) { for (byte base : new byte[] {(byte) -1, (byte) 'A'}) { for (byte referenceBase : new byte[] {(byte) -1, (byte) 'C'}) { <START> for (byte code : new byte[] {Substitution.NO_CODE, (byte) 2}) { <END> Substitution substitution = new Substitution(position, base, referenceBase); substitution.setCode(code); substitutions.add(substitution); } } } } for (Substitution s1 : substitutions) { for (Substitution s2 : substitutions) { if (s1.equals(s2)) { Assert.assertEquals(s1.hashCode(), s2. hashCode(), String.format("Comparing %s (%s) and %s (%s)", s1, s1.getCode(), s2, s2.getCode())); } } } }</code><technical_language>I works. If difference of is code is NO_CODE other isn't, equals() false hashCode() is same. OK in contract</technical_language>

Target:
public void testSubstitutionEqualsAndHashCodeAreConsistent() { final List<Substitution> substitutions = new ArrayList<>(); for (int position : new int[] {0, 1}) { for (byte base : new byte[] {(byte) -1, (byte) 'A'}) { for (byte referenceBase : new byte[] {(byte) -1, (byte) 'C'}) { for (byte code : new byte[] {Substitution.NO_CODE, (byte) 1, (byte) 2}) { Substitution substitution = new Substitution(position, base, referenceBase); substitution.setCode(code); substitutions.add(substitution); } } } } for (Substitution s1 : substitutions) { for (Substitution s2 : substitutions) { if (s1.equals(s2)) { Assert.assertEquals(s1.hashCode(), s2. hashCode(), String.format("Comparing %s (%s) and %s (%s)", s1, s1.getCode(), s2, s2.getCode())); } } } }
Source:
<code>public void onNext(final Message<AvroElasticMemoryMessage> msg) { LOG.entering(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); final AvroElasticMemoryMessage innerMsg = SingleMessageExtractor.extract(msg); switch (innerMsg.getType()) { case RoutingTableInitMsg: onRoutingTableInitMsg(innerMsg); break; case RoutingTableUpdateMsg: onRoutingTableUpdateMsg(innerMsg); break; case RemoteOpMsg: case RemoteOpResultMsg: <START> onRemoteOpResultMsg(innerMsg); <END> break; case DataMsg: onDataMsg(innerMsg); break; case CtrlMsg: onCtrlMsg(innerMsg); break; case OwnershipMsg: onOwnershipMsg(innerMsg); break; default: throw new RuntimeException("Unexpected message: " + msg); } LOG.exiting(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); }</code><technical_language>Is intentional deal RemoteOpMsg RemoveOpResultMsg? If then, rename method onRemoteOpResultMsg</technical_language>

Target:
public void onNext(final Message<AvroElasticMemoryMessage> msg) { LOG.entering(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); final AvroElasticMemoryMessage innerMsg = SingleMessageExtractor.extract(msg); switch (innerMsg.getType()) { case RoutingTableInitMsg: onRoutingTableInitMsg(innerMsg); break; case RoutingTableUpdateMsg: onRoutingTableUpdateMsg(innerMsg); break; case RemoteOpReqMsg: case RemoteOpResultMsg: onRemoteOpMsg(innerMsg); break; case DataMsg: onDataMsg(innerMsg); break; case CtrlMsg: onCtrlMsg(innerMsg); break; case OwnershipMsg: onOwnershipMsg(innerMsg); break; default: throw new RuntimeException("Unexpected message: " + msg); } LOG.exiting(ElasticMemoryMsgHandler.class.getSimpleName(), "onNext", msg); }
Source:
<code>private void loadPatterns(String directory, List<Pattern> patternList) { String dspaceHome = configurationService.getProperty("dspace.dir"); File spidersDir = new File(dspaceHome, "config/spiders"); File patternsDir = new File(spidersDir, directory); if (patternsDir.exists() && patternsDir.isDirectory()) { <START> for (File file : patternsDir.listFiles()) { <END> if (file.isFile() && !file.getName().matches(".+old$")) { Set<String> patterns; try { patterns = readPatterns(file); } catch (IOException ex) { log.error("Patterns not read from {}: {}", file.getPath(), ex.getMessage()); continue; } for (String pattern : patterns) { if (isUseCaseInsensitiveMatching()) { pattern = StringUtils.lowerCase(pattern); } patternList.add(Pattern.compile(pattern)); } log.info("Loaded pattern file: {}", file.getPath()); } } } else { log.info("No patterns loaded from {}", patternsDir.getPath()); } }</code><technical_language>considered writing a simple FileFilter implementation, passing listFiles() below? give copy of test, instead of updated if filtering requirements change</technical_language>

Target:
private void loadPatterns(String directory, List<Pattern> patternList) { String dspaceHome = configurationService.getProperty("dspace.dir"); File spidersDir = new File(dspaceHome, "config/spiders"); File patternsDir = new File(spidersDir, directory); if (patternsDir.exists() && patternsDir.isDirectory()) { for (File file : patternsDir.listFiles(new NoDotOldFilter())) { Set<String> patterns; try { patterns = readPatterns(file); } catch (IOException ex) { log.error("Patterns not read from {}: {}", file.getPath(), ex.getMessage()); continue; } for (String pattern : patterns) { if (isUseCaseInsensitiveMatching()) { pattern = StringUtils.lowerCase(pattern); } patternList.add(Pattern.compile(pattern)); } log.info("Loaded pattern file: {}", file.getPath()); } } else { log.info("No patterns loaded from {}", patternsDir.getPath()); } }
Source:
<code><START> private static String get_or_attr(Map<String, String> obj, String name) { <END> if (obj.containsKey(name)) { return obj.get(name); } else { return null; } }</code><technical_language>again, @Nullable</technical_language>

Target:
private static @Nullable String get_or_attr(Map<String, String> obj, String name) { if (obj.containsKey(name)) { return obj.get(name); } else { return null; } }
Source:
<code>public String toString() { <START> StringBuffer buffer = new StringBuffer(); <END> buffer.append("Version:") .append(CURRENT_VERSION) .append("\n") .append("StartTime:") .append(startTime) .append("\n") .append("StartOffsetOfLastIndexSegmentForDeleteCheck"); if (startOffsetOfLastIndexSegmentForDeleteCheck == null) { buffer.append("null"); } else { buffer.append(startOffsetOfLastIndexSegmentForDeleteCheck.toString()); } buffer.append("\n"); buffer.append("CurrentIndex:") .append(currentIdx) .append("\n") .append("CycleLogSize:") .append(cycleLogs.size()) .append("\n") .append("CycleLogs:"); for (CycleLog cycleLog : cycleLogs) { buffer.append(cycleLog.toString()).append("\n\n"); } return buffer.toString(); }</code><technical_language>I wanted StringBuilder here</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Version:") .append(CURRENT_VERSION) .append("\n") .append("StartTime:") .append(startTime) .append("\n") .append("StartOffsetOfLastIndexSegmentForDeleteCheck"); if (startOffsetOfLastIndexSegmentForDeleteCheck == null) { sb.append("null"); } else { sb.append(startOffsetOfLastIndexSegmentForDeleteCheck.toString()); } sb.append("\n"); sb.append("CurrentIndex:") .append(currentIdx) .append("\n") .append("CycleLogSize:") .append(cycleLogs.size()) .append("\n") .append("CycleLogs:"); for (CycleLog cycleLog : cycleLogs) { sb.append(cycleLog.toString()).append("\n\n"); } return sb.toString(); }
Source:
<code>public void testVSMResourceVersionMismatch() { setupFileVersionMismatch(true, false, false); Session session = null; try { clearErrors(); session = SessionUIManager.INSTANCE.openSession(sessionResourceURI, new NullProgressMonitor()); String[] args = { RuntimeException.class.getName(), "VSM" }; fail(Messages.format(THROWN_EXCEPTION, <START> args)); <END> } catch (RuntimeException e) { } assertTrue(SESSION_NOT_IN_SESSIONMANAGER, SessionManager.INSTANCE.getSessions().isEmpty()); }</code><technical_language>put RuntimeException.class.getName(), "VSM" here, need for intermediate variable</technical_language>

Target:
public void testVSMResourceVersionMismatch() { setupFileVersionMismatch(true, false, false); Session session = null; try { clearErrors(); session = SessionManager.INSTANCE.openSession(sessionResourceURI, new NullProgressMonitor(), SiriusEditPlugin.getPlugin().getUiCallback()); fail(Messages.format(THROWN_EXCEPTION, new String[] { RuntimeException.class.getName(), "VSM" })); } catch (RuntimeException e) { } assertTrue(SESSION_NOT_IN_SESSIONMANAGER, SessionManager.INSTANCE.getSessions().isEmpty()); }
Source:
<code>public void testGetClustersByServiceAndCompatibilityVersion() { List<VDSGroup> vdsGroups = ((VdsGroupDAODbFacadeImpl)dao).getClustersByServiceAndCompatibilityVersion(true, false, new Version("2.3")); assertNotNull(vdsGroups); assertEquals(1, vdsGroups.size()); <START> assertEquals(new Guid("ae956031-6be2-43d6-bb8f-5191c9253314"), vdsGroups.get(0).getId()); <END> }</code><technical_language>FixturesTool.GLUSTER_CLUSTER_ID</technical_language>

Target:
public void testGetClustersByServiceAndCompatibilityVersion() { List<VDSGroup> vdsGroups = ((VdsGroupDAODbFacadeImpl)dao).getClustersByServiceAndCompatibilityVersion(true, false, new Version("2.3")); assertNotNull(vdsGroups); assertEquals(1, vdsGroups.size()); assertEquals(FixturesTool.GLUSTER_CLUSTER_ID, vdsGroups.get(0).getId()); }
Source:
<code><START> public Expression convert(String input) throws OptionsParsingException { <END> if (input.isEmpty()) { return null; } if (isLegacySyntax(input)) { input = convertLegacySyntaxToBooleanFormula(input); GoogleLogger.forEnclosingClass().at(Level.WARNING).log( "Specifying a list of tags separated by comma is legacy syntax and will not be supported after" + " Jan 1, 2021. Consider changing to: " + input); } try { Expression result = Expression.parse(ParserInput.fromLines(input)); validate(result); return result; } catch (SyntaxError.Exception e) { throw new OptionsParsingException("Failed to parse expression: " + e.getMessage() + " input: " + input, e); } }</code><technical_language>@Nullable public</technical_language>

Target:
@Nullable public Expression convert(String input) throws OptionsParsingException { if (input.isEmpty()) { return null; } if (isLegacySyntax(input)) { input = convertLegacySyntaxToBooleanFormula(input); } try { Expression result = Expression.parse(ParserInput.fromLines(input)); validate(result); return result; } catch (SyntaxError.Exception e) { throw new OptionsParsingException("Failed to parse expression: " + e.getMessage() + " input: " + input, e); } }
Source:
<code>public CompletionStage<Result> queryMetrics() { try { final MetricsQuery metricsQuery = _mapper.treeToValue(request().body().asJson(), MetricsQuery.class); <START> if (!metricsQuery.getMetrics().stream().allMatch(metric -> metric.getAggregators().size() >= 1)) { <END> return CompletableFuture.completedFuture( Results.badRequest("All queried metrics must have at least one aggregator")); } return _kairosService.queryMetrics(metricsQuery) .<JsonNode>thenApply(_mapper::valueToTree) .thenApply(Results::ok); } catch (final IOException e) { return CompletableFuture.completedFuture(Results.internalServerError(e.getMessage())); } }</code><technical_language>I invert this condition is a metric aggregator list is empty i.e. java metricsQuery.getMetrics().stream().anyMatch(metric -> metric.getAggregators().isEmpty()) I intent clearer removing a ! comparison</technical_language>

Target:
public CompletionStage<Result> queryMetrics() { try { final MetricsQuery metricsQuery = _mapper.treeToValue(request().body().asJson(), MetricsQuery.class); if (_requireAggregators && metricsQuery.getMetrics().stream().anyMatch(metric -> metric.getAggregators().isEmpty())) { return CompletableFuture.completedFuture( Results.badRequest("All queried metrics must have at least one aggregator")); } return _kairosService.queryMetrics(metricsQuery) .<JsonNode>thenApply(_mapper::valueToTree) .thenApply(Results::ok); } catch (final IOException e) { return CompletableFuture.completedFuture(Results.internalServerError(e.getMessage())); } }
Source:
<code>T select( IndexSlot slot ) { <START> if ( !instances.containsKey( slot ) ) <END> { assertOpen(); instances.put( slot, factory.apply( slot ) ); } return super.select( slot ); }</code><technical_language>computeIfAbsent</technical_language>

Target:
T select( IndexSlot slot ) { return instances.computeIfAbsent( slot, s -> { assertOpen(); return factory.apply( s ); } ); }
Source:
<code>private Properties getCoordinatorStreamProperties(KafkaConfig config) { Properties coordinatorStreamProperties = new Properties(); <START> coordinatorStreamProperties.put("cleanup.policy", "compact"); <END> coordinatorStreamProperties.put("segment.bytes", config.getCoordinatorSegmentBytes()); return coordinatorStreamProperties; }</code><technical_language>1. replace hard-coded string(cleanup.policy) TopicConfig.RETENTION_MS_CONFIG . 2. replace hard-coded string: compact TopicConfig.CLEANUP_POLICY_COMPACT . 3. replace segment.policy TopicConfig. SEGMENT_BYTES_CONFIG</technical_language>

Target:
private Properties getCoordinatorStreamProperties(KafkaConfig config) { Properties coordinatorStreamProperties = new Properties(); coordinatorStreamProperties.put(TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT); coordinatorStreamProperties.put(TopicConfig.SEGMENT_BYTES_CONFIG, config.getCoordinatorSegmentBytes()); return coordinatorStreamProperties; }
Source:
<code>private void changeValue(float delta) { <START> float newValue = TeraMath.clamp(getValue() + delta, 0, getRange() + getMinimum()); <END> setValue(newValue); }</code><technical_language>getMinimum() more 0</technical_language>

Target:
private void changeValue(float delta) { float newValue = TeraMath.clamp(getValue() + delta, getMinimum(), getRange() + getMinimum()); setValue(newValue); }
Source:
<code>public static <T> List<T> getBaseClasses(final Class<T> desiredBase, final String packageName) throws URISyntaxException, IOException, IllegalArgumentException { if (desiredBase == null) { throw new IllegalArgumentException("desiredBase must not be null"); } if (StringUtils.isBlank(packageName)) { throw new IllegalArgumentException("packageName must not be blank"); } <START> if (packageName.contains("/")) { <END> throw new IllegalArgumentException("packageName is not properly formatted (i.e. 'java.lang.String')"); } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url = classLoader.getResource(packageName.replaceAll("[.]", "/")); if (url == null) { throw new URISyntaxException(packageName, "Supplied package not found"); } Path classesPath = Paths.get(url.toURI()); List<T> classes = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(classesPath)) { for (Path file: stream) { Path pathFileName = file.getFileName(); if (( ! Files.isDirectory(file)) && (pathFileName != null)) { String fullClassName = packageName + "." + pathFileName.toString().replace(".class", ""); try { Object obj = Class.forName(fullClassName).newInstance(); if (desiredBase.isInstance(obj)) { classes.add((T) obj); } } catch (Exception e) { } } } } return classes; }</code><technical_language>validate a regex</technical_language>

Target:
public static <T> List<T> getBaseClasses(final Class<T> desiredBase, final String packageName) throws IllegalArgumentException, IOException, NullPointerException, URISyntaxException { return getBaseClasses(desiredBase, packageName, Thread.currentThread().getContextClassLoader()); }
Source:
<code>private UpdateData createUpdateData() { final Object[] values = getValues(); Column[] columns = getColumns(); boolean[] explicitNulls = getExplicitNulls(); List<UpdateField> fields = new ArrayList<UpdateField>(); for (int i = 0; i < columns.length; i++) { final Object value = values[i]; if (value != null || explicitNulls[i]) { String columnName = columns[i].getName(); final UpdateField field = new UpdateField(columnName, value.toString()); fields.add(field); } } List<FilterItem> whereItems = getWhereItems(); if (!(whereItems.size() == 1 && whereItems.get(0).getSelectItem().getColumn().getName().equals("gr_id"))) { <START> throw new IllegalArgumentException("Only gr_id is allowed as a select item"); <END> } String grId = (String) whereItems.get(0).getOperand(); return new UpdateData(grId, fields.toArray(new UpdateField[fields.size()])); }</code><technical_language>phrase this a bit more user-friendly "Updates allowed individual records, identified gr_id" that. Referring a select item is a bit of internal detail user</technical_language>

Target:
private UpdateData createUpdateData() { final Object[] values = getValues(); Column[] columns = getColumns(); boolean[] explicitNulls = getExplicitNulls(); List<UpdateField> fields = new ArrayList<UpdateField>(); for (int i = 0; i < columns.length; i++) { final Object value = values[i]; if (value != null || explicitNulls[i]) { String columnName = columns[i].getName(); final UpdateField field = new UpdateField(columnName, value.toString()); fields.add(field); } } List<FilterItem> whereItems = getWhereItems(); if (!(whereItems.size() == 1 && whereItems.get(0).getSelectItem().getColumn().getName().equals("gr_id"))) { throw new IllegalArgumentException("Updates are only allowed on individual records, identified by gr_id (golden record id)"); } String grId = (String) whereItems.get(0).getOperand(); return new UpdateData(grId, fields.toArray(new UpdateField[fields.size()])); }
Source:
<code>private LNPResultsStatistics getResultsStatistics() throws IOException { Gson gson = new Gson(); JsonReader reader = new JsonReader(Files.newBufferedReader(Paths.get(getPathToTestStatisticsResultsFile()))); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); <START> JsonObject endPointAnalysis = jsonObject.getAsJsonObject("Test Endpoint"); <END> return gson.fromJson(endPointAnalysis, LNPResultsStatistics.class); }</code><technical_language>endpointStats</technical_language>

Target:
private LNPResultsStatistics getResultsStatistics() throws IOException { Gson gson = new Gson(); JsonReader reader = new JsonReader(Files.newBufferedReader(Paths.get(getPathToTestStatisticsResultsFile()))); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); JsonObject endpointStats = jsonObject.getAsJsonObject("HTTP Request Sampler"); return gson.fromJson(endpointStats, LNPResultsStatistics.class); }
Source:
<code>public void subscribe(EventService eventService) { if (pvcEnabled && !namespaceFactory.isPredefined()) eventService.subscribe( event -> { final String workspaceId = event.getWorkspace().getId(); try { <START> if (!isEphemeral(event.getWorkspace())) { <END> strategy.cleanup(workspaceId); } } catch (InfrastructureException ex) { LOG.error( "Failed to cleanup workspace '{}' data. Cause: {}", workspaceId, ex.getMessage()); } }, WorkspaceRemovedEvent.class); }</code><technical_language>move this logic strategy avoid splitting components</technical_language>

Target:
public void subscribe(EventService eventService) { if (pvcEnabled && !namespaceFactory.isPredefined()) eventService.subscribe( event -> { final Workspace workspace = event.getWorkspace(); try { strategy.cleanup(workspace); } catch (InfrastructureException ex) { LOG.error( "Failed to cleanup workspace '{}' data. Cause: {}", workspace.getId(), ex.getMessage()); } }, WorkspaceRemovedEvent.class); }
Source:
<code>public void findModDirMods(File modsDir) { File[] modList = FileListHelper.sortFileList(modsDir, null); modList = FileListHelper.sortFileList(ObjectArrays.concat(modList, ModListHelper.additionalMods.values().toArray(new File[0]), File.class)); for (File modFile : modList) { if (CoreModManager.getLoadedCoremods().contains(modFile.getName())) { FMLLog.finer("Skipping already parsed coremod or tweaker %s", modFile.getName()); } else if (modFile.isDirectory()) { FMLLog.fine("Found a candidate mod directory %s", modFile.getName()); addCandidate(new ModCandidate(modFile, modFile, ContainerType.DIR)); } else { <START> if (Files.getFileExtension(modFile.getName()).equals(".jar")) <END> { FMLLog.fine("Found a candidate jar file %s", modFile.getName()); addCandidate(new ModCandidate(modFile, modFile, ContainerType.JAR)); } else { FMLLog.info("Ignoring non-mod file %s in mods directory", modFile.getName()); } } } }</code><technical_language>Instead of this pass FileFilterUtils.suffixFileFilter(".jar") line 86</technical_language>

Target:
public void findModDirMods(File modsDir) { File[] modsDirMods = modsDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".jar") || pathname.isDirectory(); } }); File[] additionalMods = ModListHelper.additionalMods.values().toArray(new File[ModListHelper.additionalMods.size()]); File[] sortedModsList = FileListHelper.sortFileList(ObjectArrays.concat(modsDirMods, additionalMods, File.class)); for (File modFile : sortedModsList) { if (CoreModManager.getLoadedCoremods().contains(modFile.getName())) { FMLLog.finer("Skipping already parsed coremod or tweaker %s", modFile.getName()); } else if (modFile.isDirectory()) { FMLLog.fine("Found a candidate mod directory %s", modFile.getName()); addCandidate(new ModCandidate(modFile, modFile, ContainerType.DIR)); } else { FMLLog.fine("Found a candidate jar file %s", modFile.getName()); addCandidate(new ModCandidate(modFile, modFile, ContainerType.JAR)); } } }
Source:
<code>public String evaluate(TransactionContext txnCtx, Input[] args) { assert args.length == 2 : String.format(Locale.ENGLISH, "number of arguments must be 2, got %d instead", args.length); String str = (String) args[0].value(); Number len = (Number) args[1].value(); if (str == null || len == null) { return null; } switch (info.ident().name()) { case LEFT_NAME: return left(str, len.intValue()); case RIGHT_NAME: return right(str, len.intValue()); default: throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "not yet implemented: %s", <START> info.ident().name())); <END> } }</code><technical_language>supporting else here. suggest create register 2 dedicated classes instead implementing required concrete code</technical_language>

Target:
public String evaluate(TransactionContext txnCtx, Input[] args) { assert args.length == 2 : String.format(Locale.ENGLISH, "number of arguments must be 2, got %d instead", args.length); String str = (String) args[0].value(); Number len = (Number) args[1].value(); if (str == null || len == null) { return null; } return len.intValue() == 0 || str.isEmpty() ? "" : func.apply(str, len.intValue()); }
Source:
<code>static StringStatistics toStringStatistics(HiveWriterVersion hiveWriterVersion, DwrfProto.StringStatistics stringStatistics, boolean isRowGroup) { if (hiveWriterVersion == ORIGINAL && !isRowGroup) { return null; } if (!stringStatistics.hasMinimum() && !stringStatistics.hasMaximum()) { return null; } Slice maximum; Slice minimum; if (hiveWriterVersion != ORIGINAL) { maximum = stringStatistics.hasMaximum() ? maxStringTruncateAtFirstReplacementCharacter(toSlice(stringStatistics.getMaximumBytes())) : null; <START> minimum = stringStatistics.hasMinimum() ? minStringTruncateAtFirstReplacementCharacter(toSlice(stringStatistics.getMinimumBytes())) : null; <END> } else { minimum = stringStatistics.hasMinimum() ? getMinSlice(stringStatistics.getMinimum()) : null; maximum = stringStatistics.hasMaximum() ? getMaxSlice(stringStatistics.getMaximum()) : null; } long sum = stringStatistics.hasSum() ? stringStatistics.getSum() : 0; return new StringStatistics(minimum, maximum, sum); }</code><technical_language>I imagine maxStringTruncateAtFirstReplacementCharacter minStringTruncateAtFirstReplacementCharacter apply ORIGINAL</technical_language>

Target:
static StringStatistics toStringStatistics(HiveWriterVersion hiveWriterVersion, DwrfProto.StringStatistics stringStatistics, boolean isRowGroup) { if (hiveWriterVersion == ORIGINAL && !isRowGroup) { return null; } if (!stringStatistics.hasMinimum() && !stringStatistics.hasMaximum()) { return null; } Slice maximum = stringStatistics.hasMaximum() ? maxStringTruncateToValidRange(byteStringToSlice(stringStatistics.getMaximumBytes()), hiveWriterVersion) : null; Slice minimum = stringStatistics.hasMinimum() ? minStringTruncateToValidRange(byteStringToSlice(stringStatistics.getMinimumBytes()), hiveWriterVersion) : null; long sum = stringStatistics.hasSum() ? stringStatistics.getSum() : 0; return new StringStatistics(minimum, maximum, sum); }
Source:
<code>public void visitString(VisitableXmlElement<String> visitable) { JAXBElement<String> element = visitable.getElement(); <START> LOGGER.debug(element.getName().getLocalPart()); <END> LOGGER.debug(element.getValue()); builder.setProperty(element.getValue()); }</code><technical_language>want combine statements add more context message</technical_language>

Target:
public void visitString(VisitableXmlElement<String> visitable) { JAXBElement<String> element = visitable.getElement(); traceLocalPart(element.getName().getLocalPart()); traceValue(element.getValue()); builder.setProperty(element.getValue()); }
Source:
<code>public void start() throws SQLException, SchemaGenerationException { if (_initialized) { close(); } <START> _metrics = new DatabaseChunkedReaderMetrics(_chunkingTable, _readerId); <END> initializeChunkingKeyInfo(); _chunkedQuery = _chunkedQueryManager.generateChunkedQuery(_sourceQuery, new ArrayList<>(_chunkingKeys.keySet()), _chunkSize, _maxChunkIndex, _chunkIndex); _tableSchema = _databaseSource.getTableSchema(_chunkingTable); _initialized = true; }</code><technical_language>useful include DB name in metric, table name</technical_language>

Target:
public void start() throws SQLException, SchemaGenerationException { if (_initialized) { close(); } _metrics = new DatabaseChunkedReaderMetrics(String.join(".", _database , _chunkingTable), _readerId); initializeChunkingKeyInfo(); _chunkedQuery = _chunkedQueryManager.generateChunkedQuery(_sourceQuery, new ArrayList<>(_chunkingKeys.keySet()), _rowCountLimit, _maxChunkIndex, _chunkIndex); _tableSchema = _databaseSource.getTableSchema(_chunkingTable); _initialized = true; }
Source:
<code><START> public String toString() { <END> return "SearchDto{" + "searchResultDbId=" + this.searchResultDbId + '}'; }</code><technical_language>Pojomatics</technical_language>

Target:
public String toString() { return Pojomatic.toString(this); }
Source:
<code>public HoneybadgerReporter(final ConfigContext config) { this.setConfig(config); if (config.getApiKey() == null) { throw new IllegalArgumentException("API key must be set"); } if (config.getApiKey().isEmpty()) { throw new IllegalArgumentException("API key must not be empty"); } if (config.getHoneybadgerUrl() == null) { throw new IllegalArgumentException("Honeybadger URL must be set"); } if (config.getMaximumErrorReportingRetries() == null) { <START> throw new IllegalArgumentException("Honeybadger property getMaximumErrorReportingRetries must be set"); <END> } if (config.getMaximumErrorReportingRetries() < 0) { throw new IllegalArgumentException("Honeybadger property getMaximumErrorReportingRetries must be an integer greater than or equal to 0"); } }</code><technical_language>I understanding this -- is configurable property name getMaximumErrorReportingRetries, is MaximumErrorReportingRetries</technical_language>

Target:
public HoneybadgerReporter(final ConfigContext config) { this.setConfig(config); if (config.getApiKey() == null) { throw new IllegalArgumentException("API key must be set"); } if (config.getApiKey().isEmpty()) { throw new IllegalArgumentException("API key must not be empty"); } if (config.getHoneybadgerUrl() == null) { throw new IllegalArgumentException("Honeybadger URL must be set"); } if (config.getMaximumErrorReportingRetries() == null) { throw new IllegalArgumentException("Honeybadger property honeybadger.maximum_retry_attempts must be set"); } if (config.getMaximumErrorReportingRetries() < 0) { throw new IllegalArgumentException("Honeybadger property honeybadger.maximum_retry_attempts must be an " + "integer greater than or equal to 0"); } }
Source:
<code>public void setCustomParams(final Map<String, Object> customParams) { <START> this.customParams = customParams; <END> }</code><technical_language>I add a CommonHelper.assertNotNull for customParams</technical_language>

Target:
public void setCustomParams(final Map<String, Object> customParams) { CommonHelper.assertNotNull("customParams", customParams); this.customParams = customParams; }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JavaClass"); if (typeFilterRegex != null) { <START> builder.append(".inFile(" + typeFilterRegex + ")"); <END> } if (regex != null) { builder.append(".references(" + regex + ")"); } if (!locations.isEmpty()) { builder.append(".at(" + locations + ")"); } builder.append(".as(" + variable + ")"); return builder.toString(); }</code><technical_language>Output "inType"</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JavaClass"); if (typeFilterRegex != null) { builder.append(".inType(" + typeFilterRegex + ")"); } if (regex != null) { builder.append(".references(" + regex + ")"); } if (!locations.isEmpty()) { builder.append(".at(" + locations + ")"); } builder.append(".as(" + variable + ")"); return builder.toString(); }
Source:
<code>private static void checkAddress(String address, AddressFamily addrFamily) { ObjectUtil.checkNotNull(addrFamily, "addrFamily"); switch (addrFamily) { case AF_UNSPEC: if (address != null) { throw new IllegalArgumentException("unable to validate an AF_UNSPEC address: " + address); } return; case AF_UNIX: <START> if (address == null || address.getBytes(CharsetUtil.US_ASCII).length > 108) { <END> throw new IllegalArgumentException("invalid AF_UNIX address: " + address); } return; } ObjectUtil.checkNotNull(address, "address"); switch (addrFamily) { case AF_IPv4: if (!NetUtil.isValidIpV4Address(address)) { throw new IllegalArgumentException("invalid IPv4 address: " + address); } break; case AF_IPv6: if (!NetUtil.isValidIpV6Address(address)) { throw new IllegalArgumentException("invalid IPv6 address: " + address); } break; default: throw new IllegalArgumentException("unexpected addrFamily: " + addrFamily); } }</code><technical_language>address.length() > 108 good enough</technical_language>

Target:
private static void checkAddress(String address, AddressFamily addrFamily) { ObjectUtil.checkNotNull(addrFamily, "addrFamily"); switch (addrFamily) { case AF_UNSPEC: if (address != null) { throw new IllegalArgumentException("unable to validate an AF_UNSPEC address: " + address); } return; case AF_UNIX: ObjectUtil.checkNotNull(address, "address"); if (address.getBytes(CharsetUtil.US_ASCII).length > 108) { throw new IllegalArgumentException("invalid AF_UNIX address: " + address); } return; } ObjectUtil.checkNotNull(address, "address"); switch (addrFamily) { case AF_IPv4: if (!NetUtil.isValidIpV4Address(address)) { throw new IllegalArgumentException("invalid IPv4 address: " + address); } break; case AF_IPv6: if (!NetUtil.isValidIpV6Address(address)) { throw new IllegalArgumentException("invalid IPv6 address: " + address); } break; default: throw new IllegalArgumentException("unexpected addrFamily: " + addrFamily); } }
Source:
<code>@SuppressWarnings("UnusedDeclaration") @Deprecated public void setDebugging(boolean debugging) { setIndicatorsEnabled(debugging); <START> setLoggingEnabled(debugging); <END> }</code><technical_language>remove this behavior. setDebugging affect indicators</technical_language>

Target:
@SuppressWarnings("UnusedDeclaration") @Deprecated public void setDebugging(boolean debugging) { setIndicatorsEnabled(debugging); }
Source:
<code>public void testDomainSocketClosedByDN() throws Exception { BlockReaderTestUtil.enableShortCircuitShmTracing(); TemporarySocketDirectory sockDir = new TemporarySocketDirectory(); Configuration conf = createShortCircuitConf("testDomainSocketClosedByDN", sockDir); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); DistributedFileSystem fs = cluster.getFileSystem(); final ShortCircuitCache cache = fs.getClient().getClientContext().getShortCircuitCache(); DomainPeer peer = getDomainPeerToDn(conf); MutableBoolean usedPeer = new MutableBoolean(false); ExtendedBlockId blockId = new ExtendedBlockId(123, "xyz"); final DatanodeInfo datanode = new DatanodeInfo.DatanodeInfoBuilder() .setNodeID(cluster.getDataNodes().get(0).getDatanodeId()).build(); Slot slot1 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); cluster.getDataNodes().get(0).getShortCircuitRegistry() .registerSlot(blockId, slot1.getSlotId(), false); Slot slot2 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); cluster.getDataNodes().get(0).getShortCircuitRegistry() .registerSlot(blockId, slot2.getSlotId(), false); cache.scheduleSlotReleaser(slot1); Thread.sleep(5000); cache.scheduleSlotReleaser(slot2); Thread.sleep(10000); <START> Assert.assertTrue(cluster.getDataNodes().get(0).getShortCircuitRegistry() <END> .getShmNum() == 0); Assert.assertTrue(cache.getDfsClientShmManager().getShmNum() == 0); cluster.shutdown(); }</code><technical_language>suggeset assertEquals()</technical_language>

Target:
public void testDomainSocketClosedByDN() throws Exception { TemporarySocketDirectory sockDir = new TemporarySocketDirectory(); Configuration conf = createShortCircuitConf("testDomainSocketClosedByDN", sockDir); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); try { cluster.waitActive(); DistributedFileSystem fs = cluster.getFileSystem(); final ShortCircuitCache cache = fs.getClient().getClientContext().getShortCircuitCache(); DomainPeer peer = getDomainPeerToDn(conf); MutableBoolean usedPeer = new MutableBoolean(false); ExtendedBlockId blockId = new ExtendedBlockId(123, "xyz"); final DatanodeInfo datanode = new DatanodeInfo.DatanodeInfoBuilder() .setNodeID(cluster.getDataNodes().get(0).getDatanodeId()).build(); Slot slot1 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); cluster.getDataNodes().get(0).getShortCircuitRegistry() .registerSlot(blockId, slot1.getSlotId(), false); Slot slot2 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); cluster.getDataNodes().get(0).getShortCircuitRegistry() .registerSlot(blockId, slot2.getSlotId(), false); cache.scheduleSlotReleaser(slot1); Thread.sleep(2000); cache.scheduleSlotReleaser(slot2); Thread.sleep(2000); Assert.assertEquals(0, cluster.getDataNodes().get(0).getShortCircuitRegistry().getShmNum()); Assert.assertEquals(0, cache.getDfsClientShmManager().getShmNum()); } finally { cluster.shutdown(); } }
Source:
<code>public int getInt(String name, int defaultValue) { return getValue(name, new Function<String, Integer>() { @Override public Integer apply(String stringVal) { <START> return Integer.parseInt(stringVal); <END> } }, defaultValue); }</code><technical_language>This support formats JGit's Config class does. For example 2GiB, 3KiB, etc... applies for other methods perform conversion string. wrap a Config instance delegate it? supported formats for values of plugin config parameters</technical_language>

Target:
public int getInt(String name, int defaultValue) { return cfg.getInt(PLUGIN, pluginName, name, defaultValue); }
Source:
<code>public void onChunkExecStateChanged(ChunkExecStateChangedEvent event) { if (event.getDocId() != docId_ || !outputs_.containsKey(event.getChunkId())) return; <START> ChunkInlineOutput output = outputs_.get(event.getChunkId()); <END> if (event.getExecState() == NotebookDocQueue.CHUNK_EXEC_STARTED) { output.setState(ChunkInlineOutput.State.Started); } else if (event.getExecState() == NotebookDocQueue.CHUNK_EXEC_FINISHED) { output.setState(ChunkInlineOutput.State.Finished); final ScreenCoordinates pos = computePopupPosition( output.range(), output.getOffsetWidth()); output.setPopupPosition(pos.getPageX(), pos.getPageY()); output.show(); } }</code><technical_language>succeed (we bail out if hashmap chunk ID a lines above)</technical_language>

Target:
public void onChunkExecStateChanged(ChunkExecStateChangedEvent event) { if (event.getDocId() != docId_ || !outputs_.containsKey(event.getChunkId())) return; ChunkInlineOutput output = outputs_.get(event.getChunkId()); if (event.getExecState() == NotebookDocQueue.CHUNK_EXEC_STARTED) { output.setState(ChunkInlineOutput.State.Started); } else if (event.getExecState() == NotebookDocQueue.CHUNK_EXEC_FINISHED) { output.setState(ChunkInlineOutput.State.Finished); output.positionNearRange(display_, output.range()); output.show(); } }
Source:
<code>private Supplier<CharReadable> fileAsCharReadable( File file ) { return () -> { try { <START> return Readables.wrap( fs.openAsReader( file, Charset.defaultCharset() ) ); <END> } catch ( IOException e ) { throw new UncheckedIOException( e ); } }; }</code><technical_language>do want system default charset UTF-8 for example always</technical_language>

Target:
private Supplier<CharReadable> fileAsCharReadable( File file ) { return () -> { try { return Readables.wrap( fs.openAsReader( file, StandardCharsets.UTF_8 ) ); } catch ( IOException e ) { throw new UncheckedIOException( e ); } }; }
Source:
<code>public void testWriteAndReadObject() throws Exception { <START> InternalSerializationService serializationService = new DefaultSerializationServiceBuilder().build(); <END> String expected = "test input"; String actual = (String) writeAndReadObject(serializationService, expected); assertNotNull(actual); assertEquals(expected, actual); }</code><technical_language>easier serializationService a field this test? serializationServices created settings? field instead of local variable, simplify test methods</technical_language>

Target:
public void testWriteAndReadObject() throws Exception { String expected = "test input"; String actual = (String) writeAndReadObject(expected); assertNotNull(actual); assertEquals(expected, actual); }
Source:
<code><START> private static File asTemp(InputStream in, <END> String prefix, String suffix, File dir) throws IOException { File tmp = File.createTempFile(prefix, suffix, dir); boolean keep = false; try { FileOutputStream out = new FileOutputStream(tmp); try { byte[] data = new byte[8192]; int n; while ((n = in.read(data)) > 0) { out.write(data, 0, n); } keep = true; return tmp; } finally { out.close(); } } finally { if (!keep) { tmp.delete(); } } }</code><technical_language>Is this method in this class? is duplicated</technical_language>

Target:
static File asTemp(InputStream in, String prefix, String suffix, File dir) throws IOException { File tmp = File.createTempFile(prefix, suffix, dir); boolean keep = false; try (FileOutputStream out = new FileOutputStream(tmp)) { byte[] data = new byte[8192]; int n; while ((n = in.read(data)) > 0) { out.write(data, 0, n); } keep = true; return tmp; } finally { if (!keep) { tmp.delete(); } } }
Source:
<code>public void open() throws Exception { userDefinedFunctionOutputType = new RowType( outputType.getFields().subList(groupingSet.length, outputType.getFieldCount() - namedProperties.length)); <START> super.open(); <END> inputKeyAndWindow = new LinkedList<>(); windowProperty = new GenericRowData(namedProperties.length); windowAggResult = new JoinedRowData(); windowsGrouping = new HeapWindowsGrouping( maxLimitSize, windowSize, slideSize, inputTimeFieldIndex, false); }</code><technical_language>Putting super.open() end of this method? affect correctness, code more readable</technical_language>

Target:
public void open() throws Exception { userDefinedFunctionOutputType = new RowType( outputType.getFields().subList(groupingSet.length, outputType.getFieldCount() - namedProperties.length)); inputKeyAndWindow = new LinkedList<>(); windowProperty = new GenericRowData(namedProperties.length); windowAggResult = new JoinedRowData(); windowsGrouping = new HeapWindowsGrouping( maxLimitSize, windowSize, slideSize, inputTimeFieldIndex, false); super.open(); }
Source:
<code>void init(String url, String cookie, ConfigurationContext configCtxt) throws UserStoreException { try { stub = new RemoteUserRealmServiceStub(configCtxt, url + REALM_SERVICE_NAME); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, this .getSessionCookie()); } catch (AxisFault e) { if (log.isDebugEnabled()) { log.debug(CONNECTION_ERROR_MESSAGE, e); } <START> throw new UserStoreException(); <END> } userStoreMan = new WSUserStoreManager(url, cookie, configCtxt); authzMan = new WSAuthorizationManager(url, cookie, configCtxt); claimManager = new WSClaimManager(url, cookie, configCtxt); profileManager = new WSProfileConfigurationManager(url, cookie, configCtxt); }</code><technical_language>add message</technical_language>

Target:
void init(String url, String cookie, ConfigurationContext configCtxt) throws UserStoreException { try { stub = new RemoteUserRealmServiceStub(configCtxt, url + REALM_SERVICE_NAME); ServiceClient client = stub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, this .getSessionCookie()); } catch (AxisFault e) { throw new UserStoreException("Axis error occurred while creating service client stub"); } userStoreMan = new WSUserStoreManager(url, cookie, configCtxt); authzMan = new WSAuthorizationManager(url, cookie, configCtxt); claimManager = new WSClaimManager(url, cookie, configCtxt); profileManager = new WSProfileConfigurationManager(url, cookie, configCtxt); }
Source:
<code><START> public Parts split(SymbolAllocator symbolAllocator, FunctionRegistry functionRegistry) <END> { ImmutableMap.Builder<Symbol, Aggregation> intermediateAggregation = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, Aggregation> finalAggregation = ImmutableMap.builder(); for (Map.Entry<Symbol, Aggregation> entry : aggregations.entrySet()) { Aggregation originalAggregation = entry.getValue(); Signature signature = originalAggregation.getSignature(); InternalAggregationFunction function = functionRegistry.getAggregateFunctionImplementation(signature); Symbol intermediateSymbol = symbolAllocator.newSymbol(signature.getName(), function.getIntermediateType()); intermediateAggregation.put(intermediateSymbol, new Aggregation(originalAggregation.getCall(), signature, originalAggregation.getMask())); finalAggregation.put(entry.getKey(), new Aggregation( new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.of(intermediateSymbol.toSymbolReference())), signature, Optional.empty())); } return new Parts( new StatisticAggregations(intermediateAggregation.build(), groupingSymbols), new StatisticAggregations(finalAggregation.build(), groupingSymbols)); }</code><technical_language>splitAggregations? createIntermediateAggregations</technical_language>

Target:
public Parts split(SymbolAllocator symbolAllocator, FunctionRegistry functionRegistry) { ImmutableMap.Builder<Symbol, Aggregation> intermediateAggregation = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, Aggregation> finalAggregation = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, Symbol> mappings = ImmutableMap.builder(); for (Map.Entry<Symbol, Aggregation> entry : aggregations.entrySet()) { Aggregation originalAggregation = entry.getValue(); Signature signature = originalAggregation.getSignature(); InternalAggregationFunction function = functionRegistry.getAggregateFunctionImplementation(signature); Symbol intermediateSymbol = symbolAllocator.newSymbol(signature.getName(), function.getIntermediateType()); mappings.put(entry.getKey(), intermediateSymbol); intermediateAggregation.put(intermediateSymbol, new Aggregation(originalAggregation.getCall(), signature, originalAggregation.getMask())); finalAggregation.put(entry.getKey(), new Aggregation( new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.of(intermediateSymbol.toSymbolReference())), signature, Optional.empty())); } groupingSymbols.forEach(symbol -> mappings.put(symbol, symbol)); return new Parts( new StatisticAggregations(intermediateAggregation.build(), groupingSymbols), new StatisticAggregations(finalAggregation.build(), groupingSymbols), mappings.build()); }
Source:
<code>private List<Type> getImplementz(GraphqlParser.ImplementsInterfacesContext implementsInterfacesContext) { List<Type> implementz = new ArrayList<>(); while (implementsInterfacesContext != null) { <START> List<TypeName> typeNames = implementsInterfacesContext.typeName().stream().map(this::createTypeName).collect(toList()); <END> implementz.addAll(0, typeNames); implementsInterfacesContext = implementsInterfacesContext.implementsInterfaces(); } return implementz; }</code><technical_language>please map util function</technical_language>

Target:
private List<Type> getImplementz(GraphqlParser.ImplementsInterfacesContext implementsInterfacesContext) { List<Type> implementz = new ArrayList<>(); while (implementsInterfacesContext != null) { List<TypeName> typeNames = FpKit.map(implementsInterfacesContext.typeName(), this::createTypeName); implementz.addAll(0, typeNames); implementsInterfacesContext = implementsInterfacesContext.implementsInterfaces(); } return implementz; }