auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testLoadGeneratorStops() throws InterruptedException, UnknownHostException { LlapLoadGeneratorService service = new LlapLoadGeneratorService(); HiveConf conf = new HiveConf(); HiveConf.setVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_HOSTNAMES, InetAddress.getLocalHost().getHostName() + ",???"); HiveConf.setFloatVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_UTILIZATION, 0.2f); HiveConf.setTimeVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_INTERVAL, 5, TimeUnit.MILLISECONDS); service.init(conf); service.start(); Thread.sleep(5000); assertEquals("The number of threads is not correct", Runtime.getRuntime().availableProcessors(), service.threads.length); for(int i = 0; i < service.threads.length; i++) { assertTrue("The thread [" + i + "] should be alive", service.threads[i].isAlive()); } service.stop(); Thread.sleep(5000); for(int i = 0; i < service.threads.length; i++) { <START> Thread.State state = service.threads[i].getState(); <END> assertFalse("The thread [" + i + "] should be terminated", service.threads[i].isAlive()); } }</code><technical_language>This unused</technical_language>

Target:
public void testLoadGeneratorStops() throws InterruptedException, UnknownHostException { LlapLoadGeneratorService service = new LlapLoadGeneratorService(); HiveConf conf = new HiveConf(); HiveConf.setVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_HOSTNAMES, InetAddress.getLocalHost().getHostName() + ",???"); HiveConf.setFloatVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_UTILIZATION, 0.5f); HiveConf.setTimeVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_INTERVAL, 5, TimeUnit.MILLISECONDS); service.init(conf); service.start(); assertEquals("The number of threads is not correct", Runtime.getRuntime().availableProcessors(), service.threads.length); for(int i = 0; i < service.threads.length; i++) { assertTrue("The thread [" + i + "] should be alive", service.threads[i].isAlive()); } service.stop(); Thread.sleep(1000); for(int i = 0; i < service.threads.length; i++) { Thread.State state = service.threads[i].getState(); assertFalse("The thread [" + i + "] should be terminated", service.threads[i].isAlive()); } }
Source:
<code>private static String printMap(Map<String, Object[]> m) { <START> java.util.Iterator<java.util.Map.Entry<String, Object[]>> itr = m.entrySet().iterator(); <END> StringBuffer sb = new StringBuffer(); sb.append("size = ").append(m.size()).append(" "); while (itr.hasNext()) { sb.append("{"); Map.Entry<String, Object[]> entry = itr.next(); sb.append(entry.getKey()); sb.append(", "); printMapValue(entry.getValue(), sb); sb.append("}"); } return sb.toString(); }</code><technical_language>do Iterator Map require fully qualified paths</technical_language>

Target:
private static String printMap(Map<String, Object[]> m) { Iterator<Map.Entry<String, Object[]>> itr = m.entrySet().iterator(); StringBuffer sb = new StringBuffer(); sb.append("size = ").append(m.size()).append(" "); while (itr.hasNext()) { sb.append("{"); Map.Entry<String, Object[]> entry = itr.next(); sb.append(entry.getKey()); sb.append(", "); printMapValue(entry.getValue(), sb); sb.append("}"); } return sb.toString(); }
Source:
<code>Main(Logger console) { this.console = console; this.jc = new JCommander(this); this.help = new Help(jc, console); jc.setProgramName(DEFAULT_PROGRAM_NAME); jc.addCommand("help", help, "-h", "-help", "--help"); jc.addCommand("create", new CreateDatasetCommand(console)); jc.addCommand("copy", new CopyCommand(console)); jc.addCommand("transform", new TransformCommand(console)); jc.addCommand("update", new UpdateDatasetCommand(console)); jc.addCommand("delete", new DeleteDatasetCommand(console)); jc.addCommand("schema", new SchemaCommand(console)); jc.addCommand("info", new InfoCommand(console)); jc.addCommand("show", new ShowRecordsCommand(console)); jc.addCommand("obj-schema", new ObjectSchemaCommand(console)); jc.addCommand("csv-schema", new CSVSchemaCommand(console)); jc.addCommand("csv-import", new CSVImportCommand(console)); jc.addCommand("json-schema", new JSONSchemaCommand(console)); <START> jc.addCommand("json-import", new JSONImportCommand(console)); <END> jc.addCommand("partition-config", new CreatePartitionStrategyCommand(console)); jc.addCommand("mapping-config", new CreateColumnMappingCommand(console)); jc.addCommand("log4j-config", new Log4jConfigCommand(console)); jc.addCommand("flume-config", new FlumeConfigCommand(console)); }</code><technical_language>I talking @busbey nice if a single import command pass option of JSON, CSV, InputFormat. Do doable</technical_language>

Target:
Main(Logger console) { this.console = console; this.jc = new JCommander(this); this.help = new Help(jc, console); jc.setProgramName(DEFAULT_PROGRAM_NAME); jc.addCommand("help", help, "-h", "-help", "--help"); jc.addCommand("create", new CreateDatasetCommand(console)); jc.addCommand("copy", new CopyCommand(console)); jc.addCommand("transform", new TransformCommand(console)); jc.addCommand("update", new UpdateDatasetCommand(console)); jc.addCommand("delete", new DeleteCommand(console)); jc.addCommand("schema", new SchemaCommand(console)); jc.addCommand("info", new InfoCommand(console)); jc.addCommand("show", new ShowRecordsCommand(console)); jc.addCommand("obj-schema", new ObjectSchemaCommand(console)); jc.addCommand("csv-schema", new CSVSchemaCommand(console)); jc.addCommand("csv-import", new CSVImportCommand(console)); jc.addCommand("json-schema", new JSONSchemaCommand(console)); jc.addCommand("json-import", new JSONImportCommand(console)); jc.addCommand("partition-config", new CreatePartitionStrategyCommand(console)); jc.addCommand("mapping-config", new CreateColumnMappingCommand(console)); jc.addCommand("log4j-config", new Log4jConfigCommand(console)); jc.addCommand("flume-config", new FlumeConfigCommand(console)); }
Source:
<code>public HealthcheckOptionsBuilder(String uri) { <START> this.uri = Optional.of(uri); <END> this.portIndex = Optional.absent(); this.portNumber = Optional.absent(); this.protocol = Optional.absent(); this.startupTimeoutSeconds = Optional.absent(); this.startupDelaySeconds = Optional.absent(); this.startupIntervalSeconds = Optional.absent(); this.intervalSeconds = Optional.absent(); this.responseTimeoutSeconds = Optional.absent(); this.maxRetries = Optional.absent(); this.failureStatusCodes = Optional.absent(); this.healthcheckResultFilePath = Optional.absent(); }</code><technical_language>this(...) repeating args</technical_language>

Target:
public HealthcheckOptionsBuilder(String uri) { this(Optional.of(uri)); }
Source:
<code>private void setTabAndViewPagerSynchronisation() { viewPager.setFocusableInTouchMode(true); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case CONTRIBUTIONS_TAB_POSITION: Timber.d("Contributions tab selected"); tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); isContributionsFragmentVisible = true; updateMenuItem(); break; case NEARBY_TAB_POSITION: Timber.d("Nearby tab selected"); tabLayout.getTabAt(NEARBY_TAB_POSITION).select(); isContributionsFragmentVisible = false; updateMenuItem(); <START> ((NearbyParentFragment)contributionsActivityPagerAdapter.getItem(1)).nearbyParentFragmentPresenter.onTabSelected(); <END> break; default: tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); break; } } @Override public void onPageScrollStateChanged(int state) { } }); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }</code><technical_language>is this referring child fragment's presenter. ideally fragment care of it, this inform fragment tab is selected. Also, is a fragment determine is visible in resumed state, if is achieve</technical_language>

Target:
private void setTabAndViewPagerSynchronisation() { viewPager.setFocusableInTouchMode(true); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case CONTRIBUTIONS_TAB_POSITION: Timber.d("Contributions tab selected"); tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); isContributionsFragmentVisible = true; updateMenuItem(); break; case NEARBY_TAB_POSITION: Timber.d("Nearby tab selected"); tabLayout.getTabAt(NEARBY_TAB_POSITION).select(); isContributionsFragmentVisible = false; updateMenuItem(); NearbyParentFragmentPresenter.getInstance().onTabSelected(); break; default: tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); break; } } @Override public void onPageScrollStateChanged(int state) { } }); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }
Source:
<code><START> private FileStatus[] listStatusForFallbackLink() throws IOException { <END> if (theInternalDir.isRoot() && theInternalDir.getFallbackLink() != null) { URI fallBackUri = theInternalDir.getFallbackLink().targetDirLinkList[0]; return FileSystem.get(fallBackUri, conf) .listStatus(new Path(fallBackUri.toString())); } else { return new FileStatus[0]; } }</code><technical_language>Please theInternalDir.getFallbackLink().targetFileSystem instead of initializing/getting another fs. conf is need dont need uri also</technical_language>

Target:
private FileStatus[] listStatusForFallbackLink() throws IOException { if (theInternalDir.isRoot() && theInternalDir.getFallbackLink() != null) { FileSystem linkedFs = theInternalDir.getFallbackLink().getTargetFileSystem(); FileStatus[] statuses = linkedFs.listStatus(new Path("/")); for (FileStatus status : statuses) { status.setPath( new Path(myUri.toString(), status.getPath().getName())); } return statuses; } else { return new FileStatus[0]; } }
Source:
<code>private void assertUserSuggestion(SuggestionElement user, String name, String... extra) { String alias; if (extra.length > 0) { alias = extra[0]; } else { String[] parts = name.split("\\s+"); if (parts.length > 1) { alias = parts[0].toLowerCase().charAt(0) + parts[1].toLowerCase(); } else { alias = name; } } String image = alias + ".png?"; if (extra.length > 1) { image = extra[1]; } Assert.assertEquals(name, user.getLabel()); String value = user.getValue(); if (value.startsWith("XWiki.")) { Assert.assertEquals("XWiki." + alias, value); } else { Assert.assertEquals(alias, value); } if (image != null) { Assert.assertTrue(user.getIcon().contains(image)); } else { try { <START> Assert.assertEquals("", user.getIcon()); <END> } catch (NoSuchElementException e) { } } }</code><technical_language>change this? point if image is null test wants check is icon, in case getIcon() throw exception (element found). xwiki.selectize.js output.find('.xwiki-selectize-option-icon').remove(); This issue is this if typeof icon === 'object'. need fix instead</technical_language>

Target:
private void assertUserSuggestion(SuggestionElement user, String name, String... extra) { String alias; if (extra.length > 0) { alias = extra[0]; } else { String[] parts = name.split("\\s+"); if (parts.length > 1) { alias = parts[0].toLowerCase().charAt(0) + parts[1].toLowerCase(); } else { alias = name; } } String image = alias + ".png?"; if (extra.length > 1) { image = extra[1]; } Assert.assertEquals(name, user.getLabel()); String value = user.getValue(); if (value.startsWith("XWiki.")) { Assert.assertEquals("XWiki." + alias, value); } else { Assert.assertEquals(alias, value); } if (image != null) { Assert.assertTrue(user.getIcon().contains(image)); } else { try { user.getIcon(); Assert.fail(); } catch (NoSuchElementException e) { } } }
Source:
<code>public void setUp() throws Exception { project = new Project(InstrumentationRegistry.getTargetContext(), "testProject"); Group parentGroup = new Group(); background = new SingleSprite("background"); parentGroup.addActor(background.look); <START> sprite = new SingleSprite("penActor"); <END> parentGroup.addActor(sprite.look); project.getDefaultScene().addSprite(sprite); sprite2 = new SingleSprite("embroideryActor"); parentGroup.addActor(sprite2.look); project.getDefaultScene().addSprite(sprite2); sprite3 = new SingleSprite("testSprite"); parentGroup.addActor(sprite3.look); project.getDefaultScene().addSprite(sprite3); ProjectManager.getInstance().setProject(project); }</code><technical_language>please rename sprites accordingly, test more readable down..</technical_language>

Target:
public void setUp() throws Exception { project = new Project(InstrumentationRegistry.getTargetContext(), "testProject"); Group parentGroup = new Group(); background = new SingleSprite("background"); parentGroup.addActor(background.look); penActorSprite = new SingleSprite("penActor"); parentGroup.addActor(penActorSprite.look); project.getDefaultScene().addSprite(penActorSprite); embroideryActorSprite = new SingleSprite("embroideryActor"); parentGroup.addActor(embroideryActorSprite.look); project.getDefaultScene().addSprite(embroideryActorSprite); realSprite = new SingleSprite("testSprite"); parentGroup.addActor(realSprite.look); project.getDefaultScene().addSprite(realSprite); ProjectManager.getInstance().setProject(project); }
Source:
<code>public static VmDevice addManagedDevice(VmDeviceId id, VmDeviceType type, VmDeviceType device, Map<String, Object> specParams, boolean is_plugged, boolean isReadOnly, String address) { VmDevice managedDevice = addManagedDevice(id, type, device, specParams,is_plugged,isReadOnly); <START> if (!StringUtils.isEmpty(address)){ <END> managedDevice.setAddress(address); } return managedDevice; }</code><technical_language>please consider replacing StringUtils.isNotBlank - blanks a valid address</technical_language>

Target:
public static VmDevice addManagedDevice(VmDeviceId id, VmDeviceType type, VmDeviceType device, Map<String, Object> specParams, boolean is_plugged, boolean isReadOnly, String address) { VmDevice managedDevice = addManagedDevice(id, type, device, specParams,is_plugged,isReadOnly); if (StringUtils.isNotBlank(address)){ managedDevice.setAddress(address); } return managedDevice; }
Source:
<code>private void onStartupTaskCompleteListener() { if (mApi == null) { mApi = new RestApi(this, mConfig.getWebGuiUrl(), mConfig.getApiKey(), this::onApiAvailable, () -> onServiceStateChange(mCurrentState)); Log.i(TAG, "Web GUI will be available at " + mConfig.getWebGuiUrl()); } if (mSyncthingRunnable != null || mSyncthingRunnableThread != null) { Log.e(TAG, "onStartupTaskCompleteListener: Syncthing binary lifecycle violated"); return; } mSyncthingRunnable = new SyncthingRunnable(this, SyncthingRunnable.Command.main); mSyncthingRunnableThread = new Thread(mSyncthingRunnable); mSyncthingRunnableThread.start(); if (mPollWebGuiAvailableTask == null) { mPollWebGuiAvailableTask = new PollWebGuiAvailableTask( this, getWebGuiUrl(), mConfig.getApiKey(), result -> { Log.i(TAG, "Web GUI has come online at " + mConfig.getWebGuiUrl()); if (mApi != null) { mApi.readConfigFromRestApi(); } <START> }); <END> } return; }</code><technical_language>indentation is strange, do: new Foo(bar, baz, nuff, squeek -> { blah }); new Foo( bar, baz, nuf, squeek -> { faf(); } );</technical_language>

Target:
private void onStartupTaskCompleteListener() { if (mApi == null) { mApi = new RestApi(this, mConfig.getWebGuiUrl(), mConfig.getApiKey(), this::onApiAvailable, () -> onServiceStateChange(mCurrentState)); Log.i(TAG, "Web GUI will be available at " + mConfig.getWebGuiUrl()); } if (mSyncthingRunnable != null || mSyncthingRunnableThread != null) { Log.e(TAG, "onStartupTaskCompleteListener: Syncthing binary lifecycle violated"); return; } mSyncthingRunnable = new SyncthingRunnable(this, SyncthingRunnable.Command.main); mSyncthingRunnableThread = new Thread(mSyncthingRunnable); mSyncthingRunnableThread.start(); if (mPollWebGuiAvailableTask == null) { mPollWebGuiAvailableTask = new PollWebGuiAvailableTask( this, getWebGuiUrl(), mConfig.getApiKey(), result -> { Log.i(TAG, "Web GUI has come online at " + mConfig.getWebGuiUrl()); if (mApi != null) { mApi.readConfigFromRestApi(); } } ); } }
Source:
<code>public String whereIs(@CommandParam("entity id") long id) { Map<Long, EngineEntityPool> worldPoolMap = entityManager.getPoolMap(); if (worldPoolMap.containsKey(id)) { EngineEntityPool pool = worldPoolMap.get(id); for (Map.Entry<WorldInfo, EngineEntityPool> entry : entityManager.getWorldPoolsMap().entrySet()) { if (entry.getValue() == pool) { <START> return id + " is present in " + entry.getKey().getTitle(); <END> } } } return id + " not found"; }</code><technical_language>"Entity" + id</technical_language>

Target:
public String whereIs(@CommandParam("entity id") long id) { Map<Long, EngineEntityPool> worldPoolMap = entityManager.getPoolMap(); if (worldPoolMap.containsKey(id)) { EngineEntityPool pool = worldPoolMap.get(id); for (Map.Entry<WorldInfo, EngineEntityPool> entry : entityManager.getWorldPoolsMap().entrySet()) { if (entry.getValue() == pool) { return "Entity" + id + " is present in " + entry.getKey().getTitle(); } } } return "Entity" + id + " not found"; }
Source:
<code><START> @Override protected void after() { <END> tmp.delete(); }</code><technical_language>Scm api rules placement of annotations for methods</technical_language>

Target:
protected void after() { tmp.delete(); }
Source:
<code>public final void getStyles(Object element, StyleAccumulator accumulator) { <START> onGetStyles((E) element, accumulator); <END> mSuper.getStyles(element, accumulator); }</code><technical_language>is reason local styles super's styles? (instead of other around) ... if getAttributes, grabs super's attributes calls onGetAttributes ("local" attributes)</technical_language>

Target:
public final void getStyles(Object element, StyleAccumulator accumulator) { mSuper.getStyles(element, accumulator); onGetStyles((E) element, accumulator); }
Source:
<code>private static <E> E[] getArray(Class<E> clazz, List<?> baseList) { <START> E[] result = (E[]) Array.newInstance(clazz, baseList.size()); <END> for (int i = 0; i < baseList.size(); i++) { Array.set(result, i, (E) baseList.get(i)); } return (E[]) result; }</code><technical_language>This expensive. Is needed</technical_language>

Target:
private static <E> E[] getArray(Class<E> clazz, List<?> baseList) { final E[] result = (E[]) Array.newInstance(clazz, baseList.size()); for (int i = 0; i < baseList.size(); i++) { Array.set(result, i, (E) baseList.get(i)); } return (E[]) result; }
Source:
<code>public String getName() { <START> return MODULE; <END> }</code><technical_language>this constant is good... :) put string</technical_language>

Target:
public String getName() { return "logger"; }
Source:
<code>private void addSlab(int minimumSize) { this.currentSlabIndex += 1; int nextSlabSize; if (size == 0) { nextSlabSize = initialSize; <START> } else if (size > pageSize / 5) { <END> nextSlabSize = pageSize / 5; } else { nextSlabSize = size; } if (nextSlabSize < minimumSize) { if (Log.DEBUG) LOG.debug(format("slab size %,d too small for value of size %,d. Bumping up slab size", nextSlabSize, minimumSize)); nextSlabSize = minimumSize; } if (Log.DEBUG) LOG.debug(format("used %d slabs, new slab size %d", currentSlabIndex, nextSlabSize)); this.currentSlab = new byte[nextSlabSize]; this.slabs.add(currentSlab); this.capacity += nextSlabSize; this.currentSlabPosition = 0; }</code><technical_language>5 configurable too? CapacityByteArrayOutputStream abstract argument a slab size calculator etc. plug in behaviors here. do think</technical_language>

Target:
private void addSlab(int minimumSize) { int nextSlabSize; if (bytesUsed == 0) { nextSlabSize = initialSlabSize; } else if (bytesUsed > maxCapacityHint / 5) { nextSlabSize = maxCapacityHint / 5; } else { nextSlabSize = bytesUsed; } if (nextSlabSize < minimumSize) { if (Log.DEBUG) LOG.debug(format("slab size %,d too small for value of size %,d. Bumping up slab size", nextSlabSize, minimumSize)); nextSlabSize = minimumSize; } if (Log.DEBUG) LOG.debug(format("used %d slabs, adding new slab of size %d", slabs.size(), nextSlabSize)); this.currentSlab = new byte[nextSlabSize]; this.slabs.add(currentSlab); this.bytesAllocated += nextSlabSize; this.currentSlabIndex = 0; }
Source:
<code>public void testConfigurePipelineSchemaWithMissingInputNameField() throws Exception { Schema inputSchemaString = Schema.recordOf( "event", Schema.Field.of("CLF", Schema.of(Schema.Type.STRING)) ); MockPipelineConfigurer mockConfigurer = new MockPipelineConfigurer(inputSchemaString, ImmutableMap.of( CoreValidator.ID, new CoreValidator())); S3_TRANSFORM.configurePipeline(mockConfigurer); <START> Assert.assertEquals(1, mockConfigurer.getStageConfigurer().getFailureCollector().getValidationFailures().size()); <END> }</code><technical_language>assert attributes</technical_language>

Target:
public void testConfigurePipelineSchemaWithMissingInputNameField() throws Exception { Schema inputSchemaString = Schema.recordOf( "event", Schema.Field.of("CLF", Schema.of(Schema.Type.STRING)) ); MockPipelineConfigurer mockConfigurer = new MockPipelineConfigurer(inputSchemaString, ImmutableMap.of( CoreValidator.ID, new CoreValidator())); S3_TRANSFORM.configurePipeline(mockConfigurer); FailureCollector collector = mockConfigurer.getStageConfigurer().getFailureCollector(); Assert.assertEquals(1, collector.getValidationFailures().size()); Assert.assertEquals(1, collector.getValidationFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, "inputName"); Assert.assertEquals(expectedCause, collector.getValidationFailures().get(0).getCauses().get(0)); }
Source:
<code>public void testUploadBundleFromRepository() throws IOException, InterruptedException { Bundle[] bundlesBeforeUpload, bundlesAfterUpload; String uri = String.format("http://%s:%d/admin/api/bundles/upload/", HOST, PORT); HttpPost httpPost = new HttpPost(uri); MultipartEntityBuilder entity = MultipartEntityBuilder.create(); Charset chars = Charset.forName("UTF-8"); entity.setCharset(chars); entity.addTextBody("moduleSource", "Repository", ContentType.MULTIPART_FORM_DATA); entity.addTextBody("moduleId","org.motechproject:cms-lite:LATEST", ContentType.MULTIPART_FORM_DATA); entity.addTextBody("startBundle","on", ContentType.MULTIPART_FORM_DATA); httpPost.setEntity(entity.build()); bundlesBeforeUpload = bundleContext.getBundles(); HttpResponse response = getHttpClient().execute(httpPost); EntityUtils.consume(response.getEntity()); bundlesAfterUpload = bundleContext.getBundles(); <START> assertTrue(bundlesAfterUpload.length == bundlesBeforeUpload.length+1); <END> }</code><technical_language>spaces '1'</technical_language>

Target:
public void testUploadBundleFromRepository() throws IOException, InterruptedException { uploadBundle("Repository", "org.motechproject:cms-lite:LATEST", null, "on","org.motechproject.cms-lite"); }
Source:
<code>public void setLocation(Location location) { <START> if (hasPermissions()) { <END> return; } fusedLocationProviderClient.setMockLocation(location); }</code><technical_language>if permission</technical_language>

Target:
public void setLocation(Location location) { if (!hasPermissions()) { return; } if (!googleApiClient.isConnected()) { Log.d(TAG, "GoogleApiClient is not connected"); return; } fusedLocationProviderClient.setMockLocation(location); }
Source:
<code>public void testOffsetting() { SWTBotUtils.createProject(TEST_FOR_OFFSETTING); SWTBotUtils.openTrace(TEST_FOR_OFFSETTING, fLocation.getAbsolutePath(), "org.eclipse.linuxtools.tmf.core.tests.xmlstub"); SWTBotTreeItem treeItem = SWTBotUtils.selectTracesFolder(fBot, TEST_FOR_OFFSETTING); <START> final SWTWorkbenchBot bot = new SWTWorkbenchBot(); <END> SWTBotTable eventsTableBot = bot.activeEditor().bot().table(); String timestamp = eventsTableBot.cell(1, 1); assertEquals("19:00:00.000 000 000", timestamp); treeItem.select(); treeItem.getItems()[0].contextMenu("Apply Time Offset...").click(); SWTBotUtils.waitForJobs(); SWTBotShell shell = fBot.shell("Apply time offset"); shell.setFocus(); final SWTBot shellBot = shell.bot(); assertNotNull(shellBot); SWTBotTreeItem[] allItems = shellBot.tree().getAllItems(); final SWTBotTreeItem swtBotTreeItem = allItems[0]; swtBotTreeItem.select(); swtBotTreeItem.click(1); KeyStroke[] keyStrokes = new KeyStroke[1]; keyStrokes[0] = KeyStroke.getInstance('9'); swtBotTreeItem.pressShortcut(keyStrokes); keyStrokes[0] = KeyStroke.getInstance('9'); swtBotTreeItem.pressShortcut(keyStrokes); keyStrokes[0] = KeyStroke.getInstance(SWT.CR); swtBotTreeItem.pressShortcut(keyStrokes); SWTBotUtils.waitForJobs(); shellBot.button("OK").click(); SWTBotUtils.openTrace(TEST_FOR_OFFSETTING, fLocation.getAbsolutePath(), "org.eclipse.linuxtools.tmf.core.tests.xmlstub"); SWTBotUtils.waitForJobs(); timestamp = eventsTableBot.cell(1, 1); assertEquals("19:00:00.000 000 000", timestamp); }</code><technical_language>fBot here</technical_language>

Target:
public void testOffsetting() { SWTBotUtils.createProject(PROJET_NAME); SWTBotUtils.openTrace(PROJET_NAME, fLocation.getAbsolutePath(), "org.eclipse.linuxtools.tmf.core.tests.xmlstub"); SWTBotTreeItem treeItem = SWTBotUtils.selectTracesFolder(fBot, PROJET_NAME); SWTBotTable eventsTableBot = fBot.activeEditor().bot().table(); String timestamp = eventsTableBot.cell(1, 1); assertEquals("19:00:00.000 000 000", timestamp); treeItem.select(); treeItem.getItems()[0].contextMenu("Apply Time Offset...").click(); SWTBotUtils.waitForJobs(); SWTBotShell shell = fBot.shell("Apply time offset"); shell.setFocus(); SWTBotTreeItem[] allItems = fBot.tree().getAllItems(); final SWTBotTreeItem swtBotTreeItem = allItems[0]; swtBotTreeItem.select(); swtBotTreeItem.click(1); KeyStroke[] keyStrokes = new KeyStroke[1]; keyStrokes[0] = KeyStroke.getInstance('9'); swtBotTreeItem.pressShortcut(keyStrokes); keyStrokes[0] = KeyStroke.getInstance('9'); swtBotTreeItem.pressShortcut(keyStrokes); keyStrokes[0] = KeyStroke.getInstance(SWT.CR); swtBotTreeItem.pressShortcut(keyStrokes); SWTBotUtils.waitForJobs(); fBot.button("OK").click(); SWTBotUtils.openTrace(PROJET_NAME, fLocation.getAbsolutePath(), "org.eclipse.linuxtools.tmf.core.tests.xmlstub"); SWTBotUtils.waitForJobs(); timestamp = eventsTableBot.cell(1, 1); assertEquals("19:00:00.000 000 000", timestamp); SWTBotUtils.deleteProject(PROJET_NAME, fBot); }
Source:
<code>private void testTimeout() throws Exception { String url = getURL("connectionPool", true), user = getUser(); String password = getPassword(); final JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password); man.setLoginTimeout(1); createClassProxy(man.getClass()); assertThrows(IllegalArgumentException.class, man). setMaxConnections(-1); man.setMaxConnections(2); Task t = new Task() { @Override public void call() { while (!stop) { man.setMaxConnections(1); man.setMaxConnections(2); } } }; t.execute(); long time = System.nanoTime(); Connection conn2 = null; <START> try (Connection conn = man.getConnection()) { <END> conn2 = man.getConnection(); man.getConnection(); fail(); } catch (SQLException e) { if (conn2 != null) { conn2.close(); } assertContains(e.toString().toLowerCase(), "timeout"); time = System.nanoTime() - time; assertTrue("timeout after " + TimeUnit.NANOSECONDS.toMillis(time) + " ms", time > TimeUnit.SECONDS.toNanos(1)); } finally { t.get(); } man.dispose(); }</code><technical_language>no, this getConnection call needs t.execute</technical_language>

Target:
private void testTimeout() throws Exception { String url = getURL("connectionPool", true), user = getUser(); String password = getPassword(); final JdbcConnectionPool man = JdbcConnectionPool.create(url, user, password); man.setLoginTimeout(1); createClassProxy(man.getClass()); assertThrows(IllegalArgumentException.class, man). setMaxConnections(-1); man.setMaxConnections(2); Connection conn = man.getConnection(); Task t = new Task() { @Override public void call() { while (!stop) { man.setMaxConnections(1); man.setMaxConnections(2); } } }; t.execute(); long time = System.nanoTime(); Connection conn2 = null; try { conn2 = man.getConnection(); man.getConnection(); fail(); } catch (SQLException e) { if (conn2 != null) { conn2.close(); } assertContains(e.toString().toLowerCase(), "timeout"); time = System.nanoTime() - time; assertTrue("timeout after " + TimeUnit.NANOSECONDS.toMillis(time) + " ms", time > TimeUnit.SECONDS.toNanos(1)); } finally { conn.close(); t.get(); } man.dispose(); }
Source:
<code>private Type(String name) { <START> this.name = name; <END> }</code><technical_language>Modifier 'private' is redundant for Enum constructor - needs removed</technical_language>

Target:
Type(String name) { this.name = name; }
Source:
<code><START> public static @Nullable Pattern getPatternForBuild(@Nonnull AbstractBuild<?, ?> build) { <END> if (secretsForBuild.containsKey(build)) { return Pattern.compile(MultiBinding.getSecretForStrings(secretsForBuild.get(build)).getPlainText()); } else { return null; } }</code><technical_language>@CheckForNull</technical_language>

Target:
public static @CheckForNull Pattern getPatternForBuild(@Nonnull AbstractBuild<?, ?> build) { if (secretsForBuild.containsKey(build)) { return Pattern.compile(MultiBinding.getPatternStringForSecrets(secretsForBuild.get(build))); } else { return null; } }
Source:
<code>private Map<String, ResourceAssignment> partialRebalance( ResourceControllerDataProvider clusterData, Map<HelixConstants.ChangeType, Set<String>> clusterChanges, Map<String, Resource> resourceMap, final CurrentStateOutput currentStateOutput) throws HelixRebalanceException { LOG.info("Start calculating the new best possible assignment."); Map<String, ResourceAssignment> currentBaseline = getBaselineAssignment(_assignmentMetadataStore, currentStateOutput, resourceMap.keySet()); Map<String, ResourceAssignment> currentBestPossibleAssignment = getBestPossibleAssignment(_assignmentMetadataStore, currentStateOutput, resourceMap.keySet()); Map<String, ResourceAssignment> newAssignment = calculateAssignment(clusterData, clusterChanges, resourceMap, clusterData.getEnabledLiveInstances(), currentBaseline, currentBestPossibleAssignment); try { _assignmentMetadataStore.persistBestPossibleAssignment(newAssignment); } catch (Exception ex) { throw new HelixRebalanceException("Failed to persist the new best possible assignment.", HelixRebalanceException.Type.INVALID_REBALANCER_STATUS, ex); } LOG.info("Finish calculating the new best possible assignment."); <START> return newAssignment; <END> }</code><technical_language>is currentStateOutput for? I</technical_language>

Target:
private Map<String, ResourceAssignment> partialRebalance( ResourceControllerDataProvider clusterData, Map<HelixConstants.ChangeType, Set<String>> clusterChanges, Map<String, Resource> resourceMap, final CurrentStateOutput currentStateOutput) throws HelixRebalanceException { LOG.info("Start calculating the new best possible assignment."); Map<String, ResourceAssignment> currentBaseline = getBaselineAssignment(_assignmentMetadataStore, currentStateOutput, resourceMap.keySet()); Map<String, ResourceAssignment> currentBestPossibleAssignment = getBestPossibleAssignment(_assignmentMetadataStore, currentStateOutput, resourceMap.keySet()); Map<String, ResourceAssignment> newAssignment = calculateAssignment(clusterData, clusterChanges, resourceMap, clusterData.getEnabledLiveInstances(), currentBaseline, currentBestPossibleAssignment); if (_assignmentMetadataStore != null) { try { _assignmentMetadataStore.persistBestPossibleAssignment(newAssignment); } catch (Exception ex) { throw new HelixRebalanceException("Failed to persist the new best possible assignment.", HelixRebalanceException.Type.INVALID_REBALANCER_STATUS, ex); } } else { LOG.debug("Assignment Metadata Store is empty. Skip persist the baseline assignment."); } LOG.info("Finish calculating the new best possible assignment."); return newAssignment; }
Source:
<code>public void onCreate() { super.onCreate(); VialerApplication.get().component().inject(this); AudioStateChangeReceiver.fetch(); mHandler = new Handler(); mToneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, SipConstants.RINGING_VOLUME); mSipBroadcaster = new SipBroadcaster(this); mPreferences = new Preferences(this); mLogger = new Logger(SipService.class); mNativeCallManager = new NativeCallManager((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)); mLogger.d("onCreate"); IntentFilter filter = new IntentFilter(); filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); registerReceiver(phoneStateReceiver, filter); <START> IntentFilter networkFilter = new IntentFilter(); <END> networkFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mNetworkSwitch, networkFilter); mCheckServiceHandler = new Handler(); mCheckServiceRunnable = new Runnable() { @Override public void run() { checkServiceBeingUsed(); mCheckServiceHandler.postDelayed(this, CHECK_SERVICE_USER_INTERVAL_MS); } }; mCheckServiceHandler.postDelayed(mCheckServiceRunnable, CHECK_SERVICE_USER_INTERVAL_MS); PhoneAccount phoneAccount = new JsonStorage<PhoneAccount>(this).get(PhoneAccount.class); if (phoneAccount != null) { mSipConfig = mSipConfig.init(this, phoneAccount); mSipConfig.initLibrary(this); } else { mLogger.w("No sip account when trying to create service"); stopSelf(); } }</code><technical_language>I created a BroadcastReceiverManager class handling listeners easier, in AbstractCallActivity. Update SIP service new class, changing registerReceiver() unregisterReceiver() methods instead</technical_language>

Target:
public void onCreate() { super.onCreate(); VialerApplication.get().component().inject(this); AudioStateChangeReceiver.fetch(); mHandler = new Handler(); mToneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, SipConstants.RINGING_VOLUME); mSipBroadcaster = new SipBroadcaster(this); mPreferences = new Preferences(this); mLogger = new Logger(SipService.class); mNativeCallManager = new NativeCallManager((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)); mLogger.d("onCreate"); mBroadcastReceiverManager.registerReceiverViaGlobalBroadcastManager(phoneStateReceiver, TelephonyManager.ACTION_PHONE_STATE_CHANGED); mBroadcastReceiverManager.registerReceiverViaGlobalBroadcastManager(mNetworkConnectivity, ConnectivityManager.CONNECTIVITY_ACTION); mCheckServiceHandler = new Handler(); mCheckServiceRunnable = new Runnable() { @Override public void run() { checkServiceBeingUsed(); mCheckServiceHandler.postDelayed(this, CHECK_SERVICE_USER_INTERVAL_MS); } }; mCheckServiceHandler.postDelayed(mCheckServiceRunnable, CHECK_SERVICE_USER_INTERVAL_MS); PhoneAccount phoneAccount = new JsonStorage<PhoneAccount>(this).get(PhoneAccount.class); if (phoneAccount != null) { mSipConfig = mSipConfig.init(this, phoneAccount); mSipConfig.initLibrary(this); } else { mLogger.w("No sip account when trying to create service"); stopSelf(); } }
Source:
<code>private void setVotingMembers() { if (LOG.isDebugEnabled()) LOG.debug("Setting voting and non-voting members of replica set: {}", name); boolean seenPrimary = !primary.isPresent(); String expectedPrimary = primary.isPresent() ? primary.get().getHostText() + ":" + primary.get().getPort() : ""; int setSize = this.members.size(); int votingMembers = Math.min(setSize % 2 == 0 ? setSize - 1 : setSize, MAXIMUM_VOTING_MEMBERS); for (Object member : this.members) { if (member instanceof BasicBSONObject) { BasicBSONObject bsonObject = BasicBSONObject.class.cast(member); String host = bsonObject.getString("host"); if (this.primary.isPresent() && expectedPrimary.equals(host)) { bsonObject.put("votes", 1); --votingMembers; seenPrimary = true; if (LOG.isDebugEnabled()) LOG.debug("Voting member (primary) of set {}: {}", name, host); } else if (votingMembers-- > 0) { bsonObject.put("votes", 1); if (LOG.isDebugEnabled()) LOG.debug("Voting member of set {}: {}", name, host); } else { bsonObject.put("votes", 0); if (LOG.isDebugEnabled()) LOG.debug("Non-voting member of set {}: {}", name, host); } } else { LOG.error("Unexpected entry in replica set members list: " + member); } } <START> if (!seenPrimary) { <END> LOG.warn("Cannot give replica set primary a vote in reconfigured set: " + "primary was indicated as but no member with that host and port was seen in the set.", this.primary); } }</code><technical_language>strong feelings, done if (primary.isPresent() && !seenPrimary) setting seenPrimary true start if a primary</technical_language>

Target:
private void setVotingMembers() { if (LOG.isDebugEnabled()) LOG.debug("Setting voting and non-voting members of replica set: {}", name); boolean seenPrimary = false; String expectedPrimary = primary.isPresent() ? primary.get().getHostText() + ":" + primary.get().getPort() : ""; int setSize = this.members.size(); int nonPrimaryVotingMembers = Math.min(setSize % 2 == 0 ? setSize - 1 : setSize, MAXIMUM_VOTING_MEMBERS); if (primary.isPresent()) { if (LOG.isTraceEnabled()) LOG.trace("Reserving vote for primary: " + expectedPrimary); nonPrimaryVotingMembers -= 1; } for (Object member : this.members) { if (member instanceof BasicBSONObject) { BasicBSONObject bsonObject = BasicBSONObject.class.cast(member); String host = bsonObject.getString("host"); if (this.primary.isPresent() && expectedPrimary.equals(host)) { bsonObject.put("votes", 1); seenPrimary = true; if (LOG.isDebugEnabled()) LOG.debug("Voting member (primary) of set {}: {}", name, host); } else if (nonPrimaryVotingMembers-- > 0) { bsonObject.put("votes", 1); if (LOG.isDebugEnabled()) LOG.debug("Voting member of set {}: {}", name, host); } else { bsonObject.put("votes", 0); if (LOG.isDebugEnabled()) LOG.debug("Non-voting member of set {}: {}", name, host); } } else { LOG.error("Unexpected entry in replica set members list: " + member); } } if (primary.isPresent() && !seenPrimary) { LOG.warn("Cannot give replica set primary a vote in reconfigured set: " + "primary was indicated as but no member with that host and port was seen in the set. " + "The replica set now has an even number of voters.", this.primary); } }
Source:
<code>public void retrieveItems() throws IOException { String input = "{\"items\":{" <START> + "\"egg-1\":{\"id\":\"egg-1\",\"type\": \"food\",\"name\":\"egg\",\"description\":\"A nice egg\"," <END> + "\"position\":\"mouth\"," + "\"properties\":{\"weight\":1,\"value\":3,\"health\":2}}," + "\"milk-bottle\":{\"id\":\"milk-bottle\",\"type\": \"food-liquid\",\"name\":\"milk\",\"description\":\"Milk in a bottle\"," + "\"position\":\"mouth\"," + "\"properties\":{\"weight\":1,\"value\":10,\"health\":5}}" + "}}"; JsonReader jsonReader = new JsonReader(new StringReader(input)); ItemRepository itemRepo = new ItemRepository(); itemRepo.retrieve(jsonReader); Item eggItem = itemRepo.getItem("egg-1"); assertEquals("A nice egg", eggItem.getDescription()); Item milkItem = itemRepo.getItem("milk-bottle"); assertEquals("Milk in a bottle", milkItem.getDescription()); }</code><technical_language>ID match standard. fegg1</technical_language>

Target:
public void retrieveItems() throws IOException { String input = "{\"items\":{" + "\"fegg1\":{\"id\":\"fegg1\",\"type\": \"food\",\"name\":\"egg\",\"description\":\"A nice egg\"," + "\"position\":\"mouth\"," + "\"properties\":{\"weight\":1,\"value\":3,\"health\":2}}," + "\"fmil1\":{\"id\":\"fmil1\",\"type\": \"food-liquid\",\"name\":\"milk\",\"description\":\"Milk in a bottle\"," + "\"position\":\"mouth\"," + "\"properties\":{\"weight\":1,\"value\":10,\"health\":5}}" + "}}"; JsonReader jsonReader = new JsonReader(new StringReader(input)); ItemRepository itemRepo = new ItemRepository(); itemRepo.retrieve(jsonReader); Item eggItem = itemRepo.getItem("fegg1"); assertEquals("A nice egg", eggItem.getDescription()); Item milkItem = itemRepo.getItem("fmil1"); assertEquals("Milk in a bottle", milkItem.getDescription()); }
Source:
<code>public ItemLockableDataProcessor() { <START> super(t -> true, Keys.LOCK_TOKEN); <END> }</code><technical_language>this require item is a tile entity typed item provide a TileEntityLockable</technical_language>

Target:
public ItemLockableDataProcessor() { super(stack -> { Item item = stack.getItem(); return item.equals(Item.getItemFromBlock(Blocks.chest)) || item.equals(Item.getItemFromBlock(Blocks.furnace)) || item.equals(Item.getItemFromBlock(Blocks.lit_furnace)) || item.equals(Item.getItemFromBlock(Blocks.dispenser)) || item.equals(Item.getItemFromBlock(Blocks.dropper)) || item.equals(Item.getItemFromBlock(Blocks.hopper)) || item.equals(Item.getItemFromBlock(Blocks.brewing_stand)) || item.equals(Item.getItemFromBlock(Blocks.beacon)); }, Keys.LOCK_TOKEN); }
Source:
<code>static <T> T checkNotNull(T object, String message, Object... args) { <START> if (args.length > 0) message = String.format(message, args); <END> if (object == null) throw new NullPointerException(message); return object; }</code><technical_language>need format message object is null</technical_language>

Target:
static <T> T checkNotNull(T object, String message, Object... args) { if (object == null) { throw new NullPointerException(String.format(message, args)); } return object; }
Source:
<code>public void checkInputs(List inputs) throws IllegalArgumentException { Object[] list = inputs.toArray(); if (list.length < 2) <START> throw new IllegalArgumentException("requires more than two inputs"); <END> Function function = null; if (list[0] instanceof Function) { function = (Function) (list[0]); } else { throw new IllegalArgumentException("first arg to higher-order " + " function must be a function"); } if (!function.getReturnType().toString().equals(BooleanAttribute.identifier)) throw new IllegalArgumentException("higher-order function must " + "use a boolean function"); List<Evaluatable> bagArgs = new ArrayList(); List<Evaluatable> args = new ArrayList(); for (int i = 1; i < list.length; i++) { Evaluatable eval = (Evaluatable) (list[i]); if (eval.returnsBag()) { bagArgs.add(eval); } else { args.add(eval); } } if (functionId == ID_ALL_OF || functionId == ID_ANY_OF) { if (bagArgs.size() != 1) { throw new IllegalArgumentException("Only one argument SHALL be a bag of a primitive data-type for " + getIdentifier()); } for (Evaluatable arg : args) { List<Evaluatable> inputForCheck = new ArrayList(); inputForCheck.add(arg); inputForCheck.addAll(bagArgs); function.checkInputsNoBag(inputForCheck); } } else { if (args.size() > 0 && bagArgs.size() > 0) { throw new IllegalArgumentException("The arguments can be are either primitive data types or " + "bags of primitive types. " + getIdentifier()); } if (args.size() > 0) { validateAnyOfAnyInput(args, function); } else { validateAnyOfAnyInput(bagArgs, function); } } }</code><technical_language>introduce if line</technical_language>

Target:
public void checkInputs(List inputs) throws IllegalArgumentException { Object[] list = inputs.toArray(); if (list.length < 2) { throw new IllegalArgumentException("requires more than two inputs"); } Function function; if (list[0] instanceof Function) { function = (Function) (list[0]); } else { throw new IllegalArgumentException("first arg to higher-order " + " function must be a function"); } if (!function.getReturnType().toString().equals(BooleanAttribute.identifier)) throw new IllegalArgumentException("higher-order function must " + "use a boolean function"); List<Evaluatable> bagArgs = new ArrayList(); List<Evaluatable> args = new ArrayList(); for (int i = 1; i < list.length; i++) { Evaluatable eval = (Evaluatable) (list[i]); if (eval.returnsBag()) { bagArgs.add(eval); } else { args.add(eval); } } if (functionId == ID_ALL_OF || functionId == ID_ANY_OF) { if (bagArgs.size() != 1) { throw new IllegalArgumentException("Only one argument SHALL be a bag of a primitive data-type for " + getIdentifier()); } for (Evaluatable arg : args) { List<Evaluatable> inputForCheck = new ArrayList(); inputForCheck.add(arg); inputForCheck.addAll(bagArgs); function.checkInputsNoBag(inputForCheck); } } else { if (!args.isEmpty() && !bagArgs.isEmpty()) { throw new IllegalArgumentException("The arguments can be are either primitive data types or " + "bags of primitive types. " + getIdentifier()); } if (!args.isEmpty()) { validateAnyOfAnyInput(args, function); } else { validateAnyOfAnyInput(bagArgs, function); } } }
Source:
<code>private Metrics buildAppMetrics(final double sampleLoss, final double regLoss, final double accuracy, final double elapsedTime, final int numInstances) { final Map<CharSequence, Double> appMetricMap = new HashMap<>(); <START> appMetricMap.put(MetricKeys.NUM_INSTANCES, (double) numInstances); <END> appMetricMap.put(MetricKeys.SAMPLE_LOSS_AVG, sampleLoss); appMetricMap.put(MetricKeys.REG_LOSS_AVG, regLoss); appMetricMap.put(MetricKeys.ACCURACY, accuracy); appMetricMap.put(MetricKeys.DVT, numInstances / elapsedTime); return Metrics.newBuilder() .setData(appMetricMap) .build(); }</code><technical_language>number of processed instances is in [L467](<LINK_0> remove it</technical_language>

Target:
private Metrics buildAppMetrics(final double sampleLoss, final double regLoss, final double accuracy, final double elapsedTime, final int numInstances) { final Map<CharSequence, Double> appMetricMap = new HashMap<>(); appMetricMap.put(MetricKeys.SAMPLE_LOSS_AVG, sampleLoss); appMetricMap.put(MetricKeys.REG_LOSS_AVG, regLoss); appMetricMap.put(MetricKeys.ACCURACY, accuracy); appMetricMap.put(MetricKeys.DVT, numInstances / elapsedTime); return Metrics.newBuilder() .setData(appMetricMap) .build(); }
Source:
<code>protected void thingDiscovered(DiscoveryResult discoveryResult) { <START> discoveryResult.discoveredBy(this.getClass().getName()); <END> for (DiscoveryListener discoveryListener : discoveryListeners) { try { discoveryListener.thingDiscovered(this, discoveryResult); } catch (Exception e) { logger.error("An error occurred while calling the discovery listener " + discoveryListener.getClass().getName() + ".", e); } } synchronized (cachedResults) { cachedResults.put(discoveryResult.getThingUID(), discoveryResult); } }</code><technical_language>Is this right place set this property? all, DiscoveryResult interface defines potential implementors feel obliged fill (before passing here). I this point, passed instance treated immutable (otherwise added property interface all, internal implementation builder creates). some safe guard check is set (and do nothing) if is set, try set it, catch exceptions</technical_language>

Target:
protected void thingDiscovered(DiscoveryResult discoveryResult) { for (DiscoveryListener discoveryListener : discoveryListeners) { try { discoveryListener.thingDiscovered(this, discoveryResult); } catch (Exception e) { logger.error("An error occurred while calling the discovery listener " + discoveryListener.getClass().getName() + ".", e); } } synchronized (cachedResults) { cachedResults.put(discoveryResult.getThingUID(), discoveryResult); } }