auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void enableVersioning(EnableVersioningArgs args) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, <START> InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { <END> Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("versioning", ""); String config = "<VersioningConfiguration xmlns=\"<LINK_0>\">" + "<Status>Enabled</Status></VersioningConfiguration>"; Response response = executePut(args.bucket(), null, null, queryParamMap, config, 0); response.body().close(); }</code><technical_language>throw IllegalArgumentException if args is null</technical_language>

Target:
public void enableVersioning(EnableVersioningArgs args) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, XmlParserException { if (args == null) { throw new IllegalArgumentException("null arguments"); } Map<String, String> queryParamMap = new HashMap<>(); queryParamMap.put("versioning", ""); String config = "<VersioningConfiguration xmlns=\"<LINK_0>\">" + "<Status>Enabled</Status></VersioningConfiguration>"; Response response = executePut(args.bucket(), null, null, queryParamMap, config, 0); response.body().close(); }
Source:
<code>private AutoIngestCaseManager() throws AutoIngestCaseManagerException { try { init(); } catch (AutoIngestCaseManager.AutoIngestCaseManagerException ex) { Logger.getLogger(AutoIngestCaseManager.class.getName()).log(Level.SEVERE, null, ex); throw ex; <START> } <END> }</code><technical_language>is call init, in another class, this service class do logging, I prefer code simpler inline code in init method here, thanks</technical_language>

Target:
private AutoIngestCaseManager() throws AutoIngestCaseManagerException { try { coordinationService = CoordinationService.getInstance(); } catch (CoordinationServiceException ex) { throw new AutoIngestCaseManager.AutoIngestCaseManagerException("Failed to get the coordination service.", ex); } }
Source:
<code>private void setPartitionResult(int partition, Object result) { <START> assert result != null : "null result"; <END> boolean success = partitionResults.compareAndSet(partition, null, result); assert success : "two results for same partition: old=" + partitionResults.get(partition) + ", new=" + result; }</code><technical_language>Is null a legitimate result InvokeOnPartitions</technical_language>

Target:
private void setPartitionResult(int partition, Object result) { if (result == null) { result = NULL_RESULT; } boolean success = partitionResults.compareAndSet(partition, null, result); assert success : "two results for same partition: old=" + partitionResults.get(partition) + ", new=" + result; }
Source:
<code>public void onEventMainThread(DiscussionThreadPostedEvent event) { <START> if (!isFollowingTopics() && !isAllTopics() && event.getDiscussionThread().getTopicId().equalsIgnoreCase(discussionTopic.getIdentifier())) { <END> int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(event.getDiscussionThread(), i); } }</code><technical_language>this equalsIgnoreCase() changed equals() well</technical_language>

Target:
public void onEventMainThread(DiscussionThreadPostedEvent event) { if (!isFollowingTopics() && !isAllTopics() && discussionTopic.containsThread(event.getDiscussionThread())) { int i = 0; for (; i < discussionPostsAdapter.getCount(); ++i) { if (!discussionPostsAdapter.getItem(i).isPinned()) { break; } } discussionPostsAdapter.insert(event.getDiscussionThread(), i); } }
Source:
<code><START> public void setCancelIdleInterval(long cancelIdleInterval) { <END> this.cancelIdleInterval = cancelIdleInterval; }</code><technical_language>a package protected? other side I reason of setCancelIdleInterval in ImapIdleChannelAdapter..</technical_language>

Target:
public void setCancelIdleInterval(long cancelIdleInterval) { this.cancelIdleInterval = cancelIdleInterval * 1000; }
Source:
<code>protected void populateColumnSchema(ArrayList<ColumnInfo> columns) { super.populateColumnSchema(columns); <START> columns.add(new VoltTable.ColumnInfo("RSS", VoltType.INTEGER)); <END> columns.add(new VoltTable.ColumnInfo("JAVAUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("JAVAUNUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("TUPLEDATA", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLEALLOCATED", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("INDEXMEMORY", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("STRINGMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLECOUNT", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("POOLEDMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("PHYSICALMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("JAVAMAXHEAP", VoltType.INTEGER)); }</code><technical_language>sense change of INTEGER columns BIGINT</technical_language>

Target:
protected void populateColumnSchema(ArrayList<ColumnInfo> columns) { super.populateColumnSchema(columns); columns.add(new VoltTable.ColumnInfo("RSS", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("JAVAUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("JAVAUNUSED", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("TUPLEDATA", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLEALLOCATED", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("INDEXMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("STRINGMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TUPLECOUNT", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("POOLEDMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("PHYSICALMEMORY", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("JAVAMAXHEAP", VoltType.INTEGER)); }
Source:
<code>public HpccRemoteFileReader(DataPartition dp, FieldDef originalRD, IRecordBuilder recBuilder, int connectTimeout, int limit) throws Exception { <START> this(dp, originalRD, recBuilder, connectTimeout, limit, true, -1); <END> }</code><technical_language>new var</technical_language>

Target:
public HpccRemoteFileReader(DataPartition dp, FieldDef originalRD, IRecordBuilder recBuilder, int connectTimeout, int limit) throws Exception { this(dp, originalRD, recBuilder, connectTimeout, limit, true, DEFAULT_READ_SIZE_OPTION); }
Source:
<code>void populate(final int row, final PluginInfo plugin) { table.setWidget(row, 1, <START> new Anchor(plugin.name(), "/plugins/" + plugin.name() + "/")); <END> table.setText(row, 2, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }</code><technical_language>gerrit installed / server. This browser jump out of gerrit some installations</technical_language>

Target:
void populate(final int row, final PluginInfo plugin) { table.setWidget( row, 1, new Anchor(plugin.name(), Gerrit.selfRedirect("/plugins/" + plugin.name() + "/"))); table.setText(row, 2, plugin.version()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }
Source:
<code>private String sanitizedCacheName() { String cacheFileName = ctx.getCache().getName().replaceAll("[^a-zA-Z0-9-_\\.]", "_"); <START> return cacheFileName; <END> }</code><technical_language>cacheFileName variable is redundant</technical_language>

Target:
private String sanitizedCacheName() { return ctx.getCache().getName().replaceAll("[^a-zA-Z0-9-_\\.]", "_"); }
Source:
<code>protected static CommandLine parseOptions(String[] args) throws ParseException { CommandLineParser parser = new DefaultParser(); CommandLine cmdLine; <START> cmdLine = parser.parse(options, args); <END> if (cmdLine.hasOption(OPTION_HELP)) { cmdLine.getArgList().add(OPTION_HELP); setQuiet(); } else if (cmdLine.getArgList().isEmpty()) { throw new ParseException("Missing command."); } if (cmdLine.hasOption(OPTION_QUIET) || cmdLine.hasOption(OPTION_XML) || cmdLine.hasOption(OPTION_JSON)) { setQuiet(); } if (cmdLine.hasOption(OPTION_DEBUG)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_DEBUG_CATEGORY)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG_CATEGORY), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_FORCE) || cmdLine.hasOption(OPTION_STRICT)) { setStrict(true); } return cmdLine; }</code><technical_language>aggregate lines: CommandLine cmdLine = parser.parse(options, args);</technical_language>

Target:
protected static CommandLine parseOptions(String[] args) throws ParseException { CommandLineParser parser = new DefaultParser(); CommandLine cmdLine = parser.parse(options, args); if (cmdLine.hasOption(OPTION_HELP)) { cmdLine.getArgList().add(OPTION_HELP); setQuiet(); } else if (cmdLine.getArgList().isEmpty()) { throw new ParseException("Missing command."); } if (cmdLine.hasOption(OPTION_QUIET) || cmdLine.hasOption(OPTION_XML) || cmdLine.hasOption(OPTION_JSON)) { setQuiet(); } if (cmdLine.hasOption(OPTION_DEBUG)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_DEBUG_CATEGORY)) { setDebug(cmdLine.getOptionValues(OPTION_DEBUG_CATEGORY), "org.nuxeo.launcher"); } if (cmdLine.hasOption(OPTION_FORCE) || cmdLine.hasOption(OPTION_STRICT)) { setStrict(true); } return cmdLine; }
Source:
<code><START> public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { <END> f.deleteOnExit(); return null; }</code><technical_language>Please revert. @Override is permitted here, -source 5. (-source 6 updated parent POM.)</technical_language>

Target:
@Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f.deleteOnExit(); return null; }
Source:
<code>public long appendObjectState(Stream<Map.Entry> entryStream) { ImmutableMap<CheckpointEntry.CheckpointDictKey, String> mdkv = ImmutableMap.copyOf(this.mdkv); final Iterable<List<Map.Entry>> partitions = Iterables.partition(entryStream::iterator, batchSize); ExecutorService executor = Executors.newFixedThreadPool(MAX_WRITER); int i = 0; <START> for (List<Map.Entry> partition : partitions) { <END> int finalI = i; executor.submit(()-> {writeCKJob(partition, finalI);}); i++; } executor.shutdown(); return entryCount.get(); }</code><technical_language>FYI, I partitions lazily evaluated, for RocksDB implementation, need create iterator writer thread iterators start positions (they partition state)</technical_language>

Target:
public long appendObjectState(Stream<Map.Entry> entryStream ) { ImmutableMap<CheckpointEntry.CheckpointDictKey, String> mdkv = ImmutableMap.copyOf(this.mdkv); List<Future<String>> taskList = new ArrayList<>(); ExecutorService executor = Executors.newFixedThreadPool(MAX_WRITER); Iterator streamIter = entryStream.iterator (); int i = 0; List<Map.Entry> partition = new ArrayList(); while (streamIter.hasNext()) { partition.add((Map.Entry)streamIter.next()); if (partition.size () == batchSize || !streamIter.hasNext()) { int finalI = i++; List<Map.Entry> current = partition; Future<String> future = executor.submit (new Callable () { public Object call() { writeCKJob (current, finalI); return "Done" + finalI; } }); taskList.add (future); partition = new ArrayList<Map.Entry> (); } } try { for (Future<String> task : taskList) { log.debug ("task done: ", task.get()); } } catch (ExecutionException | InterruptedException e) { log.error ("Checkpoint failure with exception ", e); } log.info("Checkpoint total batches entries.", i, entryCount.get()); executor.shutdown(); return entryCount.get(); }
Source:
<code>public void should_not_propagate_unchecked_exceptions() { Level previous = TestUtils.setLogLevel(HostConnectionPool.class, Level.WARN); MemoryAppender logs = new MemoryAppender().enableFor(HostConnectionPool.class); try { Session session = cluster.connect(); <START> Session.State state = session.getState(); <END> Host host1 = scassandra.host(cluster, 1, 1); Host host2 = scassandra.host(cluster, 1, 2); assertThat(state.getOpenConnections(host1)).isEqualTo(0); assertThat(state.getOpenConnections(host2)).isEqualTo(0); assertThat(logs.get()) .contains( "Unexpected error during transport initialization", "not really", NullPointerException.class.getSimpleName(), "com.datastax.driver.core.Connection$4.apply"); } finally { TestUtils.setLogLevel(HostConnectionPool.class, previous); logs.disableFor(HostConnectionPool.class); } }</code><technical_language>I this is good, alternatively good wait for host2 checking session state (TestUtils.waitForDown("2", cluster);). This ensure a side effect of exception raised is host is marked pool is ultimately closed (the assertions maintained)</technical_language>

Target:
public void should_not_propagate_unchecked_exceptions() { Level previous = TestUtils.setLogLevel(HostConnectionPool.class, Level.WARN); MemoryAppender logs = new MemoryAppender().enableFor(HostConnectionPool.class); try { Session session = cluster.connect(); Host host1 = scassandra.host(cluster, 1, 1); Host host2 = scassandra.host(cluster, 1, 2); TestUtils.waitForDown(TestUtils.ipOfNode(2), cluster); Session.State state = session.getState(); assertThat(state.getOpenConnections(host1)).isEqualTo(0); assertThat(state.getOpenConnections(host2)).isEqualTo(0); assertThat(logs.get()) .contains( "Unexpected error during transport initialization", "not really", NullPointerException.class.getSimpleName(), "com.datastax.driver.core.Connection$4.apply"); HostConnectionPool pool1 = ((SessionManager)session).pools.get(host1); HostConnectionPool pool2 = ((SessionManager)session).pools.get(host2); assertThat(pool1).isNotNull(); assertThat(pool1.isClosed()).isFalse(); assertThat(pool2).isNull(); } finally { TestUtils.setLogLevel(HostConnectionPool.class, previous); logs.disableFor(HostConnectionPool.class); } }
Source:
<code>private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) { <START> JSONObject json; <END> final String name = cursor.getString(cursor.getColumnIndex("name")); final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type"))); final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0; final Waypoint waypoint = new Waypoint(name, type, own); waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0); waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude"))); waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); waypoint.setUserNote(cursor.getString(cursor.getColumnIndex("user_note"))); waypoint.setOriginalCoordsEmpty(cursor.getInt(cursor.getColumnIndex("org_coords_empty")) != 0); try { waypoint.setCalculatorStoredState(CalcState.fromJSON(cursor.getString(cursor.getColumnIndex("calc_state")))); } catch (JSONException e) { waypoint.setCalculatorStoredState(null); } return waypoint; }</code><technical_language>is used</technical_language>

Target:
private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) { final String name = cursor.getString(cursor.getColumnIndex("name")); final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type"))); final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0; final Waypoint waypoint = new Waypoint(name, type, own); waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0); waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude"))); waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); waypoint.setUserNote(cursor.getString(cursor.getColumnIndex("user_note"))); waypoint.setOriginalCoordsEmpty(cursor.getInt(cursor.getColumnIndex("org_coords_empty")) != 0); try { waypoint.setCalculatorStoredState(CalcState.fromJSON(cursor.getString(cursor.getColumnIndex("calc_state")))); } catch (final JSONException e) { Log.e("Unable to read calculator state information", e); } return waypoint; }
Source:
<code>private static <T extends Metric> void saveMetricTaskIdMapping(Integer taskId, MetricNames names, T metric, Map<Integer, Map<String, T>> taskIdMetrics) { Map<String, T> metrics = taskIdMetrics.computeIfAbsent(taskId, (tid) -> new HashMap<>()); <START> if (metrics.get(names.getShortName()) != null) { <END> LOG.warn("Adding duplicate short metric for with long name {}, only the last metric " + "will be reported during the V2 metrics tick.", names.getShortName(), names.longName); } metrics.put(names.getShortName(), metric); }</code><technical_language>this removed if is name collision, code in registry.register throw IllegalArgumentException</technical_language>

Target:
private static <T extends Metric> void saveMetricTaskIdMapping(Integer taskId, MetricNames names, T metric, Map<Integer, Map<String, T>> taskIdMetrics) { Map<String, T> metrics = taskIdMetrics.computeIfAbsent(taskId, (tid) -> new HashMap<>()); metrics.put(names.getShortName(), metric); }
Source:
<code>private int executeTool(Connection conn, ConnectionQueryServices queryServices, Configuration conf) { ArrayList<String> immutableList = new ArrayList<>(); LOGGER.info("Executing " + operation); for (Map.Entry<String, HashSet<String>> entry :tablesAndIndexes.entrySet()) { String dataTableFullName = entry.getKey(); HashSet<String> indexes = entry.getValue(); try (Admin admin = queryServices.getAdmin()) { PTable dataTable = PhoenixRuntime.getTableNoCache(conn, dataTableFullName); if (dataTable.isImmutableRows()) { immutableList.add(dataTableFullName); continue; } LOGGER.info("Executing " + operation + " of " + dataTableFullName); disableTable(admin, dataTableFullName, indexes); modifyTable(admin, dataTableFullName, indexes); enableTable(admin, dataTableFullName, indexes); LOGGER.info("Completed " + operation + " of " + dataTableFullName); } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while executing " + operation + " steps " + e); return -1; } } executeToolForImmutableTables(queryServices, immutableList); if (upgrade) { for (String dataTableFullName : tablesAndIndexes.keySet()) { rebuildIndexes(conn, conf, dataTableFullName); LOGGER.info("Started index rebuild post " + operation + " of " + dataTableFullName); } } <START> return 0; <END> }</code><technical_language>need create Admin for this method, data table. Docs lightweight, need churn</technical_language>

Target:
private int executeTool(Connection conn, ConnectionQueryServices queryServices, Configuration conf) { ArrayList<String> immutableList = new ArrayList<>(); ArrayList<String> mutableList = new ArrayList<>(); for (Map.Entry<String, HashSet<String>> entry :tablesAndIndexes.entrySet()) { String dataTableFullName = entry.getKey(); try { PTable dataTable = PhoenixRuntime.getTableNoCache(conn, dataTableFullName); if (dataTable.isImmutableRows()) { immutableList.add(dataTableFullName); } else { mutableList.add(dataTableFullName); } } catch (SQLException e) { LOGGER.severe("Something went wrong while getting the PTable " + dataTableFullName + " "+e); return -1; } } long startWaitTime = executeToolForImmutableTables(queryServices, immutableList); executeToolForMutableTables(conn, queryServices, conf, mutableList); enableImmutableTables(queryServices, immutableList, startWaitTime); rebuildIndexes(conn, conf, immutableList); return 0; }
Source:
<code>public void renderPath(Map<String, String> _params, UrlBuilder url) { String target = request.url(); Preconditions.checkState( target.startsWith(baseUrl), "Request URL must start with base url", <START> UnsafeArg.of("baseUrl", baseUrl)); <END> String trailing = target.substring(baseUrl.length()); int queryParamsStart = trailing.indexOf('?'); String queryPortion = queryParamsStart == -1 ? trailing : trailing.substring(0, queryParamsStart); for (String pathSegment : pathSplitter.split(queryPortion)) { url.pathSegment(urlDecode(pathSegment)); } if (queryParamsStart != -1) { String querySegments = trailing.substring(queryParamsStart + 1); querySplitter .split(querySegments) .forEach((name, value) -> url.queryParam(urlDecode(name), urlDecode(value))); } }</code><technical_language>need include target desired baseUrl is</technical_language>

Target:
public void renderPath(Map<String, String> _params, UrlBuilder url) { String target = request.url(); Preconditions.checkState( target.startsWith(baseUrl), "Request URL must start with base url", UnsafeArg.of("requestUrl", target), UnsafeArg.of("baseUrl", baseUrl)); String trailing = target.substring(baseUrl.length()); int queryParamsStart = trailing.indexOf('?'); String queryPortion = queryParamsStart == -1 ? trailing : trailing.substring(0, queryParamsStart); for (String pathSegment : pathSplitter.split(queryPortion)) { url.pathSegment(urlDecode(pathSegment)); } if (queryParamsStart != -1) { String querySegments = trailing.substring(queryParamsStart + 1); querySplitter .split(querySegments) .forEach((name, value) -> url.queryParam(urlDecode(name), urlDecode(value))); } }
Source:
<code>private void sendDeliveryComplete(IMqttDeliveryToken token) { if (this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent( <START> new MqttMessageDeliveredEvent(MqttPahoMessageHandler.this, token.getMessageId())); <END> } }</code><technical_language>need topic for correlation? I IMqttToken getTopics(). is messageId unique, is reason get deal delivered topic</technical_language>

Target:
private void sendDeliveryComplete(IMqttDeliveryToken token) { if (this.async && this.asyncEvents && this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent( new MqttMessageDeliveredEvent(this, token.getMessageId(), getClientId(), getClientInstance())); } }
Source:
<code>public String print(Node node) { <START> final PrettyPrintVisitor visitor = new PrettyPrintVisitor(configuration); <END> node.accept(visitor, null); return visitor.getSource(); }</code><technical_language>move this initialization of visitor field in PPConfiguration. call get configuration here</technical_language>

Target:
public String print(Node node) { final PrettyPrintVisitor visitor = configuration.getVisitorFactory().apply(configuration); node.accept(visitor, null); return visitor.getSource(); }
Source:
<code>public void testHealth() { EtcdHealthResponse health = etcd.getHealth(); <START> assertNotNull(health); <END> }</code><technical_language>If possible, nice test expected result of a call instead of response is null</technical_language>

Target:
public void testHealth() { EtcdHealthResponse health = etcd.getHealth(); assertNotNull(health); assertTrue(health.getHealth().equals("true")); }
Source:
<code>public PropertiesConfig(final String configTemplate, final Path localConfig, <START> final String delimiterRegex) throws IOException { <END> checkNotNull(configTemplate); checkNotNull(delimiterRegex); Resource resource = new ClassPathResource(configTemplate); Properties properties = PropertiesLoaderUtils.loadProperties(resource); if (Files.exists(localConfig)) { properties.load(Files.newBufferedReader(localConfig, StandardCharsets.UTF_8)); } user = readUser(properties); environment = readEnvironment(properties); this.properties = new Properties(collapse(properties, environment.name().toLowerCase())); delimiter = Pattern.compile(delimiterRegex); }</code><technical_language>combine this constructor other duplicate code</technical_language>

Target:
public PropertiesConfig(final String configTemplate, final Path localConfig, final String delimiterRegex) throws IOException { this(setupPropertiesFromString(configTemplate), localConfig, delimiterRegex); }
Source:
<code>public void shouldPurgeAnAutoGenerationOption() throws Exception { <START> MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); <END> req.addParameter("purge", ""); handle(req); assertNull(service.getAutoGenerationOption(Integer.parseInt(getUuid()))); }</code><technical_language>create a test dataset file edit existing one</technical_language>

Target:
public void shouldPurgeAnAutoGenerationOption() throws Exception { assertNotNull(service.getAutoGenerationOption(Integer.parseInt(getUuid()))); MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(service.getAutoGenerationOption(Integer.parseInt(getUuid()))); }
Source:
<code>public String getUsername() { <START> return "dleed"; <END> }</code><technical_language>prob want default generic</technical_language>

Target:
public String getUsername() { return ""; }
Source:
<code>public void testXYFactory() { ITmfTrace trace = getTrace(); assertNotNull(trace); try { runModule(trace); Element viewElement = TmfXmlUtils.getElementInFile(TmfXmlTestFiles.DATA_PROVIDER_SIMPLE_FILE.getPath().toOSString(), TmfXmlStrings.XY_VIEW, <START> XY_VIEW_ID_FACTORY); <END> assertNotNull(viewElement); TmfXmlXYViewCu tgViewCu = TmfXmlXYViewCu.compile(new AnalysisCompilationData(), viewElement); assertNotNull(tgViewCu); DataDrivenXYProviderFactory XYFactory = tgViewCu.generate(); ITmfTreeXYDataProvider<@NonNull ITmfTreeDataModel> provider = XYFactory.create(trace); assertNotNull(provider); assertEquals(DataDrivenXYDataProvider.ID, provider.getId()); ITmfAnalysisModuleWithStateSystems module = TmfTraceUtils.getAnalysisModuleOfClass(trace, ITmfAnalysisModuleWithStateSystems.class, ANALYSIS_ID); assertNotNull(module); Iterable<@NonNull ITmfStateSystem> stateSystems = module.getStateSystems(); assertNotNull(stateSystems); provider = XYFactory.create(trace, Objects.requireNonNull(Lists.newArrayList(stateSystems)), ANALYSIS_ID); assertNotNull(provider); assertEquals(ANALYSIS_ID, provider.getId()); } finally { trace.dispose(); TmfTraceManager.getInstance().traceClosed(new TmfTraceClosedSignal(this, trace)); } }</code><technical_language>This view ID exist in XML file, of 2</technical_language>

Target:
public void testXYFactory() { ITmfTrace trace = getTrace(); assertNotNull(trace); try { runModule(trace); Element viewElement = TmfXmlUtils.getElementInFile(TmfXmlTestFiles.DATA_PROVIDER_SIMPLE_FILE.getPath().toOSString(), TmfXmlStrings.XY_VIEW, XY_VIEW_ID_DELTA); assertNotNull(viewElement); TmfXmlXYViewCu tgViewCu = TmfXmlXYViewCu.compile(new AnalysisCompilationData(), viewElement); assertNotNull(tgViewCu); DataDrivenXYProviderFactory XYFactory = tgViewCu.generate(); ITmfTreeXYDataProvider<@NonNull ITmfTreeDataModel> provider = XYFactory.create(trace); assertNotNull(provider); assertEquals(DataDrivenXYDataProvider.ID, provider.getId()); ITmfAnalysisModuleWithStateSystems module = TmfTraceUtils.getAnalysisModuleOfClass(trace, ITmfAnalysisModuleWithStateSystems.class, ANALYSIS_ID); assertNotNull(module); Iterable<@NonNull ITmfStateSystem> stateSystems = module.getStateSystems(); assertNotNull(stateSystems); provider = XYFactory.create(trace, Objects.requireNonNull(Lists.newArrayList(stateSystems)), ANALYSIS_ID); assertNotNull(provider); assertEquals(ANALYSIS_ID, provider.getId()); } finally { trace.dispose(); TmfTraceManager.getInstance().traceClosed(new TmfTraceClosedSignal(this, trace)); } }
Source:
<code><START> private List<LoadHolder> findBestServers( <END> Map<?, LoadHolder> groupServers, Set<ServerLocation> excludedServers, int count) { TreeSet<LoadHolder> bestEntries = new TreeSet<>((l1, l2) -> { int difference = Float.compare(l1.getLoad(), l2.getLoad()); if (difference != 0) { return difference; } ServerLocation sl1 = l1.getLocation(); ServerLocation sl2 = l2.getLocation(); return sl1.compareTo(sl2); }); boolean retainAll = (count < 0); float lastBestLoad = Float.MAX_VALUE; for (Map.Entry<?, LoadHolder> loadEntry : groupServers.entrySet()) { ServerLocation location; Object key = loadEntry.getKey(); if (key instanceof ServerLocationAndMemberId) { location = ((ServerLocationAndMemberId) key).getServerLocation(); } else if (key instanceof ServerLocation) { location = ((ServerLocation) key); } else { throw new InternalGemFireException( "findBestServers method was called with incorrect type parameters."); } if (excludedServers.contains(location)) { continue; } LoadHolder nextLoadReference = loadEntry.getValue(); float nextLoad = nextLoadReference.getLoad(); if ((bestEntries.size() < count) || retainAll || (nextLoad < lastBestLoad)) { bestEntries.add(nextLoadReference); if (!retainAll && (bestEntries.size() > count)) { bestEntries.remove(bestEntries.last()); } LoadHolder lastBestHolder = bestEntries.last(); lastBestLoad = lastBestHolder.getLoad(); } } return new ArrayList<>(bestEntries); }</code><technical_language>a new method significantly changed, be, leat, unit tested. package private, annotate @VisibleForTesting access LocatorLoadSnapshotJUnitTest and/or LocatorLoadSnapshotIntegrationTest</technical_language>

Target:
List<LoadHolder> findBestServers( Map<?, LoadHolder> groupServers, Set<ServerLocation> excludedServers, int count) { if (count == 0) { return new ArrayList<>(); } TreeSet<LoadHolder> bestEntries = new TreeSet<>((l1, l2) -> { int difference = Float.compare(l1.getLoad(), l2.getLoad()); if (difference != 0) { return difference; } ServerLocation sl1 = l1.getLocation(); ServerLocation sl2 = l2.getLocation(); return sl1.compareTo(sl2); }); boolean retainAll = (count < 0); float lastBestLoad = Float.MAX_VALUE; for (Map.Entry<?, LoadHolder> loadEntry : groupServers.entrySet()) { ServerLocation location; Object key = loadEntry.getKey(); if (key instanceof ServerLocationAndMemberId) { location = ((ServerLocationAndMemberId) key).getServerLocation(); } else if (key instanceof ServerLocation) { location = ((ServerLocation) key); } else { throw new InternalGemFireException( "findBestServers method was called with incorrect type parameters."); } if (excludedServers.contains(location)) { continue; } LoadHolder nextLoadReference = loadEntry.getValue(); float nextLoad = nextLoadReference.getLoad(); if ((bestEntries.size() < count) || retainAll || (nextLoad < lastBestLoad)) { bestEntries.add(nextLoadReference); if (!retainAll && (bestEntries.size() > count)) { bestEntries.remove(bestEntries.last()); } LoadHolder lastBestHolder = bestEntries.last(); lastBestLoad = lastBestHolder.getLoad(); } } return new ArrayList<>(bestEntries); }
Source:
<code>public void logSystemInformation() { if ( getLogger().isInfoEnabled() ) { <START> getLogger().info( getOtherProperties() ); <END> } else { getOtherProperties(); } }</code><technical_language>this call getSystemInformation before</technical_language>

Target:
public void logSystemInformation() { if ( logger.isInfoEnabled() ) { logger.info( getSystemInformation() ); } else { getOtherProperties(); } }
Source:
<code>public static void copyResourcesTo(String targetDirectory) throws IOException { Class<ResourceHandler> c = ResourceHandler.class; for (String file : FILES) { <START> InputStream istream = c.getResourceAsStream("res/" + file); <END> Path target = Paths.get(targetDirectory, file); if (!Files.exists(target)) { Files.createDirectories(target); } Files.copy(istream, Paths.get(targetDirectory, file), StandardCopyOption.REPLACE_EXISTING); } }</code><technical_language>Magic constant "res/" a static final string member of class</technical_language>

Target:
public static void copyResourcesTo(String targetDirectory) throws IOException { Class<ResourceHandler> c = ResourceHandler.class; for (String file : FILES) { InputStream istream = c.getResourceAsStream(Paths.get(RESOURCE_FOLDER, file).toString()); Path target = Paths.get(targetDirectory, file); if (!Files.exists(target)) { Files.createDirectories(target); } Files.copy(istream, Paths.get(targetDirectory, file), StandardCopyOption.REPLACE_EXISTING); } }
Source:
<code>public ValidationResult checkRequiredAccountInfo(String chartOfAccountsCode, String accountNumber, String objectCode) { ValidationResult validationResult = new ValidationResult(true, new ArrayList<String>()); if (chartOfAccountsCode == null || chartOfAccountsCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_CHART_OF_ACCTS_REQUIRED); return validationResult; <START> } else if (accountNumber == null || accountNumber.isEmpty()) { <END> validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_ACCT_NBR_REQUIRED); return validationResult; } else if (objectCode == null || objectCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_OBJ_CD_REQUIRED); return validationResult; } return validationResult; }</code><technical_language>wondering if else if's needed if separate if blocks. is, if accountNumber is missing, message returned if chart is missing too. helpful messages? limited message return</technical_language>

Target:
public ValidationResult checkRequiredAccountInfo(String chartOfAccountsCode, String accountNumber, String objectCode) { ValidationResult validationResult = new ValidationResult(true, new ArrayList<String>()); if (chartOfAccountsCode == null || chartOfAccountsCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_REQUIRED), ConcurConstants.AccountingStringFieldNames.CHART)); } if (accountNumber == null || accountNumber.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_REQUIRED), ConcurConstants.AccountingStringFieldNames.ACCOUNT_NUMBER)); } if (objectCode == null || objectCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_REQUIRED), ConcurConstants.AccountingStringFieldNames.OBJECT_CODE)); } return validationResult; }
Source:
<code><START> public SenseUploadConfiguration getSenseUploadConfiguration() { return new SenseUploadConfiguration(); } <END></code><technical_language>I missing something, right understanding is values hardcoded? defeats purpose of in configuration</technical_language>

Target:
public SenseUploadConfiguration getSenseUploadConfiguration() { return this.senseUploadConfiguration; }
Source:
<code>public void onPartitionBecomeStandbyFromBootstrap(String partitionName) { PartitionStateChangeListener replicationManagerListener = partitionStateChangeListeners.get(StateModelListenerType.ReplicationManagerListener); if (replicationManagerListener != null) { try { replicationManagerListener.onPartitionBecomeStandbyFromBootstrap(partitionName); replicaSyncUpManager.waitBootstrapCompleted(partitionName); } catch (InterruptedException e) { logger.error("Bootstrap was interrupted on partition {}", partitionName); participantMetrics.bootstrapCount.addAndGet(-1); participantMetrics.errorStateCount.addAndGet(1); throw new StateTransitionException("Bootstrap failed or was interrupted", BootstrapFailure); } catch (StateTransitionException e) { logger.error("Bootstrap didn't complete on partition {}", partitionName, e); <START> participantMetrics.bootstrapCount.addAndGet(-1); <END> participantMetrics.errorStateCount.addAndGet(1); throw e; } } participantMetrics.bootstrapCount.addAndGet(-1); participantMetrics.standbyCount.addAndGet(1); }</code><technical_language>For metrics related changes in this file, cleaner update participantMetrics in finally block</technical_language>

Target:
public void onPartitionBecomeStandbyFromBootstrap(String partitionName) { PartitionStateChangeListener replicationManagerListener = partitionStateChangeListeners.get(StateModelListenerType.ReplicationManagerListener); try { if (replicationManagerListener != null) { replicationManagerListener.onPartitionBecomeStandbyFromBootstrap(partitionName); replicaSyncUpManager.waitBootstrapCompleted(partitionName); } } catch (InterruptedException e) { logger.error("Bootstrap was interrupted on partition {}", partitionName); participantMetrics.errorStateCount.addAndGet(1); throw new StateTransitionException("Bootstrap failed or was interrupted", BootstrapFailure); } catch (StateTransitionException e) { logger.error("Bootstrap didn't complete on partition {}", partitionName, e); participantMetrics.errorStateCount.addAndGet(1); throw e; } finally { participantMetrics.bootstrapCount.addAndGet(-1); } participantMetrics.standbyCount.addAndGet(1); }
Source:
<code>public void addTransformation(TransformationDescription description) { checkTransformationDescriptionId(description); ODocument source = getOrCreateModel(description.getSourceModel().toString()); ODocument target = getOrCreateModel(description.getTargetModel().toString()); ODocument edge = graph.createEdge(source, target); setIdFieldValue(edge, description.getId()); if (description.getFileName() != null) { setFilenameFieldValue(edge, description.getFileName()); } <START> Map<String, Set<String>> connections = description.getPropertyConnections(); <END> if (connections != null) { for (Map.Entry<String, Set<String>> entry : connections.entrySet()) { StringBuilder builder = new StringBuilder(); for (String property : entry.getValue()) { if (builder.length() != 0) { builder.append(","); } builder.append(property); } edge.field(entry.getKey(), builder.toString()); } } edge.save(); descriptions.put(description.getId(), description); LOGGER.debug("Added transformation description to the graph database", description); }</code><technical_language>arrow anti pattern ;-) Pls try flatten this out if possible</technical_language>

Target:
public void addTransformation(TransformationDescription description) { checkTransformationDescriptionId(description); ODocument source = getOrCreateModel(description.getSourceModel().toString()); ODocument target = getOrCreateModel(description.getTargetModel().toString()); ODocument edge = graph.createEdge(source, target); OrientModelGraphUtils.setIdFieldValue(edge, description.getId()); if (description.getFileName() != null) { OrientModelGraphUtils.setFilenameFieldValue(edge, description.getFileName()); } OrientModelGraphUtils.fillEdgeWithPropertyConnections(edge, description); edge.save(); descriptions.put(description.getId(), description); LOGGER.debug("Added transformation description to the graph database", description); }
Source:
<code>protected void handleComparePair(S3GuardFsck.ComparePair comparePair, StringBuilder sB, HandleMode handleMode) throws IOException { for (S3GuardFsck.Violation violation : comparePair.getViolations()) { try { ViolationHandler handler = violation.getHandler() .getDeclaredConstructor(S3GuardFsck.ComparePair.class) .newInstance(comparePair); <START> if (handleMode == HandleMode.LOG) { <END> final String errorStr = handler.getError(); sB.append(errorStr); } if (handleMode == HandleMode.FIX) { final String fixStr = handler.fixViolation(rawFs, metadataStore); sB.append(fixStr); } } catch (NoSuchMethodException e) { LOG.error("Can not find declared constructor for handler: {}", violation.getHandler()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { LOG.error("Can not instantiate handler: {}", violation.getHandler()); } sB.append(newLine); } }</code><technical_language>CASE statements option here</technical_language>

Target:
protected void handleComparePair(S3GuardFsck.ComparePair comparePair, StringBuilder sB, HandleMode handleMode) throws IOException { for (S3GuardFsck.Violation violation : comparePair.getViolations()) { try { ViolationHandler handler = violation.getHandler() .getDeclaredConstructor(S3GuardFsck.ComparePair.class) .newInstance(comparePair); switch (handleMode) { case FIX: final String errorStr = handler.getError(); sB.append(errorStr); break; case LOG: final String fixStr = handler.fixViolation(rawFs, metadataStore); sB.append(fixStr); break; default: throw new UnsupportedOperationException("Unknown handleMode: " + handleMode); } } catch (NoSuchMethodException e) { LOG.error("Can not find declared constructor for handler: {}", violation.getHandler()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { LOG.error("Can not instantiate handler: {}", violation.getHandler()); } sB.append(newLine); } }
Source:
<code>public static BuildData calculateBuildData( <START> String parentName, String parentFullName, List<BuildData> buildDataList) { <END> if (buildDataList != null && buildDataList.size() == 1) { return buildDataList.get(0); } String projectName = parentFullName.replace(parentName, ""); if (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.lastIndexOf('/')); } if (buildDataList == null) { return null; } for (BuildData buildData : buildDataList) { Set<String> remoteUrls = buildData.getRemoteUrls(); for (String remoteUrl : remoteUrls) { if (remoteUrl.contains(projectName)) { return buildData; } } } return null; }</code><technical_language>codestyle - move ); next line plz</technical_language>

Target:
public static BuildData calculateBuildData( String parentName, String parentFullName, List<BuildData> buildDataList ) { if (buildDataList == null) { return null; } if (buildDataList.size() == 1) { return buildDataList.get(0); } String projectName = parentFullName.replace(parentName, ""); if (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.lastIndexOf('/')); } for (BuildData buildData : buildDataList) { Set<String> remoteUrls = buildData.getRemoteUrls(); for (String remoteUrl : remoteUrls) { if (remoteUrl.contains(projectName)) { return buildData; } } } return null; }
Source:
<code>public boolean canMorph(final QualifiedName elementName) { if (readOnly) { return false; } final IValidator validator = document.getValidator(); if (validator == null) { return true; } final IElement currentElement = document.getElementForInsertionAt(getCaretOffset()); if (currentElement == document.getRootElement()) { return false; } if (!validator.isValidSequence(elementName, Node.getNodeNames(currentElement.children()), true)) { return false; } <START> <END> final IElement parent = currentElement.getParentElement(); final int startOffset = currentElement.getStartOffset(); final int endOffset = currentElement.getEndOffset(); final List<QualifiedName> seq1 = Node.getNodeNames(parent.children().before(startOffset)); final List<QualifiedName> seq2 = Arrays.asList(elementName); final List<QualifiedName> seq3 = Node.getNodeNames(parent.children().after(endOffset)); return validator.isValidSequence(parent.getQualifiedName(), seq1, seq2, seq3, true); }</code><technical_language>do #getValidMorphElements did. I more straight check everyting there</technical_language>

Target:
public boolean canMorph(final QualifiedName elementName) { final IElement currentElement = document.getElementForInsertionAt(getCaretOffset()); if (!canMorphElement(currentElement)) { return false; } final IValidator validator = document.getValidator(); if (!canContainContent(validator, elementName, Node.getNodeNames(currentElement.children()))) { return false; } final IElement parent = currentElement.getParentElement(); final List<QualifiedName> nodesBefore = Node.getNodeNames(parent.children().before(currentElement.getStartOffset())); final List<QualifiedName> nodesAfter = Node.getNodeNames(parent.children().after(currentElement.getEndOffset())); return isValidChild(validator, parent.getQualifiedName(), elementName, nodesBefore, nodesAfter); }
Source:
<code>protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException { final Response response = request.send(); final TokenExtractor<OAuth2AccessToken> extractor = api.getAccessTokenExtractor(); if (response.getCode() != 200) { if (extractor instanceof OAuth2AccessTokenJsonExtractor) { final OAuth2AccessTokenJsonExtractor jsonExtractor = (OAuth2AccessTokenJsonExtractor) extractor; throw new OAuthRequestException("Get Access token error", jsonExtractor.extractError(response.getBody())); } else { <START> throw new OAuthException("Get Access token error: " + response.getBody()); <END> } } return extractor.extract(response.getBody()); }</code><technical_language>usages of this method (except tests) extract(response.getBody()) 1.extract(response) 2.extract(response.getCode(), response.getBody()) extractor decide interpret response code</technical_language>

Target:
protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException { return api.getAccessTokenExtractor().extract(request.send()); }
Source:
<code>public void show() { <START> getElement().getClassList().add("open"); <END> }</code><technical_language>worth extract constant with: java private static final String TEXT_MUTED = "text-muted";</technical_language>

Target:
public void show() { getElement().getClassList().add(OPEN); }
Source:
<code>protected IntersectingLatencyTableViewer createTableViewer(@Nullable Composite parent) { <START> SashForm sf = new SashForm(parent, SWT.NONE); <END> TableViewer innerViewer = new TableViewer(sf, SWT.FULL_SELECTION | SWT.VIRTUAL); return new IntersectingLatencyTableViewer(innerViewer); }</code><technical_language>need for sash form here</technical_language>

Target:
protected LatencyTableViewer createTableViewer(@Nullable Composite parent) { TableViewer innerViewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.VIRTUAL); return new LatencyTableViewer(innerViewer, true); }
Source:
<code><START> private void alterMssqlTextColumns() { <END> executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN state VARCHAR(MAX)"); executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN changed_properties VARCHAR(MAX)"); }</code><technical_language>this method called once, if col type altered yet, alterCommitIdColumnIfNeeded()</technical_language>

Target:
private void alterMssqlTextColumns() { ColumnType stateColType = getTypeOf(getSnapshotTableNameWithSchema(), "state"); ColumnType changedPropertiesColType = getTypeOf(getSnapshotTableNameWithSchema(), "state"); if(stateColType.typeName.equals("text")) { executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN state VARCHAR(MAX)"); } if(changedPropertiesColType.typeName.equals("text")) { executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN changed_properties VARCHAR(MAX)"); } }