auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testGroupByFloatColumnWithExFn() { <START> if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { <END> return; } String jsFn = "function(str) { return 'super-' + str; }"; ExtractionFn jsExtractionFn = new JavaScriptExtractionFn(jsFn, false, JavaScriptConfig.getDefault()); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec("index", "index_alias", jsExtractionFn))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults; expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", "super-158.74722290039062", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", "super-166.01605224609375", "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }</code><technical_language>Please expectedException skipping test</technical_language>

Target:
public void testGroupByFloatColumnWithExFn() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("GroupBy v1 does not support dimension selectors with unknown cardinality."); } String jsFn = "function(str) { return 'super-' + str; }"; ExtractionFn jsExtractionFn = new JavaScriptExtractionFn(jsFn, false, JavaScriptConfig.getDefault()); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec("index", "index_alias", jsExtractionFn))) .setDimFilter(new SelectorDimFilter("quality", "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults; expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "index_alias", "super-158.74722290039062", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "index_alias", "super-166.01605224609375", "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }
Source:
<code>public void beforeClass(final @Optional String testType) throws IOException { <START> if (testType.equals("buckets")) { <END> throw new SkipException("Directory tests will be skipped in Manta Buckets"); } ConfigContext config = new IntegrationTestConfigContext(); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }</code><technical_language>testType null, invert equals() check so: java if ("buckets".equals(testType)) {</technical_language>

Target:
public void beforeClass(final @Optional String testType) throws IOException { if ("buckets".equals(testType)) { throw new SkipException("Directory tests will be skipped in Manta Buckets"); } ConfigContext config = new IntegrationTestConfigContext(); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }
Source:
<code>public ZeppelinServer() throws Exception { ZeppelinConfiguration conf = ZeppelinConfiguration.create(); this.depResolver = new DependencyResolver( conf.getString(ConfVars.ZEPPELIN_INTERPRETER_LOCALREPO)); this.helium = new Helium(conf.getHeliumConfPath(), conf.getHeliumDefaultLocalRegistryPath()); this.heliumApplicationFactory = new HeliumApplicationFactory(); this.schedulerFactory = new SchedulerFactory(); this.replFactory = new InterpreterFactory(conf, notebookWsServer, notebookWsServer, heliumApplicationFactory, depResolver, SecurityUtils.isAuthenticated()); this.notebookRepo = new NotebookRepoSync(conf); this.noteSearchService = new LuceneSearch(); this.notebookAuthorization = NotebookAuthorization.init(conf); this.credentials = new Credentials(conf.credentialsPersist(), conf.getCredentialsPath()); notebook = new Notebook(conf, notebookRepo, schedulerFactory, replFactory, notebookWsServer, noteSearchService, notebookAuthorization, credentials); heliumApplicationFactory.setNotebook(notebook); heliumApplicationFactory.setApplicationEventListener(notebookWsServer); notebook.addNotebookEventListener(heliumApplicationFactory); notebook.addNotebookEventListener(notebookWsServer.getNotebookInformationListener()); remoteWorksManager = new RemoteWorksManager(notebook); <START> replFactory.setRemoteController(remoteWorksManager.getInstance()); <END> }</code><technical_language>remoteWorksManager.getInstance() is invoked only, else. means need singleton pattern here</technical_language>

Target:
public ZeppelinServer() throws Exception { ZeppelinConfiguration conf = ZeppelinConfiguration.create(); this.depResolver = new DependencyResolver( conf.getString(ConfVars.ZEPPELIN_INTERPRETER_LOCALREPO)); this.helium = new Helium(conf.getHeliumConfPath(), conf.getHeliumDefaultLocalRegistryPath()); this.heliumApplicationFactory = new HeliumApplicationFactory(); this.schedulerFactory = new SchedulerFactory(); this.replFactory = new InterpreterFactory(conf, notebookWsServer, notebookWsServer, heliumApplicationFactory, depResolver, SecurityUtils.isAuthenticated()); this.notebookRepo = new NotebookRepoSync(conf); this.noteSearchService = new LuceneSearch(); this.notebookAuthorization = NotebookAuthorization.init(conf); this.credentials = new Credentials(conf.credentialsPersist(), conf.getCredentialsPath()); notebook = new Notebook(conf, notebookRepo, schedulerFactory, replFactory, notebookWsServer, noteSearchService, notebookAuthorization, credentials); heliumApplicationFactory.setNotebook(notebook); heliumApplicationFactory.setApplicationEventListener(notebookWsServer); notebook.addNotebookEventListener(heliumApplicationFactory); notebook.addNotebookEventListener(notebookWsServer.getNotebookInformationListener()); }
Source:
<code>public void setup() throws MalformedURLException, NotFoundException { MockitoAnnotations.initMocks(this); singleURL = new URL("<LINK_0>"); multipURL = new URL("<LINK_2>"); otherURL = new URL("<LINK_1>"); singleComPatch = new Patch(singleId, singleURL, null, null, null); multipComPatch = new Patch(multipId, multipURL, null, null, null); otherStatPatch = new Patch(otherId, otherURL, null, null, null); org.mockito.Mockito.when(aphrodite.getCommitStatusFromPatch(singleComPatch)).thenReturn(CommitStatus.SUCCESS); org.mockito.Mockito.when(aphrodite.getCommitStatusFromPatch(multipComPatch)).thenReturn(CommitStatus.SUCCESS); org.mockito.Mockito.when(aphrodite.getCommitStatusFromPatch(otherStatPatch)).thenReturn(CommitStatus.FAILURE); <START> } <END></code><technical_language>Is a need for full package name here</technical_language>

Target:
public void setup() throws MalformedURLException, NotFoundException { MockitoAnnotations.initMocks(this); singleURL = new URL("<LINK_0>"); multipURL = new URL("<LINK_2>"); otherURL = new URL("<LINK_1>"); singleComPatch = new Patch(singleId, singleURL, null, null, null); multipComPatch = new Patch(multipId, multipURL, null, null, null); otherStatPatch = new Patch(otherId, otherURL, null, null, null); when(aphrodite.getCommitStatusFromPatch(singleComPatch)).thenReturn(CommitStatus.SUCCESS); when(aphrodite.getCommitStatusFromPatch(multipComPatch)).thenReturn(CommitStatus.SUCCESS); when(aphrodite.getCommitStatusFromPatch(otherStatPatch)).thenReturn(CommitStatus.FAILURE); }
Source:
<code>public void testCreateExternalS3FileHandleFromExistingFile() throws Exception { assertNotNull(imageFile); assertTrue(imageFile.exists()); String md5 = MD5ChecksumHelper.getMD5Checksum(imageFile); String baseKey = "integration-test/IT049FileHandleTest/testCreateExternalS3FileHandleFromExistingFile/" + UUID.randomUUID().toString(); String key = baseKey + FILE_NAME; uploadOwnerTxtToS3(config.getS3Bucket(), baseKey, synapse.getUserProfile(userToDelete.toString()).getUserName()); synapseS3Client.putObject(config.getS3Bucket(), key, imageFile); <START> <END> ExternalS3StorageLocationSetting storageLocationSetting = new ExternalS3StorageLocationSetting(); storageLocationSetting.setBucket(config.getS3Bucket()); storageLocationSetting.setBaseKey(baseKey); storageLocationSetting.setUploadType(UploadType.S3); storageLocationSetting = synapse.createStorageLocationSetting(storageLocationSetting); S3FileHandle fh = new S3FileHandle(); fh.setStorageLocationId(storageLocationSetting.getStorageLocationId()); fh.setBucketName(config.getS3Bucket()); fh.setKey(key); fh.setContentMd5(md5); S3FileHandle result = synapse.createExternalS3FileHandle(fh); assertNotNull(result); toDelete.add(result); assertNotNull(result.getFileName()); }</code><technical_language>object necessarily exist in S3 time client returns putObject() call. other cases in putObject() is called wait for object continuing</technical_language>

Target:
public void testCreateExternalS3FileHandleFromExistingFile() throws Exception { assertNotNull(imageFile); assertTrue(imageFile.exists()); String md5 = MD5ChecksumHelper.getMD5Checksum(imageFile); String baseKey = "integration-test/IT049FileHandleTest/testCreateExternalS3FileHandleFromExistingFile/" + UUID.randomUUID().toString(); String key = baseKey + FILE_NAME; uploadOwnerTxtToS3(config.getS3Bucket(), baseKey, synapse.getUserProfile(userToDelete.toString()).getUserName()); putToS3WaitForConsistency(config.getS3Bucket(), key, imageFile); ExternalS3StorageLocationSetting storageLocationSetting = new ExternalS3StorageLocationSetting(); storageLocationSetting.setBucket(config.getS3Bucket()); storageLocationSetting.setBaseKey(baseKey); storageLocationSetting.setUploadType(UploadType.S3); storageLocationSetting = synapse.createStorageLocationSetting(storageLocationSetting); S3FileHandle fh = new S3FileHandle(); fh.setStorageLocationId(storageLocationSetting.getStorageLocationId()); fh.setBucketName(config.getS3Bucket()); fh.setKey(key); fh.setContentMd5(md5); S3FileHandle result = synapse.createExternalS3FileHandle(fh); assertNotNull(result); toDelete.add(result); assertNotNull(result.getFileName()); }
Source:
<code>private void loadUrlInWebView() { if (mWebView != null) { ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService( Activity.CONNECTIVITY_SERVICE); if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) { showHideWebView(true); loadValidUrl(); } else { showHideWebView(false); mErrorDemoText.setText( <START> translate(R.string.erro_page_text)); <END> } } }</code><technical_language>translateText</technical_language>

Target:
private void loadUrlInWebView() { if (mWebView != null) { ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService( Activity.CONNECTIVITY_SERVICE); if (cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) { showHideWebView(true); loadValidUrl(); } else { showHideWebView(false); mErrorDemoText.setTextTranslation(R.string.erro_page_text); } } }
Source:
<code>public void testSingletonFlatbushXY() { <START> List<Rectangle> items = new ArrayList<>(); <END> items.add(new Rectangle(0, 10, 1, 11)); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); assertEquals(findIntersections(rtree, new Rectangle(1, 11, 2, 12)), items); assertEquals(findIntersections(rtree, new Rectangle(11, 1, 12, 2)), ImmutableList.of()); }</code><technical_language>ImmutableList.of List<Rectangle> items = ImmutableList.of((new Rectangle(0, 10, 1, 11));</technical_language>

Target:
public void testSingletonFlatbushXY() { List<Rectangle> items = ImmutableList.of(new Rectangle(0, 10, 1, 11)); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); assertEquals(findIntersections(rtree, new Rectangle(1, 11, 2, 12)), items); assertEquals(findIntersections(rtree, new Rectangle(11, 1, 12, 2)), ImmutableList.of()); }
Source:
<code>public static void checkLabelsInDiagramToolBar(SWTBotSiriusDiagramEditor editor, String toolTip, List<String> labelsToCheck) { if (labelsToCheck.isEmpty()) { return; } final SWTBotToolbarDropDownButton toolMenuButton = editor.bot().toolbarDropDownButtonWithTooltip(toolTip); List<? extends SWTBotMenu> menuItems = toolMenuButton.menuItems(WidgetMatcherFactory.widgetOfType(MenuItem.class)); SWTBotMenu menuItemRef = null; for (SWTBotMenu menuItem : menuItems) { if (labelsToCheck.contains(menuItem.getText())) { labelsToCheck.remove(menuItem.getText()); menuItemRef = menuItem; } } Assert.assertTrue("The following menu items have not been found in the " + toolTip + " toolBars contribution : " + labelsToCheck, labelsToCheck.isEmpty()); <START> if (menuItemRef != null) { menuItemRef.click(); } <END> try { toolMenuButton.pressShortcut(KeyStroke.getInstance("ESC")); } catch (ParseException e) { throw new RuntimeException(e); } }</code><technical_language>Strangely, this part test fail Linux (as enables filter, hides a diagram element needed for rest of test), Windows. push a version this, work Linux (tested me) Windows (tested Jessy)</technical_language>

Target:
public static void checkLabelsInDiagramToolBar(SWTBotSiriusDiagramEditor editor, String toolTip, List<String> labelsToCheck) { if (labelsToCheck.isEmpty()) { return; } final SWTBotToolbarDropDownButton toolMenuButton = editor.bot().toolbarDropDownButtonWithTooltip(toolTip); List<? extends SWTBotMenu> menuItems = toolMenuButton.menuItems(WidgetMatcherFactory.widgetOfType(MenuItem.class)); for (SWTBotMenu menuItem : menuItems) { if (labelsToCheck.contains(menuItem.getText())) { labelsToCheck.remove(menuItem.getText()); } } Assert.assertTrue("The following menu items have not been found in the " + toolTip + " toolBars contribution : " + labelsToCheck, labelsToCheck.isEmpty()); try { toolMenuButton.pressShortcut(KeyStroke.getInstance("ESC")); } catch (ParseException e) { throw new RuntimeException(e); } }
Source:
<code><START> Pair<StreamProcessor, MetadataStore> createStreamProcessor(Config config, ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc, <END> StreamProcessor.StreamProcessorLifecycleListenerFactory listenerFactory, Optional<ExternalContext> externalContextOptional, MetadataStore coordinatorStreamStore) { TaskFactory taskFactory = TaskFactoryUtil.getTaskFactory(appDesc); Map<String, MetricsReporter> reporters = new HashMap<>(); String processorId = createProcessorId(new ApplicationConfig(config), getClass().getClassLoader()); appDesc.getMetricsReporterFactories().forEach((name, factory) -> reporters.put(name, factory.getMetricsReporter(name, processorId, config))); StreamProcessor streamProcessor = new StreamProcessor(processorId, config, reporters, taskFactory, appDesc.getApplicationContainerContextFactory(), appDesc.getApplicationTaskContextFactory(), externalContextOptional, listenerFactory, null, coordinatorStreamStore); return ImmutablePair.of(streamProcessor, coordinatorStreamStore); }</code><technical_language>curious. 1. passing in metadata store a argument this API returning caller of API again? prefer remove MetadataStore result of this API if sense. 2. Also, please note LocalApplicationRunner current state manage a life-cycle of stream processor. For more details, please exit of stream processors handled in LocalApplicationRunner</technical_language>

Target:
StreamProcessor createStreamProcessor(Config config, ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc, StreamProcessor.StreamProcessorLifecycleListenerFactory listenerFactory, Optional<ExternalContext> externalContextOptional, MetadataStore coordinatorStreamStore) { TaskFactory taskFactory = TaskFactoryUtil.getTaskFactory(appDesc); Map<String, MetricsReporter> reporters = new HashMap<>(); String processorId = createProcessorId(new ApplicationConfig(config), getClass().getClassLoader()); appDesc.getMetricsReporterFactories().forEach((name, factory) -> reporters.put(name, factory.getMetricsReporter(name, processorId, config))); StreamProcessor streamProcessor = new StreamProcessor(processorId, config, reporters, taskFactory, appDesc.getApplicationContainerContextFactory(), appDesc.getApplicationTaskContextFactory(), externalContextOptional, listenerFactory, null, coordinatorStreamStore); return streamProcessor; }
Source:
<code><START> public void annotationEndpointTestForError() throws URISyntaxException { <END> String url = "/v2/variants/13:32889669:C:T/annotations?species=mmusculus&assembly=grcm38&" + "annot-vep-version=1"; assertEquals("Please specify either both annotation VEP version and annotation VEP cache version, " + "or neither", testForErrorHelper(url)); }</code><technical_language>Add another assert for case cache version is provided VEP version is not</technical_language>

Target:
public void annotationEndpointTestForError() throws URISyntaxException { String url = "/v2/variants/13:32889669:C:T/annotations?species=mmusculus&assembly=grcm38&" + "annot-vep-version=1"; assertEquals("Please specify either both annotation VEP version and annotation VEP cache version, " + "or neither", testForErrorHelper(url)); url = "/v2/variants/13:32889669:C:T/annotations?species=mmusculus&assembly=grcm38&" + "annot-vep-cache-version=1"; assertEquals("Please specify either both annotation VEP version and annotation VEP cache version, " + "or neither", testForErrorHelper(url)); }
Source:
<code>public SchemaCompatibilityResult getCompatibility( final Schema reader, final Schema writer ) { <START> Stack<String> location = new Stack<String>(); <END> return getCompatibility(ROOT_REFERENCE_TOKEN, reader, writer, location); }</code><technical_language>avoid Stack here? I is subclass of Vector, synchronized accessor methods, in this case I thread-safe classes is needed here. I some implementation of Dequeue interface instead</technical_language>

Target:
public SchemaCompatibilityResult getCompatibility( final Schema reader, final Schema writer ) { Deque<String> location = new ArrayDeque<String>(); return getCompatibility(ROOT_REFERENCE_TOKEN, reader, writer, location); }
Source:
<code>private void writeToZip(Path currentPath, ZipArchiveOutputStream zipStream, Path projectPath) throws IOException { log.trace("Writing to zip", currentPath); String name = projectPath.getParent().relativize(currentPath).toString(); <START> name = FilenameUtils.separatorsToUnix(name); <END> if (Files.isDirectory(currentPath)) { log.trace("{} is a directory", currentPath); name += "/"; } ZipArchiveEntry entry = new ZipArchiveEntry(name); zipStream.putArchiveEntry(entry); if (Files.isRegularFile(currentPath)) { log.trace("{} is a regular file, copying bytes", currentPath); FileUtils.copyFile(currentPath.toFile(), zipStream); log.trace("Done copying bytes"); } log.trace("Closing entry"); zipStream.closeArchiveEntry(); }</code><technical_language>In Unix-based systems is legal \-characters in filename. want accidentally interpret path separators. I prefer implementation I proposed earlier</technical_language>

Target:
private void writeToZip(Path currentPath, ZipArchiveOutputStream zipStream, Path projectPath) throws IOException { log.trace("Writing to zip", currentPath); Path relativePath = projectPath.getParent().relativize(currentPath); String name = relativePathToZipCompliantName(relativePath, Files.isDirectory(currentPath)); ZipArchiveEntry entry = new ZipArchiveEntry(name); zipStream.putArchiveEntry(entry); if (Files.isRegularFile(currentPath)) { log.trace("{} is a regular file, copying bytes", currentPath); FileUtils.copyFile(currentPath.toFile(), zipStream); log.trace("Done copying bytes"); } log.trace("Closing entry"); zipStream.closeArchiveEntry(); }
Source:
<code>public void performance() { CurveBuildingBlockBundle emptyBlock = new CurveBuildingBlockBundle(); long startTime, endTime; final int nbTest = 100; startTime = System.currentTimeMillis(); for (int looptest = 0; looptest < nbTest; looptest++) { <START> makeCurvesFromDefinitions(DEFINITIONS_UNITS[0], GENERATORS_UNITS[0], NAMES_UNITS[0], MULTICURVE_KNOWN_DATA, emptyBlock, PSMQDC, PSMQCSDC, false); <END> } endTime = System.currentTimeMillis(); System.out.println("MulticurveBuildingDiscountingDiscountEUR3Test - " + nbTest + " curve construction / 3 units: " + (endTime - startTime) + " ms"); startTime = System.currentTimeMillis(); for (int looptest = 0; looptest < nbTest; looptest++) { makeCurvesFromDefinitions(DEFINITIONS_UNITS[1], GENERATORS_UNITS[1], NAMES_UNITS[1], MULTICURVE_KNOWN_DATA, emptyBlock, PSMQDC, PSMQCSDC, false); } endTime = System.currentTimeMillis(); System.out.println("MulticurveBuildingDiscountingDiscountEUR3Test - " + nbTest + " curve construction / 1 unit: " + (endTime - startTime) + " ms"); }</code><technical_language>Line length</technical_language>

Target:
public void performance() { CurveBuildingBlockBundle emptyBlock = new CurveBuildingBlockBundle(); long startTime, endTime; int nbTest = 100; startTime = System.currentTimeMillis(); for (int looptest = 0; looptest < nbTest; looptest++) { makeCurvesFromDefinitions(DEFINITIONS_UNITS[0], GENERATORS_UNITS[0], NAMES_UNITS[0], MULTICURVE_KNOWN_DATA, emptyBlock, PSMQDC, PSMQCSDC, false); } endTime = System.currentTimeMillis(); System.out.println("MulticurveBuildingDiscountingDiscountEUR3Test - " + nbTest + " curve construction / 3 units: " + (endTime - startTime) + " ms"); startTime = System.currentTimeMillis(); for (int looptest = 0; looptest < nbTest; looptest++) { makeCurvesFromDefinitions(DEFINITIONS_UNITS[1], GENERATORS_UNITS[1], NAMES_UNITS[1], MULTICURVE_KNOWN_DATA, emptyBlock, PSMQDC, PSMQCSDC, false); } endTime = System.currentTimeMillis(); System.out.println("MulticurveBuildingDiscountingDiscountEUR3Test - " + nbTest + " curve construction / 1 unit: " + (endTime - startTime) + " ms"); }
Source:
<code>public Builder withReceiverSection(String receiverSection) { feedbackAttributes.receiverSection = receiverSection == null <START> ? "None" <END> : receiverSection; return this; }</code><technical_language>Is a constant for this</technical_language>

Target:
public Builder withReceiverSection(String receiverSection) { frca.receiverSection = receiverSection == null ? Const.DEFAULT_SECTION : receiverSection; return this; }
Source:
<code>public void detected() { JavaCheckVerifier.verify("src/test/files/checks/SynchronizedClassUsageCheck.java", new SynchronizedClassUsageCheck()); <START> JavaCheckVerifier.verify("src/test/files/checks/SynchronizedClassUsageByAPICheck.java", new SynchronizedClassUsageCheck()); <END> }</code><technical_language>Consider adding verifyNoIssueWithoutSemantic</technical_language>

Target:
public void detected() { JavaCheckVerifier.verifyNoIssueWithoutSemantic("src/test/files/checks/SynchronizedClassUsageCheck.java", new SynchronizedClassUsageCheck()); JavaCheckVerifier.verify("src/test/files/checks/SynchronizedClassUsageCheck.java", new SynchronizedClassUsageCheck()); JavaCheckVerifier.verify("src/test/files/checks/SynchronizedClassUsageByAPICheck.java", new SynchronizedClassUsageCheck()); }
Source:
<code>private RecordReader<Group> readParquetFile(VirtualFile parquetFile, InputStream parquetFileStream) throws TranslatorException { try { File localFile = createTempFile(parquetFileStream); Path path = new Path(localFile.toURI()); String extension = getExtension(localFile.getName()); <START> if (extension != "parquet") { <END> throw new TranslatorException(ParquetPlugin.Event.TEIID23000, ParquetPlugin.Util.gs(ParquetPlugin.Event.TEIID23000)); } Configuration config = new Configuration(); reader = ParquetFileReader.open(HadoopInputFile.fromPath(path, config)); schema = reader.getFooter().getFileMetaData().getSchema(); columnIO = new ColumnIOFactory().getColumnIO(schema); PageReadStore pages = reader.readNextRowGroup(); return columnIO.getRecordReader(pages, new GroupRecordConverter(schema)); } catch (IOException e){ throw new TranslatorException(e); } }</code><technical_language>equals !=</technical_language>

Target:
private RecordReader<Group> readParquetFile(VirtualFile parquetFile, InputStream parquetFileStream) throws TranslatorException { try { if(this.visitor.getTable().getProperty(ParquetMetadataProcessor.PARTITIONED_COLUMNS) != null) { partitionedColumnsValue = getPartitionedColumnsValues(parquetFile); } File localFile = createTempFile(parquetFileStream); Path path = new Path(localFile.toURI()); Configuration config = new Configuration(); FilterCompat.Filter rowGroupFilter = getRowGroupFilter(this.visitor.getColumnPredicates()); reader = ParquetFileReader.open(HadoopInputFile.fromPath(path, config), ParquetReadOptions.builder().withRecordFilter(rowGroupFilter).build()); schema = reader.getFooter().getFileMetaData().getSchema(); filteredSchema = getFilteredSchema(schema, this.visitor.getProjectedColumnNames()); columnIO = new ColumnIOFactory().getColumnIO(filteredSchema); PageReadStore pages = reader.readNextRowGroup(); pageRowCount = pages.getRowCount(); return columnIO.getRecordReader(pages, new GroupRecordConverter(filteredSchema), rowGroupFilter); } catch (IOException e){ throw new TranslatorException(e); } }
Source:
<code>public void testGetAccountByIdBothSuccess() { <START> Account testAccount = getTestAccount(); <END> when(primaryAccountService.getAccountById(anyShort())).thenReturn(testAccount); when(secondaryAccountService.getAccountById(anyShort())).thenReturn(testAccount); assertEquals("Unexpected response", testAccount, compositeAccountService.getAccountById(testAccount.getId())); verify(primaryAccountService).getAccountById(testAccount.getId()); verify(secondaryAccountService).getAccountById(testAccount.getId()); assertEquals("Expected zero inconsistency", 0, metrics.getAccountDataInconsistencyCount.getCount()); }</code><technical_language>getTestAccount() is called in places method instantiates account/container times. a global testAccount</technical_language>

Target:
public void testGetAccountByIdBothSuccess() { when(primaryAccountService.getAccountById(anyShort())).thenReturn(testAccount); when(secondaryAccountService.getAccountById(anyShort())).thenReturn(testAccount); assertEquals("Unexpected response", testAccount, compositeAccountService.getAccountById(testAccount.getId())); verify(primaryAccountService).getAccountById(testAccount.getId()); verify(secondaryAccountService).getAccountById(testAccount.getId()); assertEquals("Expected zero inconsistency", 0, metrics.accountDataInconsistencyCount.getCount()); }
Source:
<code>private BlockingTimeoutException logAndHandleTimeout(LockRequestSpecification specification) { final String logMessage = "Lock service timed out after milliseconds" + " when servicing for client \"{}\""; log.info(logMessage, SafeArg.of("timeoutDurationMillis", blockingTimeLimitMillis), SafeArg.of("method", specification.method()), <START> UnsafeArg.of("client", specification.client()), <END> UnsafeArg.of("lockRequest", specification.lockRequest())); String errorMessage = String.format( logMessage.replace("{}", "%s"), blockingTimeLimitMillis, specification.method(), specification.client()); return new BlockingTimeoutException(errorMessage); }</code><technical_language>do consider clients Unsafe? discuss internally this is extremely useful information sensitive IMO</technical_language>

Target:
private BlockingTimeoutException logAndHandleTimeout(LockRequestSpecification specification) { final String logMessage = "Lock service timed out after milliseconds" + " when servicing for client \"{}\""; log.info(logMessage, SafeArg.of("timeoutDurationMillis", blockingTimeLimitMillis), SafeArg.of("method", specification.method()), SafeArg.of("client", specification.client()), UnsafeArg.of("lockRequest", specification.lockRequest())); String errorMessage = String.format( logMessage.replace("{}", "%s"), blockingTimeLimitMillis, specification.method(), specification.client()); return new BlockingTimeoutException(errorMessage); }
Source:
<code>public void requestPasswordReset_shouldCreateUserActivationKeyGivenEmail() throws Exception { <START> User u = new User(); <END> u.setPerson(new Person()); u.addName(new PersonName("Benjamin", "A", "Wolfe")); u.setUsername("bwolfe"); u.setEmail("bwolf@gmail.com"); u.getPerson().setGender("M"); User createdUser = userService.createUser(u, "Openmr5xy"); assertNull(dao.getLoginCredential(createdUser).getActivationKey()); assertEquals(createdUser, userService.setUserActivationKey(createdUser)); handle(newPostRequest(RESET_PASSWORD_URI, "{\"usernameOrEmail\":\"" + "bwolfe@gmail.com" + "\"}")); assertNotNull(dao.getLoginCredential(createdUser).getActivationKey()); }</code><technical_language>existing user</technical_language>

Target:
public void requestPasswordReset_shouldCreateUserActivationKeyGivenEmail() throws Exception { User u = userService.getUserByUuid("c98a1558-e131-11de-babe-001e378eb67e"); u.setEmail("butch@gmail.com"); assertNull(dao.getLoginCredential(u).getActivationKey()); handle(newPostRequest(RESET_PASSWORD_URI, "{\"usernameOrEmail\":\"" + u.getEmail() + "\"}")); assertNotNull(dao.getLoginCredential(u).getActivationKey()); }
Source:
<code>private static File extractBaseDirectory(SMInputCursor sources, File defaultBaseDirectory) throws XMLStreamException { SMInputCursor source = sources.childElementCursor("source"); while (source.getNext() != null) { String path = source.collectDescendantText(); if (!StringUtils.isBlank(path)) { File baseDirectory = new File(path); if (!baseDirectory.isDirectory()) { <START> throw new XMLStreamException("Invalid directory path in 'source' element: " + path); <END> } return baseDirectory; } } return defaultBaseDirectory; }</code><technical_language>Throwing exception analysis fail in setups currently work well. I log a warning</technical_language>

Target:
private static File extractBaseDirectory(SMInputCursor sources, File defaultBaseDirectory) throws XMLStreamException { SMInputCursor source = sources.childElementCursor("source"); while (source.getNext() != null) { String path = source.collectDescendantText(); if (!StringUtils.isBlank(path)) { File baseDirectory = new File(path); if (baseDirectory.isDirectory()) { return baseDirectory; } else { LOG.warn("Invalid directory path in 'source' element: {}", path); } } } return defaultBaseDirectory; }
Source:
<code>public Response signup(@FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("email")String email, @FormParam("message")String message) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebAppForbiddenException(); } CourseSignup entity = courseService.signup(courseId, components, email, message); <START> ResponseBuilder builder = new ResponseBuilderImpl(); <END> builder.status(201); builder.entity(entity); return builder.build(); }</code><technical_language>Is need tie application Jersey? Response.status(Response.Status.CREATED) accomplish thing</technical_language>

Target:
public Response signup(@FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("email")String email, @FormParam("message")String message) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebAppForbiddenException(); } CourseSignup entity = courseService.signup(courseId, components, email, message); ResponseBuilder builder = Response.status(Response.Status.CREATED); builder.status(201); builder.entity(entity); return builder.build(); }
Source:
<code>protected void executeCommand() { ManagedBlockStorage managedBlockStorage = cinderStorageDao.get(getParameters().getStorageDomainId()); CinderlibReturnValue returnValue; List<String> extraParams = new ArrayList<>(); extraParams.add(getParameters().getDiskId().toString()); try { CinderlibCommandParameters params = new CinderlibCommandParameters( JsonHelper.mapToJson(managedBlockStorage.getDriverOptions(), false), extraParams); returnValue = cinderlibExecutor.runCommand(CinderlibExecutor.CinderlibCommand.DELETE_VOLUME, params); <START> if (!returnValue.getSucceed()) { setSucceeded(false); return; } ManagedBlockStorageDisk disk = new ManagedBlockStorageDisk(); disk.setId(getParameters().getDiskId()); disk.setImageId(getParameters().getDiskId()); removeDiskFromDb(disk); <END> } catch (Exception e) { log.error("Failed to remove volume: {}", e); setSucceeded(false); return; } setSucceeded(true); }</code><technical_language>related try block</technical_language>

Target:
protected void executeCommand() { ManagedBlockStorage managedBlockStorage = cinderStorageDao.get(getParameters().getStorageDomainId()); List<String> extraParams = new ArrayList<>(); extraParams.add(getParameters().getDiskId().toString()); CinderlibReturnValue returnValue; try { CinderlibCommandParameters params = new CinderlibCommandParameters( JsonHelper.mapToJson(managedBlockStorage.getDriverOptions(), false), extraParams); returnValue = cinderlibExecutor.runCommand(CinderlibExecutor.CinderlibCommand.DELETE_VOLUME, params); } catch (Exception e) { log.error("Failed to remove volume: {}", e); return; } if (!returnValue.getSucceed()) { return; } removeDiskFromDb(); setSucceeded(true); }
Source:
<code>public void shouldFindByFile() throws Exception { RulesetService rulesetService = new RulesetService(); <START> JSONObject ruleset = rulesetService.findByFile("ruleset_slubhh.xml"); <END> JSONObject jsonObject = (JSONObject) ruleset.get("_source"); String actual = (String) jsonObject.get("file"); String expected = "ruleset_slubhh.xml"; assertEquals("Ruleset was not found in index!", expected, actual); }</code><technical_language>rename slubdd slubhh? ruleset_test, in other place, is</technical_language>

Target:
public void shouldFindByFile() throws Exception { RulesetService rulesetService = new RulesetService(); JSONObject ruleset = rulesetService.findByFile("ruleset_test.xml"); JSONObject jsonObject = (JSONObject) ruleset.get("_source"); String actual = (String) jsonObject.get("file"); String expected = "ruleset_test.xml"; assertEquals("Ruleset was not found in index!", expected, actual); }
Source:
<code>private boolean isPlatformExtern(String filePath, String symbolName) { <START> if (emittedPlatformSymbols.contains(symbolName)) return false; <END> if (filePath.startsWith("externs.zip String fileName = Iterables.getLast(Splitter.on("/").split(filePath)); switch (fileName) { case "chrome.js": case "deprecated.js": case "fetchapi.js": case "fileapi.js": case "flash.js": case "google.js": case "html5.js": case "intl.js": case "iphone.js": case "mediakeys.js": case "mediasource.js": case "page_visibility.js": case "streamapi.js": case "url.js": case "v8.js": case "webgl.js": case "webstorage.js": case "whatwg_encoding.js": case "window.js": return true; } return fileName.startsWith("es") || filePath.startsWith("gecko_") || filePath.startsWith("w3c_") || filePath.startsWith("ie_") || filePath.startsWith("webkit_"); }</code><technical_language>I calling this platformSymbolsMissingInTypeScript more sense me</technical_language>

Target:
private boolean isPlatformExtern(String filePath, String symbolName) { if (platformSymbolsMissingInTypeScript.contains(symbolName)) return false; if (filePath.startsWith("externs.zip String fileName = new File(filePath).getName(); return platformExternsFilenames.contains(fileName) || fileName.startsWith("es") || fileName.startsWith("gecko_") || fileName.startsWith("w3c_") || fileName.startsWith("ie_") || fileName.startsWith("webkit_"); }
Source:
<code>private String httpGet(String url) { LOGGER.debug("Sending get to: {}",url); HttpGet get = new HttpGet(url); try { CloseableHttpResponse httpResponse = httpClient.execute(get); int statusCode = httpResponse.getStatusLine().getStatusCode(); String responseAsString = EntityUtils.toString(httpResponse.getEntity()); if (statusCode != 200) { String errorMessage = String.format("Retrieving of primes failed with http status %s body %s", statusCode, responseAsString); LOGGER.info(errorMessage); throw new PrimeFailedException(errorMessage); } <START> LOGGER.info("Received response from scassandra {}", responseAsString); <END> return responseAsString; } catch (IOException e) { LOGGER.info("Retrieving failed", e); throw new PrimeFailedException("Retrieving of primes failed.", e); } }</code><technical_language>change this info info level more noisy</technical_language>

Target:
private String httpGet(String url) { LOGGER.debug("Sending get to: {}",url); HttpGet get = new HttpGet(url); try { CloseableHttpResponse httpResponse = httpClient.execute(get); int statusCode = httpResponse.getStatusLine().getStatusCode(); String responseAsString = EntityUtils.toString(httpResponse.getEntity()); if (statusCode != 200) { String errorMessage = String.format("Retrieving of primes failed with http status %s body %s", statusCode, responseAsString); LOGGER.info(errorMessage); throw new PrimeFailedException(errorMessage); } LOGGER.debug("Received response from scassandra {}", responseAsString); return responseAsString; } catch (IOException e) { LOGGER.info("Retrieving failed", e); throw new PrimeFailedException("Retrieving of primes failed.", e); } }
Source:
<code>public void setRollbackOnly() { if ( !isActive() ) { if ( jpaCompliance.isJpaTransactionComplianceEnabled() ) { throw new IllegalStateException( "JPA compliance dictates throwing IllegalStateException when #setRollbackOnly " + "is called on non-active transaction" ); } <START> else if ( LOG.isDebugEnabled() ) { <END> LOG.debug( "#setRollbackOnly called on a not-active transaction" ); } } else { markRollbackOnly(); } }</code><technical_language>wrt "logging protection"</technical_language>

Target:
public void setRollbackOnly() { if ( !isActive() ) { if ( jpaCompliance.isJpaTransactionComplianceEnabled() ) { throw new IllegalStateException( "JPA compliance dictates throwing IllegalStateException when #setRollbackOnly " + "is called on non-active transaction" ); } else { LOG.debug( "#setRollbackOnly called on a not-active transaction" ); } } else { markRollbackOnly(); } }
Source:
<code>public void close() throws IOException { <START> synchronized (this) <END> { while (mCookieUsers > 0) { try { this.wait(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } mCookieUsers = -1; } if (mCookie != null) { if (closeDexFile(mCookie)) { mCookie = null; } } }</code><technical_language>This smells a bit a reader/writer lock. if in java.util.concurrent more efficient</technical_language>

Target:
public void close() throws IOException { mCookieLock.close(); synchronized (this) { if (mCookie != null) { if (closeDexFile(mCookie)) { mCookie = null; } } } }
Source:
<code>protected boolean canAddVm(ArrayList<String> reasons, Collection<StorageDomain> destStorages) { VmStatic vmStaticFromParams = getParameters().getVmStaticData(); boolean returnValue = canAddVm(reasons, vmStaticFromParams.getName(), getStoragePoolId(), vmStaticFromParams.getPriority()); if (returnValue) { List<ValidationError> validationErrors = validateCustomProperties(vmStaticFromParams); if (!validationErrors.isEmpty()) { VmPropertiesUtils.getInstance().handleCustomPropertiesError(validationErrors, reasons); returnValue = false; } } if (returnValue && shouldCheckSpaceInStorageDomains()) { if (!getStoragePoolId().equals(getStoragePoolIdFromSourceImageContainer())) { reasons.add(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_MATCH.toString()); returnValue = false; } else { for (StorageDomain domain : destStorages) { StorageDomainValidator storageDomainValidator = new StorageDomainValidator(domain); if (!validate(storageDomainValidator.isDomainWithinThresholds()) || !validate(storageDomainValidator.isDomainHasSpaceForRequest(getNeededDiskSize(domain.getId())))) { return false; } <START> if (!validate(storageDomainValidator.isDomainExistAndActive())) { <END> return false; } } } } if (returnValue) { returnValue = isDedicatedVdsOnSameCluster(vmStaticFromParams); } return returnValue; }</code><technical_language>Move this previous check - point in checking space for inactive domain</technical_language>

Target:
protected boolean canAddVm(ArrayList<String> reasons, Collection<StorageDomain> destStorages) { VmStatic vmStaticFromParams = getParameters().getVmStaticData(); boolean returnValue = canAddVm(reasons, vmStaticFromParams.getName(), getStoragePoolId(), vmStaticFromParams.getPriority()); if (returnValue) { List<ValidationError> validationErrors = validateCustomProperties(vmStaticFromParams); if (!validationErrors.isEmpty()) { VmPropertiesUtils.getInstance().handleCustomPropertiesError(validationErrors, reasons); returnValue = false; } } if (returnValue && shouldCheckSpaceInStorageDomains()) { if (!getStoragePoolId().equals(getStoragePoolIdFromSourceImageContainer())) { reasons.add(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_MATCH.toString()); returnValue = false; } else { for (StorageDomain domain : destStorages) { StorageDomainValidator storageDomainValidator = new StorageDomainValidator(domain); if (!validate(storageDomainValidator.isDomainExistAndActive())) { return false; } if (!validate(storageDomainValidator.isDomainWithinThresholds()) || !validate(storageDomainValidator.isDomainHasSpaceForRequest(getNeededDiskSize(domain.getId())))) { return false; } } } } if (returnValue) { returnValue = isDedicatedVdsOnSameCluster(vmStaticFromParams); } return returnValue; }
Source:
<code>protected boolean checkAndInitializeSdk(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { <START> log( DEBUG, "Initializing AppLovin rewarded video..." ); <END> if ( !initialized ) { AppLovinSdk.initializeSdk( activity ); AppLovinSdk.getInstance( activity ).setPluginVersion( "MoPub-Certified-2.1.0" ); initialized = true; return true; } return false; }</code><technical_language>MoPubLog</technical_language>

Target:
protected boolean checkAndInitializeSdk(@NonNull final Activity activity, @NonNull final Map<String, Object> localExtras, @NonNull final Map<String, String> serverExtras) throws Exception { log( DEBUG, "Initializing AppLovin rewarded video..." ); if ( !initialized ) { AppLovinSdk.initializeSdk( activity ); AppLovinSdk.getInstance( activity ).setPluginVersion( "MoPub-Certified-2.1.0" ); AppLovinIncentivizedInterstitial incentivizedInterstitial = AppLovinIncentivizedInterstitial.create( activity ); incentivizedInterstitial.preload( null ); GLOBAL_INCENTIVIZED_INTERSTITIAL_ADS.put( DEFAULT_ZONE, incentivizedInterstitial ); initialized = true; return true; } return false; }
Source:
<code>public PlanNodeCostEstimate visitRowNumber(RowNumberNode node, Void context) { List<Symbol> symbols = node.getOutputSymbols(); if (!node.getMaxRowCountPerPartition().isPresent()) { symbols = ImmutableList.<Symbol>builder() .addAll(node.getPartitionBy()) .add(node.getRowNumberSymbol()) .build(); } <START> return cpuCost(getStats(node).getOutputSizeInBytes(symbols, types)); <END> }</code><technical_language>memory requirements</technical_language>

Target:
public PlanNodeCostEstimate visitRowNumber(RowNumberNode node, Void context) { List<Symbol> symbols = node.getOutputSymbols(); if (!node.getMaxRowCountPerPartition().isPresent()) { symbols = ImmutableList.<Symbol>builder() .addAll(node.getPartitionBy()) .add(node.getRowNumberSymbol()) .build(); } PlanNodeStatsEstimate stats = getStats(node); double cpuCost = stats.getOutputSizeInBytes(symbols, types); double memoryCost = node.getPartitionBy().isEmpty() ? 0 : stats.getOutputSizeInBytes(node.getSource().getOutputSymbols(), types); return new PlanNodeCostEstimate(cpuCost, memoryCost, 0); }
Source:
<code>protected List<Artifact> resolveArtifacts(List<Map<String, Object>> manualTriggerArtifacts) { List<Artifact> resolvedArtifacts = new ArrayList<>(); for (Map a : manualTriggerArtifacts) { Artifact artifact = objectMapper.convertValue(a, Artifact.class); if (Strings.isNullOrEmpty(artifact.getName()) || Strings.isNullOrEmpty(artifact.getVersion()) || Strings.isNullOrEmpty(artifact.getLocation())) { log.error("Artifact does not have enough information to fetch. " + "Artifact must contain name, version, and location."); } else { try { Artifact resolvedArtifact = artifactInfoService.get() .getArtifactByVersion(artifact.getLocation(), artifact.getName(), artifact.getVersion()); <START> if (resolvedArtifact != null) { <END> resolvedArtifacts.add(resolvedArtifact); } } catch (NotFoundException e) { log.error("Artifact " + artifact.getName() + " " + artifact.getVersion() + " not found in image provider " + artifact.getLocation()); } } } return resolvedArtifacts; }</code><technical_language>safer leave this guarding, getArtifactByVersion return null (instead of throwing NotFoundException caught below)</technical_language>

Target:
protected List<Artifact> resolveArtifacts(List<Map<String, Object>> manualTriggerArtifacts) { List<Artifact> resolvedArtifacts = new ArrayList<>(); for (Map a : manualTriggerArtifacts) { Artifact artifact = objectMapper.convertValue(a, Artifact.class); if (Strings.isNullOrEmpty(artifact.getName()) || Strings.isNullOrEmpty(artifact.getVersion()) || Strings.isNullOrEmpty(artifact.getLocation())) { log.error("Artifact does not have enough information to fetch. " + "Artifact must contain name, version, and location."); resolvedArtifacts.add(artifact); } else { try { Artifact resolvedArtifact = artifactInfoService.get() .getArtifactByVersion(artifact.getLocation(), artifact.getName(), artifact.getVersion()); resolvedArtifacts.add(resolvedArtifact); } catch (RetrofitError e) { if (e.getResponse() != null && e.getResponse().getStatus() == HttpStatus.NOT_FOUND.value()) { log.error("Artifact " + artifact.getName() + " " + artifact.getVersion() + " not found in image provider " + artifact.getLocation()); resolvedArtifacts.add(artifact); } else throw e; } } } return resolvedArtifacts; }