auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void doStartMachine(KubernetesServerResolver serverResolver) throws InfrastructureException { final KubernetesEnvironment environment = getContext().getEnvironment(); final Map<String, InternalMachineConfig> machineConfigs = environment.getMachines(); final String workspaceId = getContext().getIdentity().getWorkspaceId(); LOG.debug("Begin pods creation for workspace {}", workspaceId); for (Pod toCreate : environment.getPods().values()) { final Pod createdPod = namespace.deployments().deploy(toCreate); LOG.debug("Creating pod in workspace {}", toCreate.getMetadata().getName(), workspaceId); final ObjectMeta podMetadata = createdPod.getMetadata(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreate, container); LOG.debug("Creating machine in workspace {}", machineName, workspaceId); machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, podMetadata.getName(), container.getName(), MachineStatus.STARTING, machineConfigs.get(machineName).getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } } <START> LOG.debug("Pods creation finished in in ws {}", workspaceId); <END> }</code><technical_language>double in. please workspace instead of ws in other places</technical_language>

Target:
protected void doStartMachine(KubernetesServerResolver serverResolver) throws InfrastructureException { final KubernetesEnvironment environment = getContext().getEnvironment(); final Map<String, InternalMachineConfig> machineConfigs = environment.getMachines(); final String workspaceId = getContext().getIdentity().getWorkspaceId(); LOG.debug("Begin pods creation for workspace '{}'", workspaceId); for (Pod toCreate : environment.getPods().values()) { final Pod createdPod = namespace.deployments().deploy(toCreate); LOG.debug( "Creating pod '{}' in workspace '{}'", toCreate.getMetadata().getName(), workspaceId); final ObjectMeta podMetadata = createdPod.getMetadata(); for (Container container : createdPod.getSpec().getContainers()) { String machineName = Names.machineName(toCreate, container); LOG.debug("Creating machine '{}' in workspace '{}'", machineName, workspaceId); machines.put( getContext().getIdentity(), new KubernetesMachineImpl( workspaceId, machineName, podMetadata.getName(), container.getName(), MachineStatus.STARTING, machineConfigs.get(machineName).getAttributes(), serverResolver.resolve(machineName))); eventPublisher.sendStartingEvent(machineName, getContext().getIdentity()); } } LOG.debug("Pods creation finished in workspace '{}'", workspaceId); }
Source:
<code>private String getId(EObject object) { if (object instanceof Component) { final Component component = (Component) object; return component.getId(); } else if (object instanceof SnomedRefSetMember) { final SnomedRefSetMember member = (SnomedRefSetMember) object; return member.getUuid(); } <START> throw new IllegalStateException(); <END> }</code><technical_language>In this case, throw UnsupportedOperationException IllegalArgumentException a proper message</technical_language>

Target:
private String getId(EObject object) { if (object instanceof Component) { final Component component = (Component) object; return component.getId(); } else if (object instanceof SnomedRefSetMember) { final SnomedRefSetMember member = (SnomedRefSetMember) object; return member.getUuid(); } throw new IllegalArgumentException("Object was neither instance of Component or SnomedRefSetMember"); }
Source:
<code>public ItemOverrideList getOverrides() { <START> return new ItemOverrideList( Collections.emptyList() ) <END> { @Override public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) { final long hash; if( stack.getItem() instanceof IMemoryCard ) { final IMemoryCard memoryCard = (IMemoryCard) stack.getItem(); hash = memoryCard.getHash( stack ); } else { hash = 0x77777777; } try { return MemoryCardBakedModel.this.modelCache.get( hash, () -> new MemoryCardBakedModel( MemoryCardBakedModel.this.format, MemoryCardBakedModel.this.baseModel, MemoryCardBakedModel.this.texture, hash, MemoryCardBakedModel.this.modelCache ) ); } catch( ExecutionException e ) { AELog.error( e ); return MemoryCardBakedModel.this; } } }; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Reduce this anonymous class number of lines 21 20, a named class. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public ItemOverrideList getOverrides() { return new ItemOverrideList( Collections.emptyList() ) { @Override public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) { try { if( stack.getItem() instanceof IMemoryCard ) { final IMemoryCard memoryCard = (IMemoryCard) stack.getItem(); final AEColor[] colors = memoryCard.getColorCode( stack ); return MemoryCardBakedModel.this.modelCache.get( new CacheKey( colors ), () -> new MemoryCardBakedModel( MemoryCardBakedModel.this.format, MemoryCardBakedModel.this.baseModel, MemoryCardBakedModel.this.texture, colors, MemoryCardBakedModel.this.modelCache ) ); } } catch( ExecutionException e ) { AELog.error( e ); } return MemoryCardBakedModel.this; } }; }
Source:
<code>public void executeRecordsParityStatusForChargesExistingInLedger() { when(chargeDao.findMaxId()).thenReturn(1L); when(chargeDao.findById(1L)).thenReturn(Optional.of(chargeEntity)); when(ledgerService.getTransaction(chargeEntity.getExternalId())).thenReturn(Optional.of(new LedgerTransaction())); worker.execute(1L, OptionalLong.empty()); assertThat(chargeEntity.getParityCheckStatus(), is(ParityCheckStatus.EXISTS_IN_LEDGER)); <START> verify(stateTransitionQueue, never()).offer(any()); <END> verify(emittedEventDao, never()).recordEmission(any()); verify(chargeDao, never()).findById(2L); }</code><technical_language>This is checking functionality of HistoricalEventEmitter is scope ParityCheckTask. test affected for changes in HistoricalEventEmitter. need separate tests for HistoricalEventEmitter include tests check shouldForceEmission required behaviour</technical_language>

Target:
public void executeRecordsParityStatusForChargesExistingInLedger() { when(chargeDao.findMaxId()).thenReturn(1L); when(chargeDao.findById(1L)).thenReturn(Optional.of(chargeEntity)); when(ledgerService.getTransaction(chargeEntity.getExternalId())).thenReturn(Optional.of(new LedgerTransaction())); worker.execute(1L, OptionalLong.empty()); verify(chargeService, times(1)).updateChargeParityStatus(chargeEntity.getExternalId(), ParityCheckStatus.EXISTS_IN_LEDGER); verify(stateTransitionQueue, never()).offer(any()); verify(emittedEventDao, never()).recordEmission(any()); verify(chargeDao, never()).findById(2L); }
Source:
<code>public static void setColor(Context context, CanvasContext canvasContext, String hexColor, CanvasCallback<CanvasColor> callback) { if (APIHelpers.paramIsNull(context, canvasContext, hexColor, callback)) { return; } if(canvasContext instanceof Course || canvasContext instanceof Group) { <START> buildInterface(context, false).setColor(canvasContext.getContextId(), hexColor, callback); <END> } }</code><technical_language>Instead of nothing, nice throw exception. people integrating this jar this work. Another approach specific method for groups/courses boiled this check in a single function. least, log wrong. frustrating integrate AAR idea this failing. verify happened is source, is painful</technical_language>

Target:
public static void setColor(Context context, CanvasContext canvasContext, String hexColor, CanvasCallback<CanvasColor> callback) { if (APIHelpers.paramIsNull(context, canvasContext, hexColor, callback)) { return; } buildInterface(context, false).setColor(canvasContext.getContextId(), hexColor, callback); }
Source:
<code>public static BooleanExpression isAnyFieldSetForSelectedEntry(List<Field> fields, StateManager stateManager) { ObservableList<BibEntry> selectedEntries = stateManager.getSelectedEntries(); if (selectedEntries.isEmpty()) { return Bindings.createBooleanBinding(() -> false, selectedEntries); } <START> BibEntry entry = selectedEntries.get(0); <END> return Bindings.createBooleanBinding( () -> entry.getFields().stream().anyMatch(fields::contains), entry.getFieldsObservable(), selectedEntries); }</code><technical_language>binding refer currently selected entry this change in future binding needs reevaluated. work suggestion ObjectBinding<BibEntry> entry = Bindings.valueAt(selectedEntries, 0); return Bindings.createBooleanBinding(() -> { if (entry.get() == null) return false; else return entry.get().getFields().stream().anyMatch(fields::contains); }, entry, entry.getFieldsObserable());</technical_language>

Target:
public static BooleanExpression isAnyFieldSetForSelectedEntry(List<Field> fields, StateManager stateManager) { ObservableList<BibEntry> selectedEntries = stateManager.getSelectedEntries(); MonadicBinding<Boolean> fieldsAreSet = EasyBind.monadic(Bindings.valueAt(selectedEntries, 0)) .flatMap(entry -> Bindings.createBooleanBinding(() -> { return entry.getFields().stream().anyMatch(fields::contains); }, entry.getFieldsObservable())) .orElse(false); return BooleanExpression.booleanExpression(fieldsAreSet); }
Source:
<code>private ManagedScheduledExecutorServiceResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.MANAGED_SCHEDULED_EXECUTOR_SERVICE), EeExtension.getResourceDescriptionResolver(EESubsystemModel.MANAGED_SCHEDULED_EXECUTOR_SERVICE)) .setAddHandler(ManagedScheduledExecutorServiceAdd.INSTANCE) <START> .setRemoveHandler(ManagedScheduledExecutorServiceRemove.INSTANCE) <END> .addCapabilities(CAPABILITY)); }</code><technical_language>setRemoveHandler(new ServiceRemoveStepHandler(ManagedScheduledExecutorServiceAdd.INSTANCE))</technical_language>

Target:
private ManagedScheduledExecutorServiceResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.MANAGED_SCHEDULED_EXECUTOR_SERVICE), EeExtension.getResourceDescriptionResolver(EESubsystemModel.MANAGED_SCHEDULED_EXECUTOR_SERVICE)) .setAddHandler(ManagedScheduledExecutorServiceAdd.INSTANCE) .setRemoveHandler(new ServiceRemoveStepHandler(ManagedScheduledExecutorServiceAdd.INSTANCE)) .addCapabilities(CAPABILITY)); }
Source:
<code>protected void executeQueryCommand() { List<Disk> disks = diskDao.getAllFromDisksIncludingSnapshotsByDiskId(getParameters().getId(), getUserID(), getParameters().isFiltered()); if (disks.size() == <START> 1 && disks.get(0) instanceof LunDisk){ <END> getQueryReturnValue().setReturnValue(disks.get(0)); return; } List<DiskImage> snapshots = new ArrayList<>(); disks.stream() .filter(disk -> !(disk instanceof LunDisk)) .map(disk -> (DiskImage) disk) .forEach(disk -> { if (disk.getActive()) { disk.getSnapshots().add(DiskImage.copyOf(disk)); activeDisk = disk; activeDisk.getSnapshots().addAll(snapshots); } else { if (activeDisk != null){ activeDisk.getSnapshots().add(disk); } else { snapshots.add(disk); } } }); getQueryReturnValue().setReturnValue(activeDisk); }</code><technical_language>Is this necessary? Cinder</technical_language>

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(diskDao.get(getParameters().getId(), getUserID(), getParameters().isFiltered())); }
Source:
<code>public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length < 2) { return false; } Player player = getPlayer(args[0]); if (player == null) { playerMsg(PLAYER_NOT_FOUND); return true; } if (sender instanceof Player) { if (player.equals(sender_p)) { playerMsg(ChatColor.RED + "Please, don't try to report yourself."); return true; } } if (TFM_AdminList.isSuperAdmin(player)) { <START> playerMsg(ChatColor.RED + "You may report admin abuse on the forums, however, include screenshots! <LINK_0>"); <END> return true; } String report = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); TFM_Util.reportAction(sender_p, player, report); playerMsg(ChatColor.GREEN + "Thank you, your report has been successfully logged."); return true; }</code><technical_language>"However **please** include screenshots!" sound a lot :)</technical_language>

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length < 2) { return false; } Player player = getPlayer(args[0]); if (player == null) { playerMsg(PLAYER_NOT_FOUND); return true; } if (sender instanceof Player) { if (player.equals(sender_p)) { playerMsg(ChatColor.RED + "Please, don't try to report yourself."); return true; } } if (TFM_AdminList.isSuperAdmin(player)) { playerMsg(ChatColor.RED + "You may report admin abuse on the forums, however, please include screenshots! <LINK_0>"); return true; } String report = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); TFM_Util.reportAction(sender_p, player, report); playerMsg(ChatColor.GREEN + "Thank you, your report has been successfully logged."); return true; }
Source:
<code>protected boolean anyRejects() { for <START> (final ReceiveCommand <END> cmd : commands) { if (cmd.getResult() != Result.NOT_ATTEMPTED || cmd.getResult() != Result.OK) return false; } return true; }</code><technical_language>final is necessary. Some older code frequently slowly removing newer code</technical_language>

Target:
protected boolean anyRejects() { for (ReceiveCommand cmd : commands) { if (cmd.getResult() != Result.NOT_ATTEMPTED && cmd.getResult() != Result.OK) return true; } return false; }
Source:
<code>protected void openExampleReadme(IProject project) throws PartInitException { <START> if (ExampleData.DESC_FILE != null) { <END> IResource indexFile = project.findMember(ExampleData.DESC_FILE); if (indexFile != null) { IDE.openEditor(getPage(), (IFile) indexFile, true); } } }</code><technical_language>Remove this if block - this is a static final String null</technical_language>

Target:
protected void openExampleReadme(IProject project) throws PartInitException { IResource indexFile = project.findMember(ExampleData.DESC_FILE); if (indexFile != null) { IDE.openEditor(getPage(), (IFile) indexFile, true); } }
Source:
<code><START> private void startFileIngestStreaming() { <END> synchronized (this.stageCompletionCheckLock) { this.stage = IngestJobPipeline.Stages.STREAMING_FILE_INGEST; } if (this.hasFileIngestPipeline()) { synchronized (this.fileIngestProgressLock) { this.estimatedFilesToProcess = 0; } } if (this.doUI) { if (this.hasFileIngestPipeline()) { this.startFileIngestProgressBar(); } } logInfoMessage("Waiting for streaming files"); }</code><technical_language>want start/start stage, etc.. method names match better</technical_language>

Target:
private void startFileIngestStreaming() { synchronized (this.stageCompletionCheckLock) { this.stage = IngestJobPipeline.Stages.FIRST_STAGE_FILES_ONLY; } if (this.hasFileIngestPipeline()) { synchronized (this.fileIngestProgressLock) { this.estimatedFilesToProcess = 0; } } if (this.doUI) { if (this.hasFileIngestPipeline()) { this.startFileIngestProgressBar(); } } logInfoMessage("Waiting for streaming files"); }
Source:
<code>public Scope linkScope(StaticAnalysis analysis, Scope parentScope, ParseTree ast, Environment env, Set<ConfigCompileException> exceptions, boolean codeInheritsParentScope) { if(ast.numberOfChildren() == 0) { return parentScope; } int ind = 0; <START> Scope retTypeScope = (ast.getChildAt(ind).getData().isInstanceOf(CClassType.TYPE) <END> ? analysis.linkScope(parentScope, ast.getChildAt(ind++), env, exceptions) : parentScope); Scope paramScope = analysis.createNewScope(); if(codeInheritsParentScope) { paramScope.addParent(parentScope); } else { paramScope.addSpecificParent(parentScope, Namespace.PROCEDURE); } paramScope.addDeclaration(new ParamDeclaration("@arguments", CArray.TYPE, ast.getTarget())); Scope valScope = parentScope; while(ind < ast.numberOfChildren() - 1) { ParseTree param = ast.getChildAt(ind++); Scope[] scopes = analysis.linkParamScope(paramScope, valScope, param, env, exceptions); valScope = scopes[1]; paramScope = scopes[0]; } ParseTree code = ast.getChildAt(ast.numberOfChildren() - 1); analysis.linkScope(paramScope, code, env, exceptions); return parentScope; }</code><technical_language>retTypeScope is unused, intentional</technical_language>

Target:
public Scope linkScope(StaticAnalysis analysis, Scope parentScope, ParseTree ast, Environment env, Set<ConfigCompileException> exceptions, boolean codeInheritsParentScope) { if(ast.numberOfChildren() == 0) { return parentScope; } int ind = 0; if(ast.getChildAt(ind).getData().isInstanceOf(CClassType.TYPE)) { analysis.linkScope(parentScope, ast.getChildAt(ind++), env, exceptions); } Scope paramScope = analysis.createNewScope(); if(codeInheritsParentScope) { paramScope.addParent(parentScope); } else { paramScope.addSpecificParent(parentScope, Namespace.PROCEDURE); } paramScope.addDeclaration(new ParamDeclaration("@arguments", CArray.TYPE, ast.getTarget())); Scope valScope = parentScope; while(ind < ast.numberOfChildren() - 1) { ParseTree param = ast.getChildAt(ind++); Scope[] scopes = analysis.linkParamScope(paramScope, valScope, param, env, exceptions); valScope = scopes[1]; paramScope = scopes[0]; } ParseTree code = ast.getChildAt(ast.numberOfChildren() - 1); analysis.linkScope(paramScope, code, env, exceptions); return parentScope; }
Source:
<code>public void setDataGroupsAssignedWhileConsented(Set<String> dataGroups) { if (dataGroups != null) { this.dataGroupsAssignedWhileConsented = new HashSet<>(dataGroups); <START> } <END> }</code><technical_language>Is correct behavior ignore nulls replace empty sets? (Similarly substudies set.)</technical_language>

Target:
public void setDataGroupsAssignedWhileConsented(Set<String> dataGroups) { this.dataGroupsAssignedWhileConsented = (dataGroups != null) ? new HashSet<>(dataGroups) : new HashSet<>(); }
Source:
<code>public String resetPassword(@RequestBody final UserResetPasswordRequest userInfo) throws UserRetrievalException, MessagingException { UserResetTokenDTO userResetTokenDTO = userManager.createResetUserPasswordToken(userInfo.getUserName(), userInfo.getEmail()); <START> String htmlMessage = "<p>Please follow this link to reset your password </p>" + "<pre>" + env.getProperty("chplUrlBegin") + "/#/admin/authorizePasswordReset?token=" + userResetTokenDTO.getUserResetToken() + "</pre>"; <END> String[] toEmails = { userInfo.getEmail() }; EmailBuilder emailBuilder = new EmailBuilder(env); emailBuilder.recipients(new ArrayList<String>(Arrays.asList(toEmails))) .subject("Open Data CHPL Password Reset") .htmlMessage(htmlMessage) .htmlFooter() .sendEmail(); return "{\"passwordResetEmailSent\" : true }"; }</code><technical_language>This moved email.properties file</technical_language>

Target:
public String resetPassword(@RequestBody final UserResetPasswordRequest userInfo) throws UserRetrievalException, MessagingException { UserResetTokenDTO userResetTokenDTO = userManager.createResetUserPasswordToken(userInfo.getUserName(), userInfo.getEmail()); String htmlMessage = String.format(env.getProperty("user.resetPassword.body"), env.getProperty("chplUrlBegin"), userResetTokenDTO.getUserResetToken()); String[] toEmails = { userInfo.getEmail() }; EmailBuilder emailBuilder = new EmailBuilder(env); emailBuilder.recipients(new ArrayList<String>(Arrays.asList(toEmails))) .subject(env.getProperty("user.resetPassword.subject")) .htmlMessage(htmlMessage) .publicHtmlFooter() .sendEmail(); return "{\"passwordResetEmailSent\" : true }"; }
Source:
<code><START> public void reuseSession() { <END> getSessionId(new StorageCallback() { @Override public void onSuccess(String result) { if (result != null) { restApiSessionId = result; RestApiSessionAcquiredEvent.fire(eventBus, result); scheduleKeepAliveHeartbeat(); } else { RestApiSessionManager.logger.severe("Engine REST API session ID is not available"); } } @Override public void onFailure(Throwable caught) { RestApiSessionManager.logger.severe("Engine REST API session ID is not available"); } }); }</code><technical_language>Question: in normal login scenario, reuseSession is called right setSessionId. reuseSession (using getSessionId) & setSessionId async now, I utilize result callback setSessionId, setSessionId completes (result callback executes), proceed reuseSession. This complicates current code a bit, I modifications/testing here</technical_language>

Target:
public void reuseSession() { if (getSessionId() != null) { RestApiSessionAcquiredEvent.fire(eventBus, getSessionId()); scheduleKeepAliveHeartbeat(); } else { getSessionId(new StorageCallback() { @Override public void onSuccess(String result) { if (result != null) { restApiSessionId = result; RestApiSessionAcquiredEvent.fire(eventBus, result); scheduleKeepAliveHeartbeat(); } else { RestApiSessionManager.logger.severe("Engine REST API session ID is not available"); } } @Override public void onFailure(Throwable caught) { RestApiSessionManager.logger.severe("Engine REST API session ID is not available"); } }); } }
Source:
<code>public void onSaveClick() { editView.setError(null); editView.setSaveState(true); if (call != null) { call.cancel(); } call = new DescriptionEditClient().request(pageTitle, editView.getDescription(), new DescriptionEditClient.Callback() { @Override public void success(@NonNull Call<DescriptionEdit> call) { if (getActivity() != null) { DeviceUtil.hideSoftKeyboard(getActivity()); <START> editView.setSaveState(false); <END> startActivityForResult(DescriptionEditSuccessActivity.newIntent(getContext()), Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT); } } @Override public void abusefilter(@NonNull Call<DescriptionEdit> call, boolean disallowed) { if (disallowed) { } else { } } @Override public void failure(@NonNull Call<DescriptionEdit> call, @NonNull Throwable caught) { editView.setSaveState(false); editView.setError(caught.getMessage()); } }); }</code><technical_language>this button save checkbox button reappear</technical_language>

Target:
public void onSaveClick() { editView.setError(null); editView.setSaveState(true); if (call != null) { call.cancel(); } call = new DescriptionEditClient().request(pageTitle, editView.getDescription(), new DescriptionEditClient.Callback() { @Override public void success(@NonNull Call<DescriptionEdit> call) { if (getActivity() != null) { DeviceUtil.hideSoftKeyboard(getActivity()); editView.setSaveState(false); startActivityForResult(DescriptionEditSuccessActivity.newIntent(getContext()), Constants.ACTIVITY_REQUEST_DESCRIPTION_EDIT_SUCCESS); } } @Override public void abusefilter(@NonNull Call<DescriptionEdit> call, boolean disallowed) { if (disallowed) { } else { } } @Override public void failure(@NonNull Call<DescriptionEdit> call, @NonNull Throwable caught) { editView.setSaveState(false); editView.setError(caught.getMessage()); } }); }
Source:
<code>public void storeSpan(String tenantId, List<Span> spans, Function<Span, String> spanIdSupplier) throws StoreException { client.initTenant(tenantId); BulkRequestBuilder bulkRequestBuilder = client.getClient().prepareBulk(); try { for (Span span: spans) { final String modifiedId = spanIdSupplier.apply(span); String json = serialize(span); msgLog.tracef("Storing span: %s", json); bulkRequestBuilder .add(client.getClient() .prepareIndex(client.getIndex(tenantId), SPAN_TYPE, modifiedId) .setSource(json)); } } catch (IOException ex) { <START> throw new StoreException(ex); <END> } BulkResponse bulkItemResponses = bulkRequestBuilder.execute().actionGet(); if (bulkItemResponses.hasFailures()) { msgLog.tracef("Failed to store traces to elasticsearch: %s", bulkItemResponses.buildFailureMessage()); throw new StoreException(bulkItemResponses.buildFailureMessage()); } msgLog.trace("Success storing traces to elasticsearch"); }</code><technical_language>want log exception here</technical_language>

Target:
public void storeSpan(String tenantId, List<Span> spans, Function<Span, String> spanIdSupplier) throws StoreException { client.initTenant(tenantId); BulkRequestBuilder bulkRequestBuilder = client.getClient().prepareBulk(); for (Span span : spans) { String json; try { json = serialize(span); } catch(IOException ex){ log.errorf("Failed to serialize span %s", span); throw new StoreException(ex); } log.tracef("Storing span: %s", json); final String modifiedId = spanIdSupplier.apply(span); bulkRequestBuilder.add(client.getClient() .prepareIndex(client.getIndex(tenantId), SPAN_TYPE, modifiedId) .setSource(json)); } BulkResponse bulkItemResponses = bulkRequestBuilder.execute().actionGet(); if (bulkItemResponses.hasFailures()) { log.tracef("Failed to store traces to elasticsearch: %s", bulkItemResponses.buildFailureMessage()); throw new StoreException(bulkItemResponses.buildFailureMessage()); } log.trace("Success storing traces to elasticsearch"); }
Source:
<code>private void validateNames() { <START> if ((mQualifier != null) && !KijiNameValidator.isValidPrintableASCII(mQualifier)) { <END> throw new KijiInvalidNameException( String.format("Qualifier name not valid printable ASCII): " + mQualifier)); } if ((mFamily != null) && !KijiNameValidator.isValidLayoutName(mFamily)) { throw new KijiInvalidNameException(String.format("Invalid family name: " + mFamily)); } }</code><technical_language>In general case, column qualifiers UTF-8 strings. required ASCII</technical_language>

Target:
private void validateNames() { if (!KijiNameValidator.isValidLayoutName(mFamily)) { throw new KijiInvalidNameException(String.format("Invalid family name: %s", mFamily)); } }
Source:
<code>InputStatus emitNext(DataOutput<T> output) throws Exception; interface DataOutput<T> { void emitRecord(StreamRecord<T> streamRecord) throws Exception; void emitWatermark(Watermark watermark) throws Exception; void emitStreamStatus(StreamStatus streamStatus) throws Exception; void emitLatencyMarker(LatencyMarker latencyMarker) throws Exception; <START> default void endOutput() throws Exception <END> }</code><technical_language>is this exposed implementing PushingAsyncDataInput? I guess implementation easier? I mean, reason for StreamTaskNetworkInput StreamTaskSourceInput call output.endOutput(), runtime do for lead bugs if method is called prematurely. is easy hide emitNext()? splitting separate interfaces</technical_language>

Target:
InputStatus emitNext(DataOutput<T> output) throws Exception; interface DataOutput<T> { void emitRecord(StreamRecord<T> streamRecord) throws Exception; void emitWatermark(Watermark watermark) throws Exception; void emitStreamStatus(StreamStatus streamStatus) throws Exception; void emitLatencyMarker(LatencyMarker latencyMarker) throws Exception; }
Source:
<code>public Datepicker(Datepicker other) { this.closeText = other.closeText; this.prevText = other.prevText; this.nextText = other.nextText; this.currentText = other.currentText; this.monthNames = new LinkedList<String>(other.monthNames); this.monthNamesShort = new LinkedList<String>(other.monthNamesShort); <START> this.dayNames = new LinkedList<String>(other.dayNames); <END> this.dayNamesShort = new LinkedList<String>(other.dayNamesShort); this.dayNamesMin = new LinkedList<String>(other.dayNamesMin); this.weekHeader = other.weekHeader; this.dateFormat = other.dateFormat; this.firstDay = other.firstDay; this.isRTL = other.isRTL; this.showMonthAfterYear = other.showMonthAfterYear; this.yearSuffix = other.yearSuffix; }</code><technical_language>please add check for null</technical_language>

Target:
public Datepicker(Datepicker other) { this.closeText = other.closeText; this.prevText = other.prevText; this.nextText = other.nextText; this.currentText = other.currentText; this.monthNames = (other.monthNames != null) ? new LinkedList<String>(other.monthNames) : null; this.monthNamesShort = (other.monthNamesShort != null) ? new LinkedList<String>(other.monthNamesShort) : null; this.dayNames = (other.dayNames != null) ? new LinkedList<String>(other.dayNames) : null; this.dayNamesShort = (other.dayNamesShort != null) ? new LinkedList<String>(other.dayNamesShort) : null; this.dayNamesMin = (other.dayNamesMin != null) ? new LinkedList<String>(other.dayNamesMin) : null; this.weekHeader = other.weekHeader; this.dateFormat = other.dateFormat; this.firstDay = other.firstDay; this.isRTL = other.isRTL; this.showMonthAfterYear = other.showMonthAfterYear; this.yearSuffix = other.yearSuffix; }
Source:
<code>private String updateInternal(Entity oldEntity, Entity newEntity, Cluster cluster, BundleJob oldBundle, String user, Boolean skipDryRun) throws FalconException { String currentUser = CurrentUser.getUser(); switchUser(user); String clusterName = cluster.getName(); Date effectiveTime = getEffectiveTime(cluster, newEntity); LOG.info("Effective time " + effectiveTime); try { dryRunForUpdate(cluster, newEntity, effectiveTime, skipDryRun); boolean suspended = BUNDLE_SUSPENDED_STATUS.contains(oldBundle.getStatus()); updateCoords(clusterName, oldBundle, EntityUtil.getParallel(oldEntity), effectiveTime, newEntity); <START> String newJobId = scheduleForUpdate(newEntity, cluster, effectiveTime, user); <END> BundleJob newBundle = null; if (newJobId != null) { newBundle = getBundleInfo(clusterName, newJobId); } if (suspended) { doBundleAction(newEntity, BundleAction.SUSPEND, cluster.getName()); } switchUser(currentUser); return getUpdateString(newEntity, effectiveTime, oldBundle, newBundle); } finally { switchUser(currentUser); } }</code><technical_language>function scheduleForUpdate performs user switch (current user -> user -> current user). However, switch user calling scheduleForUpdate, switch is longer needed in scheduleForUpdate. remove "user" argument user switch in scheduleForUpdate, this function is in updateInternal</technical_language>

Target:
private String updateInternal(Entity oldEntity, Entity newEntity, Cluster cluster, BundleJob oldBundle, String user, Boolean skipDryRun) throws FalconException { String currentUser = CurrentUser.getUser(); switchUser(user); String clusterName = cluster.getName(); Date effectiveTime = getEffectiveTime(cluster, newEntity); LOG.info("Effective time " + effectiveTime); try { dryRunForUpdate(cluster, newEntity, effectiveTime, skipDryRun); boolean suspended = BUNDLE_SUSPENDED_STATUS.contains(oldBundle.getStatus()); updateCoords(clusterName, oldBundle, EntityUtil.getParallel(oldEntity), effectiveTime, newEntity); String newJobId = scheduleForUpdate(newEntity, cluster, effectiveTime); BundleJob newBundle = null; if (newJobId != null) { newBundle = getBundleInfo(clusterName, newJobId); } if (suspended) { doBundleAction(newEntity, BundleAction.SUSPEND, cluster.getName()); } return getUpdateString(newEntity, effectiveTime, oldBundle, newBundle); } finally { switchUser(currentUser); } }
Source:
<code>public long getEventsInRange(ITmfTimestamp start, ITmfTimestamp end) { int countAtStart = 0, countAtEnd = 0; <START> long startTimestamp = checkStartTime(start.getValue()); <END> long endTimestamp = checkEndTime(end.getValue()); try { final int quark = stats.getQuarkAbsolute(Attributes.TOTAL); countAtStart = stats.querySingleState(startTimestamp, quark).getStateValue().unboxInt(); countAtEnd = stats.querySingleState(endTimestamp, quark).getStateValue().unboxInt(); } catch (TimeRangeException e) { return 0; } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } long total = countAtEnd - countAtStart; return total; }</code><technical_language>ITmfTimestamp normalized nanoseconds</technical_language>

Target:
public long getEventsInRange(ITmfTimestamp start, ITmfTimestamp end) { int countAtStart = 0, countAtEnd = 0; long startTime = checkStartTime(start); long endTime = checkEndTime(end); try { final int quark = stats.getQuarkAbsolute(Attributes.TOTAL); countAtStart = stats.querySingleState(startTime, quark).getStateValue().unboxInt(); countAtEnd = stats.querySingleState(endTime, quark).getStateValue().unboxInt(); } catch (TimeRangeException e) { return 0; } catch (AttributeNotFoundException e) { e.printStackTrace(); } catch (StateValueTypeException e) { e.printStackTrace(); } long total = countAtEnd - countAtStart; return total; }
Source:
<code>private void addUsage(JNode jNode, JavaClass javaClass, CodeLinesInfo linesInfo, CodePosition codePosition, List<StringRef> lines) { UsageInfo usageInfo; synchronized (jNode) { <START> usageInfo = usageMap.get(jNode); <END> if (usageInfo == null) { usageInfo = new UsageInfo(); usageMap.put(jNode, usageInfo); } } int line = codePosition.getLine(); JavaNode javaNodeByLine = linesInfo.getJavaNodeByLine(line); StringRef codeLine = lines.get(line - 1); JNode node = nodeCache.makeFrom(javaNodeByLine == null ? javaClass : javaNodeByLine); CodeNode codeNode = new CodeNode(node, line, codeLine); usageInfo.addUsage(codeNode); }</code><technical_language>I double synchronization (one jNode in map) I suggest computeIfAbsent method: java UsageInfo usageInfo = usageMap.computeIfAbsent(jNode, key -> new UsageInfo()); description is atomic, solve synchronization problem. Anyway, checked</technical_language>

Target:
private void addUsage(JNode jNode, JavaClass javaClass, CodeLinesInfo linesInfo, CodePosition codePosition, List<StringRef> lines) { UsageInfo usageInfo = usageMap.computeIfAbsent(jNode, key -> new UsageInfo()); int line = codePosition.getLine(); JavaNode javaNodeByLine = linesInfo.getJavaNodeByLine(line); StringRef codeLine = lines.get(line - 1); JNode node = nodeCache.makeFrom(javaNodeByLine == null ? javaClass : javaNodeByLine); CodeNode codeNode = new CodeNode(node, line, codeLine); usageInfo.addUsage(codeNode); }
Source:
<code>public Response handle(Request request) { final ListDeviceRequest req = (ListDeviceRequest) request.getBody(); <START> final boolean sortOrderAsc = SortOrder.parse(req.isSortOrderAsc()); <END> final List<DeviceVO> devices = deviceDao.list(req.getName(), req.getNamePattern(), req.getNetworkId(), req.getNetworkName(), req.getSortField(), sortOrderAsc, req.getTake(), req.getSkip(), req.getPrincipal()); return Response.newBuilder() .withBody(new ListDeviceResponse(devices)) .buildSuccess(); }</code><technical_language>need change</technical_language>

Target:
public Response handle(Request request) { final ListDeviceRequest req = (ListDeviceRequest) request.getBody(); final List<DeviceVO> devices = deviceDao.list(req.getName(), req.getNamePattern(), req.getNetworkId(), req.getNetworkName(), req.getSortField(), req.isSortOrderAsc(), req.getTake(), req.getSkip(), req.getPrincipal()); return Response.newBuilder() .withBody(new ListDeviceResponse(devices)) .buildSuccess(); }
Source:
<code>private int registerWithMessageId(final Exchange exchange, final Message message) { <START> <END> enableStatus = true; int mid = message.getMID(); if (Message.NONE == mid) { mid = assignMessageId(message); if (Message.NONE != mid) { KeyMID key = KeyMID.fromOutboundMessage(message); if (exchangesByMID.putIfAbsent(key, exchange) != null) { throw new IllegalArgumentException(String.format( "automatic message ID [%d] already in use, cannot register exchange", message.getMID())); } LOGGER.debug("exchange added with generated mid {}, {}", key, message); } } else { KeyMID key = KeyMID.fromOutboundMessage(message); Exchange existingExchange = exchangesByMID.putIfAbsent(key, exchange); if (existingExchange != null) { if (existingExchange != exchange) { throw new IllegalArgumentException(String .format("message ID [%d] already in use, cannot register exchange", message.getMID())); } else if (exchange.getFailedTransmissionCount() == 0) { throw new IllegalArgumentException(String.format( "message with already registered ID [%d] is not a re-transmission, cannot register exchange", message.getMID())); } } else { LOGGER.debug("exchange added with {}, {}", key, message); } } return mid; }</code><technical_language>enableStatus aims "start logging add 'element' in store</technical_language>

Target:
private int registerWithMessageId(final Exchange exchange, final Message message) { enableStatus = true; int mid = message.getMID(); if (Message.NONE == mid) { mid = assignMessageId(message); if (Message.NONE != mid) { KeyMID key = KeyMID.fromOutboundMessage(message); if (exchangesByMID.putIfAbsent(key, exchange) != null) { throw new IllegalArgumentException(String.format( "generated mid [%d] already in use, cannot register exchange", message.getMID())); } LOGGER.debug("exchange added with generated mid {}, {}", key, message); } } else { KeyMID key = KeyMID.fromOutboundMessage(message); Exchange existingExchange = exchangesByMID.putIfAbsent(key, exchange); if (existingExchange != null) { if (existingExchange != exchange) { throw new IllegalArgumentException(String .format("mid [%d] already in use, cannot register exchange", message.getMID())); } else if (exchange.getFailedTransmissionCount() == 0) { throw new IllegalArgumentException(String.format( "message with already registered mid [%d] is not a re-transmission, cannot register exchange", message.getMID())); } } else { LOGGER.debug("exchange added with {}, {}", key, message); } } return mid; }
Source:
<code>private void handleStartingPodStatus(CompletableFuture<Void> podRunningFuture, Pod pod) { if (POD_STATUS_PHASE_RUNNING.equals(pod.getStatus().getPhase())) { <START> podRunningFuture.complete(null); <END> } if (POD_STATUS_PHASE_SUCCEEDED.equals(pod.getStatus().getPhase())) { podRunningFuture.completeExceptionally( new InfrastructureException( "Pod container has been terminated. Container must be configured to use a non-terminating command.")); } if (POD_STATUS_PHASE_FAILED.equals(pod.getStatus().getPhase())) { String exceptionMessage = "Pod '" + pod.getMetadata().getName() + "' failed to start."; String reason = pod.getStatus().getReason(); if (Strings.isNullOrEmpty(reason)) { try { String podLog = clientFactory .create() .pods() .inNamespace(namespace) .withName(pod.getMetadata().getName()) .getLog(); exceptionMessage = exceptionMessage.concat(" Pod logs: ").concat(podLog); } catch (InfrastructureException e) { exceptionMessage = exceptionMessage.concat(" Error occurred while fetching pod logs."); } } else { exceptionMessage = exceptionMessage.concat(" Reason: ").concat(reason); } podRunningFuture.completeExceptionally(new InfrastructureException(exceptionMessage)); LOG.warn(exceptionMessage); } }</code><technical_language>return this line</technical_language>

Target:
private void handleStartingPodStatus(CompletableFuture<Void> podRunningFuture, Pod pod) { if (POD_STATUS_PHASE_RUNNING.equals(pod.getStatus().getPhase())) { podRunningFuture.complete(null); return; } if (POD_STATUS_PHASE_SUCCEEDED.equals(pod.getStatus().getPhase())) { podRunningFuture.completeExceptionally( new InfrastructureException( "Pod container has been terminated. Container must be configured to use a non-terminating command.")); return; } if (POD_STATUS_PHASE_FAILED.equals(pod.getStatus().getPhase())) { String exceptionMessage = "Pod '" + pod.getMetadata().getName() + "' failed to start."; String reason = pod.getStatus().getReason(); if (Strings.isNullOrEmpty(reason)) { try { String podLog = clientFactory .create() .pods() .inNamespace(namespace) .withName(pod.getMetadata().getName()) .getLog(); exceptionMessage = exceptionMessage.concat(" Pod logs: ").concat(podLog); } catch (InfrastructureException e) { exceptionMessage = exceptionMessage.concat(" Error occurred while fetching pod logs."); } } else { exceptionMessage = exceptionMessage.concat(" Reason: ").concat(reason); } podRunningFuture.completeExceptionally(new InfrastructureException(exceptionMessage)); LOG.warn(exceptionMessage); } }
Source:
<code>public boolean batchFetch(List<RowLocation> locations, List<ExecRow> destRows,FormatableBitSet validColumns,boolean waitForLock) throws StandardException{ if (locations.size() == 0) return false; Partition htable = getTable(); KeyHashDecoder rowDecoder = null; try{ DataGet baseGet=opFactory.newDataGet(trans.getTxnInformation(),locations.get(0).getBytes(),null); baseGet.returnAllVersions(); DataGet get = createGet(baseGet,destRows.get(0).getRowArray(),validColumns); Iterator<DataResult> results = htable.batchGet(get, Lists.transform(locations, ROWLOCATION_TO_BYTES)); assert results != null:"Results Returned are Null"; int i = 0; DescriptorSerializer[] serializers = null; int[] cols=FormatableBitSetUtils.toIntArray(validColumns); while (results.hasNext()) { DataResult result = results.next(); DataValueDescriptor[] destRow = destRows.get(i).getRowArray(); if (serializers ==null) { serializers = VersionedSerializers.forVersion(tableVersion, true).getSerializers(destRow); rowDecoder=new EntryDataDecoder(cols,null,serializers); } ExecRow row=new ValueRow(destRow.length); row.setRowArray(destRow); row.resetRowArray(); DataCell keyValue=result.userData(); rowDecoder.set(keyValue.valueArray(),keyValue.valueOffset(),keyValue.valueLength()); rowDecoder.decode(row); i++; } return true; }catch(Exception e){ <START> e.printStackTrace(); <END> throw Exceptions.parseException(e); } finally { if (rowDecoder !=null) Closeables.closeAndSwallowIOExceptions(rowDecoder); } }</code><technical_language>lose extra printStackTrace() please</technical_language>

Target:
public boolean batchFetch(List<RowLocation> locations, List<ExecRow> destRows,FormatableBitSet validColumns,boolean waitForLock) throws StandardException{ if (locations.size() == 0) return false; Partition htable = getTable(); KeyHashDecoder rowDecoder = null; try{ DataGet baseGet=opFactory.newDataGet(trans.getTxnInformation(),locations.get(0).getBytes(),null); baseGet.returnAllVersions(); DataGet get = createGet(baseGet,destRows.get(0).getRowArray(),validColumns); Iterator<DataResult> results = htable.batchGet(get, Lists.transform(locations, ROWLOCATION_TO_BYTES)); assert results != null:"Results Returned are Null"; int i = 0; DescriptorSerializer[] serializers = null; int[] cols=FormatableBitSetUtils.toIntArray(validColumns); while (results.hasNext()) { DataResult result = results.next(); DataValueDescriptor[] destRow = destRows.get(i).getRowArray(); if (serializers ==null) { serializers = VersionedSerializers.forVersion(tableVersion, true).getSerializers(destRow); rowDecoder=new EntryDataDecoder(cols,null,serializers); } ExecRow row=new ValueRow(destRow.length); row.setRowArray(destRow); row.resetRowArray(); DataCell keyValue=result.userData(); rowDecoder.set(keyValue.valueArray(),keyValue.valueOffset(),keyValue.valueLength()); rowDecoder.decode(row); i++; } return true; }catch(Exception e){ throw Exceptions.parseException(e); } finally { if (rowDecoder !=null) Closeables.closeAndSwallowIOExceptions(rowDecoder); } }
Source:
<code><START> public StringListType(StringType... rows) { <END> typeDetails = new ArrayList<>(rows.length); for (StringType row : rows) { typeDetails.add(row.toString()); } }</code><technical_language>convenience constructors delegate constructor is responsible for setting typeDetails? suggestion is new ctor others delegate it</technical_language>

Target:
public StringListType(StringType... rows) { typeDetails = Arrays.stream(rows) .map(StringType::toString) .collect(Collectors.toList()); }
Source:
<code>public static ReplicationPeerManager create(ZKWatcher zk, Configuration conf, String clusterId) throws ReplicationException { ReplicationPeerStorage peerStorage = ReplicationStorageFactory.getReplicationPeerStorage(zk, conf); ConcurrentMap<String, ReplicationPeerDescription> peers = new ConcurrentHashMap<>(); for (String peerId : peerStorage.listPeerIds()) { ReplicationPeerConfig peerConfig = peerStorage.getPeerConfig(peerId); ReplicationPeerConfig updatedPeerConfig = ReplicationPeerConfigUtil. addBasePeerConfigsIfNotPresent(conf,peerConfig); <START> peerStorage.updatePeerConfig(peerId,updatedPeerConfig); <END> boolean enabled = peerStorage.isPeerEnabled(peerId); SyncReplicationState state = peerStorage.getPeerSyncReplicationState(peerId); peers.put(peerId, new ReplicationPeerDescription(peerId, enabled, updatedPeerConfig, state)); } return new ReplicationPeerManager(peerStorage, ReplicationStorageFactory.getReplicationQueueStorage(zk, conf), peers, conf, clusterId); }</code><technical_language>nit: , updatedPeerConfig (space)</technical_language>

Target:
public static ReplicationPeerManager create(ZKWatcher zk, Configuration conf, String clusterId) throws ReplicationException { ReplicationPeerStorage peerStorage = ReplicationStorageFactory.getReplicationPeerStorage(zk, conf); ConcurrentMap<String, ReplicationPeerDescription> peers = new ConcurrentHashMap<>(); for (String peerId : peerStorage.listPeerIds()) { ReplicationPeerConfig peerConfig = peerStorage.getPeerConfig(peerId); peerConfig = ReplicationPeerConfigUtil.addBasePeerConfigsIfNotPresent(conf, peerConfig); peerStorage.updatePeerConfig(peerId, peerConfig); boolean enabled = peerStorage.isPeerEnabled(peerId); SyncReplicationState state = peerStorage.getPeerSyncReplicationState(peerId); peers.put(peerId, new ReplicationPeerDescription(peerId, enabled, peerConfig, state)); } return new ReplicationPeerManager(peerStorage, ReplicationStorageFactory.getReplicationQueueStorage(zk, conf), peers, conf, clusterId); }
Source:
<code>public void setUserProperty(String prop, String value) { getUserProperties().put(prop, value); <START> Context.clearCacheForCurrentUser(); <END> }</code><technical_language>@CacheEvict(value="userSearchLocales") public User saveUser(User user, String password) instead. get rid of CacheManager in Context well. evict for user, key consists of user currentLocale. SaveUser is called invalidating entries is issue anyway</technical_language>

Target:
public void setUserProperty(String prop, String value) { getUserProperties().put(prop, value); }
Source:
<code>public boolean remove(String lookupName) { final LookupExtractorFactory lookupExtractorFactory = lookupMap.remove(lookupName); if (lookupExtractorFactory != null) { <START> LOGGER.debug("Removing lookup [%s]", lookupName); <END> if (!isClosed() && lookupSnapshotTaker != null) { lookupSnapshotTaker.takeSnapshot(getAllAsList()); } return lookupExtractorFactory.close(); } return false; }</code><technical_language>noticed this line "removing" _after_ removed. adjust tense verb line actual timeline</technical_language>

Target:
public boolean remove(String lookupName) { synchronized (lock) { final LookupExtractorFactory lookupExtractorFactory = lookupMap.remove(lookupName); if (lookupExtractorFactory != null) { LOGGER.debug("Removed lookup [%s]", lookupName); if (lookupSnapshotTaker != null) { lookupSnapshotTaker.takeSnapshot(getAllAsList()); } return lookupExtractorFactory.close(); } } return false; }
Source:
<code>@CheckReturnValue public final @Nullable T fromJson(String string) throws IOException { JsonReader reader = JsonReader.of(new Buffer().writeUtf8(string)); T result = fromJson(reader); if (reader.peek() != JsonReader.Token.END_DOCUMENT) { <START> throw new JsonDataException("JSON document was not fully consumed."); <END> } return result; }</code><technical_language>I include next token additional hint</technical_language>

Target:
@CheckReturnValue public final @Nullable T fromJson(String string) throws IOException { JsonReader reader = JsonReader.of(new Buffer().writeUtf8(string)); T result = fromJson(reader); if (!isLenient() && reader.peek() != JsonReader.Token.END_DOCUMENT) { throw new JsonDataException("JSON document was not fully consumed."); } return result; }
Source:
<code><START> public SecurityEventVisitor<?, String> build() { <END> return new SimpleSecurityEventFormatter(this); }</code><technical_language>this wildcard StringBuilder a bit off</technical_language>

Target:
public SecurityEventVisitor<Void, String> build() { return new SimpleSecurityEventFormatter(this); }