auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ResponseEntity<?> getPartition(@PathVariable("name") final String eventTypeName, @PathVariable("partition") final String partition, @Nullable @RequestParam(value = "consumed_offset", required = false) <START> final String consumedOffset, final NativeWebRequest request, <END> final Client client) { LOG.trace("Get partition endpoint for event-type '{}', partition '{}' is called", eventTypeName, partition); try { final EventType eventType = eventTypeRepository.findByName(eventTypeName); authorizeStreamRead(authorizationService, client, eventType); if (consumedOffset != null) { final CursorLag cursorLag = getCursorLag(eventTypeName, partition, consumedOffset); return ok().body(cursorLag); } else { final EventTypePartitionView result = getTopicPartition(eventTypeName, partition); return ok().body(result); } } catch (final NoSuchEventTypeException e) { return create(Problem.valueOf(NOT_FOUND, "topic not found"), request); } catch (final NakadiException e) { LOG.error("Could not get partition. Respond with SERVICE_UNAVAILABLE.", e); return create(e.asProblem(), request); } catch (final InvalidCursorException e) { return create(Problem.valueOf(MoreStatus.UNPROCESSABLE_ENTITY, INVALID_CURSOR_MESSAGE), request); } }</code><technical_language>broken formatting</technical_language>

Target:
public ResponseEntity<?> getPartition(@PathVariable("name") final String eventTypeName, @PathVariable("partition") final String partition, @Nullable @RequestParam(value = "consumed_offset", required = false) final String consumedOffset, final NativeWebRequest request, final Client client) { LOG.trace("Get partition endpoint for event-type '{}', partition '{}' is called", eventTypeName, partition); try { final EventType eventType = eventTypeRepository.findByName(eventTypeName); authorizationValidator.authorizeStreamRead(client, eventType); if (consumedOffset != null) { final CursorLag cursorLag = getCursorLag(eventTypeName, partition, consumedOffset); return ok().body(cursorLag); } else { final EventTypePartitionView result = getTopicPartition(eventTypeName, partition); return ok().body(result); } } catch (final NoSuchEventTypeException e) { return create(Problem.valueOf(NOT_FOUND, "topic not found"), request); } catch (final NakadiException e) { LOG.error("Could not get partition. Respond with SERVICE_UNAVAILABLE.", e); return create(e.asProblem(), request); } catch (final InvalidCursorException e) { return create(Problem.valueOf(MoreStatus.UNPROCESSABLE_ENTITY, INVALID_CURSOR_MESSAGE), request); } }
Source:
<code>void startRenamingProcess(String name, int maxAmount) { currentName = name; currentMaxAmount = maxAmount; renamingDialog.getInputEditText().setText(name); if (maxAmount > 1) { renameAmountDialog.setActionButton(DialogAction.NEUTRAL, R.string.all_of_them); renameAmountDialog.setContent(R.string.multiple_renames_title, name , maxAmount); EditText input = renameAmountDialog.getInputEditText(); if (input != null) { <START> input.setText("" + maxAmount); <END> input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(String.valueOf(maxAmount).length())}); } renameAmountDialog.show(); } else { amountToRename = 1; renamingDialog.setActionButton(DialogAction.NEUTRAL, null); renamingDialog.show(); } }</code><technical_language>suggestion input.setText("" + String.valueOf(maxAmount));</technical_language>

Target:
public void startRenamingProcess(String name, int maxAmount) { currentName = name; currentMaxAmount = maxAmount; renamingDialog.getInputEditText().setText(name); if (maxAmount > 1) { EditText input = renameAmountDialog.getInputEditText(); if (input != null) { input.setText(""); input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(String.valueOf(maxAmount).length())}); } renameAmountDialog.show(); } else { amountToRename = 1; renamingDialog.setActionButton(DialogAction.NEUTRAL, null); renamingDialog.show(); } }
Source:
<code><START> public Integer getMaxConcurrency() throws IOException { <END> final String concurrency = (String) this.client.getConfig().get(getMaxConcurrencyConfigName()); return concurrency == null ? null : Integer.parseInt(concurrency); }</code><technical_language>asymmetric allow returning a null Integer for getMaxConcurrency, setMaxConcurrency allows a primitive int null. Is meaningful for max concurrency null? If so, do clear max concurrency</technical_language>

Target:
public int getMaxConcurrency() throws IOException { final String concurrency = (String) this.client.getConfig().get(getMaxConcurrencyConfigName()); return concurrency == null ? -1 : Integer.parseInt(concurrency); }
Source:
<code>public List<Long> histogramQuery(final long start, final long end, final int nb) { final List<Long> list = new LinkedList<Long>(); final long increment = (end - start) / nb; <START> waitUntilBuilt(); <END> long prevTotal = (start == totalsStats.getStartTime()) ? 0 : getEventCountAt(start); long curTime = start + increment; long curTotal, count; for (int i = 0; i < nb - 1; i++) { curTotal = getEventCountAt(curTime); count = curTotal - prevTotal; list.add(count); curTime += increment; prevTotal = curTotal; } curTotal = getEventCountAt(end); count = curTotal - prevTotal; list.add(count); return list; }</code><technical_language>Do need wait totalsStats</technical_language>

Target:
public List<Long> histogramQuery(final long start, final long end, final int nb) { final List<Long> list = new LinkedList<Long>(); final long increment = (end - start) / nb; if (!totalsStats.waitUntilBuilt()) { return list; } long prevTotal = (start == totalsStats.getStartTime()) ? 0 : getEventCountAt(start); long curTime = start + increment; long curTotal, count; for (int i = 0; i < nb - 1; i++) { curTotal = getEventCountAt(curTime); count = curTotal - prevTotal; list.add(count); curTime += increment; prevTotal = curTotal; } curTotal = getEventCountAt(end); count = curTotal - prevTotal; list.add(count); return list; }
Source:
<code>protected VdcReturnValueBase evaluateCorrelationId(CommandBase<?> commandBase) { VdcReturnValueBase returnValue = null; returnValue = ExecutionHandler.evaluateCorrelationId(commandBase.getParameters()); if (returnValue != null) { <START> log.warn("Validate of action '{}' failed. Reasons: {}", commandBase.getActionType(), <END> StringUtils.join(returnValue.getValidateMessages(), ',')); } commandBase.setCorrelationId(commandBase.getParameters().getCorrelationId()); return returnValue; }</code><technical_language>message "Validation of action"</technical_language>

Target:
protected VdcReturnValueBase evaluateCorrelationId(CommandBase<?> commandBase) { VdcReturnValueBase returnValue = null; returnValue = ExecutionHandler.evaluateCorrelationId(commandBase.getParameters()); if (returnValue != null) { log.warn("Validation of action '{}' failed. Reasons: {}", commandBase.getActionType(), StringUtils.join(returnValue.getValidationMessages(), ',')); } commandBase.setCorrelationId(commandBase.getParameters().getCorrelationId()); return returnValue; }
Source:
<code>public boolean equals(final Object other) { <START> if(other == null) { <END> return false; } if(this.getClass() != other.getClass()) { return false; } final Bin otherBin = (Bin)other; return this.referenceSequence == otherBin.referenceSequence && this.binNumber == otherBin.binNumber; }</code><technical_language>please stick single-line style ifs for guard statements? I.e. java if (other == null) return false; is preferred java if (other == null) { return false; } especially return early top of methods</technical_language>

Target:
public boolean equals(final Object other) { if(other == null) return false; if(this.getClass() != other.getClass()) return false; final Bin otherBin = (Bin)other; return this.referenceSequence == otherBin.referenceSequence && this.binNumber == otherBin.binNumber; }
Source:
<code>private void parseConfiguration(String config) throws IllegalArgumentException { String[] mappings = config.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); if (params.length < 2) { <START> throw new IllegalArgumentException("Configuration " + mapping + " is in-correctly formed. " + <END> "Format should be <fieldname>:<decoder-type>"); } String field = params[0]; String type = params[1].toUpperCase(); DecoderType eType = DecoderType.valueOf(type); if (decodeMap.containsKey(field)) { throw new IllegalArgumentException("Field " + field + " already has decoder set. Check the mapping."); } else { decodeMap.put(field, eType); } } }</code><technical_language>is incorrectly formed</technical_language>

Target:
private void parseConfiguration(String config) throws IllegalArgumentException { String[] mappings = config.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); if (params.length < 2) { throw new IllegalArgumentException("Configuration '" + mapping + "' is incorrectly formed. " + "Format should be <fieldname>:<decoder-type>"); } String field = params[0]; String type = params[1].toUpperCase(); DecoderType eType = DecoderType.valueOf(type); if (decodeMap.containsKey(field)) { throw new IllegalArgumentException("Field " + field + " already has decoder set. Check the mapping."); } else { decodeMap.put(field, eType); } } }
Source:
<code>public QueueClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString); this.sharedKeyCredential = SharedKeyCredential.fromConnectionString(connectionString); <START> Objects.requireNonNull(connectionString); <END> this.sharedKeyCredential = SharedKeyCredential.fromConnectionString(connectionString); getEndPointFromConnectionString(connectionString); return this; }</code><technical_language>This code is duplicated</technical_language>

Target:
public QueueClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString); this.sharedKeyCredential = SharedKeyCredential.fromConnectionString(connectionString); getEndPointFromConnectionString(connectionString); return this; }
Source:
<code>private void setupTimeoutAlert() { Object obj = RealtimeIndexTask.this.getContextValue("alertTimeout"); if (obj == null) { return; } long timeout = parseLong(obj); Timer timer = new Timer("RealtimeIndexTask-Timer", true); timer.schedule( new TimerTask() { @Override public void run() { <START> log.makeAlert("RealtimeIndexTask hasn't finished in configured time [%d] ms.", timeout); <END> } }, timeout ); }</code><technical_language>need .emit() alert too. Also, dataSource included in somewhere, in message addData</technical_language>

Target:
private void setupTimeoutAlert() { if (spec.getTuningConfig().getAlertTimeout() > 0) { Timer timer = new Timer("RealtimeIndexTask-Timer", true); timer.schedule( new TimerTask() { @Override public void run() { log.makeAlert( "RealtimeIndexTask for dataSource [%s] hasn't finished in configured time [%d] ms.", spec.getDataSchema().getDataSource(), spec.getTuningConfig().getAlertTimeout() ).emit(); } }, spec.getTuningConfig().getAlertTimeout() ); } }
Source:
<code>protected ITmfStateProvider createStateProvider() { ITmfTrace trace = getTrace(); <START> if (!(trace instanceof LttngKernelTrace)) { <END> throw new IllegalStateException(); } return new LttngKernelCpuUsageStateProvider(trace, ((LttngKernelTrace) trace).getEventLayout()); }</code><technical_language>I analysis class a dependency a specific trace type</technical_language>

Target:
protected ITmfStateProvider createStateProvider() { ITmfTrace trace = getTrace(); IKernelAnalysisEventLayout layout; if (trace instanceof LttngKernelTrace) { layout = ((LttngKernelTrace) trace).getEventLayout(); } else { layout = LttngEventLayout.getInstance(); } return new LttngKernelCpuUsageStateProvider(trace, layout); }
Source:
<code>public int getPropertyId() { if ( propertyIds.length != 1 ) { throw new IllegalStateException( <START> "Single property schema required one property but had " + propertyIds.length ); <END> } return propertyIds[0]; }</code><technical_language>previous version more correct. requirement is in place, present tense used. new version implies schema _used require_, a requirement is longer in force, is true</technical_language>

Target:
public int getPropertyId() { if ( propertyIds.length != 1 ) { throw new IllegalStateException( "Single property schema requires one property but had " + propertyIds.length ); } return propertyIds[0]; }
Source:
<code>public HistoricalEventEmitter(EmittedEventDao emittedEventDao, StateTransitionQueue stateTransitionQueue, EventQueue eventQueue, RefundDao refundDao, boolean shouldForceEmission) { this.emittedEventDao = emittedEventDao; this.stateTransitionQueue = stateTransitionQueue; this.eventQueue = eventQueue; this.refundDao = refundDao; this.paymentGatewayStateTransitions = PaymentGatewayStateTransitions.getInstance(); <START> this.doNotForceEmission = !shouldForceEmission; <END> }</code><technical_language>follow variable everywhere. confusing (at for me) if need start thinking of true false false true this point</technical_language>

Target:
public HistoricalEventEmitter(EmittedEventDao emittedEventDao, StateTransitionQueue stateTransitionQueue, EventQueue eventQueue, RefundDao refundDao, boolean shouldForceEmission) { this.emittedEventDao = emittedEventDao; this.stateTransitionQueue = stateTransitionQueue; this.eventQueue = eventQueue; this.refundDao = refundDao; this.paymentGatewayStateTransitions = PaymentGatewayStateTransitions.getInstance(); this.shouldForceEmission = shouldForceEmission; }
Source:
<code>public String getXRegistryAuthHeaderValue(String registry, @Nullable AuthConfigs paramsAuthConfigs) { Map<String, AuthConfig> authConfigsMap = null; if (paramsAuthConfigs != null) { authConfigsMap = paramsAuthConfigs.getConfigs(); } AuthConfig authConfig = null; if (authConfigsMap != null) { for(Map.Entry<String, AuthConfig> entry : authConfigsMap.entrySet()) { AuthConfig value = entry.getValue(); if (value.getServeraddress().contains(registry)) { authConfig = value; break; } } } if (authConfig == null) { <START> if (DEFAULT_REGISTRY.equals(registry)) { <END> registry = DEFAULT_REGISTRY_VALUE; } for(Map.Entry<String, AuthConfig> entry : initialAuthConfig.getAuthConfigs().getConfigs().entrySet()) { AuthConfig value = entry.getValue(); if (value.getServeraddress().contains(registry)) { authConfig = value; break; } } } if (authConfig != null) { XRegistryAuthUnit auth = new XRegistryAuthUnit(authConfig.getUsername(), authConfig.getPassword()); return Base64.encodeBase64String(JsonHelper.toJson(auth).getBytes()); } return Base64.encodeBase64String("{}".getBytes()); }</code><technical_language>I good improvement a set default registry names: docker.io, index.docker.io, <LINK_0>, "" allow of a default resitry identifier auth conf provided a parameter of this method</technical_language>

Target:
public String getXRegistryAuthHeaderValue(String registry, @Nullable AuthConfigs paramsAuthConfigs) { Map<String, AuthConfig> authConfigsMap = null; if (paramsAuthConfigs != null) { authConfigsMap = paramsAuthConfigs.getConfigs(); } if (DEFAULT_REGISTRY.contains(registry)) { registry = DEFAULT_REGISTRY_VALUE; } AuthConfig authConfig = null; if (authConfigsMap != null) { for(Map.Entry<String, AuthConfig> entry : authConfigsMap.entrySet()) { AuthConfig value = entry.getValue(); if (value.getServeraddress().contains(registry)) { authConfig = value; break; } } } if (authConfig == null) { for(Map.Entry<String, AuthConfig> entry : initialAuthConfig.getAuthConfigs().getConfigs().entrySet()) { AuthConfig value = entry.getValue(); if (value.getServeraddress().contains(registry)) { authConfig = value; break; } } } if (authConfig != null) { XRegistryAuthUnit auth = new XRegistryAuthUnit(authConfig.getUsername(), authConfig.getPassword()); return Base64.encodeBase64String(JsonHelper.toJson(auth).getBytes()); } return Base64.encodeBase64String("{}".getBytes()); }
Source:
<code>void addEmptyColumnToDataPutMutation(Put put, PTable ptable, long ts) throws Exception{ PName pdefaultFamilyName = ptable.getDefaultFamilyName(); addCellToPutMutation(put, <START> pdefaultFamilyName == null ? QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES : pdefaultFamilyName.getBytes(), <END> QueryConstants.EMPTY_COLUMN_BYTES, ts, QueryConstants.EMPTY_COLUMN_VALUE_BYTES); }</code><technical_language>SchemaUtil.getEmptyColumnFamily(table)</technical_language>

Target:
void addEmptyColumnToDataPutMutation(Put put, PTable ptable, long ts) throws Exception { addCellToPutMutation(put, SchemaUtil.getEmptyColumnFamily(ptable), QueryConstants.EMPTY_COLUMN_BYTES, ts, QueryConstants.EMPTY_COLUMN_VALUE_BYTES); }
Source:
<code>public void subscribeToDataStoreInternal(@NonNull CompositeSubscription compositeSubscription) { Log.v(TAG, "subscribeToDataStoreInternal"); ConnectableObservable<DataStreamNotification<GitHubRepositorySearch>> repositorySearchSource = searchString .filter((string) -> string.length() > 2) <START> .debounce(1000, TimeUnit.MILLISECONDS) <END> .switchMap(getGitHubRepositorySearch::call) .publish(); compositeSubscription.add(repositorySearchSource .map(toProgressStatus()) .subscribe(this::setNetworkStatusText)); compositeSubscription.add(repositorySearchSource .filter(DataStreamNotification::isOnNext) .map(DataStreamNotification::getValue) .map(GitHubRepositorySearch::getItems) .flatMap(toGitHubRepositoryList()) .doOnNext(list -> Log.d(TAG, "Publishing " + list.size() + " repositories from the ViewModel")) .subscribe(RepositoriesViewModel.this.repositories::onNext)); compositeSubscription.add(repositorySearchSource.connect()); }</code><technical_language>change a constant instead of magic number</technical_language>

Target:
public void subscribeToDataStoreInternal(@NonNull CompositeSubscription compositeSubscription) { Log.v(TAG, "subscribeToDataStoreInternal"); ConnectableObservable<DataStreamNotification<GitHubRepositorySearch>> repositorySearchSource = searchString .filter((string) -> string.length() > 2) .debounce(SEARCH_INPUT_DELAY, TimeUnit.MILLISECONDS) .switchMap(getGitHubRepositorySearch::call) .publish(); compositeSubscription.add(repositorySearchSource .map(toProgressStatus()) .subscribe(this::setNetworkStatusText)); compositeSubscription.add(repositorySearchSource .filter(DataStreamNotification::isOnNext) .map(DataStreamNotification::getValue) .map(GitHubRepositorySearch::getItems) .flatMap(toGitHubRepositoryList()) .doOnNext(list -> Log.d(TAG, "Publishing " + list.size() + " repositories from the ViewModel")) .subscribe(RepositoriesViewModel.this.repositories::onNext)); compositeSubscription.add(repositorySearchSource.connect()); }
Source:
<code><START> public synchronized Class<?> defineClass(String name, byte[] bytecode) { <END> return defineClass(name, convertClassToResourcePath(name), bytecode); }</code><technical_language>@manstis this synchronized removed? this method is calling defineClass overload is sync'ed</technical_language>

Target:
public Class<?> defineClass(String name, byte[] bytecode) { return defineClass(name, convertClassToResourcePath(name), bytecode); }
Source:
<code>public void close() throws Exception { for (final EventProcessor eventProcessor : eventProcessors) { <START> eventProcessor.close(); <END> } }</code><technical_language>changed</technical_language>

Target:
public void close() throws Exception { eventProcessors.forEach(eventProcessor -> eventProcessor.close()); }
Source:
<code>public void sendAsynchronousRequest(final ChannelBuffer message, <START> final boolean oneway, <END> final Listener listener) throws TException { final int sequenceId = extractSequenceId(message); executeInIoThread(new Runnable() { @Override public void run() { ChannelFuture sendFuture = writeRequest(message); final Request request = makeRequest(sequenceId, listener); queueSendTimeout(request); sendFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { cancelRequestTimeouts(request); listener.requestSent(); if (oneway) { retireRequest(sequenceId); } else { queueReceiveTimeout(request); } } else { TTransportException transportException = new TTransportException("Sending request failed", future.getCause()); listener.channelError(transportException); onError(transportException); } } }); } }); }</code><technical_language>add "final" primitive method arguments</technical_language>

Target:
public void sendAsynchronousRequest(final ChannelBuffer message, final boolean oneway, final Listener listener) throws TException { final int sequenceId = extractSequenceId(message); executeInIoThread(new Runnable() { @Override public void run() { ChannelFuture sendFuture = writeRequest(message); final Request request = makeRequest(sequenceId, listener); queueSendTimeout(request); sendFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { cancelRequestTimeouts(request); listener.onRequestSent(); if (oneway) { retireRequest(sequenceId); } else { queueReceiveTimeout(request); } } else { TTransportException transportException = new TTransportException("Sending request failed", future.getCause()); listener.onChannelError(transportException); onError(transportException); } } }); } }); }
Source:
<code>protected long toLastCommitted(TopicPartition topicPartition) { Long offset = lastCommittedOffsets.get(topicPartition); if (offset == null) { OffsetAndMetadata offsetMeta = consumer.committed(topicPartition); if (offsetMeta != null) { offset = offsetMeta.offset(); } } if (offset != null) { consumer.seek(topicPartition, offset); } else { consumer.seekToBeginning(Collections.singletonList(topicPartition)); offset = consumer.position(topicPartition); } <START> log.debug(String.format(" toLastCommitted: %s-%02d:+%d", getNameForTopic(topicPartition.topic()), <END> topicPartition.partition(), offset)); return offset; }</code><technical_language>isDebugEnabled</technical_language>

Target:
protected long toLastCommitted(TopicPartition topicPartition) { Long offset = lastCommittedOffsets.get(topicPartition); if (offset == null) { OffsetAndMetadata offsetMeta = consumer.committed(topicPartition); if (offsetMeta != null) { offset = offsetMeta.offset(); } } if (offset != null) { consumer.seek(topicPartition, offset); } else { consumer.seekToBeginning(Collections.singletonList(topicPartition)); offset = consumer.position(topicPartition); } if (log.isDebugEnabled()) { log.debug(String.format(" toLastCommitted: %s-%02d:+%d", getNameForTopic(topicPartition.topic()), topicPartition.partition(), offset)); } return offset; }
Source:
<code>public void testLookupVariant() { <START> @SuppressWarnings("null") <END> VariantDefinition result = fixture.lookupVariant(ENUM_8); assertNull(result); }</code><technical_language>is point testing this if method is marked @NonNull. a compiler check instead of a "unit test check". This means remove this test altogether</technical_language>

Target:
public void testLookupVariant() { VariantDefinition result = fixture.lookupVariant(ENUM_8); assertNull(result); }
Source:
<code><START> public final static VelocityModeHandler modeHandler(PageMode mode, HttpServletRequest request, HttpServletResponse response) { <END> switch (mode) { case PREVIEW_MODE: return new VelocityPreviewMode(request, response); case EDIT_MODE: return new VelocityEditMode(request, response); default: return new VelocityLiveMode(request, response); } }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Reorder modifiers comply Java Language Specification. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public static final VelocityModeHandler modeHandler(PageMode mode, HttpServletRequest request, HttpServletResponse response) { switch (mode) { case PREVIEW_MODE: return new VelocityPreviewMode(request, response); case EDIT_MODE: return new VelocityEditMode(request, response); default: return new VelocityLiveMode(request, response); } }
Source:
<code>public void addKoreRules(Module module, TermContext termContext) { KOREtoBackendKIL transformer = new KOREtoBackendKIL(termContext); JavaConversions.setAsJavaSet(module.sentences()).stream().forEach(s -> { if (s instanceof org.kframework.definition.Rule) { org.kframework.definition.Rule rule = (org.kframework.definition.Rule) s; K leftHandSide = RewriteToTop.toLeft(rule.body()); org.kframework.kil.Rule oldRule = new org.kframework.kil.Rule(); oldRule.setAttributes(new KOREtoKIL().convertAttributes(rule.att())); Location loc = rule.att().getOptional(Location.class).orElse(null); <START> Source source = rule.att().getOptional(Source.class).orElse(null); <END> oldRule.setLocation(loc); oldRule.setSource(source); if (leftHandSide instanceof KApply && module.attributesFor().apply(((KApply)leftHandSide).klabel()).contains("function")) { oldRule.putAttribute("function", ""); } addRule(new Rule( "", transformer.convert(leftHandSide), transformer.convert(RewriteToTop.toRight(rule.body())), Collections.singletonList(transformer.convert(rule.requires())), Collections.singletonList(transformer.convert(rule.ensures())), Collections.emptySet(), Collections.emptySet(), ConjunctiveFormula.of(termContext), false, null, null, null, null, oldRule, termContext)); } }); }</code><technical_language>explain Location Source work? This counter intuitive a glance</technical_language>

Target:
public void addKoreRules(Module module, TermContext termContext) { KOREtoBackendKIL transformer = new KOREtoBackendKIL(termContext); JavaConversions.setAsJavaSet(module.sentences()).stream().forEach(s -> { if (s instanceof org.kframework.definition.Rule) { org.kframework.definition.Rule rule = (org.kframework.definition.Rule) s; K leftHandSide = RewriteToTop.toLeft(rule.body()); org.kframework.kil.Rule oldRule = new org.kframework.kil.Rule(); oldRule.setAttributes(new KOREtoKIL().convertAttributes(rule.att())); Location loc = rule.att().getOptional(Location.class).orElse(null); Source source = rule.att().getOptional(Source.class).orElse(null); oldRule.setLocation(loc); oldRule.setSource(source); if (leftHandSide instanceof KApply && module.attributesFor().apply(((KApply)leftHandSide).klabel()).contains(Attribute.FUNCTION_KEY)) { oldRule.putAttribute(Attribute.FUNCTION_KEY, ""); } addRule(new Rule( "", transformer.convert(leftHandSide), transformer.convert(RewriteToTop.toRight(rule.body())), Collections.singletonList(transformer.convert(rule.requires())), Collections.singletonList(transformer.convert(rule.ensures())), Collections.emptySet(), Collections.emptySet(), ConjunctiveFormula.of(termContext), false, null, null, null, null, oldRule, termContext)); } }); }
Source:
<code>private Downloader download(String url, String title, boolean expectedResult, boolean deleteExisting, String username, String password, boolean deleteOnFail) { FeedFile feedFile = setupFeedFile(url, title, deleteExisting); DownloadRequest request = new DownloadRequest(feedFile.getFile_url(), url, title, 0, feedFile.getTypeAsInt(), username, password, deleteOnFail, null, false); Downloader downloader = new HttpDownloader(request); downloader.call(); DownloadStatus status = downloader.getResult(); assertNotNull(status); <START> assertEquals(status.isSuccessful(), expectedResult); <END> assertTrue(status.isDone()); assertTrue(!deleteExisting || new File(feedFile.getFile_url()).exists() == expectedResult); return downloader; }</code><technical_language>expected result added front</technical_language>

Target:
private Downloader download(String url, String title, boolean expectedResult, boolean deleteExisting, String username, String password, boolean deleteOnFail) { FeedFile feedFile = setupFeedFile(url, title, deleteExisting); DownloadRequest request = new DownloadRequest(feedFile.getFile_url(), url, title, 0, feedFile.getTypeAsInt(), username, password, deleteOnFail, null, false); Downloader downloader = new HttpDownloader(request); downloader.call(); DownloadStatus status = downloader.getResult(); assertNotNull(status); assertEquals(expectedResult, status.isSuccessful()); assertTrue(status.isDone()); assertTrue(!deleteExisting || new File(feedFile.getFile_url()).exists() == expectedResult); return downloader; }
Source:
<code>private void refreshAccessToken() { if (refreshTokenNetworkRequest != null) { refreshTokenNetworkRequest.cancel(); } Future<?> task = SyncManager.NETWORK_POOL_EXECUTOR.submit(new ExponentialBackoffTask<AuthenticateResponse>() { @Override protected AuthenticateResponse execute() { <START> return authServer.refreshUser(user.getUserToken(), configuration.getServerUrl(), user.getAuthenticationUrl()); <END> } @Override protected void onSuccess(AuthenticateResponse response) { RealmLog.debug("Access Token refreshed successfully"); if (updateSessionAccessToken(response.getAccessToken().value())) { RealmLog.debug("Token applied"); ObjectServerUser.AccessDescription desc = new ObjectServerUser.AccessDescription( response.getAccessToken(), configuration.getPath(), configuration.shouldDeleteRealmOnLogout() ); user.addRealm(configuration.getServerUrl(), desc); scheduleRefreshAccessToken(response.getAccessToken().expiresMs()); } } @Override protected void onError(AuthenticateResponse response) { } }); refreshTokenNetworkRequest = new RealmAsyncTaskImpl(task, SyncManager.NETWORK_POOL_EXECUTOR); }</code><technical_language>retry if wrong</technical_language>

Target:
private void refreshAccessToken() { if (refreshTokenNetworkRequest != null) { refreshTokenNetworkRequest.cancel(); } Future<?> task = SyncManager.NETWORK_POOL_EXECUTOR.submit(new ExponentialBackoffTask<AuthenticateResponse>() { @Override protected AuthenticateResponse execute() { return authServer.refreshUser(user.getUserToken(), configuration.getServerUrl(), user.getAuthenticationUrl()); } @Override protected void onSuccess(AuthenticateResponse response) { synchronized (ObjectServerSession.this) { RealmLog.debug("Access Token refreshed successfully"); if (updateSessionAccessToken(response.getAccessToken().value())) { RealmLog.debug("Token applied"); ObjectServerUser.AccessDescription desc = new ObjectServerUser.AccessDescription( response.getAccessToken(), configuration.getPath(), configuration.shouldDeleteRealmOnLogout() ); user.addRealm(configuration.getServerUrl(), desc); scheduleRefreshAccessToken(response.getAccessToken().expiresMs()); } } } @Override protected void onError(AuthenticateResponse response) { RealmLog.error("Unrecoverable error, while refreshing the access Token (" + response.getError().toString() + ") reschedule will not happen"); } }); refreshTokenNetworkRequest = new RealmAsyncTaskImpl(task, SyncManager.NETWORK_POOL_EXECUTOR); }
Source:
<code>public Feature< Link, Double, DoublePropertyMap< Link > > compute( final Model model ) { final ModelGraph graph = model.getGraph(); final DoublePropertyMap< Link > pm = new DoublePropertyMap<>( graph.edges(), Double.NaN ); final Spot ref1 = graph.vertexRef(); final Spot ref2 = graph.vertexRef(); @SuppressWarnings( "unchecked" ) final Feature< Link, Double, DoublePropertyMap< Link > > displacementFeature = <START> ( Feature< Link, Double, DoublePropertyMap< Link > > ) model.getFeatureModel().getFeature( LinkDisplacementComputer.KEY ); <END> final DoublePropertyMap< Link > displacement = displacementFeature.getPropertyMap(); for ( final Link link : graph.edges() ) { if ( displacement.isSet( link ) ) { final double disp = displacement.getDouble( link ); final Spot source = link.getSource( ref1 ); final Spot target = link.getTarget( ref2 ); final double dt = Math.abs( source.getTimepoint() - target.getTimepoint() ); pm.set( link, disp / dt ); } } graph.releaseRef( ref1 ); graph.releaseRef( ref2 ); final Map< String, FeatureProjection< Link > > projections = Collections.singletonMap( KEY, FeatureProjectors.project( pm ) ); final Feature< Link, Double, DoublePropertyMap< Link > > feature = new Feature<>( KEY, Link.class, pm, projections ); return feature; }</code><technical_language>FeatureModel.getFeature(...) trigger computation if feature is present? require fuse DefaultFeatureModel DefaultFeatureComputerService. This provide automatic dependency resolution. (In case, I additionally explicit dependency resolution topological sort for progress report circular dependency detection.)</technical_language>

Target:
public Feature< Link, DoublePropertyMap< Link > > compute( final Model model ) { final ModelGraph graph = model.getGraph(); final DoublePropertyMap< Link > pm = new DoublePropertyMap<>( graph.edges(), Double.NaN ); final Spot ref1 = graph.vertexRef(); final Spot ref2 = graph.vertexRef(); @SuppressWarnings( "unchecked" ) final Feature< Link, DoublePropertyMap< Link > > displacementFeature = ( Feature< Link, DoublePropertyMap< Link > > ) model.getFeatureModel().getFeature( LinkDisplacementComputer.KEY ); final DoublePropertyMap< Link > displacement = displacementFeature.getPropertyMap(); for ( final Link link : graph.edges() ) { if ( displacement.isSet( link ) ) { final double disp = displacement.getDouble( link ); final Spot source = link.getSource( ref1 ); final Spot target = link.getTarget( ref2 ); final double dt = Math.abs( source.getTimepoint() - target.getTimepoint() ); pm.set( link, disp / dt ); } } graph.releaseRef( ref1 ); graph.releaseRef( ref2 ); final Map< String, FeatureProjection< Link > > projections = Collections.singletonMap( KEY, FeatureProjectors.project( pm ) ); final Feature< Link, DoublePropertyMap< Link > > feature = new Feature<>( KEY, Link.class, pm, projections ); return feature; }
Source:
<code>public RegisteredService findServiceBy(final String serviceId) { if (StringUtils.isBlank(serviceId)) { return null; } <START> RegisteredService service = getCandidateServicesToMatch(serviceId) <END> .filter(r -> r.matches(serviceId)) .findFirst() .orElse(null); if (service == null) { service = this.serviceRegistry.findServiceByExactServiceId(serviceId); } if (service != null) { service.initialize(); } return validateRegisteredService(service); }</code><technical_language>suggestion var service = getCandidateServicesToMatch(serviceId)</technical_language>

Target:
public RegisteredService findServiceBy(final String serviceId) { if (StringUtils.isBlank(serviceId)) { return null; } var service = getCandidateServicesToMatch(serviceId) .filter(r -> r.matches(serviceId)) .findFirst() .orElse(null); if (service == null) { LOGGER.trace("The service that matches the serviceId is not found in the cache, trying to find it from [{}]", serviceId, serviceRegistry.getName()); service = serviceRegistry.findServiceBy(serviceId); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in and populated to the cache ", serviceRegistry.getName(), service); } } if (service != null) { service.initialize(); } return validateRegisteredService(service); }
Source:
<code>public void close() throws Exception { <START> closeAll(stream, file::release, () -> buffersToClose.forEach(Buffer::recycleBuffer)); <END> }</code><technical_language>recycling buffers end, close fly? GBs of extra (unnecessary) memory usage if unconsumed buffers channels. ownership of buffers returned iterator belong caller of next() method</technical_language>

Target:
public void close() throws Exception { closeAll(stream, file::release); }
Source:
<code>public String getDisplayName() { <START> return "Azure DevOps Services Release Webhook"; <END> }</code><technical_language>pl. rename this TFS/Team Services Release Webhook, do this name refresh afterwards.</technical_language>

Target:
public String getDisplayName() { return "TFS/Team Services Release Webhook"; }
Source:
<code>private void doAuthenticate(ExtMap input, ExtMap output) { <START> input.putIfAbsent(Base.ContextKeys.CONFIGURATION, configuration); <END> broker.runAdAction( AdActionType.AuthenticateUser, new LdapUserPasswordBaseParameters(input, output) ); output.mput( Authn.InvokeKeys.USER_MESSAGE, configuration.getProperty("config.change.password.msg") ).mput( Authn.InvokeKeys.CREDENTIALS_CHANGE_URL, configuration.getProperty("config.change.password.url" ) ); }</code><technical_language>I do understand need pu tconfiguration</technical_language>

Target:
private void doAuthenticate(ExtMap input, ExtMap output) { output.mput( (ExtMap) broker.runAdAction( AdActionType.AuthenticateUser, new LdapUserPasswordBaseParameters( configuration, input.<String> get(Authn.InvokeKeys.USER), input.<String> get(Authn.InvokeKeys.CREDENTIALS) ) ).getReturnValue()); output.mput( Authn.InvokeKeys.USER_MESSAGE, configuration.getProperty("config.change.password.msg") ).mput( Authn.InvokeKeys.CREDENTIALS_CHANGE_URL, configuration.getProperty("config.change.password.url" ) ); }
Source:
<code>public void matchEmpiAndUpdateLinks(ResourceModifiedMessage theMsg) { String resourceType = theMsg.getId(myFhirContext).getResourceType(); validateResourceType(resourceType); EmpiTransactionContext empiContext = createEmpiContext(theMsg); try { switch (theMsg.getOperationType()) { case CREATE: handleCreatePatientOrPractitioner(theMsg, empiContext); break; case UPDATE: case MANUALLY_TRIGGERED: handleUpdatePatientOrPractitioner(theMsg, empiContext); break; case DELETE: default: ourLog.trace("Not processing modified message for {}", theMsg.getOperationType()); } }catch (Exception e) { log(empiContext, "Failure during EMPI processing: " + e.getMessage()); } finally { HookParams params = new HookParams() <START> .add(BaseResourceModifiedMessage.class, (BaseResourceModifiedMessage) theMsg) <END> .add(TransactionLogMessages.class, empiContext.getTransactionLogMessages()); myInterceptorBroadcaster.callHooks(Pointcut.EMPI_AFTER_PERSISTED_RESOURCE_CHECKED, params); } }</code><technical_language>is upcast necessary? strange..</technical_language>

Target:
public void matchEmpiAndUpdateLinks(ResourceModifiedMessage theMsg) { String resourceType = theMsg.getId(myFhirContext).getResourceType(); validateResourceType(resourceType); EmpiTransactionContext empiContext = createEmpiContext(theMsg); try { switch (theMsg.getOperationType()) { case CREATE: handleCreatePatientOrPractitioner(theMsg, empiContext); break; case UPDATE: case MANUALLY_TRIGGERED: handleUpdatePatientOrPractitioner(theMsg, empiContext); break; case DELETE: default: ourLog.trace("Not processing modified message for {}", theMsg.getOperationType()); } }catch (Exception e) { log(empiContext, "Failure during EMPI processing: " + e.getMessage()); } finally { ResourceOperationMessage outgoingMsg = new ResourceOperationMessage(myFhirContext, theMsg.getPayload(myFhirContext), theMsg.getOperationType()); outgoingMsg.setTransactionId(theMsg.getTransactionId()); HookParams params = new HookParams() .add(ResourceOperationMessage.class, outgoingMsg) .add(TransactionLogMessages.class, empiContext.getTransactionLogMessages()); myInterceptorBroadcaster.callHooks(Pointcut.EMPI_AFTER_PERSISTED_RESOURCE_CHECKED, params); } }
Source:
<code>private List<Network> findNetworksOnInterface(VdsNetworkInterface iface) { String nameWithoutVlanId = NetworkUtils.StripVlan(iface.getName()); List<Network> networks = new ArrayList<Network>(); for (VdsNetworkInterface tmp : params.getInterfaces()) { if (NetworkUtils.StripVlan(tmp.getName()).equals(nameWithoutVlanId) && tmp.getNetworkName() != null) { <START> if (existingClusterNetworks.containsKey(tmp.getNetworkName())) { <END> networks.add(existingClusterNetworks.get(tmp.getNetworkName())); } } } return networks; }</code><technical_language>call getExistingClusterNetworks()</technical_language>

Target:
private List<Network> findNetworksOnInterface(VdsNetworkInterface iface) { String nameWithoutVlanId = NetworkUtils.StripVlan(iface.getName()); List<Network> networks = new ArrayList<Network>(); for (VdsNetworkInterface tmp : params.getInterfaces()) { if (NetworkUtils.StripVlan(tmp.getName()).equals(nameWithoutVlanId) && tmp.getNetworkName() != null) { if (getExistingClusterNetworks().containsKey(tmp.getNetworkName())) { networks.add(getExistingClusterNetworks().get(tmp.getNetworkName())); } } } return networks; }
Source:
<code>public void nickname() { SyncCredentials creds = SyncCredentials.nickname("foo", false); assertEquals(SyncCredentials.IdentityProvider.NICKNAME, creds.getIdentityProvider()); assertFalse(creds.getUserInfo().isEmpty()); <START> } <END></code><technical_language>assert anisAdmin entry is false</technical_language>

Target:
public void nickname() { SyncCredentials creds = SyncCredentials.nickname("foo", false); assertEquals(SyncCredentials.IdentityProvider.NICKNAME, creds.getIdentityProvider()); assertFalse(creds.getUserInfo().isEmpty()); assertFalse((Boolean) creds.getUserInfo().get("is_admin")); }
Source:
<code>public int runCmd(CommandLine cmdLine) throws Exception { final long lid = getOptionLedgerIdValue(cmdLine, "ledgerid", -1); if (lid == -1) { System.err.println("Must specify a ledger id"); return -1; } LedgerManagerFactory mFactory = null; LedgerManager m = null; try { mFactory = LedgerManagerFactory.newLedgerManagerFactory( bkConf, <START> new ZkLayoutManager( <END> ZooKeeperClient.newBuilder() .connectString(bkConf.getZkServers()) .sessionTimeoutMs(bkConf.getZkTimeout()) .build(), bkConf.getZkLedgersRootPath(), ZkUtils.getACLs(bkConf))); m = mFactory.newLedgerManager(); ReadMetadataCallback cb = new ReadMetadataCallback(lid); m.readLedgerMetadata(lid, cb); printLedgerMetadata(cb); } finally { if (m != null) { try { m.close(); mFactory.uninitialize(); } catch (IOException ioe) { LOG.error("Failed to close ledger manager : ", ioe); } } } return 0; }</code><technical_language>try avoid ZkLayoutManager</technical_language>

Target:
public int runCmd(CommandLine cmdLine) throws Exception { final long lid = getOptionLedgerIdValue(cmdLine, "ledgerid", -1); if (lid == -1) { System.err.println("Must specify a ledger id"); return -1; } try (RegistrationManager rm = RegistrationManager.instantiateRegistrationManager(bkConf)) { try (LedgerManagerFactory mFactory = LedgerManagerFactory.newLedgerManagerFactory(bkConf, rm.getLayoutManager())){ try (LedgerManager m = mFactory.newLedgerManager()) { ReadMetadataCallback cb = new ReadMetadataCallback(lid); m.readLedgerMetadata(lid, cb); printLedgerMetadata(cb); } } } return 0; }
Source:
<code>private static void readTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) { assumeTrue(testTrace.exists()); Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName); perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); if (inGlobalSummary) { perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); } for (int loops = 0; loops < LOOP_COUNT; loops++) { pm.start(); try (CTFTrace trace = testTrace.getTrace(); CTFTraceReader traceReader = new CTFTraceReader(trace);) { while (traceReader.hasMoreEvents()) { EventDefinition ed = traceReader.getCurrentEventDef(); ed.getCPU(); traceReader.advance(); } } catch (CTFReaderException e) { <START> fail(); <END> } finally { pm.stop(); } } pm.commit(); }</code><technical_language>add a verbose message fail, loops number error happened (may reason if run X)</technical_language>

Target:
private static void readTrace(CtfTestTrace testTrace, String testName, boolean inGlobalSummary) { assumeTrue(testTrace.exists()); Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + '#' + testName); perf.tagAsSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); if (inGlobalSummary) { perf.tagAsGlobalSummary(pm, TEST_SUITE_NAME + ':' + testName, Dimension.CPU_TIME); } for (int loop = 0; loop < LOOP_COUNT; loop++) { pm.start(); try (CTFTrace trace = testTrace.getTrace(); CTFTraceReader traceReader = new CTFTraceReader(trace);) { while (traceReader.hasMoreEvents()) { EventDefinition ed = traceReader.getCurrentEventDef(); ed.getCPU(); traceReader.advance(); } } catch (CTFReaderException e) { fail("Test failed at iteration " + loop + ':' + e.getMessage()); } pm.stop(); } pm.commit(); }
Source:
<code><START> void baiIndexInitializationCheck() { <END> if (byteOffsetFromContainer == UNINITIALIZED_INDEXING_PARAMETER) { throw new CRAMException("Cannot index this Slice for BAI because its byteOffsetFromContainer is unknown."); } if (containerByteOffset == UNINITIALIZED_INDEXING_PARAMETER) { throw new CRAMException("Cannot index this Slice for BAI because its containerByteOffset is unknown."); } if (index == UNINITIALIZED_INDEXING_PARAMETER) { throw new CRAMException("Cannot index this Slice for BAI because its index is unknown."); } }</code><technical_language>This a good check, called test (craiIndexInitializationCheck *is* called indexing)</technical_language>

Target:
public void baiIndexInitializationCheck() { final StringBuilder error = new StringBuilder(); if (byteOffsetFromContainer == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for BAI because its byteOffsetFromContainer is unknown.").append(System.lineSeparator()); } if (containerByteOffset == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for BAI because its containerByteOffset is unknown.").append(System.lineSeparator()); } if (index == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for BAI because its index is unknown.").append(System.lineSeparator()); } if (error.length() > 0) { throw new CRAMException(error.toString()); } }
Source:
<code>public void shouldReturnTheCorrectLengthOfAnNonEmptyList() { final List<Integer> list = Collections.unmodifiableList( <START> IntStream.range(0, 4) <END> .boxed() .collect(Collectors.toList()) ); final int actual = ListOps.length(list); final int expected = list.size(); assertEquals(expected, actual); }</code><technical_language>Arrays.asList(...) for short lists</technical_language>

Target:
public void shouldReturnTheCorrectLengthOfAnNonEmptyList() { final List<Integer> list = Collections.unmodifiableList( Arrays.asList(0, 1, 2, 3, 4) ); final int actual = ListOps.length(list); final int expected = list.size(); assertEquals(expected, actual); }
Source:
<code>public void createTxTest() throws Exception { FedoraTransaction tx = repository.startTransaction(); FolderObject obj = repository.createFolderObject(pid, model); assertTrue(FedoraTransaction.hasTxId()); assertTrue(obj.getTypes().contains(Cdr.Folder.getURI())); assertTrue(obj.getTypes().contains(PcdmModels.Object.getURI())); assertEquals("Folder Title", obj.getResource() .getProperty(DcElements.title).getString()); tx.close(); assertFalse(FedoraTransaction.hasTxId()); <START> assertNull(tx.getTxUri()); <END> }</code><technical_language>good add final assertion folder created exists a non-transactional uri tx closes, a non-tx client get a 200 response obj uri</technical_language>

Target:
public void createTxTest() throws Exception { FedoraTransaction tx = repository.startTransaction(); FolderObject obj = null; try { obj = repository.createFolderObject(pid, model); assertTrue(FedoraTransaction.hasTxId()); assertTrue(obj.getTypes().contains(Cdr.Folder.getURI())); assertTrue(obj.getTypes().contains(PcdmModels.Object.getURI())); assertEquals("Folder Title", obj.getResource() .getProperty(DcElements.title).getString()); } finally { tx.close(); } assertFalse(FedoraTransaction.hasTxId()); assertNull(tx.getTxUri()); verifyNonTxStatusCode(obj.getPid(), 200); }
Source:
<code>protected Object adaptToViewItem(IServer server) { ControllableServerBehavior beh = (ControllableServerBehavior)server.loadAdapter(ControllableServerBehavior.class, new NullProgressMonitor()); ServiceManagerEnvironment adb = null; if( beh != null ) { adb = (ServiceManagerEnvironment)beh.getSharedData(ServiceManagerEnvironment.SHARED_INFO_KEY); } if( adb != null ) { OpenshiftUIModel model = new OpenshiftUIModel(); <START> return model.getConnectionWrapperForConnection(new CDKOpenshiftUtility().findExistingOpenshiftConnection(server, adb)); <END> } return null; }</code><technical_language>I problem pointing unnoticed :( singletons more robust option manual disposal I singletons problems</technical_language>

Target:
protected Object adaptToViewItem(IServer server) { ControllableServerBehavior beh = (ControllableServerBehavior)server.loadAdapter(ControllableServerBehavior.class, new NullProgressMonitor()); ServiceManagerEnvironment adb = null; if( beh != null ) { adb = (ServiceManagerEnvironment)beh.getSharedData(ServiceManagerEnvironment.SHARED_INFO_KEY); } if( adb != null ) { return OpenshiftUIModel.getInstance().getConnectionWrapperForConnection( new CDKOpenshiftUtility().findExistingOpenshiftConnection(server, adb)); } return null; }