auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private File generateSegment(File outputDir) throws Exception { TableConfig tableConfig = JsonUtils.fileToObject(new File(_tableConfigFileName), TableConfig.class); _tableName = tableConfig.getTableName(); Schema schema = JsonUtils.fileToObject(new File(_schemaFileName), Schema.class); RecordReaderConfig recordReaderConfig = RecordReaderFactory.getRecordReaderConfig(DEFAULT_FILE_FORMAT, _recordReaderConfigFileName); SegmentGeneratorConfig segmentGeneratorConfig = new SegmentGeneratorConfig(tableConfig, schema); segmentGeneratorConfig.setInputFilePath(_inputDataFileName); segmentGeneratorConfig.setFormat(DEFAULT_FILE_FORMAT); segmentGeneratorConfig.setOutDir(outputDir.getAbsolutePath()); segmentGeneratorConfig.setReaderConfig(recordReaderConfig); segmentGeneratorConfig.setTableName(_tableName); segmentGeneratorConfig.setSegmentName(_segmentName); SegmentIndexCreationDriver driver = new SegmentIndexCreationDriverImpl(); driver.init(segmentGeneratorConfig); driver.build(); <START> String segmentName = driver.getSegmentName(); <END> File indexDir = new File(outputDir, segmentName); LOGGER.info("Successfully created segment: at directory: {}", segmentName, indexDir); File segmentTarFile = new File(outputDir, segmentName + TarGzCompressionUtils.TAR_GZ_FILE_EXTENSION); TarGzCompressionUtils.createTarGzFile(indexDir, segmentTarFile); LOGGER.info("Tarring segment from: to: {}", indexDir, segmentTarFile); return segmentTarFile; }</code><technical_language>do this? Wy _segmentName</technical_language>

Target:
private File generateSegment(File outputDir) throws Exception { TableConfig tableConfig = JsonUtils.fileToObject(new File(_tableConfigFileName), TableConfig.class); _tableName = tableConfig.getTableName(); Schema schema = JsonUtils.fileToObject(new File(_schemaFileName), Schema.class); RecordReaderConfig recordReaderConfig = RecordReaderFactory.getRecordReaderConfig(DEFAULT_FILE_FORMAT, _recordReaderConfigFileName); SegmentGeneratorConfig segmentGeneratorConfig = new SegmentGeneratorConfig(tableConfig, schema); segmentGeneratorConfig.setInputFilePath(_inputDataFileName); segmentGeneratorConfig.setFormat(DEFAULT_FILE_FORMAT); segmentGeneratorConfig.setOutDir(outputDir.getAbsolutePath()); segmentGeneratorConfig.setReaderConfig(recordReaderConfig); segmentGeneratorConfig.setTableName(_tableName); segmentGeneratorConfig.setSegmentName(_segmentName); SegmentIndexCreationDriver driver = new SegmentIndexCreationDriverImpl(); driver.init(segmentGeneratorConfig); driver.build(); File indexDir = new File(outputDir, _segmentName); LOGGER.info("Successfully created segment: at directory: {}", _segmentName, indexDir); File segmentTarFile = new File(outputDir, _segmentName + TarGzCompressionUtils.TAR_GZ_FILE_EXTENSION); TarGzCompressionUtils.createTarGzFile(indexDir, segmentTarFile); LOGGER.info("Tarring segment from: to: {}", indexDir, segmentTarFile); return segmentTarFile; }
Source:
<code>public static RowKind fromByteValue(byte value) { switch (value) { case 0: return INSERT; case 1: return UPDATE_BEFORE; case 2: return UPDATE_AFTER; case 3: return DELETE; default: throw new UnsupportedOperationException( <START> "Do not support to parse byte value " + value + " to RowKind."); <END> } }</code><technical_language>nit: Unsupported byte ' + + ' for row kind</technical_language>

Target:
public static RowKind fromByteValue(byte value) { switch (value) { case 0: return INSERT; case 1: return UPDATE_BEFORE; case 2: return UPDATE_AFTER; case 3: return DELETE; default: throw new UnsupportedOperationException( "Unsupported byte value '" + value + "' for row kind."); } }
Source:
<code>public FileBasedConfig openJGitConfig(Config parent, FS fs) { Path jgitConfigPath = Paths.get(getXDGConfigHome(fs), <START> ".config", "jgit", "config"); END> return new FileBasedConfig(parent, jgitConfigPath.toFile(), fs); }</code><technical_language>* git-for-windows rely XDG_CONFIG_HOME Windows (implementation of function is in path.c). I if is a bug. I a Windows system environment variable is set :-) OK, Windows, too; fallback</technical_language>

Target:
public FileBasedConfig openJGitConfig(Config parent, FS fs) { Path xdgPath = getXDGConfigHome(fs); if (xdgPath != null) { Path configPath = null; try { configPath = xdgPath.resolve("jgit"); Files.createDirectories(configPath); configPath = configPath.resolve(Constants.CONFIG); return new FileBasedConfig(parent, configPath.toFile(), fs); } catch (IOException e) { LOG.error(JGitText.get().createJGitConfigFailed, configPath, e); } } return new FileBasedConfig(parent, new File(fs.userHome(), ".jgitconfig"), fs); }
Source:
<code>private Xpp3Dom getLibertyPluginConfig() { Plugin libertyPlugin = getLibertyPluging(); <START> Xpp3Dom overrides = configuration(element(name("looseApplication"), "true")); <END> return getPluginConfig(libertyPlugin, overrides); }</code><technical_language>looseApplication defaults true. This is needed</technical_language>

Target:
private Xpp3Dom getLibertyPluginConfig() { Plugin libertyPlugin = getLibertyPlugin(); Xpp3Dom overrides = configuration(element(name("looseApplication"), "true")); return getPluginConfig(libertyPlugin, overrides); }
Source:
<code>public long getFirstRowIndex() { <START> if (firstRowIndex < 0) { <END> throw new IllegalStateException( "No row synchronization is required; all pages shall be read."); } return firstRowIndex; }</code><technical_language>a query this state relying exception thrown</technical_language>

Target:
public long getFirstRowIndex() { if (firstRowIndex < 0) { throw new NotInPageFilteringModeException("First row index is not available"); } return firstRowIndex; }
Source:
<code>public void intersectionTest() { DataUtil.IntersectionLambda intersectionLambda = new AndroidUtil.AndroidIntersectionLambda(); Vector<String> setOne = new Vector<>(); setOne.add("one"); setOne.add("two"); Vector<String> setTwo = new Vector<>(); setTwo.add("one"); setTwo.add("three"); <START> Vector<String> unionSet = intersectionLambda.intersection(setOne, setTwo); <END> assertFalse(unionSet == setOne); assertFalse(unionSet == setTwo); assertTrue(setOne.contains("one")); assertTrue(setOne.contains("two")); assertTrue(setTwo.contains("one")); assertTrue(setTwo.contains("three")); assertTrue(unionSet.contains("one")); assertFalse(unionSet.contains("two")); assertFalse(unionSet.contains("three")); }</code><technical_language>Rename this intersectionSet</technical_language>

Target:
public void intersectionTest() { DataUtil.IntersectionLambda intersectionLambda = new AndroidUtil.AndroidIntersectionLambda(); Vector<String> setOne = new Vector<>(); setOne.add("one"); setOne.add("two"); Vector<String> setTwo = new Vector<>(); setTwo.add("one"); setTwo.add("three"); Vector<String> intersectSet = intersectionLambda.intersection(setOne, setTwo); assertFalse(intersectSet == setOne); assertFalse(intersectSet == setTwo); assertTrue(setOne.contains("one")); assertTrue(setOne.contains("two")); assertTrue(setTwo.contains("one")); assertTrue(setTwo.contains("three")); assertTrue(intersectSet.contains("one")); assertFalse(intersectSet.contains("two")); assertFalse(intersectSet.contains("three")); }
Source:
<code>static UriComponentsBuilder getBuilder() { HttpServletRequest request = getCurrentRequest(); String forwardedSsl = request.getHeader("X-Forwarded-Ssl"); <START> UriComponentsBuilder builder = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)); <END> if (hasText(forwardedSsl) && forwardedSsl.equalsIgnoreCase("on")) { builder.scheme("https"); } return builder; }</code><technical_language>slightly change logic here? Previously, if a protocol header defined in way, SSL setting disregarded. I override here, we</technical_language>

Target:
static UriComponentsBuilder getBuilder() { HttpServletRequest request = getCurrentRequest(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)); String forwardedSsl = request.getHeader("X-Forwarded-Ssl"); ForwardedHeader forwarded = ForwardedHeader.of(request.getHeader(ForwardedHeader.NAME)); String proto = hasText(forwarded.getProto()) ? forwarded.getProto() : request.getHeader("X-Forwarded-Proto"); if (!hasText(proto) && hasText(forwardedSsl) && forwardedSsl.equalsIgnoreCase("on")) { builder.scheme("https"); } return builder; }
Source:
<code>public boolean seek(final CtfLocationData ctfLocationData) { boolean ret = false; long currTimestamp = ctfLocationData.getTimestamp(); final long offsetTimestamp = currTimestamp - this.getTrace().getOffset(); if (offsetTimestamp < 0) { ret = super.seek(0L); } else { ret = super.seek(offsetTimestamp); } <START> currTimestamp = this.getCurrentEvent().getTimestampValue(); <END> long offset = 0; for (long i = 0; i < ctfLocationData.getIndex(); i++) { if (currTimestamp == this.getCurrentEvent().getTimestampValue()) { offset++; } else { offset = 0; } this.advance(); } if (ret) { curLocation.setLocation(new CtfLocationData(getCurrentEvent().getTimestampValue(), offset)); } else { curLocation = NULL_LOCATION; } return ret; }</code><technical_language>rename offset index</technical_language>

Target:
public boolean seek(final CtfLocationData ctfLocationData) { boolean ret = false; long currTimestamp = ctfLocationData.getTimestamp(); final long offsetTimestamp = currTimestamp - this.getTrace().getOffset(); if (offsetTimestamp < 0) { ret = super.seek(0L); } else { ret = super.seek(offsetTimestamp); } currTimestamp = this.getCurrentEvent().getTimestampValue(); long index = 0; for (long i = 0; i < ctfLocationData.getIndex(); i++) { if (currTimestamp == this.getCurrentEvent().getTimestampValue()) { index++; } else { index = 0; } this.advance(); } if (ret) { curLocation.setLocation(new CtfLocationData(getCurrentEvent().getTimestampValue(), index)); } else { curLocation = NULL_LOCATION; } return ret; }
Source:
<code>public boolean isFinished() { <START> return (finishing && inputPage == null) || (remainingLimit == 0 && inputPage == null && unfinishedWork == null); <END> }</code><technical_language>add a hasUnfinishedInput method in RowNumber commit? I code easier read</technical_language>

Target:
public boolean isFinished() { return !hasUnfinishedInput() && (finishing || remainingLimit == 0); }
Source:
<code><START> public Handles setForceEndTransactions(boolean forceEndTransactions) { <END> this.forceEndTransactions = forceEndTransactions; return this; }</code><technical_language>This is a incompatible change merged</technical_language>

Target:
public void setForceEndTransactions(boolean forceEndTransactions) { this.forceEndTransactions = forceEndTransactions; }
Source:
<code>public void parsePartOneTwo_WithFailedRerun() { configuration.addReducingMethod(MERGE_FEATURES_AND_SCENARIOS_WITH_LATEST); setUpWithJson(PART_ONE, PART_TWO, PART_TWO_RERUN_FAILED); assertThat(reportResult.getAllFeatures()).hasSize(3); Reportable current = reportResult.getFeatureReport(); <START> assertThat(current.getFailedScenarios()).isEqualTo(1); <END> }</code><technical_language>hasSize()</technical_language>

Target:
public void parsePartOneTwo_WithFailedRerun() { configuration.addReducingMethod(MERGE_FEATURES_WITH_RETEST); setUpWithJson(PART_ONE, PART_TWO, PART_TWO_RERUN_FAILED); Reportable current = reportResult.getFeatureReport(); assertThat(reportResult.getAllFeatures()).hasSize(3); assertThat(current.getFailedScenarios()).isEqualTo(1); }
Source:
<code>protected void updateSlider() { if (dragging && draggable) { if (mouseY < sliderTopY + slider.height / 2) { slider.y = sliderTopY; sliderProgress = (slider.y - sliderTopY) / (float) (sliderBotY - sliderTopY); } else if (mouseY > sliderBotY + slider.height / 2) { slider.y = sliderBotY; sliderProgress = (slider.y - sliderTopY) / (float) (sliderBotY - sliderTopY); } else { slider.y = mouseY - slider.height / 2; sliderProgress = (slider.y - sliderTopY) / (float) (sliderBotY - sliderTopY); } <START> System.out.println(sliderProgress); <END> } else { if (draggable == false) slider.enabled = false; slider.y = (int) (sliderTopY + (sliderBotY - sliderTopY) * sliderProgress); } }</code><technical_language>Again, remove merging</technical_language>

Target:
protected void updateSlider() { if (dragging && draggable) { slider.y = MathHelper.clamp(mouseY - slider.height / 2, sliderTopY, sliderBotY); } else { if (draggable == false) slider.enabled = false; slider.y = (int) (sliderTopY + (sliderBotY - sliderTopY) * sliderProgress); } }
Source:
<code>private void checkNetworkAddressCacheSettings() { final String property = Security.getProperty("networkaddress.cache.ttl"); if (property == null) { return; } int cacheTTL = Integer.parseInt(property); <START> if (cacheTTL == -1) <END> { logger.warn( "networkaddress.cache.ttl is currently set to cache DNS lookups forever. If you use domain names " + "for the Riak server connection, and an IP address changes (riak host or a load balancer)" + ", this will block the client from creating connections with the new IP addresses."); } }</code><technical_language>this: if networkaddress.cache.ttl is -1 _and_ host names for Riak node addresses, set TTL 60 seconds recommended internets. A setting added override this behavior</technical_language>

Target:
private void checkNetworkAddressCacheSettings() { final String property = Security.getProperty("networkaddress.cache.ttl"); final boolean usingSecurityMgr = System.getSecurityManager() != null; final boolean propertyUndefined = property == null; boolean logWarning = false; if(propertyUndefined && usingSecurityMgr) { logWarning = true; } else if(!propertyUndefined) { final int cacheTTL = Integer.parseInt(property); logWarning = (cacheTTL == -1); } if (logWarning) { logger.warn( "The Java Security \"networkaddress.cache.ttl\" property may be set to cache DNS lookups forever. " + "Using domain names for Riak nodes or an intermediate load balancer could result in stale IP " + "addresses being used for new connections, causing connection errors. " + "If you use domain names for Riak nodes, please set this property to a value greater than zero."); } }
Source:
<code>@Test public void queryWithRawQuery() { final List<User> users = TestFactory.newUsers(20); int counter = 1; for (User user : users) { char[] chars = new char[counter++]; Arrays.fill(chars, '*'); user.setEmail(new String(chars)); } putUsers(users); final List<User> usersWithLongName = new ArrayList<>(users.size()); int lengthSum = 0; for (User user : users) { lengthSum += user.getEmail().length(); } final int avrLength = lengthSum / users.size(); for (User user : users) { if (user.getEmail().length() > avrLength) { usersWithLongName.add(user); } } <START> final String query = "Select * from " + User.TABLE <END> + " where length(" + User.COLUMN_EMAIL + ") > " + "(select avg(length(" + User.COLUMN_EMAIL + ")) from users)"; final List<User> usersFromQuery = storIODb .get() .listOfObjects(User.class) .withMapFunc(User.MAP_FROM_CURSOR) .withQuery(new RawQuery.Builder() .query(query) .build()) .prepare() .executeAsBlocking(); checkNotEmptyAndEquals(usersWithLongName, usersFromQuery); }</code><technical_language>WOW, length(), avg() SQL beats NoSQL</technical_language>

Target:
@Test public void queryWithRawQuery() { final List<User> users = TestFactory.newUsers(20); int counter = 1; for (User user : users) { char[] chars = new char[counter++]; Arrays.fill(chars, '*'); user.setEmail(new String(chars)); } putUsers(users); final List<User> usersWithLongName = new ArrayList<>(users.size()); int lengthSum = 0; for (User user : users) { lengthSum += user.getEmail().length(); } final int avrLength = lengthSum / users.size(); for (User user : users) { if (user.getEmail().length() > avrLength) { usersWithLongName.add(user); } } final String query = "Select * from " + User.TABLE + " where length(" + User.COLUMN_EMAIL + ") > " + "(select avg(length(" + User.COLUMN_EMAIL + ")) from users)"; final List<User> usersFromQuery = storIODb .get() .listOfObjects(User.class) .withMapFunc(User.MAP_FROM_CURSOR) .withQuery(new RawQuery.Builder() .query(query) .build()) .prepare() .executeAsBlocking(); assertEquals(usersWithLongName, usersFromQuery); }
Source:
<code>public static String parseUserVisibleError(Response<ResponseBody> response) { String message; try { JSONObject errorKeyAndDefault = new JSONObject(response.errorBody().string()); message = Localization.getWithDefault( errorKeyAndDefault.getString("error"), errorKeyAndDefault.getString("default_response")); } catch (JSONException | IOException e) { <START> message = "Unknown issue"; <END> } return message; }</code><technical_language>I a net positive in this case publish errorBody error? A 406 is specific enough I feel happy in event of issue able dig error itself</technical_language>

Target:
public static String parseUserVisibleError(Response<ResponseBody> response) { String message; String responseStr = null; try { responseStr = response.errorBody().string(); JSONObject errorKeyAndDefault = new JSONObject(responseStr); message = Localization.getWithDefault( errorKeyAndDefault.getString("error"), errorKeyAndDefault.getString("default_response")); } catch (JSONException | IOException e) { message = responseStr != null ? responseStr : "Unknown issue"; } return message; }
Source:
<code>private synchronized void initServer() { LOG.debug("Creating journal with max segment size {}", mConf.getMaxLogSize()); Storage storage = Storage.builder() .withDirectory(mConf.getPath()) .withStorageLevel(StorageLevel.valueOf(mConf.getStorageLevel().name())) .withMinorCompactionInterval(Duration.ofDays(200)) .withMaxSegmentSize((int) mConf.getMaxLogSize()) .build(); if (mStateMachine != null) { mStateMachine.close(); } mStateMachine = new JournalStateMachine(mJournals, () -> this.getJournalSinks(null)); GrpcMessagingProxy serverProxy = null; if (mConf.getProxyAddress() != null) { serverProxy = new GrpcMessagingProxy(); serverProxy.addProxy(getLocalAddress(mConf), new Address(mConf.getProxyAddress())); <START> } <END> mServer = CopycatServer.builder(getLocalAddress(mConf)) .withStorage(storage) .withElectionTimeout(Duration.ofMillis(mConf.getElectionTimeoutMs())) .withHeartbeatInterval(Duration.ofMillis(mConf.getHeartbeatIntervalMs())) .withSnapshotAllowed(mSnapshotAllowed) .withSerializer(createSerializer()) .withTransport(new GrpcMessagingTransport( ServerConfiguration.global(), ServerUserState.global(), RAFTSERVER_CLIENT_TYPE) .withServerProxy(serverProxy)) .withStateMachine(new OnceSupplier<>(mStateMachine)) .withAppenderBatchSize((int) ServerConfiguration .getBytes(PropertyKey.MASTER_EMBEDDED_JOURNAL_APPENDER_BATCH_SIZE)) .build(); mPrimarySelector.init(mServer); }</code><technical_language>Consider creating GrpcMessagingTransport here? do null checks in GrpcMessagingTransport assume proxy is set if necessary</technical_language>

Target:
private synchronized void initServer() { LOG.debug("Creating journal with max segment size {}", mConf.getMaxLogSize()); Storage storage = Storage.builder() .withDirectory(mConf.getPath()) .withStorageLevel(StorageLevel.valueOf(mConf.getStorageLevel().name())) .withMinorCompactionInterval(Duration.ofDays(200)) .withMaxSegmentSize((int) mConf.getMaxLogSize()) .build(); if (mStateMachine != null) { mStateMachine.close(); } mStateMachine = new JournalStateMachine(mJournals, () -> this.getJournalSinks(null)); GrpcMessagingProxy serverProxy = new GrpcMessagingProxy(); if (mConf.getProxyAddress() != null) { serverProxy.addProxy(getLocalAddress(mConf), new Address(mConf.getProxyAddress())); } mServer = CopycatServer.builder(getLocalAddress(mConf)) .withStorage(storage) .withElectionTimeout(Duration.ofMillis(mConf.getElectionTimeoutMs())) .withHeartbeatInterval(Duration.ofMillis(mConf.getHeartbeatIntervalMs())) .withSnapshotAllowed(mSnapshotAllowed) .withSerializer(createSerializer()) .withTransport(new GrpcMessagingTransport( ServerConfiguration.global(), ServerUserState.global(), RAFTSERVER_CLIENT_TYPE) .withServerProxy(serverProxy)) .withStateMachine(new OnceSupplier<>(mStateMachine)) .withAppenderBatchSize((int) ServerConfiguration .getBytes(PropertyKey.MASTER_EMBEDDED_JOURNAL_APPENDER_BATCH_SIZE)) .build(); mPrimarySelector.init(mServer); }
Source:
<code>public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { final AudioRecorderViewModel viewModel = new ViewModelProvider(requireActivity(), audioRecorderViewModelFactory).get(AudioRecorderViewModel.class); viewModel.getCurrentSession().observe(getViewLifecycleOwner(), session -> { if (session == null) { binding.getRoot().setVisibility(GONE); } else if (session.getFile() == null) { binding.getRoot().setVisibility(VISIBLE); binding.timeCode.setText(LengthFormatterKt.formatLength(session.getDuration())); if (session.getPaused()) { <START> binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_play_arrow_24dp)); <END> binding.pauseRecording.setOnClickListener(v -> viewModel.resume()); } else { binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_pause_24dp)); binding.pauseRecording.setOnClickListener(v -> viewModel.pause()); } if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) { binding.pauseRecording.setVisibility(GONE); } } else { binding.getRoot().setVisibility(GONE); } }); binding.stopRecording.setOnClickListener(v -> viewModel.stop()); }</code><technical_language>I this a red record circle</technical_language>

Target:
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { final AudioRecorderViewModel viewModel = new ViewModelProvider(requireActivity(), audioRecorderViewModelFactory).get(AudioRecorderViewModel.class); viewModel.getCurrentSession().observe(getViewLifecycleOwner(), session -> { if (session == null) { binding.getRoot().setVisibility(GONE); } else if (session.getFile() == null) { binding.getRoot().setVisibility(VISIBLE); binding.timeCode.setText(LengthFormatterKt.formatLength(session.getDuration())); if (session.getPaused()) { binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_baseline_mic_24)); binding.pauseRecording.setContentDescription(getString(R.string.resume_recording)); binding.pauseRecording.setOnClickListener(v -> viewModel.resume()); binding.recordingStatus.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_pause_24dp)); } else { binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_pause_24dp)); binding.pauseRecording.setContentDescription(getString(R.string.pause_recording)); binding.pauseRecording.setOnClickListener(v -> viewModel.pause()); binding.recordingStatus.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_baseline_mic_24)); } if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) { binding.pauseRecording.setVisibility(GONE); } } else { binding.getRoot().setVisibility(GONE); } }); binding.stopRecording.setOnClickListener(v -> viewModel.stop()); }
Source:
<code>public void testBadCallback() throws Exception { testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, null, new ErrorCodeChecker() { @Override <START> public void check(RouterErrorCode expectedError) <END> throws Exception { final CountDownLatch callbackCalled = new CountDownLatch(1); List<Future> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { if (i == 1) { futures.add(router.deleteBlob(blobIdString, new Callback<Void>() { @Override public void onCompletion(Void result, Exception exception) { callbackCalled.countDown(); throw new RuntimeException("Throwing an exception in the user callback"); } })); } else { futures.add(router.deleteBlob(blobIdString)); } } for (Future future : futures) { future.get(); } Assert.assertTrue("Callback not called.", callbackCalled.await(2, TimeUnit.SECONDS)); Assert.assertEquals("All operations should be finished.", 0, router.getOperationsCount()); Assert.assertTrue("Router should not be closed", router.isOpen()); router.deleteBlob(blobIdString, new ClientCallback()).get(); Assert.assertTrue("Callback not called.", operationCompleteLatch.await(2, TimeUnit.SECONDS)); } }); }</code><technical_language>this function class named differently do more check error code - in some sense, execute test</technical_language>

Target:
public void testBadCallback() throws Exception { testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, null, new ErrorCodeChecker() { @Override public void testAndAssert(RouterErrorCode expectedError) throws Exception { final CountDownLatch callbackCalled = new CountDownLatch(1); List<Future> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { if (i == 1) { futures.add(router.deleteBlob(blobIdString, new Callback<Void>() { @Override public void onCompletion(Void result, Exception exception) { callbackCalled.countDown(); throw new RuntimeException("Throwing an exception in the user callback"); } })); } else { futures.add(router.deleteBlob(blobIdString)); } } for (Future future : futures) { future.get(AWAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } Assert.assertTrue("Callback not called.", callbackCalled.await(AWAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)); Assert.assertEquals("All operations should be finished.", 0, router.getOperationsCount()); Assert.assertTrue("Router should not be closed", router.isOpen()); router.deleteBlob(blobIdString).get(); } }); }
Source:
<code>public int getPurgingAge(){ int numberOfDays = 0; String line = null; try { File file = new File("config.txt"); if (file.createNewFile()){ FileWriter fileWriter = new FileWriter(file); fileWriter.append("100"); fileWriter.close(); return 100; }else{ FileReader fileReader = new FileReader(file); <START> BufferedReader bufferedReader = new BufferedReader(fileReader); <END> while((line = bufferedReader.readLine() )!= null){ numberOfDays = Integer.parseInt(line.trim()); return numberOfDays; } } } catch (IOException e) { logger.log(Level.FINE, e.getMessage(), e); } return numberOfDays; }</code><technical_language>Need this stream is closed (use try/finally block)</technical_language>

Target:
public int getPurgingAge(){ int numberOfDays = 0; String line; try { File file = new File("config.txt"); if (file.createNewFile()){ FileWriter fileWriter = new FileWriter(file); fileWriter.append("100"); fileWriter.close(); return 100; }else{ FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine() )!= null){ numberOfDays = Integer.parseInt(line.trim()); return numberOfDays; } bufferedReader.close(); } } catch (IOException e) { logger.log(Level.FINE, e.getMessage(), e); } finally { return numberOfDays; } }
Source:
<code>private static HttpCookie parseLine(@NonNull String line, @NonNull Date creationDate) { if (line.isEmpty() || (line.startsWith("#") && !line.startsWith(HTTP_ONLY_PREAMBLE))) { return null; } String[] cookieLineParts = line.split(COLUMN_SEPARATOR, 7); if (cookieLineParts == null) { throw new IllegalArgumentException(MessageFormat .format(JGitText.get().couldNotFindTabInLine, line)); } if (cookieLineParts.length < 7) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().couldNotFindSixTabsInLine, <START> new Integer(cookieLineParts.length), <END> line)); } String name = cookieLineParts[5]; String value = cookieLineParts[6]; HttpCookie cookie = new HttpCookie(name, value); String domain = cookieLineParts[0]; if (domain.startsWith(HTTP_ONLY_PREAMBLE)) { cookie.setHttpOnly(true); domain = domain.substring(HTTP_ONLY_PREAMBLE.length()); } if (domain.startsWith(".")) { domain = domain.substring(1); } cookie.setDomain(domain); cookie.setPath(cookieLineParts[2]); cookie.setSecure(Boolean.parseBoolean(cookieLineParts[3])); long expires = Long.parseLong(cookieLineParts[4]); long maxAge = (expires - creationDate.getTime()) / 1000; if (maxAge <= 0) { return null; } cookie.setMaxAge(maxAge); return cookie; }</code><technical_language>Integer.valueOf</technical_language>

Target:
private static HttpCookie parseLine(@NonNull String line, @NonNull Date creationDate) { if (line.isEmpty() || (line.startsWith("#") && !line.startsWith(HTTP_ONLY_PREAMBLE))) { return null; } String[] cookieLineParts = line.split(COLUMN_SEPARATOR, 7); if (cookieLineParts == null) { throw new IllegalArgumentException(MessageFormat .format(JGitText.get().couldNotFindTabInLine, line)); } if (cookieLineParts.length < 7) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().couldNotFindSixTabsInLine, Integer.valueOf(cookieLineParts.length), line)); } String name = cookieLineParts[5]; String value = cookieLineParts[6]; HttpCookie cookie = new HttpCookie(name, value); String domain = cookieLineParts[0]; if (domain.startsWith(HTTP_ONLY_PREAMBLE)) { cookie.setHttpOnly(true); domain = domain.substring(HTTP_ONLY_PREAMBLE.length()); } if (domain.startsWith(".")) { domain = domain.substring(1); } cookie.setDomain(domain); cookie.setPath(cookieLineParts[2]); cookie.setSecure(Boolean.parseBoolean(cookieLineParts[3])); long expires = Long.parseLong(cookieLineParts[4]); long maxAge = (expires - creationDate.getTime()) / 1000; if (maxAge <= 0) { return null; } cookie.setMaxAge(maxAge); return cookie; }
Source:
<code>protected void onDestroy() { super.onDestroy(); if (mIdpProviders != null) { for (final IDPProvider provider : mIdpProviders) { <START> if (GoogleProvider.class.isInstance(provider)) { <END> ((GoogleProvider) provider).disconnect(); } } } }</code><technical_language>nit: prefer provider instanceof GoogleProvider</technical_language>

Target:
protected void onDestroy() { super.onDestroy(); if (mIdpProviders != null) { for (final IDPProvider provider : mIdpProviders) { if (provider instanceof GoogleProvider) { ((GoogleProvider) provider).disconnect(); } } } }
Source:
<code>public void itInsertsABranchWhenNonePresent() throws Exception { long before = Math.floorDiv(System.currentTimeMillis(), 1000L) * 1000; GitInfo original = newGitInfo(123, "Overwatch", "master"); GitInfo inserted = branchService.upsert(original); assertThat(inserted.getId().isPresent()).isTrue(); Optional<GitInfo> retrieved = branchService.get(inserted.getId().get()); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get()).isEqualTo(inserted); assertThat(retrieved.get().getCreatedTimestamp()).isBetween(before, System.currentTimeMillis()); <START> <END> assertThat(retrieved.get().getUpdatedTimestamp()) .isBetween(before, System.currentTimeMillis()) .isEqualTo(retrieved.get().getCreatedTimestamp()); }</code><technical_language>BTW in assertThat(retrieved.get()).isEqualTo(inserted) assertion rely implementation of equals for GitInfo is problematic in opinion. GitInfo is modeling a db entry for a branch adding properties for this db entry created updated. timestamps in implementation of equals. Is GitInfo is essentially capturing info for a branch care db entry specific info in case? equals is counting id (surrogate key) db entry is getting. If wanted equals is introduce a BranchInfo class a separate BranchInfoDbEntry class adds surrogate key timestamp properties</technical_language>

Target:
public void itInsertsABranchWhenNonePresent() throws Exception { long before = System.currentTimeMillis() - 1000; GitInfo original = newGitInfo(123, "Overwatch", "master"); GitInfo inserted = branchService.upsert(original); assertThat(inserted.getId().isPresent()).isTrue(); Optional<GitInfo> retrieved = branchService.get(inserted.getId().get()); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get()).isEqualTo(inserted); assertThat(retrieved.get().getCreatedTimestamp()).isBetween(before, System.currentTimeMillis()); assertThat(retrieved.get().getUpdatedTimestamp()) .isBetween(before, System.currentTimeMillis()) .isEqualTo(retrieved.get().getCreatedTimestamp()); }
Source:
<code>T build(ServiceLocator serviceLocator) { Store.Provider storeProvider = serviceLocator.findService(Store.Provider.class); final StoreConfigurationImpl<K, V> storeConfig = new StoreConfigurationImpl<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader); final Store<K, V> store = storeProvider.createStore(storeConfig); CacheConfiguration<K, V> cacheConfig = new BaseCacheConfiguration<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, new ServiceConfiguration<?>[]{}); <START> this.statisticsExecutor = Executors.newScheduledThreadPool( <END> Integer.getInteger("org.ehcache.StandaloneCacheBuilder.statisticsExecutor.poolSize", 1) , new ThreadFactory() { private AtomicInteger cnt = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "Statistics Thread-" + cnt.incrementAndGet()); t.setDaemon(true); return t; } }); final Ehcache<K, V> ehcache = new Ehcache<K, V>(cacheConfig, store, cacheLoader, cacheWriter, statisticsExecutor); return (T) ehcache; }</code><technical_language>This is 2nd time I exact executor implementation. worth factoring out in some utility class</technical_language>

Target:
T build(ServiceLocator serviceLocator) { Store.Provider storeProvider = serviceLocator.findService(Store.Provider.class); ExecutorFactoryService executorService = serviceLocator.findService(ExecutorFactoryService.class); if (executorService != null && executorService.getStatisticsExecutor() != null) { statisticsExecutor = executorService.getStatisticsExecutor(); } else { statisticsExecutor = StatisticsThreadPoolUtil.getDefaultStatisticsExecutorService(); } final StoreConfigurationImpl<K, V> storeConfig = new StoreConfigurationImpl<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry); final Store<K, V> store = storeProvider.createStore(storeConfig); CacheConfiguration<K, V> cacheConfig = new BaseCacheConfiguration<K, V>(keyType, valueType, capacityConstraint, evictionVeto, evictionPrioritizer, classLoader, expiry, new ServiceConfiguration<?>[]{}); final Ehcache<K, V> ehcache = new Ehcache<K, V>(cacheConfig, store, cacheLoader, cacheWriter, statisticsExecutor); return (T) ehcache; }
Source:
<code>public String getAmqpUrl() { <START> return String.format("amqp://" + getContainerIpAddress() + ":" + getMappedPort(DEFAULT_AMQP_PORT)); <END> }</code><technical_language>I suggest calling getAmqpPort() (and in other get*Url methods) avoid a duplication of this code</technical_language>

Target:
public String getAmqpUrl() { return "amqp://" + getContainerIpAddress() + ":" + getAmqpPort(); }
Source:
<code>public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long start = System.currentTimeMillis(); Object result = method.invoke(this.previousContext, args); long delta = System.currentTimeMillis() - start; String methodName = method.getName(); int argsLength = args != null ? args.length : 0; <START> <END> if (methodName != null && !methodName.equalsIgnoreCase("close")) { logDetails(start, delta, ((DirContext) this.previousContext).getEnvironment(), methodName, argsLength, stringify(args)); } return result; }</code><technical_language>unnecessary blank spaces in this class. Please refactor</technical_language>

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long start = System.currentTimeMillis(); Object result = method.invoke(this.previousContext, args); long delta = System.currentTimeMillis() - start; String methodName = method.getName(); int argsLength = 0; if (args != null) { argsLength = args.length; } if (!StringUtils.equalsIgnoreCase("close", methodName)) { CorrelationLogDTO correlationLogDTO = new CorrelationLogDTO(); correlationLogDTO.setStartTime(start); correlationLogDTO.setDelta(delta); correlationLogDTO.setEnvironment(((DirContext) this.previousContext).getEnvironment()); correlationLogDTO.setMethodName(methodName); correlationLogDTO.setArgsLength(argsLength); correlationLogDTO.setArgs(stringify(args)); logDetails(correlationLogDTO); } return result; }
Source:
<code>protected void generateStaticRelationSlots(Role role, PrintWriter out) { newline(out); Role otherRole = role.getOtherRole(); boolean isDirectRelation = role.isDirect(); String genericType = "<" + getTypeFullName((isDirectRelation ? otherRole : role).getType()) + "," + getTypeFullName((isDirectRelation ? role : otherRole).getType()) + ">"; String relationSlotName = role.getRelation().getName(); String directRelationType = getDirectRelationType(); String methodName = "getRelation" + role.getRelation().getName(); if (isDirectRelation) { print(out, "private final static class "); print(out, relationSlotName); newBlock(out); <START> print(out, "public static final "); <END> print(out, directRelationType); print(out, genericType); print(out, " relation"); print(out, " = "); print(out, "new "); print(out, directRelationType); print(out, genericType); print(out, "("); print(out, getRoleHandlerName(role, false)); print(out, ", \""); print(out, role.getRelation().getName()); print(out, "\""); generateDefaultRelationListeners(role, out); print(out, ");"); closeBlock(out); } if (isDirectRelation || !role.getType().equals(otherRole.getType())) { printMethod(out, "public static", getDirectRelationInterfaceType() + genericType, methodName); startMethodBody(out); print(out, "return "); if (isDirectRelation) { print(out, relationSlotName + ".relation"); } else { print(out, role.getType().getFullName() + "." + methodName + "()"); } print(out, ";"); endMethodBody(out); } }</code><technical_language>is relation static field public? I suppose private, right</technical_language>

Target:
protected void generateStaticRelationSlots(Role role, PrintWriter out) { newline(out); Role otherRole = role.getOtherRole(); boolean isDirectRelation = role.isDirect(); String genericType = "<" + getTypeFullName((isDirectRelation ? otherRole : role).getType()) + "," + getTypeFullName((isDirectRelation ? role : otherRole).getType()) + ">"; String relationSlotName = role.getRelation().getName(); String directRelationType = getDirectRelationType(); String methodName = "getRelation" + role.getRelation().getName(); if (isDirectRelation) { print(out, "private final static class "); print(out, relationSlotName); newBlock(out); print(out, "private static final "); print(out, directRelationType); print(out, genericType); print(out, " relation"); print(out, " = "); print(out, "new "); print(out, directRelationType); print(out, genericType); print(out, "("); print(out, getRoleHandlerName(role, false)); print(out, ", \""); print(out, role.getRelation().getName()); print(out, "\""); generateDefaultRelationListeners(role, out); print(out, ");"); closeBlock(out); } if (isDirectRelation || !role.getType().equals(otherRole.getType())) { printMethod(out, "public static", getDirectRelationInterfaceType() + genericType, methodName); startMethodBody(out); print(out, "return "); if (isDirectRelation) { print(out, relationSlotName + ".relation"); } else { print(out, role.getType().getFullName() + "." + methodName + "()"); } print(out, ";"); endMethodBody(out); } }
Source:
<code><START> String getErrorMessage(ClientResponse clientResponse) { <END> String response = clientResponse.getEntity(String.class); try { ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }</code><technical_language>Method protected, writing this for sub-classing</technical_language>

Target:
protected String getErrorMessage(ClientResponse clientResponse) { String response = clientResponse.getEntity(String.class); try { ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }
Source:
<code>public void executeJavaScriptTest() throws Exception { String javascript = "alert('Alert!')"; assertFalse(iface.isDialogVisible()); iface.executeJavascript(javascript); assertTrue(iface.isDialogVisible()); assertTrue(iface.wd.switchTo().alert().getText().contains("Alert!")); iface.acceptDialog(); assertFalse(iface.isDialogVisible()); javascript = "alert(arguments[0])"; String arg = "one"; assertFalse(iface.isDialogVisible()); iface.executeJavascript(javascript, arg); assertTrue(iface.isDialogVisible()); assertTrue(iface.wd.switchTo().alert().getText().contains(arg)); iface.acceptDialog(); <START> assertFalse(iface.isDialogVisible()); <END> javascript = "alert(arguments[0] + ' and ' + arguments[1])"; String[] args = { "two", "three" }; assertFalse(iface.isDialogVisible()); iface.executeJavascript(javascript, args); assertTrue(iface.isDialogVisible()); assertTrue(iface.wd.switchTo().alert().getText().contains(args[0])); assertTrue(iface.wd.switchTo().alert().getText().contains(args[1])); iface.acceptDialog(); assertFalse(iface.isDialogVisible()); }</code><technical_language>I feel need assertion ensure alert is longer visible a test for this purpose presentAcceptDismissDialogTest()</technical_language>

Target:
public void executeJavaScriptTest() throws Exception { String javascript = "alert('Alert!')"; iface.executeJavascript(javascript); assertTrue(iface.wd.switchTo().alert().getText().contains("Alert!")); iface.acceptDialog(); javascript = "alert(arguments[0])"; String arg = "one"; iface.executeJavascript(javascript, arg); assertTrue(iface.wd.switchTo().alert().getText().contains(arg)); iface.acceptDialog(); javascript = "alert(arguments[0] + ' and ' + arguments[1])"; String[] args = { "two", "three" }; iface.executeJavascript(javascript, args); assertTrue(iface.wd.switchTo().alert().getText().contains(args[0])); assertTrue(iface.wd.switchTo().alert().getText().contains(args[1])); iface.acceptDialog(); }
Source:
<code>public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { String attributeValue = null; <START> Matcher emailMatcher = Utils.emailPattern.matcher(attributeValue); <END> if (!emailMatcher.find()) { throw new WrongAttributeValueException(attribute, user, "Email is not in correct form."); } }</code><technical_language>Variable attributeValue contains null (see line 24), this matcher match</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException { String attributeValue = (String) attribute.getValue(); Matcher emailMatcher = Utils.emailPattern.matcher(attributeValue); if (!emailMatcher.find()) { throw new WrongAttributeValueException(attribute, user, "Email is not in correct form."); } }
Source:
<code>public void deleteBlob(String key) throws AuthorizationException, KeyNotFoundException, TException { try { String topoName = ConfigUtils.getIdFromBlobKey(key); if (topoName != null) { if (isTopologyActiveOrActivating(stormClusterState, topoName)) { String message = "Attempting to delete blob " + key + " from under active topology " + topoName; LOG.warn(message); <START> throw new TException(message); <END> } } blobStore.deleteBlob(key, getSubject()); LOG.info("Deleted blob for key {}", key); } catch (Exception e) { LOG.warn("delete blob exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }</code><technical_language>this AuthorizationException</technical_language>

Target:
public void deleteBlob(String key) throws AuthorizationException, KeyNotFoundException, IllegalStateException, TException { try { String topoName = ConfigUtils.getIdFromBlobKey(key); if (topoName != null) { if (isTopologyActiveOrActivating(stormClusterState, topoName)) { String message = "Attempting to delete blob " + key + " from under active topology " + topoName; LOG.warn(message); throw new WrappedIllegalStateException(message); } } blobStore.deleteBlob(key, getSubject()); LOG.info("Deleted blob for key {}", key); } catch (Exception e) { LOG.warn("delete blob exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }
Source:
<code>private Runnable cleaner( AtomicLong nextId, AtomicReference<Throwable> error, AtomicInteger cleanedPointers ) { return () -> { try ( PageCursor cursor = pagedFile.io( 0, PagedFile.PF_SHARED_READ_LOCK ); PageCursor writeCursor = pagedFile.io( 0, PagedFile.PF_SHARED_WRITE_LOCK ) ) { <START> while ( nextId.get() < highTreeNodeId ) <END> { int batchCount = 0; for ( ; batchCount < 1_000; batchCount++ ) { long id = nextId.getAndIncrement(); if ( id >= highTreeNodeId ) { break; } PageCursorUtil.goTo( cursor, "clean", id ); if ( hasCrashedGSPP( treeNode, cursor ) ) { writeCursor.next( cursor.getCurrentPageId() ); cleanTreeNode( treeNode, writeCursor, cleanedPointers ); } } if ( error.get() != null ) { break; } } } catch ( Throwable e ) { error.compareAndSet( null, e ); } }; }</code><technical_language>if pass ranges if ids check speed up, remove common contention point is nextId currently, ranges of ids in thread potentially faster process of locality</technical_language>

Target:
private Runnable cleaner( AtomicLong nextId, AtomicReference<Throwable> error, AtomicInteger cleanedPointers ) { return () -> { try ( PageCursor cursor = pagedFile.io( 0, PagedFile.PF_SHARED_READ_LOCK ); PageCursor writeCursor = pagedFile.io( 0, PagedFile.PF_SHARED_WRITE_LOCK ) ) { long localNextId; while ( ( localNextId = nextId.getAndAdd( batchSize )) < highTreeNodeId ) { for ( int i = 0; i < batchSize && localNextId < highTreeNodeId; i++, localNextId++ ) { PageCursorUtil.goTo( cursor, "clean", localNextId ); if ( hasCrashedGSPP( treeNode, cursor ) ) { writeCursor.next( cursor.getCurrentPageId() ); cleanTreeNode( treeNode, writeCursor, cleanedPointers ); } } if ( error.get() != null ) { break; } } } catch ( Throwable e ) { error.compareAndSet( null, e ); } }; }
Source:
<code>public boolean detect() { try { return jdbcTemplate.queryForInt("select count(*) from information_schema.tables where table_schema = 'pg_catalog' and table_name = 'stl_s3client'") > 0; } catch (SQLException e) { <START> e.printStackTrace(); <END> return false; } }</code><technical_language>a logger instead? abstraction is essential for playing clients</technical_language>

Target:
public boolean detect() { try { return jdbcTemplate.queryForInt("select count(*) from information_schema.tables where table_schema = 'pg_catalog' and table_name = 'stl_s3client'") > 0; } catch (SQLException e) { LOG.error("Unable to check whether this is a Redshift database", e); return false; } }
Source:
<code>public Future<?> submit(Runnable r) { if (useMainThread) { <START> r.run(); <END> return new FutureTask<Void>(() -> {}, null); } else { return threadPool.submit(r); } }</code><technical_language>logic r.run() assumes caller is calling main thread. case, a tad weary</technical_language>

Target:
public Future<?> submit(Runnable r) { if (useCallerThread) { r.run(); return new FutureTask<Void>(() -> {}, null); } else { return threadPool.submit(r); } }