auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public FutureResult<ScheduleExecution> executeSchedule(final Schedule schedule) { notNull(schedule, "schedule"); ScheduleExecution scheduleExecution; try { scheduleExecution = restTemplate.postForObject(schedule.getExecutionsUri(), new ScheduleExecution(), ScheduleExecution.class); } catch (GoodDataException | RestClientException e) { throw new ScheduleExecutionException("Cannot execute schedule", e); } return new PollResult<>(this, new AbstractPollHandler<ScheduleExecution, ScheduleExecution>(scheduleExecution.getUri(), ScheduleExecution.class, ScheduleExecution.class) { @Override public boolean isFinished(ClientHttpResponse response) throws IOException { <START> final ScheduleExecution pollResult = new ObjectMapper().readValue(response.getBody(), ScheduleExecution.class); <END> return isFinished(pollResult.getStatus()); } @Override public void handlePollResult(final ScheduleExecution pollResult) { setResult(pollResult); } @Override public void handlePollException(final GoodDataRestException e) { throw new ScheduleExecutionException("Cannot execute schedule", e); } private boolean isFinished(final String status) { return Arrays.asList("OK", "ERROR", "CANCELED", "TIMEOUT").contains(status); } }); }</code><technical_language>extractData()</technical_language>

Target:
public FutureResult<ScheduleExecution> executeSchedule(final Schedule schedule) { notNull(schedule, "schedule"); ScheduleExecution scheduleExecution; try { scheduleExecution = restTemplate.postForObject(schedule.getExecutionsUri(), new ScheduleExecution(), ScheduleExecution.class); } catch (GoodDataException | RestClientException e) { throw new ScheduleExecutionException("Cannot execute schedule", e); } return new PollResult<>(this, new AbstractPollHandler<ScheduleExecution, ScheduleExecution>(scheduleExecution.getUri(), ScheduleExecution.class, ScheduleExecution.class) { @Override public boolean isFinished(ClientHttpResponse response) throws IOException { final ScheduleExecution pollResult = extractData(response, ScheduleExecution.class); return pollResult.isFinished(); } @Override public void handlePollResult(final ScheduleExecution pollResult) { setResult(pollResult); } @Override public void handlePollException(final GoodDataRestException e) { throw new ScheduleExecutionException("Cannot execute schedule", e); } }); }
Source:
<code>protected void findUsers(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, <START> new SearchParameters("ADUSER@" + extractAuthorizationProvider((String) getProfile().getSelectedItem()) + ": " + searchString, SearchType.DirectoryUser), query); END> }</code><technical_language>reason put authz name in separate field instead of parsing re-parsing</technical_language>

Target:
protected void findUsers(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, new SearchParameters("ADUSER@" + extractAuthorizationProvider((ProfileEntry) getProfile().getSelectedItem()) + ": " + searchString, SearchType.DirectoryUser), query); }
Source:
<code>private static String initMiniCluster(Configuration conf, ReadOnlyProps overrideProps) { setUpConfigForMiniCluster(conf, overrideProps); utility = new HBaseTestingUtility(conf); try { <START> utility.startMiniCluster(NUM_SLAVES_BASE, true); <END> return getLocalClusterUrl(utility); } catch (Throwable t) { throw new RuntimeException(t); } }</code><technical_language>curious this change. Is necessary</technical_language>

Target:
private static String initMiniCluster(Configuration conf, ReadOnlyProps overrideProps) { setUpConfigForMiniCluster(conf, overrideProps); utility = new HBaseTestingUtility(conf); try { utility.startMiniCluster(NUM_SLAVES_BASE); return getLocalClusterUrl(utility); } catch (Throwable t) { throw new RuntimeException(t); } }
Source:
<code>public void setUp() { workerApplicationContext = new AnnotationConfigApplicationContext(WorkerConfiguration.class); <START> System.out.println("Started a worker.."); <END> }</code><technical_language>remove system.outs..</technical_language>

Target:
public void setUp() throws Exception { this.brokerService = new BrokerService(); this.brokerService.addConnector(this.brokerUrl); this.brokerService.setDataDirectory(BROKER_DATA_DIRECTORY); this.brokerService.start(); this.workerApplicationContext = new AnnotationConfigApplicationContext(WorkerConfiguration.class); }
Source:
<code>private void setupAudioButton(int rowId, AudioPlaybackButton audioPlaybackButton, MenuDisplayable menuDisplayable) { final String audioURI = menuDisplayable.getAudioURI(); String audioFilename = ""; if (audioURI != null && !audioURI.equals("")) { try { audioFilename = ReferenceManager.instance().DeriveReference(audioURI).getLocalURI(); } catch (InvalidReferenceException e) { Log.e("AVTLayout", "Invalid reference exception"); e.printStackTrace(); } } File audioFile = new File(audioFilename); ViewId viewId = ViewId.buildListViewId(rowId); if (!"".equals(audioFilename) && audioFile.exists()) { audioPlaybackButton.modifyButtonForNewView(viewId, audioURI, true); } else { if (audioPlaybackButton != null) { audioPlaybackButton.modifyButtonForNewView(viewId, audioURI, false); <START> audioPlaybackButton.setVisibility(View.GONE); <END> } } }</code><technical_language>If select options "Gear" icon a menu audio upload widget right there: ![screen shot 2017-09-06 3 13 35 pm](<LINK_0></technical_language>

Target:
private void setupAudioButton(int rowId, AudioPlaybackButton audioPlaybackButton, MenuDisplayable menuDisplayable) { final String audioURI = menuDisplayable.getAudioURI(); String audioFilename = ""; if (audioURI != null && !audioURI.equals("")) { try { audioFilename = ReferenceManager.instance().DeriveReference(audioURI).getLocalURI(); } catch (InvalidReferenceException e) { Log.e("AVTLayout", "Invalid reference exception"); e.printStackTrace(); } } File audioFile = new File(audioFilename); ViewId viewId = ViewId.buildListViewId(rowId); if (!"".equals(audioFilename) && audioFile.exists()) { audioPlaybackButton.modifyButtonForNewView(viewId, audioURI, true); } else { if (audioPlaybackButton != null) { audioPlaybackButton.modifyButtonForNewView(viewId, audioURI, false); } } }
Source:
<code>private Connection getConnectionWithRetry(String connectionURL) { Connection connection=null; try{ connection = getConnectionWithRetry(connectionURL, true); } catch (Exception e) { <START> LOG.error("Failed to get connection with namespace enabled", e); <END> try { connection = getConnectionWithRetry(connectionURL, false); } catch (Exception ex) { LOG.error("Failed to get connection without namespace enabled", ex); } } return connection; }</code><technical_language>Change this INFO</technical_language>

Target:
private Connection getConnectionWithRetry(String connectionURL) { Connection connection=null; try{ connection = getConnectionWithRetry(connectionURL, true); } catch (Exception e) { LOG.info("Failed to get connection with namespace enabled", e); try { connection = getConnectionWithRetry(connectionURL, false); } catch (Exception ex) { LOG.info("Failed to get connection without namespace enabled", ex); } } return connection; }
Source:
<code>public static OzoneClient getRpcClient(String omServiceId, Configuration config) throws IOException { Preconditions.checkNotNull(omServiceId); Preconditions.checkNotNull(config); <START> config.set(OZONE_OM_ADDRESS_KEY, omServiceId); <END> return getClient(getClientProtocol(config, omServiceId), config); }</code><technical_language>I understand this is required. discuss tomorrow</technical_language>

Target:
public static OzoneClient getRpcClient(String omServiceId, Configuration config) throws IOException { Preconditions.checkNotNull(omServiceId); Preconditions.checkNotNull(config); return getClient(getClientProtocol(config, omServiceId), config); }
Source:
<code>private void createReasonNote(ActionForm form) { KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form; try { Note noteObj = SpringContext.getBean(DocumentService.class).createNoteFromDocument(kualiDocumentFormBase.getDocument(), ((PurchasingFormBase)kualiDocumentFormBase).getReasonToChange()); populateIdentifierOnNoteAndExtension(noteObj); kualiDocumentFormBase.getDocument().addNote(noteObj); <START> if (isNoteReadyToBeSaved(kualiDocumentFormBase.getDocument(), noteObj)) { <END> getNoteService().save(noteObj); } ((PurchasingFormBase)kualiDocumentFormBase).setReasonToChange(KFSConstants.EMPTY_STRING); } catch(Exception e){ String errorMessage = "Error creating and saving close note for reason change requirement with document service"; LOG.error("createReasonNote " + errorMessage, e); throw new RuntimeException(errorMessage, e); } }</code><technical_language>I if need isNoteReadyToBeSaved logic here. in createReasonNote function, populateIdentifierOnNoteAndExtension takes care of condition caused root problem of this Jira. want save note here</technical_language>

Target:
private void createReasonNote(ActionForm form) { KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form; try { Note noteObj = SpringContext.getBean(DocumentService.class).createNoteFromDocument(kualiDocumentFormBase.getDocument(), ((PurchasingFormBase)kualiDocumentFormBase).getReasonToChange()); populateIdentifierOnNoteAndExtension(noteObj); kualiDocumentFormBase.getDocument().addNote(noteObj); if (doesDocumentAllowImmediateSaveOfNewNote(kualiDocumentFormBase.getDocument(), noteObj)) { getNoteService().save(noteObj); } ((PurchasingFormBase)kualiDocumentFormBase).setReasonToChange(KFSConstants.EMPTY_STRING); } catch(Exception e){ String errorMessage = "Error creating and saving close note for reason change requirement with document service"; LOG.error("createReasonNote " + errorMessage, e); throw new RuntimeException(errorMessage, e); } }
Source:
<code>public void onError(Throwable t) { throw newIllegalStateException(t, <START> "Error observing the external messages for consumer " + <END> "with tag %s.", delegate.getTag()); }</code><technical_language>Consider formatting parameter a new line, allow string piece</technical_language>

Target:
public void onError(Throwable t) { throw newIllegalStateException(t, "Error observing the messages for consumer with tag %s.", delegate.getTag()); }
Source:
<code>public void uploadFile(final Path localPath, final Path remotePath, final AbstractBackupPath path, final int retry, final boolean deleteAfterSuccessfulUpload) throws FileNotFoundException, BackupRestoreException { if (localPath == null || remotePath == null || !localPath.toFile().exists() || localPath.toFile().isDirectory()) throw new FileNotFoundException("File do not exist or is a directory. localPath: " + localPath + ", remotePath: " + remotePath); <START> if (!tasksQueued.contains(localPath)) { <END> tasksQueued.add(localPath); logger.info("Uploading file: to location: {}", localPath, remotePath); try { notifyEventStart(new BackupEvent(path)); long uploadedFileSize = new BoundedExponentialRetryCallable<Long>(500, 10000, retry) { @Override public Long retriableCall() throws Exception { return uploadFileImpl(localPath, remotePath); } }.call(); backupMetrics.recordUploadRate(uploadedFileSize); backupMetrics.incrementValidUploads(); path.setCompressedFileSize(uploadedFileSize); notifyEventSuccess(new BackupEvent(path)); logger.info("Successfully uploaded file: to location: {}", localPath, remotePath); if (deleteAfterSuccessfulUpload) FileUtils.deleteQuietly(localPath.toFile()); } catch (Exception e) { backupMetrics.incrementInvalidUploads(); notifyEventFailure(new BackupEvent(path)); logger.error("Error while uploading file: to location: {}", localPath, remotePath); throw new BackupRestoreException(e.getMessage()); } finally { tasksQueued.remove(localPath); } } else logger.info("Already in queue, no-op. File: {}", localPath); }</code><technical_language>do if (tasksQueued.add(localPath))</technical_language>

Target:
public void uploadFile(final Path localPath, final Path remotePath, final AbstractBackupPath path, final int retry, final boolean deleteAfterSuccessfulUpload) throws FileNotFoundException, BackupRestoreException { if (localPath == null || remotePath == null || !localPath.toFile().exists() || localPath.toFile().isDirectory()) throw new FileNotFoundException("File do not exist or is a directory. localPath: " + localPath + ", remotePath: " + remotePath); if (tasksQueued.add(localPath)) { logger.info("Uploading file: to location: {}", localPath, remotePath); try { notifyEventStart(new BackupEvent(path)); long uploadedFileSize = new BoundedExponentialRetryCallable<Long>(500, 10000, retry) { @Override public Long retriableCall() throws Exception { return uploadFileImpl(localPath, remotePath); } }.call(); backupMetrics.recordUploadRate(uploadedFileSize); backupMetrics.incrementValidUploads(); path.setCompressedFileSize(uploadedFileSize); notifyEventSuccess(new BackupEvent(path)); logger.info("Successfully uploaded file: to location: {}", localPath, remotePath); if (deleteAfterSuccessfulUpload) FileUtils.deleteQuietly(localPath.toFile()); } catch (Exception e) { backupMetrics.incrementInvalidUploads(); notifyEventFailure(new BackupEvent(path)); logger.error("Error while uploading file: to location: {}", localPath, remotePath); throw new BackupRestoreException(e.getMessage()); } finally { tasksQueued.remove(localPath); } } else logger.info("Already in queue, no-op. File: {}", localPath); }
Source:
<code>public void tailsNonUtf() throws Exception { final SSHD sshd = new SSHD(this.temp.newFolder()); final File home = new File(sshd.home(), "testTail"); FileUtils.forceMkdir(home); final String clean = "some output"; <START> FileUtils.write( <END> new File(home, "stdout"), String.format("%s\u00ea", clean) ); final Talk talk = new Talk.InFile(); final String hash = "a1b5c3e3"; talk.modify( new Directives().xpath("/talk") .add("daemon") .attr(TailITCase.DIRECTIVE_ID_KEY, hash) .add("title").set("tail").up() .add("script").set("empty").up() .add("dir").set(home.getAbsolutePath()).up() .add("code").set("-7").up() .add("started").set(new Time().iso()).up() .add("ended").set(new Time().iso()).up().up() .add("shell").attr(TailITCase.DIRECTIVE_ID_KEY, hash) .add("host").set("localhost").up() .add("port").set(Integer.toString(sshd.port())).up() .add("login").set(sshd.login()).up() .add("key").set(sshd.key()).up().up() ); final Tail agent = new Tail(talk.read(), hash); MatcherAssert.assertThat( IOUtils.toString(agent.read(), Charsets.UTF_8), Matchers.equalTo(String.format("%sê\n", clean)) ); }</code><technical_language>@original-brownbear pure java 7 feature java.nio.file.Files.write()</technical_language>

Target:
public void tailsNonUtf() throws Exception { final SSHD sshd = new SSHD(this.temp.newFolder()); final File home = new File(sshd.home(), "testTail"); FileUtils.forceMkdir(home); final String clean = "some output"; FileUtils.write( new File(home, "stdout"), String.format("%s\u00ea", clean) ); final Talk talk = new Talk.InFile(); final String hash = "a1b5c3e3"; final String key = "id"; talk.modify( new Directives().xpath("/talk") .add("daemon") .attr(key, hash) .add("title").set("tail").up() .add("script").set("empty").up() .add("dir").set(home.getAbsolutePath()).up() .add("code").set("-7").up() .add("started").set(new Time().iso()).up() .add("ended").set(new Time().iso()).up().up() .add("shell").attr(key, hash) .add("host").set("localhost").up() .add("port").set(Integer.toString(sshd.port())).up() .add("login").set(sshd.login()).up() .add("key").set(sshd.key()).up().up() ); MatcherAssert.assertThat( IOUtils.toString( new Tail(talk.read(), hash).read(), Charsets.UTF_8 ), Matchers.is(String.format("%sê\n", clean)) ); }
Source:
<code>public static void setInterestClient(EurekaInterestClient interestClient) { <START> Eureka2Clients.interestClient = interestClient; <END> }</code><technical_language>Is a need shutdown existing client, if present</technical_language>

Target:
public static EurekaInterestClient setInterestClient(EurekaInterestClient interestClient) { return Eureka2Clients.interestClient.getAndSet(interestClient); }
Source:
<code>public boolean addPredicates(AbstractSqlWriter writer) throws OseeCoreException { Collection<String> ids = criteria.getIds(); if (ids.size() > 1) { joinQuery = writer.writeCharJoin(ids); writer.write(artAlias); writer.write(".guid = "); writer.write(jguidAlias); writer.write(".id AND "); writer.write(jguidAlias); writer.write(".query_id = ?"); writer.addParameter(joinQuery.getQueryId()); } else { writer.write(artAlias); writer.write(".guid = ?"); writer.addParameter(ids.iterator().next()); } if (withClause != null) { writer.write(" AND "); writer.write(withClauseName); writer.write(".transaction_id = "); writer.write(txsAlias); writer.write(".transaction_id AND "); writer.write(withClauseName); writer.write(".art_id = "); writer.write(artAlias); writer.write(".art_id\n"); } writer.write(" AND "); writer.write(artAlias); writer.write(".gamma_id = "); writer.write(txsAlias); writer.write(".gamma_id AND "); <START> ArtifactQuerySqlWriter specificWriter = (ArtifactQuerySqlWriter) writer; <END> writer.write(specificWriter.getTxFilterWithBranch(txsAlias, OptionsUtil.areDeletedArtifactsIncluded(writer.getOptions()))); return true; }</code><technical_language>Handlers specific writers - blind cast here</technical_language>

Target:
public boolean addPredicates(AbstractSqlWriter writer) throws OseeCoreException { Collection<String> ids = criteria.getIds(); if (ids.size() > 1) { joinQuery = writer.writeCharJoin(ids); writer.write(artAlias); writer.write(".guid = "); writer.write(jguidAlias); writer.write(".id AND "); writer.write(jguidAlias); writer.write(".query_id = ?"); writer.addParameter(joinQuery.getQueryId()); } else { writer.write(artAlias); writer.write(".guid = ?"); writer.addParameter(ids.iterator().next()); } if (withClause != null) { writer.write(" AND "); writer.write(withClauseName); writer.write(".transaction_id = "); writer.write(txsAlias); writer.write(".transaction_id AND "); writer.write(withClauseName); writer.write(".art_id = "); writer.write(artAlias); writer.write(".art_id\n"); } writer.write(" AND "); writer.write(artAlias); writer.write(".gamma_id = "); writer.write(txsAlias); writer.write(".gamma_id AND "); writer.write(getTxFilterWithBranch(txsAlias, OptionsUtil.areDeletedArtifactsIncluded(writer.getOptions()), branchId, writer)); return true; }
Source:
<code>public void run(ITestInvocationListener listener) throws DeviceNotAvailableException { for (int j = 0; j < mRepeatedRun; j++) { String runName = mBaseRunName + j; if (mIncludeFilters.isEmpty()) { listener.testRunStarted(runName, mNumTest); } else { <START> CLog.e("%s", mIncludeFilters); <END> listener.testRunStarted(runName, mIncludeFilters.size() / mRepeatedRun); } for (int i = 0; i < mNumTest - mFailedTest; i++) { TestDescription test = new TestDescription(runName + "class", "test" + i); if (!mIncludeFilters.isEmpty() && !mIncludeFilters.contains(test.toString())) { continue; } listener.testStarted(test); listener.testEnded(test, new HashMap<String, Metric>()); } for (int i = 0; i < mFailedTest; i++) { TestDescription test = new TestDescription(runName + "class", "fail" + i); if (!mIncludeFilters.isEmpty() && !mIncludeFilters.contains(test.toString())) { continue; } listener.testStarted(test); listener.testFailed(test, "I failed."); listener.testEnded(test, new HashMap<String, Metric>()); } listener.testRunEnded(0, new HashMap<String, Metric>()); } }</code><technical_language>CLog.e</technical_language>

Target:
public void run(ITestInvocationListener listener) throws DeviceNotAvailableException { for (int j = 0; j < mRepeatedRun; j++) { String runName = mBaseRunName + j; if (mIncludeFilters.isEmpty()) { listener.testRunStarted(runName, mNumTest); } else { listener.testRunStarted(runName, mIncludeFilters.size() / mRepeatedRun); } for (int i = 0; i < mNumTest - mFailedTest; i++) { TestDescription test = new TestDescription(runName + "class", "test" + i); if (!mIncludeFilters.isEmpty() && !mIncludeFilters.contains(test.toString())) { continue; } listener.testStarted(test); listener.testEnded(test, new HashMap<String, Metric>()); } for (int i = 0; i < mFailedTest; i++) { TestDescription test = new TestDescription(runName + "class", "fail" + i); if (!mIncludeFilters.isEmpty() && !mIncludeFilters.contains(test.toString())) { continue; } listener.testStarted(test); listener.testFailed(test, "I failed."); listener.testEnded(test, new HashMap<String, Metric>()); } listener.testRunEnded(0, new HashMap<String, Metric>()); } }
Source:
<code>public void play() { try { <START> Log.i(TAG, filePath); <END> new File((new File(this.filePath).getParentFile().list())[0]) .exists(); if (player.isPlaying()) { player.stop(); } this.paused = false; player.reset(); FileInputStream fis = new FileInputStream(this.filePath); player.setDataSource(fis.getFD()); player.prepare(); player.start(); this.messagingService .getService() .sendPlayStatusMessage(PlayStatusMessage.PLAY_MESSAGE); } catch (Exception e) { Log.wtf(TAG, "Unable to play song: " + this.filePath); e.printStackTrace(); } }</code><technical_language>Do want this log</technical_language>

Target:
public void play() { if (isValidPath()) { try { if (player.isPlaying()) { player.stop(); } this.paused = false; player.reset(); FileInputStream fis = new FileInputStream(entry.getFilePath()); player.setDataSource(fis.getFD()); player.prepare(); player.start(); this.messagingService.getService().sendPlayStatusMessage( this.entry, true); } catch (Exception e) { Log.wtf(TAG, "Unable to play song: " + entry.getFilePath()); } } else { Log.w(TAG, "File Path was not valid"); } }
Source:
<code>void toggleCamera() { editor = sp.edit(); CameraSettings settings = barcodeView.getBarcodeView().getCameraSettings(); if (barcodeView.getBarcodeView().isPreviewActive()) { barcodeView.pause(); } <START> if (cameraState == Camera.CameraInfo.CAMERA_FACING_BACK) { <END> cameraState = Camera.CameraInfo.CAMERA_FACING_FRONT; } else { cameraState = Camera.CameraInfo.CAMERA_FACING_BACK; } settings.setRequestedCameraId(cameraState); barcodeView.getBarcodeView().setCameraSettings(settings); editor.putInt("cameraState",cameraState); editor.apply(); barcodeView.resume(); }</code><technical_language>I guess keeping this line previous if (settings.getRequestedCameraId() == Camera.CameraInfo.CAMERA_FACING_BACK) more functionally thing</technical_language>

Target:
void toggleCamera() { editor = sp.edit(); CameraSettings settings = barcodeView.getBarcodeView().getCameraSettings(); if (barcodeView.getBarcodeView().isPreviewActive()) { barcodeView.pause(); } if (settings.getRequestedCameraId() == Camera.CameraInfo.CAMERA_FACING_BACK) { cameraState = Camera.CameraInfo.CAMERA_FACING_FRONT; } else { cameraState = Camera.CameraInfo.CAMERA_FACING_BACK; } settings.setRequestedCameraId(cameraState); barcodeView.getBarcodeView().setCameraSettings(settings); editor.putInt("cameraState",cameraState); editor.apply(); barcodeView.resume(); }
Source:
<code>private void beforeTest(Config cfg, boolean memory, boolean enableHttpd) throws Exception { server = startServer(cfg, memory, enableHttpd); server.getTestInjector().injectMembers(this); <START> init(); <END> }</code><technical_language>start a new server if this test @GerritConfig @GerritConfigs</technical_language>

Target:
private void beforeTest(Config cfg, boolean memory, boolean enableHttpd) throws Exception { server = startServer(cfg, memory, enableHttpd); server.getTestInjector().injectMembers(this); try { dbHandle = server.getTestInjector().getInstance(InMemoryDatabase.class); } catch (Exception e) init(); }
Source:
<code>setChannelOptions(Configuration configuration, BigtableOptions.Builder builder) throws IOException { setCredentialOptions(builder, configuration); builder.setRetryOptions(createRetryOptions(configuration)); int channelCount = configuration.getInt( BIGTABLE_DATA_CHANNEL_COUNT_KEY, BigtableOptions.BIGTABLE_DATA_CHANNEL_COUNT_DEFAULT); builder.setDataChannelCount(channelCount); <START> StringBuilder agentBuidler = new StringBuilder(); <END> agentBuidler.append("hbase-").append(VersionInfo.getVersion()); String customUserAgent = configuration.get(CUSTOM_USER_AGENT_KEY); if (customUserAgent != null) { agentBuidler.append(',').append(customUserAgent); } builder.setUserAgent(agentBuidler.toString()); }</code><technical_language>agentBuidler -> agentBuilder</technical_language>

Target:
setChannelOptions(Configuration configuration, BigtableOptions.Builder builder) throws IOException { setCredentialOptions(builder, configuration); builder.setRetryOptions(createRetryOptions(configuration)); int channelCount = configuration.getInt( BIGTABLE_DATA_CHANNEL_COUNT_KEY, BigtableOptions.BIGTABLE_DATA_CHANNEL_COUNT_DEFAULT); builder.setDataChannelCount(channelCount); StringBuilder agentBuilder = new StringBuilder(); agentBuilder.append("hbase-").append(VersionInfo.getVersion()); String customUserAgent = configuration.get(CUSTOM_USER_AGENT_KEY); if (customUserAgent != null) { agentBuilder.append(',').append(customUserAgent); } builder.setUserAgent(agentBuilder.toString()); }
Source:
<code>private void validateProjects(Devfile devfile) throws DevfileFormatException { Set<String> existingNames = new HashSet<>(); for (Project project : devfile.getProjects()) { if (!existingNames.add(project.getName())) { throw new DevfileFormatException( format("Duplicate project name found:'%s'", project.getName())); } if (!PROJECT_NAME_PATTERN.matcher(project.getName()).matches()) { throw new DevfileFormatException( format( <START> "Invalid project name found:'%s'. Name must contain only Latin letters,\n" <END> + "digits or these following special characters ._-", project.getName())); } } }</code><technical_language>error message \n</technical_language>

Target:
private void validateProjects(Devfile devfile) throws DevfileFormatException { Set<String> existingNames = new HashSet<>(); for (Project project : devfile.getProjects()) { if (!existingNames.add(project.getName())) { throw new DevfileFormatException( format("Duplicate project name found:'%s'", project.getName())); } if (!PROJECT_NAME_PATTERN.matcher(project.getName()).matches()) { throw new DevfileFormatException( format( "Invalid project name found:'%s'. Name must contain only Latin letters," + "digits or these following special characters ._-", project.getName())); } } }
Source:
<code>private static Set<CfgBranchingBlock> findRootBranchingBlocks(ControlFlowGraph flowGraph, IterationStatementTree iteration, @Nullable JavaScriptTree condition) { return flowGraph.blocks().stream() .filter(cfgBlock -> cfgBlock instanceof CfgBranchingBlock) .map(cfgBlock -> (CfgBranchingBlock) cfgBlock) <START> .filter(cfgBranchingBlock -> { <END> final Tree branchingTree = cfgBranchingBlock.branchingTree(); if (iteration.equals(branchingTree)) { return true; } if (condition != null) { return condition.equals(branchingTree) || condition.isAncestorOf((JavaScriptTree) branchingTree); } return false; }) .collect(Collectors.toSet()); }</code><technical_language>@inverno extracting body of this lambda a separate method? This method findRootBranchingBlocks more readable more homogeneous</technical_language>

Target:
private static Set<CfgBranchingBlock> findRootBranchingBlocks(ControlFlowGraph flowGraph, IterationStatementTree iteration, @Nullable JavaScriptTree condition) { return flowGraph.blocks().stream() .filter(cfgBlock -> cfgBlock instanceof CfgBranchingBlock) .map(cfgBlock -> (CfgBranchingBlock) cfgBlock) .filter(cfgBranchingBlock -> blockBelongsToLoopEndCondition(cfgBranchingBlock, iteration, condition)) .collect(Collectors.toSet()); }
Source:
<code>public KeyAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; URL buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); if (pipeline != null) { return new KeyAsyncClient(vaultUrl, pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError( new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.CREDENTIAL_REQUIRED))); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); <START> policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), properties.get(SDK_NAME), <END> properties.get(SDK_VERSION), buildConfiguration)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyAsyncClient(vaultUrl, pipeline, serviceVersion); }</code><technical_language>Needs defaults</technical_language>

Target:
public KeyAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; URL buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw logger .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED))); } KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); if (pipeline != null) { return new KeyAsyncClient(vaultUrl, pipeline, serviceVersion); } if (credential == null) { throw logger.logExceptionAsError( new IllegalStateException(KeyVaultErrorCodeStrings .getErrorString(KeyVaultErrorCodeStrings.CREDENTIAL_REQUIRED))); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new KeyVaultCredentialPolicy(credential)); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new KeyAsyncClient(vaultUrl, pipeline, serviceVersion); }
Source:
<code>public List<SourceRecord> poll() throws InterruptedException { log.trace("{} Polling for new data"); while (!stop.get()) { final TableQuerier querier = tableQueue.peek(); if (!querier.querying()) { final long nextUpdate = querier.getLastUpdate() + config.getInt(JdbcSourceTaskConfig.POLL_INTERVAL_MS_CONFIG); final long untilNext = nextUpdate - time.milliseconds(); if (untilNext > 0) { log.trace("Waiting ms to poll next", untilNext, querier.toString()); time.sleep(untilNext); continue; } } final List<SourceRecord> results = new ArrayList<>(); try { log.debug("Checking for next block of results from {}", querier.toString()); querier.maybeStartQuery(cachedConnectionProvider.getValidConnection()); int batchMaxRows = config.getInt(JdbcSourceTaskConfig.BATCH_MAX_ROWS_CONFIG); boolean hadNext = true; while (results.size() < batchMaxRows && (hadNext = querier.next())) { results.add(querier.extractRecord()); } if (!hadNext) { resetAndRequeueHead(querier); } if (results.isEmpty()) { log.trace("No updates for {}", querier.toString()); continue; } log.debug("Returning records for {}", results.size(), querier.toString()); return results; } catch (SQLException sqle) { log.error("Failed to run query for table {}: {}", querier.toString(), sqle); resetAndRequeueHead(querier); return null; <START> } catch (Exception e) { <END> resetAndRequeueHead(querier); throw e; } } final TableQuerier querier = tableQueue.peek(); if (querier != null) { resetAndRequeueHead(querier); } return null; }</code><technical_language>Throwable</technical_language>

Target:
public List<SourceRecord> poll() throws InterruptedException { log.trace("{} Polling for new data"); while (!stop.get()) { final TableQuerier querier = tableQueue.peek(); if (!querier.querying()) { final long nextUpdate = querier.getLastUpdate() + config.getInt(JdbcSourceTaskConfig.POLL_INTERVAL_MS_CONFIG); final long untilNext = nextUpdate - time.milliseconds(); if (untilNext > 0) { log.trace("Waiting ms to poll next", untilNext, querier.toString()); time.sleep(untilNext); continue; } } final List<SourceRecord> results = new ArrayList<>(); try { log.debug("Checking for next block of results from {}", querier.toString()); querier.maybeStartQuery(cachedConnectionProvider.getValidConnection()); int batchMaxRows = config.getInt(JdbcSourceTaskConfig.BATCH_MAX_ROWS_CONFIG); boolean hadNext = true; while (results.size() < batchMaxRows && (hadNext = querier.next())) { results.add(querier.extractRecord()); } if (!hadNext) { resetAndRequeueHead(querier); } if (results.isEmpty()) { log.trace("No updates for {}", querier.toString()); continue; } log.debug("Returning records for {}", results.size(), querier.toString()); return results; } catch (SQLException sqle) { log.error("Failed to run query for table {}: {}", querier.toString(), sqle); resetAndRequeueHead(querier); return null; } catch (Throwable t) { resetAndRequeueHead(querier); throw t; } } final TableQuerier querier = tableQueue.peek(); if (querier != null) { resetAndRequeueHead(querier); } return null; }
Source:
<code>@Override public RelNode convert(RelNode rel) { LogicalRepeatUnion union = (LogicalRepeatUnion) rel; EnumerableConvention out = EnumerableConvention.INSTANCE; RelTraitSet traitSet = union.getTraitSet().replace(out); RelNode seedRel = union.getSeedRel(); RelNode iterativeRel = union.getIterativeRel(); <START> return new EnumerableRepeatUnion( <END> union.getMaxRep(), rel.getCluster(), traitSet, convert(seedRel, seedRel.getTraitSet().replace(EnumerableConvention.INSTANCE)), convert(iterativeRel, iterativeRel.getTraitSet().replace(EnumerableConvention.INSTANCE))); }</code><technical_language>(if all) enumerable operators include a static factory method takes account deducing collation distribution. include one</technical_language>

Target:
@Override public RelNode convert(RelNode rel) { LogicalRepeatUnion union = (LogicalRepeatUnion) rel; EnumerableConvention out = EnumerableConvention.INSTANCE; RelTraitSet traitSet = union.getTraitSet().replace(out); RelNode seedRel = union.getSeedRel(); RelNode iterativeRel = union.getIterativeRel(); return new EnumerableRepeatUnion( rel.getCluster(), traitSet, convert(seedRel, seedRel.getTraitSet().replace(out)), convert(iterativeRel, iterativeRel.getTraitSet().replace(out)), union.all, union.maxRep); }
Source:
<code>CapacityPermit permitFor(String name, ScheduledExecutorConfig config) { <START> CapacityPermit permit = permits.get(name); <END> if (permit == null) { CapacityPermit newPermit = new MemberCapacityPermit(name, config.getCapacity()); permit = permits.putIfAbsent(name, newPermit); permit = (permit == null) ? newPermit : permit; } return permit; }</code><technical_language>return permits.computeIfAbsent(name, n -> new MemberCapacityPermit(n, config.getCapacity())); instead</technical_language>

Target:
CapacityPermit permitFor(String name, ScheduledExecutorConfig config) { return permits.computeIfAbsent(name, n -> new MemberCapacityPermit(n, config.getCapacity())); }
Source:
<code>public String getClasspath(){ try{ if(classpath != null) return classpath; if(!new File(targetDir + File.separator + "tacoco.cp").exists()) { MavenCli mavenCli = new MavenCli(); mavenCli.doMain(new String[]{"dependency:build-classpath", "-Dmdep.outputFile=tacoco.cp"}, targetDir, System.out, System.out); } classpath = new String(Files.readAllBytes(Paths.get(targetDir,"tacoco.cp"))) + File.pathSeparator + StringUtils.join(new String[]{targetDir, "target", "test-classes"}, File.separator) <START> + File.pathSeparator + StringUtils.join(new String[]{targetDir, "target", "classes"}, File.separator); <END> }catch(Exception e){ e.printStackTrace(); } return classpath; }</code><technical_language>a StringBuffer, Guava write a custom utility method String Join</technical_language>

Target:
public String getClasspath(){ try{ if(classpath != null) return classpath; final String tacocoCpPath = new PathBuilder().path(targetDir).path("tacoco.cp").buildFilePath(); if(!new File(tacocoCpPath).exists()) { MavenCli mavenCli = new MavenCli(); mavenCli.doMain(new String[]{"dependency:build-classpath", "-Dmdep.outputFile=tacoco.cp"}, targetDir, System.out, System.out); } final String tacocoDependencies = new String(Files.readAllBytes(Paths.get(targetDir, "tacoco.cp"))); final String targetPath = new PathBuilder().path(targetDir).path("classes").buildFilePath(); final String targetTestPath = new PathBuilder().path(targetDir).path("test-classes").buildFilePath(); classpath = new PathBuilder().path(tacocoDependencies) .path(targetPath) .path(targetTestPath) .buildClassPath(); }catch(Exception e){ e.printStackTrace(); } return classpath; }
Source:
<code>public <T> Repository<T> createRepository(EventStore eventStore, AggregateFactory<T> aggregateFactory, SnapshotTriggerDefinition snapshotTriggerDefinition, ParameterResolverFactory parameterResolverFactory) { return createRepository(eventStore, aggregateFactory, snapshotTriggerDefinition, parameterResolverFactory, <START> new ClasspathHandlerDefinition(getClass().getClassLoader())); <END> }</code><technical_language>aggregateFactory.getAggregateType()'s class loader instead</technical_language>

Target:
public <T> Repository<T> createRepository(EventStore eventStore, AggregateFactory<T> aggregateFactory, SnapshotTriggerDefinition snapshotTriggerDefinition, ParameterResolverFactory parameterResolverFactory) { return createRepository(eventStore, aggregateFactory, snapshotTriggerDefinition, parameterResolverFactory, ClasspathHandlerDefinition.forClass(aggregateFactory.getAggregateType()), null); }
Source:
<code>BookieStateManager(ServerConfiguration conf, RegistrationManager registrationManager) throws IOException { this.conf = conf; this.registrationManager = registrationManager; <START> this.statsLogger = null; <END> this.ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()), NullStatsLogger.INSTANCE); this.bookieId = getMyId(); }</code><technical_language>NullStatsLogger.INSTANCE plain null I this constructor this other constructor this(conf, NullStatsLogger.INSTANCE, registrationManager, new LedgerDirsManager(...));</technical_language>

Target:
BookieStateManager(ServerConfiguration conf, RegistrationManager registrationManager) throws IOException { this(conf, NullStatsLogger.INSTANCE, registrationManager, new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()), NullStatsLogger.INSTANCE)); }
Source:
<code>private FileSystem getHadoopFileSystem(String sourceFileUrl, String hadoopConfigPath) throws Exception { final Configuration config = getConfiguration(sourceFileUrl, hadoopConfigPath); final Path path = new Path(sourceFileUrl); FileSystem fs = null; for (int attempt = 1; attempt <= maxAttempts; attempt++) { try { if(HdfsFetcher.keytabPath.length() > 0 && currentHadoopUser == null) { synchronized (HdfsFetcher.class) { if (currentHadoopUser == null) { if(!new File(HdfsFetcher.keytabPath).exists()) { logger.error("Invalid keytab file path. Please provide a valid keytab path"); throw new VoldemortException("Error in getting Hadoop filesystem. Invalid keytab file path."); } UserGroupInformation.setConfiguration(config); UserGroupInformation.loginUserFromKeytab(HdfsFetcher.kerberosPrincipal, HdfsFetcher.keytabPath); currentHadoopUser = UserGroupInformation.getCurrentUser(); logger.info("I have logged in as " + currentHadoopUser.getUserName()); } } } <START> fs = path.getFileSystem(config); <END> break; } catch(Exception e) { if(attempt < maxAttempts) { sleepForRetryDelayMs(attempt); } else { throw e; } } } return fs; }</code><technical_language>Is getFileSystem call thread safe ? Previously this in a synchronized block, is out of synchronization block</technical_language>

Target:
private FileSystem getHadoopFileSystem(String sourceFileUrl, String hadoopConfigPath) throws Exception { final Configuration config = getConfiguration(sourceFileUrl, hadoopConfigPath); final Path path = new Path(sourceFileUrl); FileSystem fs = null; for (int attempt = 1; attempt <= maxAttempts; attempt++) { try { if (HdfsFetcher.keytabPath.length() > 0) { synchronized (HdfsFetcher.class) { if (currentHadoopUser == null) { if (!new File(HdfsFetcher.keytabPath).exists()) { logger.error("Invalid keytab file path. Please provide a valid keytab path"); throw new VoldemortException("Error in getting Hadoop filesystem. Invalid keytab file path."); } UserGroupInformation.setConfiguration(config); UserGroupInformation.loginUserFromKeytab(HdfsFetcher.kerberosPrincipal, HdfsFetcher.keytabPath); currentHadoopUser = UserGroupInformation.getCurrentUser(); logger.info("I have logged in as " + currentHadoopUser.getUserName()); } else { currentHadoopUser.reloginFromKeytab(); } } } fs = path.getFileSystem(config); fs.exists(path); break; } catch(VoldemortException e) { throw e; } catch(Exception e) { if (ExceptionUtils.recursiveClassEquals(e, AuthenticationException.class)) { logger.info("Got an AuthenticationException from HDFS. " + "Will retry to login from scratch, on next attempt.", e); synchronized (HdfsFetcher.class) { currentHadoopUser = null; } } if(attempt < maxAttempts) { sleepForRetryDelayMs(attempt); } else { throw e; } } } return fs; }
Source:
<code>public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && DeterminismEvaluator.isDeterministic(expression) && <START> !NullabilityAnalyzer.mayReturnNullOnNonNullInput(expression) && <END> !isDynamicFilter(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }</code><technical_language>static import functions</technical_language>

Target:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression) && !isDynamicFilter(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }
Source:
<code>private static Optional<Credential> getImpersonatedCredential( Configuration config, Credential credential) throws IOException { String serviceAccountToImpersonate = IMPERSONATION_SERVICE_ACCOUNT_SUFFIX .withPrefixes(CONFIG_KEY_PREFIXES) .get(config, config::get); if (isNullOrEmpty(serviceAccountToImpersonate)) { <START> Map<String, String> serviceAccountMapping = <END> IMPERSONATION_IDENTIFIER_PREFIX .withPrefixes(CONFIG_KEY_PREFIXES) .getPropsWithPrefix(config); for (Map.Entry<String, String> entry : serviceAccountMapping.entrySet()) { if (matchedUserOrGroup(entry.getKey())) { serviceAccountToImpersonate = entry.getValue(); break; } } } if (isNullOrEmpty(serviceAccountToImpersonate)) { return Optional.empty(); } GoogleCloudStorageOptions options = GoogleHadoopFileSystemConfiguration.getGcsFsOptionsBuilder(config) .build() .getCloudStorageOptions(); HttpTransport httpTransport = HttpTransportFactory.createHttpTransport( options.getTransportType(), options.getProxyAddress(), options.getProxyUsername(), options.getProxyPassword()); GoogleCredential impersonatedCredential = new GoogleCredentialWithIamAccessToken( httpTransport, new CredentialHttpRetryInitializer(credential), serviceAccountToImpersonate, CredentialFactory.GCS_SCOPES); return Optional.of(impersonatedCredential.createScoped(CredentialFactory.GCS_SCOPES)); }</code><technical_language>get this map options object getImpersonationServiceAccounts() method instead</technical_language>

Target:
private static Optional<Credential> getImpersonatedCredential( Configuration config, Credential credential) throws IOException { GoogleCloudStorageOptions options = GoogleHadoopFileSystemConfiguration.getGcsFsOptionsBuilder(config) .build() .getCloudStorageOptions(); String serviceAccountToImpersonate = IMPERSONATION_SERVICE_ACCOUNT_SUFFIX .withPrefixes(CONFIG_KEY_PREFIXES) .get(config, config::get); if (isNullOrEmpty(serviceAccountToImpersonate)) { Optional<String> serviceAccountToImpersonateFromUser = getMatchedServiceAccountToImpersonateFromGroup( options.getUserImpersonationServiceAccounts(), ImmutableList.of(UserGroupInformation.getCurrentUser().getShortUserName())); Optional<String> serviceAccountToImpersonateFromGroup = getMatchedServiceAccountToImpersonateFromGroup( options.getGroupImpersonationServiceAccounts(), ImmutableList.copyOf(UserGroupInformation.getCurrentUser().getGroupNames())); serviceAccountToImpersonate = serviceAccountToImpersonateFromUser.orElse( serviceAccountToImpersonateFromGroup.orElse(null)); } if (isNullOrEmpty(serviceAccountToImpersonate)) { return Optional.empty(); } HttpTransport httpTransport = HttpTransportFactory.createHttpTransport( options.getTransportType(), options.getProxyAddress(), options.getProxyUsername(), options.getProxyPassword()); GoogleCredential impersonatedCredential = new GoogleCredentialWithIamAccessToken( httpTransport, new CredentialHttpRetryInitializer(credential), serviceAccountToImpersonate, CredentialFactory.GCS_SCOPES); return Optional.of(impersonatedCredential.createScoped(CredentialFactory.GCS_SCOPES)); }