auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void clearField(String structureInode, Field field) throws DotDataException { if(field.getFieldContentlet() == null || ! (field.getFieldContentlet().matches("^.*\\d+$"))){ return; } Queries queries = getQueries(field); List<String> inodesToFlush = new ArrayList<>(); <START> try(Connection conn = DbConnectionFactory.getConnection();PreparedStatement ps = conn.prepareStatement(queries.getSelect())) { <END> ps.setObject(1, structureInode); final int BATCH_SIZE = 200; try(ResultSet rs = ps.executeQuery();PreparedStatement ps2 = conn.prepareStatement(queries.getUpdate())) { for (int i = 1; rs.next(); i++) { String contentInode = rs.getString("inode"); inodesToFlush.add(contentInode); ps2.setString(1, contentInode); ps2.addBatch(); if (i % BATCH_SIZE == 0) { ps2.executeBatch(); } } ps2.executeBatch(); } } catch (SQLException e) { throw new DotDataException(String.format("Error clearing field '%s' for Content Type with ID: %s", field.getVelocityVarName(), structureInode), e); } for (String inodeToFlush : inodesToFlush) { cc.remove(inodeToFlush); } }</code><technical_language>I pretty if autoclose conn here. handle AOP</technical_language>

Target:
protected void clearField(String structureInode, Field field) throws DotDataException { if(field.getFieldContentlet() == null || ! (field.getFieldContentlet().matches("^.*\\d+$"))){ return; } Queries queries = getQueries(field); List<String> inodesToFlush = new ArrayList<>(); Connection conn = DbConnectionFactory.getConnection(); try(PreparedStatement ps = conn.prepareStatement(queries.getSelect())) { ps.setObject(1, structureInode); final int BATCH_SIZE = 200; try(ResultSet rs = ps.executeQuery();) { PreparedStatement ps2 = conn.prepareStatement(queries.getUpdate()); for (int i = 1; rs.next(); i++) { String contentInode = rs.getString("inode"); inodesToFlush.add(contentInode); ps2.setString(1, contentInode); ps2.addBatch(); if (i % BATCH_SIZE == 0) { ps2.executeBatch(); } } ps2.executeBatch(); } } catch (SQLException e) { throw new DotDataException(String.format("Error clearing field '%s' for Content Type with ID: %s", field.getVelocityVarName(), structureInode), e); } for (String inodeToFlush : inodesToFlush) { cc.remove(inodeToFlush); } }
Source:
<code>public CPPStreamConnectionProvider() { List<String> commands = new ArrayList<>(); if(store.getString(PreferenceConstants.P_SERVER_CHOICE).equals("cquery")) { languageServer = new CqueryLanguageServer(); } else if(store.getString(PreferenceConstants.P_SERVER_CHOICE).equals("clangd")) { languageServer = new ClangdLanguageServer(); <START> } <END> File defaultLSLocation = getDefaultLSLocation(store.getString(PreferenceConstants.P_SERVER_CHOICE)); if(defaultLSLocation != null) { store.setDefault(PreferenceConstants.P_SERVER_PATH, defaultLSLocation.getAbsolutePath()); } File languageServerLocation = getLanguageServerLocation(); String parent = ""; String flags = store.getString(PreferenceConstants.P_SERVER_OPTIONS); if (languageServerLocation != null) { commands.add(languageServerLocation.getAbsolutePath()); if (!flags.isEmpty()) { commands.add(flags); } parent = languageServerLocation.getParent(); } setWorkingDirectory(parent); setCommands(commands); }</code><technical_language>If, for reason, choice is "cquery" "clangd", then, allowing CPPStreamConnectionProvider constructed languageServer null (thus setting for NPE later), fail early, throwing UnsupportedOperationException("Unsupported language server")</technical_language>

Target:
public CPPStreamConnectionProvider() throws UnsupportedOperationException { List<String> commands = new ArrayList<>(); if (store.getString(PreferenceConstants.P_SERVER_CHOICE).equals("cquery")) { languageServer = new CqueryLanguageServer(); } else if (store.getString(PreferenceConstants.P_SERVER_CHOICE).equals("clangd")) { languageServer = new ClangdLanguageServer(); } else { throw new UnsupportedOperationException("Unsupported Language Server"); } File defaultLSLocation = getDefaultLSLocation(store.getString(PreferenceConstants.P_SERVER_CHOICE)); if(defaultLSLocation != null) { store.setDefault(PreferenceConstants.P_SERVER_PATH, defaultLSLocation.getAbsolutePath()); } File languageServerLocation = getLanguageServerLocation(); String parent = ""; String flags = store.getString(PreferenceConstants.P_SERVER_OPTIONS); if (languageServerLocation != null) { commands.add(languageServerLocation.getAbsolutePath()); if (!flags.isEmpty()) { commands.add(flags); } parent = languageServerLocation.getParent(); } setWorkingDirectory(parent); setCommands(commands); }
Source:
<code>public void testCommentsAndWhitespacePersists() throws Exception { InputStream inputStream = FrameworkUtil.getBundle(this.getClass()) .getEntry("testing-files/target-files/PersistTestCaseTarget.txt").openStream(); ITargetPlatformService service = PDECore.getDefault().acquireService(ITargetPlatformService.class); ITargetDefinition targetDefinition = service.newTarget(); TargetDefinitionPersistenceHelper.initFromXML(targetDefinition, inputStream); ByteArrayOutputStream actualOutput = new ByteArrayOutputStream(); TargetDefinitionPersistenceHelper.persistXML(targetDefinition, actualOutput); try (Scanner s = new Scanner(FrameworkUtil.getBundle(this.getClass()) .getEntry("testing-files/target-files/PersistTestCaseTarget.txt").openStream()).useDelimiter("\\A")) { String result = s.hasNext() ? s.next() : ""; assertEquals(result, actualOutput.toString(StandardCharsets.UTF_8.toString())); } catch <START> (Exception e) <END> { } }</code><technical_language>I more specific exception IOException catched</technical_language>

Target:
public void testCommentsAndWhitespacePersists() throws Exception { InputStream inputStream = FrameworkUtil.getBundle(this.getClass()) .getEntry("testing-files/target-files/PersistTestCaseTarget.txt").openStream(); ITargetPlatformService service = PDECore.getDefault().acquireService(ITargetPlatformService.class); ITargetDefinition targetDefinition = service.newTarget(); TargetDefinitionPersistenceHelper.initFromXML(targetDefinition, inputStream); ByteArrayOutputStream actualOutput = new ByteArrayOutputStream(); TargetDefinitionPersistenceHelper.persistXML(targetDefinition, actualOutput); try (Scanner s = new Scanner(FrameworkUtil.getBundle(this.getClass()) .getEntry("testing-files/target-files/PersistTestCaseTarget.txt").openStream()).useDelimiter("\\A")) { String result = s.hasNext() ? s.next() : ""; assertEquals(result, actualOutput.toString(StandardCharsets.UTF_8.toString())); } catch (IOException e) { } }
Source:
<code>public DescribeCommand always(boolean always) { this.alwaysFlag = always; <START> mojo.getLog().info("--always = " + always); <END> return this; }</code><technical_language>Awesome, thanks a lot</technical_language>

Target:
public DescribeCommand always(boolean always) { this.alwaysFlag = always; log.info("--always = {}", always); return this; }
Source:
<code>public void testTmfEventRequest() { TmfEventRequest request = new TmfEventRequestStub(ITmfEvent.class); assertEquals("getRequestId", fRequestCount++, request.getRequestId()); assertEquals("getDataType", ITmfEvent.class, request.getDataType()); assertEquals("StartTime", TmfTimestamp.BIG_BANG, request.getRange().getStartTime()); assertEquals("EndTime", TmfTimestamp.BIG_CRUNCH, request.getRange().getEndTime()); <START> <END> assertEquals("getIndex", 0, request.getIndex()); assertEquals("getNbRequestedEvents", TmfEventRequest.ALL_DATA, request.getNbRequested()); assertFalse("isCompleted", request.isCompleted()); assertFalse("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertEquals("getNbRead", 0, request.getNbRead()); }</code><technical_language>check for request.getRange().equals(ETERNITY)</technical_language>

Target:
public void testTmfEventRequest() { TmfEventRequest request = new TmfEventRequestStub(ITmfEvent.class); assertEquals("getRequestId", fRequestCount++, request.getRequestId()); assertEquals("getDataType", ITmfEvent.class, request.getDataType()); assertEquals("StartTime", TmfTimestamp.BIG_BANG, request.getRange().getStartTime()); assertEquals("EndTime", TmfTimestamp.BIG_CRUNCH, request.getRange().getEndTime()); assertEquals("getRange", TmfTimeRange.ETERNITY, request.getRange()); assertSame("getRange", TmfTimeRange.ETERNITY, request.getRange()); assertEquals("getIndex", 0, request.getIndex()); assertEquals("getNbRequestedEvents", TmfEventRequest.ALL_DATA, request.getNbRequested()); assertFalse("isCompleted", request.isCompleted()); assertFalse("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertEquals("getNbRead", 0, request.getNbRead()); }
Source:
<code>public static void showDialogDeletePermanently(final Activity activity, final Note note) { new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Dialog)) .setTitle(R.string.delete_dialog_title) .setMessage(R.string.delete_dialog_message) .setNegativeButton(R.string.cancel, null) .setPositiveButton( R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (note != null) { note.delete(); if (activity instanceof NotesActivity) { NotesActivity notesActivity = (NotesActivity) activity; <START> if(notesActivity.getNoteListFragment() != null) { <END> notesActivity.getNoteListFragment().updateSelectionAfterTrashAction(); } else { ((NotesActivity) activity).showDetailPlaceholder(); } } else if (activity instanceof NoteEditorActivity) { ((NoteEditorActivity) activity).finish(); } } else { DialogUtils.showDialogWithEmail( activity, activity.getString(R.string.delete_dialog_error_message) ); } } } ) .show(); }</code><technical_language>suggestion if (notesActivity.getNoteListFragment() != null) { This is missing a space if (</technical_language>

Target:
public static void showDialogDeletePermanently(final Activity activity, final Note note) { new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Dialog)) .setTitle(R.string.delete_dialog_title) .setMessage(R.string.delete_dialog_message) .setNegativeButton(R.string.cancel, null) .setPositiveButton( R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (note != null) { note.delete(); if (activity instanceof NotesActivity) { NotesActivity notesActivity = (NotesActivity) activity; if (notesActivity.getNoteListFragment() != null) { notesActivity.getNoteListFragment().updateSelectionAfterTrashAction(); } else { notesActivity.showDetailPlaceholder(); } } else if (activity instanceof NoteEditorActivity) { ((NoteEditorActivity) activity).finish(); } } else { DialogUtils.showDialogWithEmail( activity, activity.getString(R.string.delete_dialog_error_message) ); } } } ) .show(); }
Source:
<code>private boolean updateRngDevice() { if (!getParameters().isUpdateRngDevice()) { rngDeviceUtils.handleUrandomRandomChange( getParameters().getClusterLevelChangeFromVersion(), getCluster().getCompatibilityVersion(), getVmId(), cloneContextAndDetachFromParent(), true); return true; } <START> VdcQueryReturnValue query = runInternalQuery(VdcQueryType.GetRngDevice, new IdQueryParameters(getParameters().getVmId())); List<VmRngDevice> rngDevs = query.getReturnValue(); VdcReturnValueBase rngCommandResult = null; if (rngDevs.isEmpty()) { if (getParameters().getRngDevice() != null) { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); rngCommandResult = runInternalAction(VdcActionType.AddRngDevice, params, cloneContextAndDetachFromParent()); } } else { if (getParameters().getRngDevice() == null) { RngDeviceParameters params = new RngDeviceParameters(rngDevs.get(0), true); rngCommandResult = runInternalAction(VdcActionType.RemoveRngDevice, params, cloneContextAndDetachFromParent()); } else { RngDeviceParameters params = new RngDeviceParameters(getParameters().getRngDevice(), true); params.getRngDevice().setDeviceId(rngDevs.get(0).getDeviceId()); rngCommandResult = runInternalAction(VdcActionType.UpdateRngDevice, params, cloneContextAndDetachFromParent()); } } if (rngCommandResult != null && !rngCommandResult.getSucceeded()) { return false; } <END> return true; }</code><technical_language>this *old* flow completely separate new handling added, mind moving a separate method - e.g. handleRegularRngDeviceChange() this method read more in sense private boolean updateRngDevice() { if (shouldHanldeUrandomRandomChange()) { return handleUrandomRandomChange(); } else { return handleRegularRngDeviceChange(); } }</technical_language>

Target:
private boolean updateRngDevice() { if (getParameters().isUpdateRngDevice()) { return regularUpdateRngDevice(); } rngDeviceUtils.handleUrandomRandomChange( getParameters().getClusterLevelChangeFromVersion(), getCluster().getCompatibilityVersion(), getVmId(), cloneContextAndDetachFromParent(), true); return true; }
Source:
<code>protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { InfinispanConfiguration conf; if (configuration != null) { conf = configuration.copy(); } else { conf = new InfinispanConfiguration(); } String[] confParameters = new String[] {"hosts", "cacheContainerConfiguration", "configurationUri", "cacheContainer"}; <START> if (!Arrays.stream(confParameters).anyMatch(parameters::containsKey) || setCacheFromComponent) { <END> if (cacheContainer == null) { cacheContainer = new DefaultCacheManager(new GlobalConfigurationBuilder().defaultCacheName("default").build(), new org.infinispan.configuration.cache.ConfigurationBuilder().build()); setCacheFromComponent = false; } conf.setCacheContainer(cacheContainer); } else { conf.setCacheContainer(null); } InfinispanEndpoint endpoint = new InfinispanEndpoint(uri, remaining, this, conf); setProperties(endpoint, parameters); return endpoint; }</code><technical_language>need check values set InfinispanConfiguration</technical_language>

Target:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { InfinispanConfiguration conf; if (configuration != null) { conf = configuration.copy(); } else { conf = new InfinispanConfiguration(); } if (!isConfigProvided(parameters, conf) || setCacheFromComponent) { if (cacheContainer == null) { cacheContainer = new DefaultCacheManager(new GlobalConfigurationBuilder().defaultCacheName("default").build(), new org.infinispan.configuration.cache.ConfigurationBuilder().build()); setCacheFromComponent = false; log.debug("Default cacheContainer has been created"); } conf.setCacheContainer(cacheContainer); } else { conf.setCacheContainer(null); } InfinispanEndpoint endpoint = new InfinispanEndpoint(uri, remaining, this, conf); setProperties(endpoint, parameters); return endpoint; }
Source:
<code>public EventProcessorAsyncClient createInstance() { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};" <START> + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}"; <END> EventProcessorAsyncClient eventProcessorAsyncClient = new EventHubClientBuilder() .connectionString(connectionString) .partitionProcessorFactory((PartitionProcessorImpl::new)) .consumerGroupName("consumer-group") .buildEventProcessorAsyncClient(); END: com.azure.messaging.eventhubs.eventprocessorasyncclient.instantiation return eventProcessorAsyncClient; }</code><technical_language>eventHubPath -> eventHubName</technical_language>

Target:
public EventProcessorAsyncClient createInstance() { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};" + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}"; EventProcessorAsyncClient eventProcessorAsyncClient = new EventHubClientBuilder() .connectionString(connectionString) .partitionProcessorFactory((PartitionProcessorImpl::new)) .consumerGroupName("consumer-group") .buildEventProcessorAsyncClient(); END: com.azure.messaging.eventhubs.eventprocessorasyncclient.instantiation return eventProcessorAsyncClient; }
Source:
<code>public void deleteExtraDownloadedFiles() { new Thread(new Runnable() { @Override public void run() { final ProfileModel profile = getEnvironment(MainApplication.this).getUserPrefs().getProfile(); final IDatabase db = getEnvironment(MainApplication.this).getDatabase(); <START> if (profile != null) <END> db.getAllVideos(Sha1Util.SHA1(profile.username), new DataCallback<List<VideoModel>>() { @Override public void onResult(List<VideoModel> result) { ArrayList<File> extraFiles = FileUtil.getAllFileFromExternalStorage(MainApplication.this, profile); FileUtil.deleteExtraFilesNotInDatabase(result, extraFiles); } @Override public void onFail(Exception ex) { Log.e(this.getClass().getSimpleName(), "Unable to get to get list of Videos" ); } }); } }).start(); }</code><technical_language>This if block brackets for code clarity</technical_language>

Target:
public void deleteExtraDownloadedFiles() { new Thread(new Runnable() { @Override public void run() { final ProfileModel profile = getEnvironment(MainApplication.this).getUserPrefs().getProfile(); final IDatabase db = getEnvironment(MainApplication.this).getDatabase(); if (profile != null) { db.getAllVideos(Sha1Util.SHA1(profile.username), new DataCallback<List<VideoModel>>() { @Override public void onResult(List<VideoModel> result) { ArrayList<File> extraFiles = FileUtil.getAllFileFromExternalStorage(MainApplication.this, profile); FileUtil.deleteExtraFilesNotInDatabase(result, extraFiles); } @Override public void onFail(Exception ex) { Log.e(this.getClass().getSimpleName(), "Unable to get to get list of Videos" ); } }); } } }).start(); }
Source:
<code>public void onError(int error) { <START> if (error == 7) { <END> changeUIStateToRetry(); } }</code><technical_language>some constant in SDK use? 7 is a magic number; avoid this code hard read</technical_language>

Target:
public void onError(int error) { if (error == SpeechRecognizer.ERROR_NO_MATCH) { changeUIStateToRetry(); } }
Source:
<code>private void trackQuickActionCompleted(QuickActionTrackPropertyValue type) { Map<String, String> properties = new HashMap<>(1); properties.put("quick_action", type.toString()); <START> AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_QUICK_ACTIONS_QUICKACTION_TOUCH, properties); <END> }</code><technical_language>I add a call AnalyticsTracker.flush(); - Analytics data remote server</technical_language>

Target:
private void trackQuickActionCompleted(QuickActionTrackPropertyValue type) { Map<String, String> properties = new HashMap<>(1); properties.put("quick_action", type.toString()); AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_QUICK_ACTIONS_QUICKACTION_TOUCHED, properties); AnalyticsTracker.flush(); }
Source:
<code>public Response getCompleteTasks( @QueryParam("n") final Integer maxTaskStatuses, @Context final HttpServletRequest req ) { final Function<String, Task> taskFunction = taskId -> { final Optional<Task> optionalTask = taskStorageQueryAdapter.getTask(taskId); if (!optionalTask.isPresent()) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return optionalTask.get(); }; Function<TaskStatus, Iterable<ResourceAction>> raGenerator = taskStatus -> { final Task task = taskFunction.apply(taskStatus.getId()); return Lists.newArrayList( new ResourceAction( new Resource(task.getDataSource(), ResourceType.DATASOURCE), Action.READ ) ); }; final List<TaskStatus> recentlyFinishedTasks = Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, taskStorageQueryAdapter.getRecentlyFinishedTaskStatuses(maxTaskStatuses), raGenerator, authorizerMapper ) ); final List<TaskStatusPlus> completeTasks = recentlyFinishedTasks .stream() .map(status -> new TaskStatusPlus( status.getId(), taskFunction.apply(status.getId()).getType(), taskStorageQueryAdapter.getCreatedTime(status.getId()), DateTimes.EPOCH, status.getStatusCode(), status.getDuration(), TaskLocation.unknown(), <START> taskStorageQueryAdapter.getTask(status.getId()).get().getDataSource() <END> ) ) .collect(Collectors.toList()); return Response.ok(completeTasks).build(); }</code><technical_language>add a method TaskStorageQueryAdapter getCreatedDateTimeAndDataSource fetches datasource created time in single query instead of issuing multiple queries metadata storage</technical_language>

Target:
public Response getCompleteTasks( @QueryParam("n") final Integer maxTaskStatuses, @Context final HttpServletRequest req ) { final Function<String, Task> taskFunction = taskId -> { final Optional<Task> optionalTask = taskStorageQueryAdapter.getTask(taskId); if (!optionalTask.isPresent()) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return optionalTask.get(); }; Function<TaskStatus, Iterable<ResourceAction>> raGenerator = taskStatus -> { final Task task = taskFunction.apply(taskStatus.getId()); return Lists.newArrayList( new ResourceAction( new Resource(task.getDataSource(), ResourceType.DATASOURCE), Action.READ ) ); }; final List<TaskStatus> recentlyFinishedTasks = Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, taskStorageQueryAdapter.getRecentlyFinishedTaskStatuses(maxTaskStatuses), raGenerator, authorizerMapper ) ); final List<TaskStatusPlus> completeTasks = Lists.newArrayList(Iterables.transform( recentlyFinishedTasks, status -> { final Pair<DateTime, String> pair = taskStorageQueryAdapter.getCreatedDateAndDataSource(status.getId()); return new TaskStatusPlus( status.getId(), taskFunction.apply(status.getId()).getType(), pair.lhs, DateTimes.EPOCH, status.getStatusCode(), status.getDuration(), TaskLocation.unknown(), pair.rhs); })); return Response.ok(completeTasks).build(); }
Source:
<code>public int compare(ScanResultValue o1, ScanResultValue o2) { int comparison; <START> if (scanQuery.getResultFormat().equals(ScanQuery.RESULT_FORMAT_LIST)) { <END> comparison = Longs.compare( (Long) ((Map<String, Object>) ((List<Object>) o1.getEvents()).get(0)).get(ColumnHolder.TIME_COLUMN_NAME), (Long) ((Map<String, Object>) ((List<Object>) o2.getEvents()).get(0)).get(ColumnHolder.TIME_COLUMN_NAME) ); } else if (scanQuery.getResultFormat().equals(ScanQuery.RESULT_FORMAT_COMPACTED_LIST)) { int val1TimeColumnIndex = o1.getColumns().indexOf(ColumnHolder.TIME_COLUMN_NAME); int val2TimeColumnIndex = o2.getColumns().indexOf(ColumnHolder.TIME_COLUMN_NAME); List<Object> event1 = (List<Object>) ((List<Object>) o1.getEvents()).get(0); List<Object> event2 = (List<Object>) ((List<Object>) o2.getEvents()).get(0); comparison = Longs.compare( (Long) event1.get(val1TimeColumnIndex), (Long) event2.get(val2TimeColumnIndex) ); } else { throw new UOE("Result format [%s] is not supported", scanQuery.getResultFormat()); } if (scanQuery.getTimeOrder().equals(ScanQuery.TIME_ORDER_DESCENDING)) { return comparison * -1; } return comparison; }</code><technical_language>This creates coupling result format query toolchest, try avoid, tougher add new result formats. Adding a getFirstTimestamp() method ScanResultValue a good of that, imo</technical_language>

Target:
public int compare(ScanResultValue o1, ScanResultValue o2) { int comparison; comparison = Longs.compare( o1.getFirstEventTimestamp(scanQuery), o2.getFirstEventTimestamp(scanQuery)); if (scanQuery.getTimeOrder().equals(ScanQuery.TimeOrder.DESCENDING)) { return comparison; } return comparison * -1; }
Source:
<code>public static void notifyLocationChanged( final Iterable<Pair<TaskRunnerListener, Executor>> listeners, final String taskId, final TaskLocation location ) { log.info("Task [%s] location changed to [%s].", taskId, location); for (final Pair<TaskRunnerListener, Executor> listener : listeners) { try { listener.rhs.execute( new Runnable() { @Override public void run() { listener.lhs.locationChanged(taskId, location); } } ); } <START> catch (Exception e) { <END> log.warn(e, "Unable to notify listener for task[%s].", taskId); } } }</code><technical_language>is intended handling of InterruptedException here</technical_language>

Target:
public static void notifyLocationChanged( final Iterable<Pair<TaskRunnerListener, Executor>> listeners, final String taskId, final TaskLocation location ) { log.info("Task [%s] location changed to [%s].", taskId, location); for (final Pair<TaskRunnerListener, Executor> listener : listeners) { try { listener.rhs.execute( new Runnable() { @Override public void run() { listener.lhs.locationChanged(taskId, location); } } ); } catch (Exception e) { log.makeAlert(e, "Unable to notify task listener") .addData("taskId", taskId) .addData("taskLocation", location) .addData("listener", listener.toString()) .emit(); } } }
Source:
<code>private void assertCommandWithIdsIssued(String expectedCommand) throws MessagingException, IOException { ArgumentCaptor<String> commandPrefixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> commandSuffixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Set> commandUidsCaptor = ArgumentCaptor.forClass(Set.class); verify(imapConnection, atLeastOnce()).executeCommandWithIdSet( commandPrefixCaptor.capture(), commandSuffixCaptor.capture(), commandUidsCaptor.capture()); List<String> commandPrefixes = commandPrefixCaptor.getAllValues(); List<String> commandSuffixes = commandSuffixCaptor.getAllValues(); List<Set> commandUids = commandUidsCaptor.getAllValues(); for (int i = 0, end = commandPrefixes.size(); i < end; i++) { String command = commandPrefixes.get(i) + " " + ImapUtility.join(",", commandUids.get(i)) + " " + commandSuffixes.get(i); <START> if (command.trim().equals(expectedCommand)) { <END> return; } } fail("Expected IMAP command not issued: " + expectedCommand); }</code><technical_language>fix construction of command trimming erroneously added space end</technical_language>

Target:
private void assertCommandWithIdsIssued(String expectedCommand) throws MessagingException, IOException { ArgumentCaptor<String> commandPrefixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> commandSuffixCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Set> commandUidsCaptor = ArgumentCaptor.forClass(Set.class); verify(imapConnection, atLeastOnce()).executeCommandWithIdSet( commandPrefixCaptor.capture(), commandSuffixCaptor.capture(), commandUidsCaptor.capture()); List<String> commandPrefixes = commandPrefixCaptor.getAllValues(); List<String> commandSuffixes = commandSuffixCaptor.getAllValues(); List<Set> commandUids = commandUidsCaptor.getAllValues(); for (int i = 0, end = commandPrefixes.size(); i < end; i++) { String command = commandPrefixes.get(i) + " " + ImapUtility.join(",", commandUids.get(i)) + ((commandSuffixes.get(i).length() == 0) ? "" : " " + commandSuffixes.get(i)); if (command.equals(expectedCommand)) { return; } } fail("Expected IMAP command not issued: " + expectedCommand); }
Source:
<code>private void testSumOverSameGroup(int max, boolean fullGiraphEnv) throws Exception { TestGraphUtils.runTest( TestGraphUtils.chainModifiers( new Small1GraphInit<IntWritable, IntWritable, NullWritable>(), <START> new EachVertexInit<>((vertex) -> vertex.getValue().set(- vertex.getId().get() % max))), <END> (graph) -> { int[] sums = new int[max]; for (int i = 0; i < max; i ++) { sums[i] -= i; } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { sums[vtx.getId().get() % max] += vtx.getId().get(); } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { Assert.assertEquals(sums[vtx.getId().get() % max], vtx.getValue().get()); } }, (GiraphConfiguration conf) -> { BlockUtils.setBlockFactoryClass(conf, MessagesWithoutVerticesBlockFactory.class); TestGraphUtils.USE_FULL_GIRAPH_ENV_IN_TESTS.set(conf, fullGiraphEnv); }); }</code><technical_language>confirm: this work if message is existing vertex, correct? in test case well</technical_language>

Target:
private void testSumOverSameGroup(int max, boolean fullGiraphEnv) throws Exception { Int2IntFunction f = (id) -> id % max - 1; TestGraphUtils.runTest( TestGraphUtils.chainModifiers( new Small1GraphInit<IntWritable, IntWritable, NullWritable>(), new EachVertexInit<>((vertex) -> vertex.getValue().set(f.apply(vertex.getId().get())))), (graph) -> { Int2IntOpenHashMap sums = new Int2IntOpenHashMap(); for (int i = 0; i < max; i ++) { sums.addTo(f.apply(i), f.apply(i) + 1); } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { sums.addTo(f.apply(vtx.getId().get()), vtx.getId().get() + 1); } for (Vertex<IntWritable, IntWritable, NullWritable> vtx : graph.getTestGraph()) { Assert.assertEquals(sums.get(f.apply(vtx.getId().get())), vtx.getValue().get()); } Assert.assertNull(graph.getVertex(-1)); }, (GiraphConfiguration conf) -> { BlockUtils.setBlockFactoryClass(conf, MessagesWithoutVerticesBlockFactory.class); TestGraphUtils.USE_FULL_GIRAPH_ENV_IN_TESTS.set(conf, fullGiraphEnv); }); }
Source:
<code>public void init(Path configPath, Supplier<String> nodeName, Supplier<NodeContext> nodeContext) throws UncheckedNomadException { requireNonNull(configPath); requireNonNull(nodeName); requireNonNull(nodeContext); this.configurationManager = new NomadConfigurationManager(configPath, parameterSubstitutor); this.configurationManager.createDirectories(); DynamicConfigEventServiceImpl eventService = new DynamicConfigEventServiceImpl(); this.eventRegistrationService = eventService; this.eventFiringService = eventService; try { this.nomadServer = nomadServerFactory.createServer(getConfigurationManager(), null, nodeName.get(), getEventFiringService()); } catch (SanskritException | NomadException e) { throw new UncheckedNomadException("Exception initializing Nomad Server: " + e.getMessage(), e); } DynamicConfigServiceImpl dynamicConfigService = new DynamicConfigServiceImpl(nodeContext.get(), licenseService, this, objectMapperFactory); DynamicConfigListener auditListener = new AuditListener(); <START> this.dynamicConfigService = new AuditService(dynamicConfigService, auditListener); <END> this.topologyService = dynamicConfigService; getEventRegistrationService().register(dynamicConfigService); getEventRegistrationService().register(auditListener); LOGGER.info("Bootstrapped nomad system with root: {}", parameterSubstitutor.substitute(configPath.toString())); }</code><technical_language>new AuditService(dynamicConfigService); is enough: need decorate DynamicConfigService interface</technical_language>

Target:
public void init(Path configPath, Supplier<String> nodeName, Supplier<NodeContext> nodeContext) throws UncheckedNomadException { requireNonNull(configPath); requireNonNull(nodeName); requireNonNull(nodeContext); this.configurationManager = new NomadConfigurationManager(configPath, parameterSubstitutor); this.configurationManager.createDirectories(); DynamicConfigEventServiceImpl eventService = new DynamicConfigEventServiceImpl(); this.eventRegistrationService = eventService; this.eventFiringService = eventService; try { this.nomadServer = nomadServerFactory.createServer(getConfigurationManager(), null, nodeName.get(), getEventFiringService()); } catch (SanskritException | NomadException e) { throw new UncheckedNomadException("Exception initializing Nomad Server: " + e.getMessage(), e); } DynamicConfigServiceImpl dynamicConfigService = new DynamicConfigServiceImpl(nodeContext.get(), licenseService, this, objectMapperFactory); this.dynamicConfigService = new AuditService(dynamicConfigService); this.topologyService = dynamicConfigService; getEventRegistrationService().register(dynamicConfigService); getEventRegistrationService().register(new AuditListener()); LOGGER.info("Bootstrapped nomad system with root: {}", parameterSubstitutor.substitute(configPath.toString())); }
Source:
<code>public TaskStatus run(final TaskToolbox toolbox) throws Exception { try { if (useLegacy) { return runInternalLegacy(toolbox); } else { return runInternal(toolbox); } } catch (Exception e) { log.error(e, "Encountered exception while running task."); Map<String, Object> context = Maps.newHashMap(); List<String> savedParseExceptionMessages = IndexTask.getMessagesFromSavedParseExceptions(savedParseExceptions); if (savedParseExceptionMessages != null) { context.put("unparseableEvents", savedParseExceptionMessages); } return TaskStatus.failure( getId(), getTaskCompletionMetrics(), <START> e.getMessage(), <END> getTaskCompletionContext() ); } }</code><technical_language>passing full stack trace a simple message? helpful understand on. If some applications need error messages, parse stack trace own</technical_language>

Target:
public TaskStatus run(final TaskToolbox toolbox) throws Exception { try { if (useLegacy) { return runInternalLegacy(toolbox); } else { return runInternal(toolbox); } } catch (Exception e) { log.error(e, "Encountered exception while running task."); errorMsg = Throwables.getStackTraceAsString(e); toolbox.getTaskReportFileWriter().write(getTaskCompletionReports()); return TaskStatus.failure( getId(), errorMsg ); } }
Source:
<code><START> public void testInterfacesHierarchy() <END> { Rule a = new NoOpRule(Pattern.matchByClass(A.class)); Rule b = new NoOpRule(Pattern.matchByClass(B.class)); Rule ab = new NoOpRule(Pattern.matchByClass(AB.class)); MatchingEngine matchingEngine = MatchingEngine.builder() .register(a) .register(b) .register(ab) .build(); assertEquals( matchingEngine.getCandidates(new A() {}).collect(toList()), ImmutableList.of(a)); assertEquals( matchingEngine.getCandidates(new B() {}).collect(toList()), ImmutableList.of(b)); assertEquals( matchingEngine.getCandidates(new AB()).collect(toList()), ImmutableList.of(ab, a, b)); }</code><technical_language>last! :)</technical_language>

Target:
public void testInterfacesHierarchy() { Rule a = new NoOpRule(Pattern.typeOf(A.class)); Rule b = new NoOpRule(Pattern.typeOf(B.class)); Rule ab = new NoOpRule(Pattern.typeOf(AB.class)); MatchingEngine matchingEngine = MatchingEngine.builder() .register(a) .register(b) .register(ab) .build(); assertEquals( matchingEngine.getCandidates(new A() {}).collect(toList()), ImmutableList.of(a)); assertEquals( matchingEngine.getCandidates(new B() {}).collect(toList()), ImmutableList.of(b)); assertEquals( matchingEngine.getCandidates(new AB()).collect(toList()), ImmutableList.of(ab, a, b)); }
Source:
<code>private Credential getCredentialFromFlow(GoogleAuthorizationCodeFlow flow) throws IOException { return new AuthorizationCodeInstalledApp( <START> flow, new LocalServerReceiver()).authorize("user"); <END> }</code><technical_language>username ID avoid "user" magic string? I this allow usage of StoredCredential file for accounts - multiple folders account avoided. useFreshCredentials is true, delete user credential data store instead of clearing entire store</technical_language>

Target:
private Credential getCredentialFromFlow(GoogleAuthorizationCodeFlow flow) throws IOException { return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(username); }
Source:
<code>@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof VoltLogicalCalc && call.rel(1) instanceof VoltLogicalTableScan) { VoltLogicalCalc calc = call.rel(0); VoltLogicalTableScan tableScan = call.rel(1); <START> RelDistributionUtils.checkedFallBack(! RelDistributionUtils.isCalcScanSP(tableScan, calc)); <END> } else { RelNode child = call.rel(1); RelDistribution childDist = child.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { SingleRel node = call.rel(0); call.transformTo(node.copy(node.getTraitSet().replace(childDist), node.getInputs())); } } }</code><technical_language>RelDistributionUtils.isCalcScanSP - actual SP/MP check update existing nodes's traits work. do a check. additional method create a new calc/scan pair updated traits registered rule</technical_language>

Target:
@Override public void onMatch(RelOptRuleCall call) { if (call.rel(0) instanceof VoltLogicalCalc && call.rel(1) instanceof VoltLogicalTableScan) { VoltLogicalCalc calc = call.rel(0); VoltLogicalTableScan tableScan = call.rel(1); final Pair<Boolean, RexNode> r = RelDistributionUtils.isCalcScanSP(tableScan, calc); final RelDistribution tableDist = tableScan.getTable().getDistribution() .with(r.getSecond(), r.getFirst()); call.transformTo(calc.copy(calc.getTraitSet().replace(tableDist), calc.getInputs())); } else { RelNode child = call.rel(1); RelDistribution childDist = child.getTraitSet().getTrait(RelDistributionTraitDef.INSTANCE); if (childDist != RelDistributions.ANY) { SingleRel node = call.rel(0); call.transformTo(node.copy(node.getTraitSet().replace(childDist), node.getInputs())); } } }
Source:
<code>public List<MarketDataFunction<?, ?>> marketDataFunctions() { return ImmutableList.of( <START> DiscountCurveMarketDataFunction.INSTANCE, <END> new RateIndexCurveMarketDataFunction(), DiscountFactorsMarketDataFunction.INSTANCE, new CurveGroupMarketDataFunction(RootFinderConfig.defaults()), new ParRatesMarketDataFunction()); }</code><technical_language>a bit weird a mix of singletons new instances. Arguably new instances singletons too, do it, consistent</technical_language>

Target:
public List<MarketDataFunction<?, ?>> marketDataFunctions() { return ImmutableList.of( new DiscountCurveMarketDataFunction(), new RateIndexCurveMarketDataFunction(), new DiscountFactorsMarketDataFunction(), new CurveGroupMarketDataFunction(RootFinderConfig.defaults()), new ParRatesMarketDataFunction()); }
Source:
<code>private static List<File> getCardFolders() { File cardsDirectory = new File(SC_PATH); List<File> cardFolders = new ArrayList<>(); <START> for (File card : Objects.requireNonNull(cardsDirectory.listFiles())) { <END> if (card.getName().startsWith(CARD_FOLDER) && card.isDirectory()) { cardFolders.add(card); } } return cardFolders; }</code><technical_language>I this is NPE is generated. [requireNonNull()](<LINK_0> throws NPE if argument is null. catch this exception skip iteration (or a temporary variable for file list null check it!)</technical_language>

Target:
private static List<File> getCardFolders() { File cardsDirectory = new File(SC_PATH); List<File> cardFolders = new ArrayList<>(); File[] allContents = cardsDirectory.listFiles(); if (allContents != null) { for (File card : allContents) { if (card.getName().startsWith(CARD_FOLDER) && card.isDirectory()) { cardFolders.add(card); } } } else { LOG.warn("Warning: No Audio Cards Found !"); } return cardFolders; }
Source:
<code>public Page getPageByMappingKey(String mappingKey) throws PageNotFoundException { try { final SPageMapping sPageMapping = pageMappingService.get(mappingKey); return convertToPage(pageService.getPage(sPageMapping.getId())); <START> } catch (final SBonitaReadException e) { <END> throw new PageNotFoundException(e); } catch (final SObjectNotFoundException e) { throw new PageNotFoundException(mappingKey, PageAttribute.MAPPING_KEY); } }</code><technical_language>SBonitaRead != page RetrieveException is runtime</technical_language>

Target:
public Page getPageByMappingKey(String mappingKey) throws PageNotFoundException { try { final SPageMapping sPageMapping = pageMappingService.get(mappingKey); return convertToPage(pageService.getPage(sPageMapping.getId())); } catch (final SBonitaReadException e) { throw new RetrieveException(String.format("Failed to retrieve a page mapping for %s", mappingKey)); } catch (final SObjectNotFoundException e) { throw new PageNotFoundException(e); } }
Source:
<code>public void before() throws Exception { sourceTopic = SOURCE_TOPIC + "-" + testName.getMethodName(); CLUSTER.createTopic(sourceTopic); <START> STREAMS_CONFIG.put(StreamsConfig.APPLICATION_ID_CONFIG, "ktable-restore-from-source-" + testName.getMethodName()); <END> final KTable<String, String> kTable = streamsBuilder.table(sourceTopic, Materialized.as("store")); kTable.toStream().foreach(readKeyValues::put); expectedInitialResultsMap = createExpectedResultsMap("a", "b", "c"); expectedResultsWithDataWrittenDuringRestoreMap = createExpectedResultsMap("a", "b", "c", "d", "f", "g", "h"); }</code><technical_language>nit: IntegrationTestUtils#safeUniqueTestName for name</technical_language>

Target:
public void before() throws Exception { sourceTopic = SOURCE_TOPIC + "-" + testName.getMethodName(); CLUSTER.createTopic(sourceTopic); STREAMS_CONFIG.put(StreamsConfig.APPLICATION_ID_CONFIG, IntegrationTestUtils.safeUniqueTestName(getClass(), testName)); final KTable<String, String> kTable = streamsBuilder.table(sourceTopic, Materialized.as("store")); kTable.toStream().foreach(readKeyValues::put); expectedInitialResultsMap = createExpectedResultsMap("a", "b", "c"); expectedResultsWithDataWrittenDuringRestoreMap = createExpectedResultsMap("a", "b", "c", "d", "f", "g", "h"); }
Source:
<code>public List<Part> getProgress(File stateDir, String objectId) throws IOException { log.debug("Loading local progress for from {}", objectId, stateDir.toString()); ObjectSpecification spec = loadSpecification(stateDir, objectId); <START> log.debug("Completed loading local object specification (meta file)"); <END> for (Part part : spec.getParts()) { log.debug("Checking md5 for part {}", part.getPartNumber()); if (isCompleted(stateDir, objectId, part)) { Part completedPart = loadPart(stateDir, objectId, getPartName(part)); part.setMd5(completedPart.getMd5()); } } return spec.getParts(); }</code><technical_language>throw in File stateDir, String objectId message for good measure</technical_language>

Target:
public ObjectSpecification getProgress(File stateDir, String objectId) throws IOException { log.debug("Loading local progress for from {}", objectId, stateDir.toString()); ObjectSpecification spec = loadSpecification(stateDir, objectId); log.debug("Completed loading local object specification (meta file)"); for (Part part : spec.getParts()) { log.debug("Checking md5 for part {}", part.getPartNumber()); if (isCompleted(stateDir, objectId, part)) { Part completedPart = loadPart(stateDir, objectId, getPartName(part)); part.setMd5(completedPart.getMd5()); } } return spec; }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { <START> Timber.d(data!=null?data.toString():""); <END> super.onActivityResult(requestCode, resultCode, data); controller.handleActivityResult(this, requestCode, resultCode, data); }</code><technical_language>add a message intent data empty instead of "" (assuming relevance of log here)</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { Timber.d(data!=null?data.toString():"onActivityResult data is null"); super.onActivityResult(requestCode, resultCode, data); controller.handleActivityResult(this, requestCode, resultCode, data); }
Source:
<code>private void explode() throws IOException { destDir.mkdirs(); File explodeTime = new File(destDir,".timestamp2"); if(explodeTime.exists() && explodeTime.lastModified()==archive.lastModified()) return; Project p = new Project(); if (destDir.exists()) { Delete d = new Delete(); d.setProject(p); if (destDir.isDirectory()) d.setDir(destDir); else d.setFile(destDir); d.execute(); } Expand e = new Expand(); e.setProject(p); e.setTaskType("unzip"); e.setSrc(archive); e.setDest(destDir); e.execute(); if (new File(destDir,"WEB-INF/classes").exists()) { <START> throw new IOException("Core override plugin cannot have WEB-INF/classes: "+destDir); <END> } new FileOutputStream(explodeTime).close(); explodeTime.setLastModified(archive.lastModified()); }</code><technical_language>If idea is require 'empty' plugins for core override plugins, this check work. I added a trivial ItemListener remoting plugin, Feb 20, 2017 10:31:04 PM jenkins.bootstrap.Plugin process INFO: Loading core overrides /Users/danielbeck/PR-2754-Home/plugins/remoting/WEB-INF/lib ... Feb 20, 2017 10:31:09 PM org.jenkinsci.plugins.remoting.Listener onLoaded INFO: Loaded items! Feb 20, 2017 10:31:09 PM hudson.WebAppMain$2 run INFO: Jenkins is fully running</technical_language>

Target:
private void explode() throws IOException { destDir.mkdirs(); File explodeTime = new File(destDir,".timestamp2"); if(explodeTime.exists() && explodeTime.lastModified()==archive.lastModified()) return; if (destDir.exists()) { if (destDir.isDirectory()) Files.walk(destDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); else destDir.delete(); } destDir.mkdirs(); try (JarFile jar = new JarFile(archive)) { Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry file = (JarEntry) enumEntries.nextElement(); File f = new File(destDir + File.separator + file.getName()); if (file.isDirectory()) { f.mkdir(); continue; } try (InputStream is = jar.getInputStream(file); FileOutputStream fos = new FileOutputStream(f)) { while (is.available() > 0) { fos.write(is.read()); } } } } new FileOutputStream(explodeTime).close(); explodeTime.setLastModified(archive.lastModified()); }
Source:
<code>public void testSuccceedForCheckDisksNotInBackupStorage() { final VM vm = new VM(); command.setVm(vm); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); command.setCluster(new Cluster()); Guid storageDomainId = initDiskImage(vm); when(storageDomainStaticDao.get(storageDomainId)).thenReturn(backupStorageDomain(false)); <START> assertTrue( <END> "checkDisksNotInBackupStorage() succeed to run since there are no disks which are on a backup storage domain", command.checkDisksInBackupStorage()); }</code><technical_language>assertFalse</technical_language>

Target:
public void testSuccceedForCheckDisksNotInBackupStorage() { final VM vm = new VM(); command.setVm(vm); when(vmDao.get(command.getParameters().getVmId())).thenReturn(vm); command.setCluster(new Cluster()); Guid storageDomainId = initDiskImage(vm); when(storageDomainStaticDao.get(storageDomainId)).thenReturn(backupStorageDomain(false)); assertFalse( "checkDisksNotInBackupStorage() succeed to run since there are no disks which are on a backup storage domain", command.checkDisksInBackupStorage()); }