auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void typedRealmAndDynamicRealmShareTheSameCache() { RealmConfiguration config1 = configFactory.createConfigurationBuilder() <START> .name("same_name") <END> .build(); RealmConfiguration config2 = configFactory.createConfigurationBuilder() .name("same_name") .initialData(new Realm.Transaction() { @Override public void execute(Realm realm) { fail(); } }) .build(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config1); Realm realm = null; try { realm = Realm.getInstance(config2); fail(); } catch (IllegalArgumentException ignored) { } finally { dynamicRealm.close(); if (realm != null) { realm.close(); } } }</code><technical_language>database filename ends .realm</technical_language>

Target:
public void typedRealmAndDynamicRealmShareTheSameCache() { final String DB_NAME = "same_name.realm"; RealmConfiguration config1 = configFactory.createConfigurationBuilder() .name(DB_NAME) .build(); RealmConfiguration config2 = configFactory.createConfigurationBuilder() .name(DB_NAME) .initialData(new Realm.Transaction() { @Override public void execute(Realm realm) { fail(); } }) .build(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config1); Realm realm = null; try { realm = Realm.getInstance(config2); fail(); } catch (IllegalArgumentException ignored) { } finally { dynamicRealm.close(); if (realm != null) { realm.close(); } } }
Source:
<code>public void testCompoundJoin() { final Schema schema = getExampleSchema(); final QueryPostprocessDataContext dc = new QueryPostprocessDataContext() { @Override protected DataSet materializeMainSchemaTable(Table table, Column[] columns, int maxRows) { <START> Object[] values = new Object[columns.length]; <END> for (int i = 0; i < columns.length; i++) { values[i] = columns[i].getColumnNumber(); } DataSetHeader header = new SimpleDataSetHeader(columns); DefaultRow row = new DefaultRow(header, values); return new InMemoryDataSet(row); } @Override protected String getMainSchemaName() throws MetaModelException { return "MetaModelSchema"; } @Override protected Schema getMainSchema() throws MetaModelException { return schema; } }; Query query = dc.parseQuery("SELECT c.contributor_id,p.project_id from contributor c INNER JOIN role r ON c.contributor_id=r.contributor_id INNER JOIN project p ON p.project_id=r.project_id"); System.out.println(query); assertEquals("SELECT c.contributor_id, p.project_id FROM MetaModelSchema.contributor c INNER JOIN MetaModelSchema.role r ON c.contributor_id = r.contributor_id INNER JOIN MetaModelSchema.project p ON p.project_id = r.project_id", query.toSql()); }</code><technical_language>Implementing this method needless query is executed. throw UnsupportedOperationException here</technical_language>

Target:
public void testCompoundJoin() { final Schema schema = getExampleSchema(); final QueryPostprocessDataContext dc = new QueryPostprocessDataContext() { @Override protected DataSet materializeMainSchemaTable(Table table, Column[] columns, int maxRows) { throw new UnsupportedOperationException("This method is not used"); } @Override protected String getMainSchemaName() throws MetaModelException { return "MetaModelSchema"; } @Override protected Schema getMainSchema() throws MetaModelException { return schema; } }; Query query = dc.parseQuery("SELECT c.contributor_id,p.project_id from contributor c INNER JOIN role r ON c.contributor_id=r.contributor_id INNER JOIN project p ON p.project_id=r.project_id"); assertEquals("SELECT c.contributor_id, p.project_id FROM MetaModelSchema.contributor c INNER JOIN MetaModelSchema.role r ON c.contributor_id = r.contributor_id INNER JOIN MetaModelSchema.project p ON p.project_id = r.project_id", query.toSql()); }
Source:
<code>private boolean isTokenValid(UserResetTokenDTO userResetToken) { Date checkDate = userResetToken.getCreationDate(); Instant now = Instant.now(); <START> return (!checkDate.toInstant().isBefore(now.minus(24 , ChronoUnit.HOURS))) <END> && (checkDate.toInstant().isBefore(now)); }</code><technical_language>24 hours a in properties file</technical_language>

Target:
private boolean isTokenValid(UserResetTokenDTO userResetToken) { Date checkDate = userResetToken.getCreationDate(); Instant now = Instant.now(); return (!checkDate.toInstant().isBefore(now.minus(Integer.parseInt(env.getProperty("resetLinkExpirationTimeInHours")), ChronoUnit.HOURS))) && (checkDate.toInstant().isBefore(now)); }
Source:
<code>public void evaluate_shouldReturnAllPatientsThatHaveTakenAnyofListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); drugSetList.add(new Concept(20)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("ANY"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); <START> System.out.println("Taking Drugs Any" + cohort.getMemberIds() + " " + cohortDefinition+ "==="); <END> Assert.assertTrue(cohort.contains(2)); Assert.assertTrue(cohort.contains(21)); Assert.assertTrue(cohort.contains(22)); Assert.assertEquals(3, cohort.size()); }</code><technical_language>a this? <LINK_0></technical_language>

Target:
public void evaluate_shouldReturnAllPatientsThatHaveTakenAnyofListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("ANY"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); Assert.assertTrue(cohort.contains(2)); Assert.assertTrue(cohort.contains(7)); Assert.assertEquals(2, cohort.size()); }
Source:
<code>public void validPropertiesUnsupportedVersion() { DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateProperties(Version.v3_2, VmDeviceGeneralType.DISK, "bootable=true"); <START> assertFalse(errors.isEmpty()); <END> assertEquals(ValidationFailureReason.UNSUPPORTED_VERSION, errors.get(0).getReason()); }</code><technical_language>this lines repeated for failed test, please extract a method receives failure reason errors list, in negative tests i.e. : private void validateFailure(List<ValidationError> errors, ValidationFailureReason reason) { assertFalse(errors.isEmpty()); assertEquals(reason, errors.get(0).getReason()); }</technical_language>

Target:
public void validPropertiesUnsupportedVersion() { DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateProperties(Version.v3_2, VmDeviceGeneralType.DISK, utils.convertProperties("bootable=true")); validateFailure(errors, ValidationFailureReason.UNSUPPORTED_VERSION); }
Source:
<code><START> private void restartVmsWithLeaseIfNeeded(List<VmDynamic> vms) { <END> if (vms.isEmpty()) { return; } int skippedIterations = Config.<Integer>getValue(ConfigValues.NumberVdsRefreshesBeforeRetryToStartUnknownVms); autoRestartUnknownVmsIteration = (autoRestartUnknownVmsIteration + 1) % (skippedIterations + 1); if (autoRestartUnknownVmsIteration != 0) { return; } resourceManager.getEventListener().restartVmsWithLease(vms.stream() .map(VmDynamic::getId) .filter(vmId -> resourceManager.getVmManager(vmId).getLeaseStorageDomainId() != null) .collect(Collectors.toList())); }</code><technical_language>code more readable? autoRestartUnknownVmsIteration++; if (autoRestartUnknownVmsIteration % skippedIterations == 0) { // want restart VMs lease frequently resourceManager.getEventListener().restartVmsWithLease(vms.stream() .map(VmDynamic::getId) .filter(vmId -> resourceManager.getVmManager(vmId).getLeaseStorageDomainId() != null) .collect(Collectors.toList())); }</technical_language>

Target:
private void restartVmsWithLeaseIfNeeded(List<VmDynamic> vms) { if (vms.isEmpty() || !autoStartVmsWithLeasesLock.tryLock()) { return; } try { int skippedIterations = Config.<Integer>getValue(ConfigValues.NumberVdsRefreshesBeforeRetryToStartUnknownVms); autoRestartUnknownVmsIteration++; if (autoRestartUnknownVmsIteration % (skippedIterations + 1) == 0) { resourceManager.getEventListener().restartVmsWithLease(vms.stream() .map(VmDynamic::getId) .filter(vmId -> resourceManager.getVmManager(vmId).getLeaseStorageDomainId() != null) .collect(Collectors.toList())); } } finally { autoStartVmsWithLeasesLock.unlock(); } }
Source:
<code>static ParquetMetadata readSummaryMetadata(Configuration configuration, Path basePath, boolean skipRowGroups) throws IOException { Path summaryFile = new Path(basePath, PARQUET_METADATA_FILE); <START> Path summaryFileLight = new Path(basePath, PARQUET_COMMON_METADATA_FILE); <END> FileSystem fileSystem = basePath.getFileSystem(configuration); if (skipRowGroups && fileSystem.exists(summaryFileLight)) { if (Log.INFO) LOG.info("reading summary file: " + summaryFileLight); return readFooter(configuration, summaryFileLight, filter(skipRowGroups)); } else if (fileSystem.exists(summaryFile)) { if (Log.INFO) LOG.info("reading summary file: " + summaryFile); return readFooter(configuration, summaryFile, filter(skipRowGroups)); } else { return null; } }</code><technical_language>name variable parquetCommonMetaDataFile instead of summaryFileLigt? summaryFile parquetMetadataFile</technical_language>

Target:
static ParquetMetadata readSummaryMetadata(Configuration configuration, Path basePath, boolean skipRowGroups) throws IOException { Path metadataFile = new Path(basePath, PARQUET_METADATA_FILE); Path commonMetaDataFile = new Path(basePath, PARQUET_COMMON_METADATA_FILE); FileSystem fileSystem = basePath.getFileSystem(configuration); if (skipRowGroups && fileSystem.exists(commonMetaDataFile)) { if (Log.INFO) LOG.info("reading summary file: " + commonMetaDataFile); return readFooter(configuration, commonMetaDataFile, filter(skipRowGroups)); } else if (fileSystem.exists(metadataFile)) { if (Log.INFO) LOG.info("reading summary file: " + metadataFile); return readFooter(configuration, metadataFile, filter(skipRowGroups)); } else { return null; } }
Source:
<code>public void testRWZKConnectionLost() throws Exception { ZooKeeper zk = ZooKeeperClient.newBuilder() .connectString(zkUtil.getZooKeeperConnectString()) .sessionTimeoutMs(10000) .build(); try { ReplicationWorker rw = new ReplicationWorker(zk, baseConf, getBookie(0)); rw.start(); for (int i = 0; i < 10; i++) { if (rw.isRunning()) { break; } Thread.sleep(1000); } assertTrue("Replication worker should be running", rw.isRunning()); stopZKCluster(); <START> Thread.sleep(1000); <END> startZKCluster(); assertTrue("Replication worker should still be running", rw.isRunning()); } finally { zk.close(); } }</code><technical_language>Instead of sleep, check '!zk.getState().isConnected()' in a loop. add additional assertion verify 'rw.isRunning()'. start ZK cluster do rw.isRunning() verification now</technical_language>

Target:
public void testRWZKConnectionLost() throws Exception { ZooKeeper zk = ZooKeeperClient.newBuilder() .connectString(zkUtil.getZooKeeperConnectString()) .sessionTimeoutMs(10000) .build(); try { ReplicationWorker rw = new ReplicationWorker(zk, baseConf, getBookie(0)); rw.start(); for (int i = 0; i < 10; i++) { if (rw.isRunning()) { break; } Thread.sleep(1000); } assertTrue("Replication worker should be running", rw.isRunning()); stopZKCluster(); for (int i = 0; i < 10; i++) { if (!zk.getState().isConnected()) { break; } Thread.sleep(1000); } assertFalse(zk.getState().isConnected()); startZKCluster(); assertTrue("Replication worker should still be running", rw.isRunning()); } finally { zk.close(); } }
Source:
<code>public Properties trackScreenView(@NonNull String screenName, @Nullable String courseId, @Nullable String action) { SegmentAnalyticsEvent aEvent = new SegmentAnalyticsEvent(); aEvent.setAppNameContext(); if (!TextUtils.isEmpty(action)) { aEvent.properties.put(Keys.ACTION, action); } if (!TextUtils.isEmpty(courseId)) { aEvent.properties.put(Keys.COURSE_ID, courseId); } <START> tracker.screen("", screenName, aEvent.properties); <END> addCategoryToBiEvents(aEvent.properties, Values.SCREEN, screenName); tracker.track(screenName, aEvent.properties); return aEvent.properties; }</code><technical_language>This needs a category</technical_language>

Target:
public Properties trackScreenView(@NonNull String screenName, @Nullable String courseId, @Nullable String action) { return trackScreenView(screenName, courseId, action, null); }
Source:
<code>private void appendUserScriptsTo(StringBuilder stringBuilder) throws IOException { try { List<String> passiveFunctionNames = new ArrayList<String>(); this.extensionScript .getScripts(ExtensionFrontEndScanner.SCRIPT_TYPE_CLIENT_PASSIVE) .stream() .filter(script -> script.isEnabled()) .map(script -> script.getFile()) .map(file -> file.toPath()) <START> .map(scriptFileName -> readFromFile(scriptFileName)) <END> .map(code -> wrapInFunction(code, passiveFunctionNames)) .forEach(code -> stringBuilder.append(code)); stringBuilder .append("const SCRIPTS = [ " + String.join(", ", passiveFunctionNames) + "];"); } catch (UncheckedIOException e) { throw new IOException(e); } }</code><technical_language>script.getContents() instead of reading file</technical_language>

Target:
private void appendUserScriptsTo(StringBuilder stringBuilder) throws IOException { try { List<String> passiveFunctionNames = new ArrayList<String>(); this.extensionScript .getScripts(ExtensionFrontEndScanner.SCRIPT_TYPE_CLIENT_PASSIVE) .stream() .filter(script -> script.isEnabled()) .map(script -> script.getContents()) .map(code -> wrapInFunction(code, passiveFunctionNames)) .forEach(code -> stringBuilder.append(code)); stringBuilder .append("const SCRIPTS = [ " + String.join(", ", passiveFunctionNames) + "];"); } catch (UncheckedIOException e) { throw new IOException(e); } }
Source:
<code><START> public ReentrantLock getLock() { <END> return lock; }</code><technical_language>suggestion ReentrantLock getLock() {</technical_language>

Target:
ReentrantLock getLock() { return lock; }
Source:
<code>public Object execute(final ExecutionEvent event) throws ExecutionException { final Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event)); final Shell shell = getShell(event); IResource[] resourcesInScope; try { IResource[] selectedResources = getSelectedResources(event); IWorkbenchPart part = getPart(event); resourcesInScope = GitScopeUtil.getRelatedChanges(part, selectedResources); } catch (InterruptedException e) { return null; } CommitUI commitUi = new CommitUI(shell, repos[0], resourcesInScope, false); commitUi.commit(); <START> if (commitUi.isExecutePush()) { <END> executePushCommand(HandlerUtil.getCurrentSelection(event)); } return null; }</code><technical_language>curly brackets for single line bolocks</technical_language>

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { final Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event)); final Shell shell = getShell(event); IResource[] resourcesInScope; try { IResource[] selectedResources = getSelectedResources(event); IWorkbenchPart part = getPart(event); resourcesInScope = GitScopeUtil.getRelatedChanges(part, selectedResources); } catch (InterruptedException e) { return null; } CommitUI commitUi = new CommitUI(shell, repos[0], resourcesInScope, false); commitUi.commit(); if (commitUi.isExecutePush()) executePushCommand(HandlerUtil.getCurrentSelection(event)); return null; }
Source:
<code>protected ConnectorPageSource createLookupPageSource(SplitInfo splitInfo, List<String> outputColumnNames) { IndexedTable indexedTable = indexedData.getIndexedTable( splitInfo.getTableName(), schemaNameToScaleFactor(splitInfo.getSchemaName()), ImmutableSet.copyOf(splitInfo.getLookupColumnNames())) <START> .orElseThrow(() -> new IllegalArgumentException("Index is not present")); <END> List<Type> lookupColumnTypes = types(splitInfo.getTableName(), splitInfo.getLookupColumnNames()); RecordSet keyRecordSet = new ListBasedRecordSet(splitInfo.getKeys(), lookupColumnTypes); RecordSet outputRecordSet = lookupIndexKeys(keyRecordSet, indexedTable, outputColumnNames); return new RecordPageSource(outputRecordSet); }</code><technical_language>String.format("No index %s%s", splitInfo.getSchemaName(), splitInfo.getLookupColumnNames())</technical_language>

Target:
protected ConnectorPageSource createLookupPageSource(SplitInfo splitInfo, List<String> outputColumnNames) { IndexedTable indexedTable = indexedData.getIndexedTable( splitInfo.getTableName(), schemaNameToScaleFactor(splitInfo.getSchemaName()), ImmutableSet.copyOf(splitInfo.getLookupColumnNames())) .orElseThrow(() -> new IllegalArgumentException(String.format("No such index: %s%s", splitInfo.getTableName(), splitInfo.getLookupColumnNames()))); List<Type> lookupColumnTypes = types(splitInfo.getTableName(), splitInfo.getLookupColumnNames()); RecordSet keyRecordSet = new ListBasedRecordSet(splitInfo.getKeys(), lookupColumnTypes); RecordSet outputRecordSet = lookupIndexKeys(keyRecordSet, indexedTable, outputColumnNames); return new RecordPageSource(outputRecordSet); }
Source:
<code>public void enterTopLevel(TopLevelContext topLevelCtx) { List<IdentifierContext> names = DeclarationListener.getConstantNames(topLevelCtx); names.forEach( ctx -> { String constantName = CharFormatUtil.unescapeIdentifier(ctx.getText()); Location location = ListenerUtil.getContextStartLocation(ctx); <START> if (CharFormatUtil.isEnclosedInBackticks(ctx.getText())) { <END> location.column += 1; } if (CharFormatUtil.isKPrefixed(constantName)) { printer.warn(Rules.CONSTANT_K_PREFIX, Messages.CONSTANT + Messages.NAME + Messages.K_PREFIXED, location); } } ); }</code><technical_language>create a function returns character of identifier accounts for escaped case (since this in a couple of places)</technical_language>

Target:
public void enterTopLevel(TopLevelContext topLevelCtx) { List<IdentifierContext> names = DeclarationListener.getConstantNames(topLevelCtx); names.forEach( ctx -> { String constantName = CharFormatUtil.unescapeIdentifier(ctx.getText()); Location location = ListenerUtil.getIdentifierStartLocation(ctx); if (CharFormatUtil.isKPrefixed(constantName)) { printer.warn(Rules.CONSTANT_K_PREFIX, Messages.CONSTANT + Messages.NAME + Messages.K_PREFIXED, location); } } ); }
Source:
<code>public RelBuilder scan(Iterable<String> tableNames) { <START> final List<String> names = Lists.newArrayList(tableNames); <END> final RelOptTable relOptTable = relOptSchema.getTableForMember(names); if (relOptTable == null) { throw Static.RESOURCE.tableNotFound(Joiner.on(".").join(names)).ex(); } final RelNode scan = scanFactory.createScan(cluster, relOptTable); push(scan); return this; }</code><technical_language>ImmutableList.copyOf</technical_language>

Target:
public RelBuilder scan(Iterable<String> tableNames) { final List<String> names = ImmutableList.copyOf(tableNames); final RelOptTable relOptTable = relOptSchema.getTableForMember(names); if (relOptTable == null) { throw Static.RESOURCE.tableNotFound(Joiner.on(".").join(names)).ex(); } final RelNode scan = scanFactory.createScan(cluster, relOptTable); push(scan); return this; }
Source:
<code>public void testStaledCompletion() throws InterruptedException { long txnId = m_mpTxnEgo.getTxnId(); TransactionTask[] firstFrag = new TransactionTask[SITE_COUNT]; for (int i = 0; i < SITE_COUNT; i++) { firstFrag[i] = createFrag(m_localTxnEgo[i].getTxnId(), txnId, m_txnTaskQueues.get(i)); addTask(firstFrag[i], m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } TransactionTask comp = null; for (int i = 0; i < SITE_COUNT - 1; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } long seq = m_repairGenerator.getNextSeqNum(); for (int i = 0; i < SITE_COUNT; i++) { <START> comp = createRepairCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i), seq, true); <END> addTask(comp, m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } flushBacklog(firstFrag); for (int i = SITE_COUNT - 1; i < SITE_COUNT; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } verify(); }</code><technical_language>intention set AbortRepair flag here</technical_language>

Target:
public void testStaledCompletion() throws InterruptedException { long txnId = m_mpTxnEgo.getTxnId(); TransactionTask[] firstFrag = new TransactionTask[SITE_COUNT]; for (int i = 0; i < SITE_COUNT; i++) { firstFrag[i] = createFrag(m_localTxnEgo[i].getTxnId(), txnId, m_txnTaskQueues.get(i)); addTask(firstFrag[i], m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } TransactionTask comp = null; for (int i = 0; i < SITE_COUNT - 1; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } long seq = m_repairGenerator.getNextSeqNum(); for (int i = 0; i < SITE_COUNT; i++) { comp = createRepairCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i), seq, false); addTask(comp, m_txnTaskQueues.get(i), m_expectedOrders.get(i)); } flushBacklog(firstFrag); for (int i = SITE_COUNT - 1; i < SITE_COUNT; i++) { comp = createCompletion(firstFrag[i].getTransactionState(), firstFrag[i].getTxnId(), m_txnTaskQueues.get(i)); addTask(comp, m_txnTaskQueues.get(i), null); } verify(); }
Source:
<code>public void emptySpoilerTest() throws Exception { final String xml = "<spoiler xmlns='urn:xmpp:spoiler:0'/>"; SpoilerManager m = SpoilerManager.getInstanceFor(connection); SpoilerElement empty = m.createSpoiler(); assertNull(empty.getHint()); assertNull(empty.getLanguage()); assertXMLEqual(xml, empty.toXML().toString()); XmlPullParser parser = TestUtils.getParser(xml); <START> SpoilerElement parsed = new SpoilerProvider().parse(parser); <END> assertXMLEqual(xml, parsed.toXML().toString()); }</code><technical_language>common Smack idiom is a public field instance of a provider, for testing purposes, e.g. SpoilerProvider.INSTANCE</technical_language>

Target:
public void emptySpoilerTest() throws Exception { final String xml = "<spoiler xmlns='urn:xmpp:spoiler:0'/>"; Message message = new Message(); SpoilerElement.addSpoiler(message); SpoilerElement empty = message.getExtension(SpoilerElement.ELEMENT, SpoilerManager.NAMESPACE_0); assertNull(empty.getHint()); assertNull(empty.getLanguage()); assertXMLEqual(xml, empty.toXML().toString()); XmlPullParser parser = TestUtils.getParser(xml); SpoilerElement parsed = SpoilerProvider.INSTANCE.parse(parser); assertXMLEqual(xml, parsed.toXML().toString()); }
Source:
<code>public void delta(Delta delta, PersistenceExceptionHandler exceptionHandler) { checkWritesAllowed(); Stopwatch stopwatch = deltaImpl(delta, exceptionHandler); if (LOG.isDebugEnabled()) LOG.debug("Checkpointed delta of memento in {}: " + "updated entities, locations, policies, enrichers, catalog items; " <START> + "removed entities, locations, policies, enrichers catalog items", <END> new Object[] {Time.makeTimeStringRounded(stopwatch), delta.entities().size(), delta.locations().size(), delta.policies().size(), delta.enrichers().size(), delta.catalogItems().size(), delta.removedEntityIds().size(), delta.removedLocationIds().size(), delta.removedPolicyIds().size(), delta.removedEnricherIds().size(), delta.removedCatalogItemIds().size()}); }</code><technical_language>Insert another comma: enrichers, catalog items</technical_language>

Target:
public void delta(Delta delta, PersistenceExceptionHandler exceptionHandler) { checkWritesAllowed(); Stopwatch stopwatch = deltaImpl(delta, exceptionHandler); if (LOG.isDebugEnabled()) LOG.debug("Checkpointed delta of memento in {}: " + "updated entities, locations, policies, enrichers, catalog items; " + "removed entities, locations, policies, enrichers, catalog items", new Object[] {Time.makeTimeStringRounded(stopwatch), delta.entities().size(), delta.locations().size(), delta.policies().size(), delta.enrichers().size(), delta.catalogItems().size(), delta.removedEntityIds().size(), delta.removedLocationIds().size(), delta.removedPolicyIds().size(), delta.removedEnricherIds().size(), delta.removedCatalogItemIds().size()}); }
Source:
<code>private boolean tryFetchLookupSourceProvider() { if (lookupSourceProvider == null) { if (!lookupSourceProviderFuture.isDone()) { return false; } lookupSourceProvider = requireNonNull(getDone(lookupSourceProviderFuture)); statisticsCounter.updateLookupSourcePositions(lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.getLookupSource().getJoinPositionCount())); if (!probeOnOuterSide && !finishing && <START> !finished && <END> lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.hasSpilled() ? false : lookupSourceLease.getLookupSource().isEmpty())) { finishing = true; finished = true; } } return true; }</code><technical_language>finishing == true this point? finished == true this point</technical_language>

Target:
private boolean tryFetchLookupSourceProvider() { if (lookupSourceProvider == null) { if (!lookupSourceProviderFuture.isDone()) { return false; } lookupSourceProvider = requireNonNull(getDone(lookupSourceProviderFuture)); statisticsCounter.updateLookupSourcePositions(lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.getLookupSource().getJoinPositionCount())); if (!probeOnOuterSide && lookupSourceProvider.withLease(lookupSourceLease -> lookupSourceLease.getLookupSource().isEmpty())) { finishing = true; } } return true; }
Source:
<code>public void reportsThreadInformation() throws Exception { Runnable fastOne = new FastRunnable(); Runnable slowOne = new SlowRunnable(); Counter created = registry.counter("factory.created"); Counter running = registry.counter("factory.running"); Counter finished = registry.counter("factory.finished"); Thread fastThread = instrumentedFactory.newThread(fastOne); Thread slowThread = instrumentedFactory.newThread(slowOne); assertThat(created.getCount()).isEqualTo(2); assertThat(running.getCount()).isEqualTo(0); assertThat(finished.getCount()).isEqualTo(0); fastThread.start(); <START> slowThread.start(); <END> Thread.sleep(100); assertThat(running.getCount()).isEqualTo(1); assertThat(finished.getCount()).isEqualTo(1); Thread.sleep(1000); assertThat(running.getCount()).isEqualTo(0); assertThat(finished.getCount()).isEqualTo(2); }</code><technical_language>threads need get shut down</technical_language>

Target:
public void reportsThreadInformation() throws Exception { Runnable fastOne = new FastRunnable(); Meter created = registry.meter("factory.created"); Meter terminated = registry.meter("factory.terminated"); assertThat(created.getCount()).isEqualTo(0); assertThat(terminated.getCount()).isEqualTo(0); for (int i = 10; i < 20; i++) { executor.submit(fastOne); } assertThat(created.getCount()).isEqualTo(10); assertThat(terminated.getCount()).isEqualTo(0); executor.shutdown(); assertThat(executor.awaitTermination(1, TimeUnit.SECONDS)).isTrue(); assertThat(terminated.getCount()).isEqualTo(10); }
Source:
<code>private Map<String, DbComponent> getDbFilesByKey() { try (DbSession dbSession = dbClient.openSession(false)) { List<ComponentWithPathDto> componentDtos = dbClient.componentDao().selectFilesWithPathFromProject(dbSession, rootHolder.getRoot().getUuid()); return componentDtos.stream() .map(dto -> new DbComponent(dto.getId(), dto.getDbKey(), dto.uuid(), dto.path())) <START> .collect(Collectors.toMap(DbComponent::getKey, x -> x)); <END> } }</code><technical_language>FYI, java.util.Function#identity() exists</technical_language>

Target:
private Map<String, DbComponent> getDbFilesByKey() { try (DbSession dbSession = dbClient.openSession(false)) { List<ComponentDto> componentDtos = dbClient.componentDao().selectDescendants( dbSession, ComponentTreeQuery.builder() .setBaseUuid(rootHolder.getRoot().getUuid()) .setQualifiers(FILE_QUALIFIERS) .setStrategy(Strategy.LEAVES) .build()); return from(componentDtos) .transform(componentDto -> new DbComponent(componentDto.getId(), componentDto.getDbKey(), componentDto.uuid(), componentDto.path())) .uniqueIndex(DbComponent::getKey); } }
Source:
<code><START> public FieldValueCounter save(FieldValueCounter fieldValueCounter) { <END> map.put(fieldValueCounter.getName(), fieldValueCounter); return fieldValueCounter; }</code><technical_language>methods removed (or minima private) implementation inlined in getOrCreate()</technical_language>

Target:
private FieldValueCounter save(FieldValueCounter fieldValueCounter) { map.put(fieldValueCounter.getName(), fieldValueCounter); return fieldValueCounter; }
Source:
<code><START> public UnitCard(DatabaseAccessor db, Project project, String title, int chapter, int firstVerse, int endVerse, OnTakeDeleteListener listener) { <END> mTitle = title; mFirstVerse = firstVerse; mEndVerse = endVerse; mChapter = chapter; mProject = project; onTakeDeleteListener = listener; refreshTakeCount(db); }</code><technical_language>line length</technical_language>

Target:
public UnitCard( DatabaseAccessor db, Project project, String title, int chapter, int firstVerse, int endVerse, OnTakeDeleteListener listener ) { mTitle = title; mFirstVerse = firstVerse; mEndVerse = endVerse; mChapter = chapter; mProject = project; onTakeDeleteListener = listener; databaseAccessor = db; refreshTakeCount(); }
Source:
<code>public void unmanagedDeployment() throws Exception { ops.viewDeployment(browser, navigation, DEPLOYMENT_MED_10); String content = page.getDeploymentContentTableRow("Managed"); assertTrue(content.contains("false")); content = page.getDeploymentContentTableRow("Managed"); <START> assertTrue(content.contains("false")); <END> content = page.getDeploymentContentTableRow("Status"); assertTrue("Status of deployment should be 'OK'", content.contains("OK")); }</code><technical_language>difference assertions</technical_language>

Target:
public void unmanagedDeployment() throws Exception { page.viewDeployment(DEPLOYMENT_UNMANAGED_10); String content = page.getDeploymentContentTableRow("Managed"); assertTrue(content.contains("false")); content = page.getDeploymentContentTableRow("Status"); assertTrue("Status of deployment should be 'OK'", content.contains("OK")); }
Source:
<code>private Callable<Void> readRecoveredStateTask(RecoveredInputChannel inputChannel, ChannelStateReader reader, boolean verifyRelease) { return () -> { try { inputChannel.readRecoveredState(reader); } catch (Throwable t) { <START> assertTrue("The expected exception should only happen in the case of released channel.", verifyRelease && inputChannel.isReleased()); <END> } return null; }; }</code><technical_language>clarify: do expect exception thrown in this case is a (undeterministic) outcome? If expect it, test needs modified. If undeterministic, is a deterministic</technical_language>

Target:
private Callable<Void> readRecoveredStateTask(RecoveredInputChannel inputChannel, ChannelStateReader reader, boolean verifyRelease) { return () -> { try { inputChannel.readRecoveredState(reader); } catch (Throwable t) { if (!(verifyRelease && inputChannel.isReleased())) { throw new AssertionError("Exceptions are expected here only if the input channel was released", t); } } return null; }; }
Source:
<code>private ArrayList<SearchResult> ctxSearch(String query, SearchControls sc, LdapContext ctx) throws NamingException { <START> NamingEnumeration<SearchResult> resultQuery = null; <END> ArrayList<SearchResult> result = new ArrayList<SearchResult>(); if (subDNs != null && subDNs.size() > 0){ for (String subDN : subDNs.getList()) { resultQuery = ctx.search(subDN + "," + baseDN, query, sc); try { if (resultQuery != null && resultQuery.hasMore()) { result.addAll(Collections.list(resultQuery)); } } finally { closeQuietly(resultQuery); resultQuery = null; } } } else { resultQuery = ctx.search(baseDN, query, sc); try { if (resultQuery != null && resultQuery.hasMore()) { result.addAll(Collections.list(resultQuery)); } } finally { closeQuietly(resultQuery); resultQuery = null; } } return result; }</code><technical_language>variable declared is</technical_language>

Target:
private ArrayList<SearchResult> ctxSearch(String query, SearchControls sc, LdapContext ctx) throws NamingException { ArrayList<SearchResult> result = new ArrayList<SearchResult>(); if (subDNs != null && subDNs.size() > 0){ for (String subDN : subDNs.getList()) { addSearchResult(result, subDN + "," + baseDN, query, sc, ctx); } } else { addSearchResult(result, baseDN, query, sc, ctx); } return result; }
Source:
<code>public void whenMatchExactlyEnabled_disablesPrefs() { rule.mainMenu() .clickOnMenu() .clickGeneralSettings() .clickFormManagement() .clickUpdateForms() .clickOption(R.string.match_exactly) <START> .assertDisabled(R.string.automatic_download); <END> }</code><technical_language>Additionally, I checkbox selected clear updates happen automatically in match mode. If mode changes match of other modes, checkbox unchecked automatic downloads applicable manual mode default for updates existing forms. I ok for for update frequency stay set in case of manual update I find disabled automatic download option confusing</technical_language>

Target:
public void whenMatchExactlyEnabled_disablesPrefs() { new MainMenuPage(rule).assertOnPage() .clickOnMenu() .clickGeneralSettings() .clickFormManagement() .clickUpdateForms() .clickOption(R.string.match_exactly) .assertEnabled(R.string.form_update_frequency_title) .assertDisabled(R.string.automatic_download); }
Source:
<code>private void writeNormalizedConfigDocuments(Collection<Report> reports) { for (Report report : reports) { for (Configuration.Setup setup : report.getConfiguration().getSetups()) { Set<Integer> slaves = report.getCluster().getSlaves(setup.group); Set<String> normalized = new HashSet<>(); for (Map.Entry<Integer, Map<String, Properties>> entry : report.getNormalizedServiceConfigs().entrySet()) { if (slaves.contains(entry.getKey()) && entry.getValue() != null) { normalized.addAll(entry.getValue().keySet()); } } for (String config : normalized) { NormalizedConfigDocument document = new NormalizedConfigDocument( targetDir, report.getConfiguration().name, setup.group, report.getCluster(), config, report.getNormalizedServiceConfigs(), slaves); freemarker.template.Configuration cfg = initConfig(); try { document.createReportDirectory(); Template reportTemplate = cfg.getTemplate("normalizedReport.ftl"); PrintWriter printWriter = new PrintWriter(targetDir + File.separator + document.getFileName()); Map root = new HashMap(); root.put("normalized", document); reportTemplate.process(root, printWriter); <START> printWriter.close(); <END> } catch (Exception e) { log.error("Templating exception", e); } } } } }</code><technical_language>Resources closed in finally block. Preferably try-with-resources construct</technical_language>

Target:
private void writeNormalizedConfigDocuments(Collection<Report> reports) { for (Report report : reports) { for (Configuration.Setup setup : report.getConfiguration().getSetups()) { Set<Integer> slaves = report.getCluster().getSlaves(setup.group); Set<String> normalized = new HashSet<>(); for (Map.Entry<Integer, Map<String, Properties>> entry : report.getNormalizedServiceConfigs().entrySet()) { if (slaves.contains(entry.getKey()) && entry.getValue() != null) { normalized.addAll(entry.getValue().keySet()); } } for (String config : normalized) { NormalizedConfigDocument document = new NormalizedConfigDocument( targetDir, report.getConfiguration().name, setup.group, report.getCluster(), config, report.getNormalizedServiceConfigs(), slaves); document.createReportDirectory(); Map root = new HashMap(); root.put("normalized", document); processTemplate(root, targetDir, document.getFileName(), "normalizedReport.ftl"); } } } }
Source:
<code><START> public <END> UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) { this.serverPluginProviders = sf; }</code><technical_language>public? Gerrit conversion is mark injected constructors package provided</technical_language>

Target:
UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) { this.serverPluginProviders = sf; }
Source:
<code>public void putMetadata(String key, Object value) { <START> metadata.put(key, value); <END> }</code><technical_language><LINK_0> handled case metadata null, check need also</technical_language>

Target:
public void putMetadata(String key, Object value) { if (metadata == null) { metadata = new HashMap<>(); } metadata.put(key, value); }
Source:
<code>public void debug() { <START> ActiveMQServerLogger.LOGGER.debugStarted(globalSizeBytes.get(), numberOfMessages.get()); <END> }</code><technical_language>Please.. this out.. a debug.. in real life</technical_language>

Target:
public void debug() { logger.info("size = " + globalSizeBytes + " bytes, messages = " + numberOfMessages); }
Source:
<code><START> static private void validateGenotypes(final VariantContext variantContext) { <END> final ArrayList<Genotype> genotypes = variantContext.genotypes.getGenotypes(); if (genotypes == null) { throw new IllegalStateException("Genotypes is null"); } for (int i = 0; i < genotypes.size(); i++) { final Genotype genotype = genotypes.get(i); if (genotype.isAvailable()) { final List<Allele> alleles = genotype.getAlleles(); for (int j = 0, size = alleles.size(); j < size; j++) { final Allele gAllele = alleles.get(j); if (!variantContext.hasAllele(gAllele) && gAllele.isCalled()) { throw new IllegalStateException("Allele in genotype " + gAllele + " not in the variant context " + alleles); } } } } }</code><technical_language>suggestion private static void validateGenotypes(final VariantContext variantContext) {</technical_language>

Target:
private static void validateGenotypes(final VariantContext variantContext) { final ArrayList<Genotype> genotypes = variantContext.genotypes.getGenotypes(); if (genotypes == null) { throw new IllegalStateException("Genotypes is null"); } for (int i = 0; i < genotypes.size(); i++) { final Genotype genotype = genotypes.get(i); if (genotype.isAvailable()) { final List<Allele> alleles = genotype.getAlleles(); for (int j = 0, size = alleles.size(); j < size; j++) { final Allele gAllele = alleles.get(j); if (!variantContext.hasAllele(gAllele) && gAllele.isCalled()) { throw new IllegalStateException("Allele in genotype " + gAllele + " not in the variant context " + alleles); } } } } }
Source:
<code>public List<Entity> findLastJobs() { final List<Entity> jobs = new ArrayList<>(); Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS); User currentUser = userAccountService.getCurrentUser(); dataService .getMeta() .getEntityTypes() .filter(this::isAllowedJobExecutionEntityType) .forEach( e -> { Query<Entity> q = dataService.query(e.getId()).ge(JobExecutionMetaData.SUBMISSION_DATE, weekAgo); <START> if (!Boolean.TRUE.equals(currentUser.isSuperuser())) { <END> q.and().eq(USER, currentUser.getUsername()); } dataService.findAll(e.getId(), q).forEach(jobs::add); }); jobs.sort( (job1, job2) -> job2.getInstant(SUBMISSION_DATE).compareTo(job1.getInstant(SUBMISSION_DATE))); if (jobs.size() > MAX_JOBS_TO_RETURN) { return jobs.subList(0, MAX_JOBS_TO_RETURN); } return jobs; }</code><technical_language>User.isSuperuser() return a boolean instead of Boolean UserMetadata states superuser is required</technical_language>

Target:
public List<Entity> findLastJobs() { final List<Entity> jobs = new ArrayList<>(); Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS); User currentUser = userAccountService.getCurrentUser(); dataService .getMeta() .getEntityTypes() .filter(this::isAllowedJobExecutionEntityType) .forEach( e -> { Query<Entity> q = dataService.query(e.getId()).ge(JobExecutionMetaData.SUBMISSION_DATE, weekAgo); if (!currentUser.isSuperuser()) { q.and().eq(USER, currentUser.getUsername()); } dataService.findAll(e.getId(), q).forEach(jobs::add); }); jobs.sort( (job1, job2) -> job2.getInstant(SUBMISSION_DATE).compareTo(job1.getInstant(SUBMISSION_DATE))); if (jobs.size() > MAX_JOBS_TO_RETURN) { return jobs.subList(0, MAX_JOBS_TO_RETURN); } return jobs; }
Source:
<code>private static List<ContainerUUID> getColumnContainers (Element splitBody ) { <START> Pattern parseContainerPatter = Pattern.compile( "(?<=#parseContainer\\(').*?(?='\\))" ); <END> List<ContainerUUID> containers = new ArrayList<>(); Matcher matcher = parseContainerPatter.matcher( splitBody.text() ); while ( matcher.find() ) { String parseContainerArguments = matcher.group(); if (parseContainerArguments != null) { String[] splitArguments = parseContainerArguments.split(","); String id = splitArguments[0]; String uuid = splitArguments.length > 1 ? splitArguments[1] : ParseContainer.DEFAULT_UUID_VALUE; containers.add(new ContainerUUID(id, uuid)); } } return containers; }</code><technical_language>Pattern is a thread-safe object create static final of part of class</technical_language>

Target:
private static List<ContainerUUID> getColumnContainers (Element splitBody ) { List<ContainerUUID> containers = new ArrayList<>(); Matcher matcher = parseContainerPatter.matcher( splitBody.text() ); while ( matcher.find() ) { String parseContainerArguments = matcher.group(); if (parseContainerArguments != null) { String[] splitArguments = parseContainerArguments.split(","); String id = splitArguments[0]; String uuid = splitArguments.length > 1 ? splitArguments[1] : ParseContainer.DEFAULT_UUID_VALUE; containers.add(new ContainerUUID(id, uuid)); } } return containers; }
Source:
<code>public Optional<Statistic> getById(String id) { <START> return Optional.ofNullable(this.statisticMappings.get(id.toLowerCase())); <END> }</code><technical_language>This define a locale for lowercase method</technical_language>

Target:
public Optional<Statistic> getById(String id) { return Optional.ofNullable(this.statisticMappings.get(id.toLowerCase(Locale.ENGLISH))); }
Source:
<code>private static String getExtension(File file) { String name = file.getName(); int ext = <START> name.lastIndexOf("."); <END> return 0 < ext ? name.substring(ext, name.length()) : ""; }</code><technical_language>'.'</technical_language>

Target:
private static String getExtension(File file) { return getExtension(file.getName()); }
Source:
<code>public Color getDiffImageColor() { <START> int rgba = new BigInteger(diffImageColorRgbaHex.substring(2), 16).intValue(); <END> return new Color(rgba, true); }</code><technical_language>Is proper decode (by 0x account) - for example Integer.decode is doing</technical_language>

Target:
public Color getDiffImageColor() { int rgba = Long.decode(diffImageColorRgbaHex).intValue(); return new Color(rgba, true); }
Source:
<code>public ScarwoodBandits(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}{G}"); this.subtype.add("Human"); <START> this.subtype.add("Rogue"); <END> this.power = new MageInt(2); this.toughness = new MageInt(2); this.addAbility(new ForestwalkAbility()); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new ScarwoodBanditsEffect(new GenericManaCost(2)), new ManaCostsImpl("{2}{G}")); ability.addCost(new TapSourceCost()); ability.addTarget(new TargetArtifactPermanent()); this.addAbility(ability); }</code><technical_language>string subtype is deprecated, SubType.HUMAN SubType.ROGUE instead</technical_language>

Target:
public ScarwoodBandits(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}{G}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.ROGUE); this.power = new MageInt(2); this.toughness = new MageInt(2); this.addAbility(new ForestwalkAbility()); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new DoUnlessAnyOpponentPaysEffect( new ConditionalContinuousEffect( new GainControlTargetEffect(Duration.Custom, true), new SourceOnBattlefieldCondition(), "gain control of target artifact for as long as {this} remains on the battlefield"), new GenericManaCost(2)), new ManaCostsImpl("{2}{G}")); ability.addCost(new TapSourceCost()); ability.addTarget(new TargetArtifactPermanent()); this.addAbility(ability); }
Source:
<code>public CompletableFuture<Boolean> setPointer(PublicSigningKey owner, PublicSigningKey signer, byte[] sharingKeySignedBtreeRootHashes) { byte[] message = signer.unsignMessage(sharingKeySignedBtreeRootHashes); HashCasPair cas = HashCasPair.fromCbor(CborObject.fromByteArray(message)); long t1 = System.currentTimeMillis(); return storage.recursivePin(cas.updated.get()).thenCompose(pins -> { if (!pins.contains(cas.updated.get())) <START> return CompletableFuture.completedFuture(false); <END> long t2 = System.currentTimeMillis(); if (LOGGING) System.out.println("Pinning "+cas.updated+" took: " + (t2 -t1) + " mS"); return target.setPointer(owner, signer, sharingKeySignedBtreeRootHashes) .thenCompose(b -> { if (!b) return CompletableFuture.completedFuture(false); long t3 = System.currentTimeMillis(); return !cas.original.isPresent() ? CompletableFuture.completedFuture(true) : storage.recursiveUnpin(cas.original.get()) .thenApply(unpins -> { long t4 = System.currentTimeMillis(); if (LOGGING) System.out.println("Unpinning "+cas.original+" took: " + (t4 -t3) + " mS"); return unpins.contains(cas.original.get()); }); }); }); }</code><technical_language>suggest making this error state throw error happen</technical_language>

Target:
public CompletableFuture<Boolean> setPointer(PublicSigningKey owner, PublicSigningKey signer, byte[] sharingKeySignedBtreeRootHashes) { byte[] message = signer.unsignMessage(sharingKeySignedBtreeRootHashes); HashCasPair cas = HashCasPair.fromCbor(CborObject.fromByteArray(message)); long t1 = System.currentTimeMillis(); return storage.recursivePin(cas.updated.get()).thenCompose(pins -> { if (!pins.contains(cas.updated.get())) { CompletableFuture<Boolean> err = new CompletableFuture<>(); err.completeExceptionally(new IllegalStateException("Couldn't pin new hash: " + cas.updated.get())); return err; } long t2 = System.currentTimeMillis(); if (LOGGING) System.out.println("Pinning "+cas.updated+" took: " + (t2 -t1) + " mS"); return target.setPointer(owner, signer, sharingKeySignedBtreeRootHashes) .thenCompose(b -> { if (!b) { CompletableFuture<Boolean> err = new CompletableFuture<>(); err.completeExceptionally(new IllegalStateException("Couldn't update mutable pointer, cas failed: " + cas)); return err; } long t3 = System.currentTimeMillis(); return !cas.original.isPresent() ? CompletableFuture.completedFuture(true) : storage.recursiveUnpin(cas.original.get()) .thenApply(unpins -> { long t4 = System.currentTimeMillis(); if (LOGGING) System.out.println("Unpinning "+cas.original+" took: " + (t4 -t3) + " mS"); return unpins.contains(cas.original.get()); }); }); }); }
Source:
<code>private static String getMetricNameWithUniqueId(InstanceType instance, String name) { <START> if (sSourceName == null) { <END> switch (instance) { case CLIENT: if (CONF.isSet(PropertyKey.USER_APP_ID)) { sSourceName = CONF.get(PropertyKey.USER_APP_ID); } else { sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); } break; case WORKER: if (CONF.isSet(PropertyKey.WORKER_HOSTNAME)) { sSourceName = CONF.get(PropertyKey.WORKER_HOSTNAME); } else { sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); } break; case JOB_WORKER: if (CONF.isSet(PropertyKey.JOB_WORKER_HOSTNAME)) { sSourceName = CONF.get(PropertyKey.JOB_WORKER_HOSTNAME); } else { sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); } break; default: sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); break; } } if (name.startsWith(instance.toString())) { return Joiner.on(".").join(name, sSourceName); } return Joiner.on(".").join(instance, name, sSourceName); }</code><technical_language>add ensure sSourceName is set once? do assume JVM 1 instance type</technical_language>

Target:
private static String getMetricNameWithUniqueId(InstanceType instance, String name) { if (name.startsWith(instance.toString())) { return Joiner.on(".").join(name, sSourceNameSupplier); } return Joiner.on(".").join(instance, name, sSourceNameSupplier); }