auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void onInit() throws Exception { super.onInit(); if (this.expectMessage) { Assert.notNull(this.serializer, "'serializer' has to be provided where 'expectMessage == true'."); } if (this.taskExecutor == null) { String beanName = this.getComponentName(); this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType()); } if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) { MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory())); <START> errorHandler.setDefaultErrorChannel(this.errorChannel); <END> this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler); } }</code><technical_language>MessagePublishingErrorHandler fixed get deal errorChannelName well, is a separate JIRA</technical_language>

Target:
protected void onInit() throws Exception { super.onInit(); if (!this.extractPayload) { Assert.notNull(this.serializer, "'serializer' has to be provided where 'extractPayload == false'."); } if (this.taskExecutor == null) { String beanName = this.getComponentName(); this.taskExecutor = new SimpleAsyncTaskExecutor((beanName == null ? "" : beanName + "-") + this.getComponentType()); } if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor) && this.getBeanFactory() != null) { MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler(new BeanFactoryChannelResolver(this.getBeanFactory())); errorHandler.setDefaultErrorChannel(this.errorChannel); this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, errorHandler); } }
Source:
<code>private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); try { if(file.equals(mFile)) { processStopRequest(true); } } <START> catch (NullPointerException e) { <END> Log_OC.e(TAG, "NullPointerException while stopping on OCFile ", e); } }</code><technical_language>In general, NullPointerExceptions cached - input of block tested prevent occurs</technical_language>

Target:
private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); if(file != null && file.equals(mFile)) { processStopRequest(true); } }
Source:
<code>private static CustomJCommander parseArguments(CommandRepository commandRepository, RemoteMainCommand mainCommand, String[] args) { <START> CustomJCommander jCommander = new CustomJCommander(CONFIG_TOOL, commandRepository, mainCommand); <END> try { jCommander.parse(args); } catch (ParameterException e) { jCommander.printUsage(); throw e; } return jCommander; }</code><technical_language>remove. specific command behaviours handled in command, a common place commands</technical_language>

Target:
private static CustomJCommander parseArguments(CommandRepository commandRepository, RemoteMainCommand mainCommand, String[] args) { CustomJCommander jCommander = new CustomJCommander("config-tool", commandRepository, mainCommand) { @Override public void appendDefinitions(StringBuilder out, String indent) { out.append(indent).append(lineSeparator()).append("Definitions:").append(lineSeparator()); out.append(indent).append(" ").append("namespace").append(lineSeparator()); Map<String, String> nameSpaces = new LinkedHashMap<>(); nameSpaces.put("stripe.<stripeId>.node.<nodeId>", "to apply a change only on a specific node"); nameSpaces.put("stripe.<stripeId>", "to apply a change only on a specific stripe"); nameSpaces.put("'' (empty namespace)", "to apply a change only on all nodes of the cluster"); int maxNamespaceLength = Integer.MIN_VALUE; for (String nameSpace : nameSpaces.keySet()) { if (nameSpace.length() > maxNamespaceLength) { maxNamespaceLength = nameSpace.length(); } } for (Map.Entry<String, String> entry : nameSpaces.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); out.append(indent).append(" ").append(key); for (int i = 0; i < maxNamespaceLength - key.length() + 4; i++) { out.append(" "); } out.append(value).append(lineSeparator()); } } }; try { jCommander.parse(args); } catch (ParameterException e) { jCommander.printUsage(); throw e; } return jCommander; }
Source:
<code>public void invalidLowMTU() { Set<ConstraintViolation<MtuContainer>> validate = validate(new MtuContainer(30)); <START> Assert.assertFalse(validate.isEmpty()); <END> }</code><technical_language>modify static import</technical_language>

Target:
public void invalidLowMTU() { Set<ConstraintViolation<MtuContainer>> validate = validate(new MtuContainer(30)); assertFalse(validate.isEmpty()); }
Source:
<code><START> public void expireOnOneServer_shouldResultInKeyRemovalFromOtherServer() { <END> String key = "key"; jedis1.set(key, "value"); jedis1.expire(key, 2); assertThat(jedis2.ttl(key)).isGreaterThan(0); GeodeAwaitility.await().until(() -> jedis2.ttl(key) == TTLExecutor.NOT_EXISTS); }</code><technical_language>this is for extra. combine them, mutually exclusive asserts</technical_language>

Target:
public void expireOnOneServer_shouldResultInKeyRemovalFromOtherServer() { String key = "key"; jedis1.set(key, "value"); jedis1.expire(key, 2); GeodeAwaitility.await().until(() -> jedis2.ttl(key) == TTLExecutor.NOT_EXISTS); }
Source:
<code>private static Set<List<JavaFileScannerContext.Location>> flowsForMethodArguments(ExplodedGraph.Node node, MethodInvocationTree mit, int parameterCausingExceptionIndex) { ProgramState programState = node.programState; List<ProgramState.SymbolicValueSymbol> arguments = Lists.reverse(programState.peekValuesAndSymbols(mit.arguments().size())); SymbolicValue parameterCausingExceptionSV = arguments.get(parameterCausingExceptionIndex).symbolicValue(); Set<SymbolicValue> argSymbolicValues = new LinkedHashSet<>(); Set<Symbol> argSymbols = new LinkedHashSet<>(); for (ProgramState.SymbolicValueSymbol svs : arguments) { Symbol symbol = svs.symbol(); SymbolicValue sv = svs.symbolicValue(); <START> if (parameterCausingExceptionSV == sv) { <END> argSymbolicValues.add(sv); } else { PMap<Class<? extends Constraint>, Constraint> constraints = programState.getConstraints(sv); if (constraints == null || (domainsFromConstraints(constraints).size() == 1 && constraints.get(ObjectConstraint.class) == ObjectConstraint.NOT_NULL)) { continue; } argSymbolicValues.add(sv); } if (symbol != null) { argSymbols.add(symbol); } } List<Class<? extends Constraint>> domains = domainsFromArguments(programState, argSymbolicValues); return FlowComputation.flow(node, argSymbolicValues, c -> true, c -> false, domains, argSymbols); }</code><technical_language>I this test easier understand if extract logic a method a good name hasOnlyNonNullConstraint this condition parameterCausingExceptionSV==sv || !hasOnlyNonNullConstraint(sv) , need else branch continue</technical_language>

Target:
private static Set<List<JavaFileScannerContext.Location>> flowsForMethodArguments(ExplodedGraph.Node node, MethodInvocationTree mit, int parameterCausingExceptionIndex) { ProgramState programState = node.programState; List<ProgramState.SymbolicValueSymbol> arguments = Lists.reverse(programState.peekValuesAndSymbols(mit.arguments().size())); SymbolicValue parameterCausingExceptionSV = arguments.get(parameterCausingExceptionIndex).symbolicValue(); Set<SymbolicValue> argSymbolicValues = new LinkedHashSet<>(); Set<Symbol> argSymbols = new LinkedHashSet<>(); arguments.stream() .filter(svs -> parameterCausingExceptionSV == svs.symbolicValue() || hasConstraintOtherThanNonNull(svs, programState)) .forEach(svs -> { argSymbolicValues.add(svs.symbolicValue()); Symbol symbol = svs.symbol(); if (symbol != null) { argSymbols.add(symbol); } }); List<Class<? extends Constraint>> domains = domainsFromArguments(programState, argSymbolicValues); return FlowComputation.flow(node, argSymbolicValues, c -> true, c -> false, domains, argSymbols); }
Source:
<code>public int getAudioStreamType() { if <START> (!mProto.hasAudioTrackIndex() && <END> mProto.getAudioTrackIndex() == -1) { return INVALID_STREAMTYPE; } return mProto.getAudioStreamTypes(mProto.getAudioTrackIndex()).getNumber(); }</code><technical_language>I this is right fix. If show "hasAudioTrackIndex" is incorrect. I need file bug nanoproto read is this if true. I suspect a this is letting unset audioTrackIndex return default of 0. "hasAudioTrackIndex" is wrong</technical_language>

Target:
public int getAudioStreamType() { if (mProto.getAudioTrackIndex() == -1) { return INVALID_STREAMTYPE; } return mProto.getAudioStreamTypes(mProto.getAudioTrackIndex()).getNumber(); }
Source:
<code>public String getWelcomeSections(final Locale locale) { Map<String, String> messageMap = getMessageMap(WELCOME, locale); List<BrandingTheme> brandingThemes = getBrandingThemes(); StringBuilder templateBuilder = new StringBuilder(); for (BrandingTheme theme: brandingThemes) { String template = theme.getWelcomePageSectionTemplate(); String replacedTemplate = template; Matcher keyMatcher = TEMPLATE_PATTERN.matcher(template); while (keyMatcher.find()) { String key = keyMatcher.group(1); replacedTemplate = replacedTemplate.replaceAll("\\{" + key + "\\}", messageMap.get(key)); } <START> replacedTemplate = replacedTemplate.replaceAll("\\{0\\}", locale.toString()); <END> templateBuilder.append(replacedTemplate); } return templateBuilder.toString(); }</code><technical_language>In README.branding "WELCOME PAGE TEMPLATE" section, mention "{0}" translates current user locale. consider replacing (quite generic) "{0}" more sensible, i.e. "{userLocale}"</technical_language>

Target:
public String getWelcomeSections(final Locale locale) { Map<String, String> messageMap = getMessageMap(WELCOME, locale); List<BrandingTheme> brandingThemes = getBrandingThemes(); StringBuilder templateBuilder = new StringBuilder(); for (BrandingTheme theme: brandingThemes) { String template = theme.getWelcomePageSectionTemplate(); String replacedTemplate = template; Matcher keyMatcher = TEMPLATE_PATTERN.matcher(template); while (keyMatcher.find()) { String key = keyMatcher.group(1); if (!USER_LOCALE_HOLDER.substring(2, USER_LOCALE_HOLDER.length() - 2).equals(key)) { replacedTemplate = replacedTemplate.replaceAll("\\{" + key + "\\}", messageMap.get(key)); } } replacedTemplate = replacedTemplate.replaceAll(USER_LOCALE_HOLDER, locale.toString()); templateBuilder.append(replacedTemplate); } return templateBuilder.toString(); }
Source:
<code>public void forEachMetric(BiConsumer<MetricName, Metric> consumer) { first.getMetrics().forEach(consumer); <START> second.getMetrics().forEach(consumer); <END> }</code><technical_language>prefer first.forEachMetric more performant</technical_language>

Target:
public void forEachMetric(BiConsumer<MetricName, Metric> consumer) { first.forEachMetric(consumer); second.forEachMetric(consumer); }
Source:
<code><START> private static Optional<TimeRangeFilter> extractTimeRangeFilter(Collection<Filter> filters){ <END> return filters.stream() .filter(f -> f instanceof TimeRangeFilter) .map(f -> (TimeRangeFilter)f) .findFirst(); }</code><technical_language>Nit: return a TimeRangeFilter (which is null) missing instead of do .orElse(null)</technical_language>

Target:
private static TimeRangeFilter extractTimeRangeFilter(Collection<Filter> filters){ return filters.stream() .filter(f -> f instanceof TimeRangeFilter) .map(f -> (TimeRangeFilter)f) .findFirst().orElse(null); }
Source:
<code>public static String asValidHref(String urlString) { try { <START> return new URL(urlString).toExternalForm(); <END> } catch (MalformedURLException e) { return ""; } }</code><technical_language>relative links? Protocol-relative URLs? Tests cover those</technical_language>

Target:
public static String asValidHref(String urlString) { try { return new URL(urlString).toExternalForm(); } catch (MalformedURLException e) { LOG.debug("Malformed url - {}, empty string will be returned", urlString); return ""; } }
Source:
<code>public void deleteProcessorNode(String processorId) { for (ProcessorNode processorNode : getAllProcessorNodes()) { <START> if (processorNode.getProcessorData().getProcessorId().equals(processorId)) { <END> LOG.info("Deleting the ephemeral node: of the processor: in zookeeper.", processorNode.getEphemeralPath(), processorId); zkClient.delete(processorNode.getEphemeralPath()); } } }</code><technical_language>do u need guard NPE's here</technical_language>

Target:
public synchronized void deleteProcessorNode(String processorId) { try { if (ephemeralPath != null) { LOG.info("Deleting the ephemeral node: of the processor: in zookeeper.", ephemeralPath, processorId); zkClient.delete(ephemeralPath); } } catch (Exception e) { LOG.error("Exception occurred on deletion of ephemeral node: {}.", ephemeralPath, e); } }
Source:
<code>private UsngCoordinate parseMgrsString(String mgrs) { try { return translator.parseMgrsString(mgrs); } catch (ParseException e) { <START> LOGGER.debug("Detected string was not actually valid MGRS", e); <END> return null; } }</code><technical_language>nit: "Detected string ~~actually~~ valid MGRS"</technical_language>

Target:
private UsngCoordinate parseMgrsString(String mgrs) { try { return translator.parseMgrsString(mgrs); } catch (ParseException e) { LOGGER.debug("Detected string was not valid MGRS", mgrs, e); return null; } }
Source:
<code>public CorfuTable(Index.Registry<K, V> indices, Supplier<ContextAwareMap<K, V>> streamingMapSupplier, VersionPolicy versionPolicy) { this.indexSpec = new HashSet<>(); this.secondaryIndexes = new HashMap<>(); this.mainMap = streamingMapSupplier.get(); this.versionPolicy = versionPolicy; this.optimisticTable = new CorfuTable<>(this.mainMap.getOptimisticMap(), this.indexSpec, this.secondaryIndexes, null); indices.forEach(index -> { secondaryIndexes.put(index.getName().get(), new HashMap<>()); indexSpec.add(index); }); <START> if (secondaryIndexes.keySet().size() > 0) { <END> log.info( "CorfuTable: creating CorfuTable with the following indexes: {}", secondaryIndexes.keySet() ); } }</code><technical_language>!secondaryIndexes.isEmpty()</technical_language>

Target:
public CorfuTable(Index.Registry<K, V> indices, Supplier<ContextAwareMap<K, V>> streamingMapSupplier, VersionPolicy versionPolicy) { this.indexSpec = new HashSet<>(); this.secondaryIndexes = new HashMap<>(); this.mainMap = streamingMapSupplier.get(); this.versionPolicy = versionPolicy; this.optimisticTable = new CorfuTable<>(this.mainMap.getOptimisticMap(), this.indexSpec, this.secondaryIndexes, null); indices.forEach(index -> { secondaryIndexes.put(index.getName().get(), new HashMap<>()); indexSpec.add(index); }); if (!secondaryIndexes.isEmpty()) { log.info( "CorfuTable: creating CorfuTable with the following indexes: {}", secondaryIndexes.keySet() ); } }
Source:
<code>private Mono<Void> run(CancellationToken cancellationToken) { return Flux.just(this) .flatMap(value -> this.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = this.partitionLoadBalancingStrategy.selectLeasesToTake(allLeases); this.logger.debug("Found leases, taking {}", allLeases.size(), leasesToTake.size()); if (cancellationToken.isCancellationRequested()) return Mono.empty(); return Flux.fromIterable(leasesToTake) .flatMap(lease -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); return this.partitionController.addOrUpdateLease(lease); }) .then(Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseAcquireInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100)) .repeat( () -> { ZonedDateTime currentTime = ZonedDateTime.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }).last(); }) ); }) .onErrorResume(throwable -> { <START> logger.warn("Unexpected exception thown while trying to acquire available leases", throwable); <END> return Mono.empty(); }) .repeat(() -> { return !cancellationToken.isCancellationRequested(); }) .then() .onErrorResume(throwable -> { logger.info("Partition load balancer task stopped."); return this.stop(); }); }</code><technical_language>minor spelling: thown -> thrown</technical_language>

Target:
private Mono<Void> run(CancellationToken cancellationToken) { return Flux.just(this) .flatMap(value -> this.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = this.partitionLoadBalancingStrategy.selectLeasesToTake(allLeases); this.logger.debug("Found leases, taking {}", allLeases.size(), leasesToTake.size()); if (cancellationToken.isCancellationRequested()) return Mono.empty(); return Flux.fromIterable(leasesToTake) .flatMap(lease -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); return this.partitionController.addOrUpdateLease(lease); }) .then(Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseAcquireInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100)) .repeat( () -> { ZonedDateTime currentTime = ZonedDateTime.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }).last(); }) ); }) .onErrorResume(throwable -> { logger.warn("Unexpected exception thrown while trying to acquire available leases", throwable); return Mono.empty(); }) .repeat(() -> { return !cancellationToken.isCancellationRequested(); }) .then() .onErrorResume(throwable -> { logger.info("Partition load balancer task stopped."); return this.stop(); }); }
Source:
<code>public void reblog(ReaderPost post) { List<SiteModel> sites = mSiteStore.getVisibleSites(); switch (sites.size()) { case 0: ToastUtils.showToast(getActivity(), R.string.reader_no_site_to_reblog); break; case 1: <START> ActivityLauncher.openEditorForReblog(getActivity(), getSelectedSite(), this.mPostToReblog); <END> break; default: this.mPostToReblog = post; ActivityLauncher.showSitePickerForResult(this, getSelectedSite()); break; } }</code><technical_language>I post instead of this.mPostToReblog</technical_language>

Target:
public void reblog(ReaderPost post) { mViewModel.onReblogButtonClicked(post); }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_list_item, parent, false); } convertView.setEnabled(true); TextView tvName = convertView.findViewById(android.R.id.text1); TextView tvFiles = convertView.findViewById(android.R.id.text2); DatumTransformation transformation = getItem(position); <START> tvName.setText(transformation.getName()); <END> StringBuilder sb = new StringBuilder(); if (transformation.isMissingProjectionEngineFiles()) { sb.append("Missing grid files"); if (transformation instanceof GeographicTransformation) { GeographicTransformation gt = (GeographicTransformation)transformation; for (GeographicTransformationStep step : gt.getSteps()) { if (step.isMissingProjectionEngineFiles()) { sb.append(": " ); sb.append(TextUtils.join(", ", step.getProjectionEngineFilenames())); } } } convertView.setEnabled(false); } if ((defaultValue != null) && (defaultValue.equals(transformation) )) { tvName.setTypeface(null, Typeface.BOLD); } else { tvName.setTypeface(null, Typeface.NORMAL); } tvFiles.setText(sb.toString()); return convertView; }</code><technical_language>a bit belts braces, capture for getName returning null setting text "Name found" similar. prevent ListView populating empty rows</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_list_item, parent, false); } convertView.setEnabled(true); TextView tvName = convertView.findViewById(android.R.id.text1); TextView tvFiles = convertView.findViewById(android.R.id.text2); DatumTransformation transformation = getItem(position); tvName.setText(transformation.getName()); StringBuilder sb = new StringBuilder(); if (transformation.isMissingProjectionEngineFiles()) { sb.append(getContext().getResources().getString(R.string.adapter_missing_files)); if (transformation instanceof GeographicTransformation) { GeographicTransformation gt = (GeographicTransformation)transformation; for (GeographicTransformationStep step : gt.getSteps()) { if (step.isMissingProjectionEngineFiles()) { sb.append(": " ); sb.append(TextUtils.join(", ", step.getProjectionEngineFilenames())); } } } convertView.setEnabled(false); } if ((defaultValue != null) && (defaultValue.equals(transformation) )) { tvName.setTypeface(null, Typeface.BOLD); } else { tvName.setTypeface(null, Typeface.NORMAL); } tvFiles.setText(sb.toString()); return convertView; }
Source:
<code>public static void deleteDirIfExists(String hdfsPath, FileSystem fs) throws IOException { Path path = new Path(hdfsPath); if (fs.exists(path)) { <START> System.out.println("Deleting HDFS path: "+ path + " on "+fs.getConf().get("fs.default.name")); <END> fs.delete(path, true); } }</code><technical_language>Logger</technical_language>

Target:
public static void deleteDirIfExists(String hdfsPath, FileSystem fs) throws IOException { Path path = new Path(hdfsPath); if (fs.exists(path)) { logger.info("Deleting HDFS path: "+ path + " on "+fs.getConf().get("fs.default.name")); fs.delete(path, true); } }
Source:
<code>private ITimeGraphState createTimeGraphState(ITmfStateInterval interval, ITmfStateSystem ss) throws StateSystemDisposedException { long startTime = interval.getStartTime(); long endTime = interval.getEndTime(); long duration = endTime - startTime + 1; Object statusObj = interval.getValue(); Type type = fEntryModelTypes.get(interval.getAttribute()); if (statusObj instanceof Integer) { int status = (int) statusObj; if (type == Type.CPU) { if (status == StateValues.CPU_STATUS_RUN_USERMODE || status == StateValues.CPU_STATUS_RUN_SYSCALL) { return fTimeEventNames.getUnchecked(interval); } } else if (type == Type.CURRENT_THREAD) { Object processName = null; synchronized (fExecNamesCache) { if (fExecNamesCache.containsEntry(status, interval)) { processName = fExecNamesCache.get(status).first().getValue(); } else { int quark = ss.optQuarkAbsolute(Attributes.THREADS, Integer.toString(status), Attributes.EXEC_NAME); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE) { ITmfStateInterval namedInterval = ss.querySingleState(endTime, quark); <START> fExecNamesCache.put(status, <END> namedInterval); processName = namedInterval.getValue(); } } } if (processName instanceof String) { return new TimeGraphState(startTime, duration, status, (String) processName); } } return new TimeGraphState(startTime, duration, status); } return new TimeGraphState(startTime, duration, Integer.MIN_VALUE); }</code><technical_language>risk a large map</technical_language>

Target:
private ITimeGraphState createTimeGraphState(ITmfStateInterval interval, ITmfStateSystem ss) throws StateSystemDisposedException { long startTime = interval.getStartTime(); long endTime = interval.getEndTime(); long duration = endTime - startTime + 1; Object statusObj = interval.getValue(); Type type = fEntryModelTypes.get(interval.getAttribute()); if (statusObj instanceof Integer) { int status = (int) statusObj; if (type == Type.CPU) { if (status == StateValues.CPU_STATUS_RUN_USERMODE || status == StateValues.CPU_STATUS_RUN_SYSCALL) { return fTimeEventNames.getUnchecked(interval); } } else if (type == Type.CURRENT_THREAD) { Object processName = null; if (fExecNamesCache.containsEntry(status, interval)) { processName = fExecNamesCache.get(status).first().getValue(); } else { int quark = ss.optQuarkAbsolute(Attributes.THREADS, Integer.toString(status), Attributes.EXEC_NAME); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE) { ITmfStateInterval namedInterval = ss.querySingleState(endTime, quark); fExecNamesCache.put(status, namedInterval); processName = namedInterval.getValue(); } } if (processName instanceof String) { return new TimeGraphState(startTime, duration, status, (String) processName); } } return new TimeGraphState(startTime, duration, status); } return new TimeGraphState(startTime, duration, Integer.MIN_VALUE); }
Source:
<code>private synchronized void onSenderInitialized(final String senderId) { senderRepresenterMap.get(senderId) <START> .checkAndSetState(PushShuffleSenderImpl.State.CREATED, PushShuffleSenderImpl.State.SENDING); <END> LOG.log(Level.FINE, "A sender is initialized " + senderId); initializedSenderNum++; broadcastIfShuffleIsInitialized(); }</code><technical_language>SENDING means sender is sending. in this case, state is READY SEND. If so, rename state</technical_language>

Target:
private synchronized void onSenderInitialized(final String senderId) { if (initialized) { sendSenderCanSendMessage(senderId); } else { initializedSenderIdList.add(senderId); } }
Source:
<code>public void cancel(Cancellable cancellable) { if (cancellable.getCancellationUrl() != null) { String url = cancellable.getCancellationUrl().getUrl(); Response response = postEmptyEntity(url); Status status = Status.fromStatusCode(response.getStatus()); if (status == OK) { return; } else if (status == CONFLICT) { throw new NotCancellableException(); } throw handleGeneralError(response, status); } else { <START> throw new NotCancellableException(); <END> } }</code><technical_language>In cases a Cancellable _not_ a cancellationUrl? (is "cancellable"? ;) ) Is add some more info NotCancellableException in case of status == CONFLICT? stands now, is distinguish if cancel()-method erroneously called for entity cancellationUrl post to, if request server declined cancellation for some reason</technical_language>

Target:
public void cancel(Cancellable cancellable) { if (cancellable.getCancellationUrl() != null) { String url = cancellable.getCancellationUrl().getUrl(); Response response = postEmptyEntity(url); Status status = Status.fromStatusCode(response.getStatus()); if (status == OK) { return; } else if (status == CONFLICT) { throw new JobIsCompletedException(); } throw handleGeneralError(response, status); } else { throw new NotCancellableException(); } }
Source:
<code>public DatabaseChunkedReader(Properties props, DataSource source, String sourceQuery, String table, DatabaseSource databaseSource, String id) throws SQLException, SchemaGenerationException { _databaseChunkedReaderConfig = new DatabaseChunkedReaderConfig(props); _sourceQuery = sourceQuery; _dataSource = source; _databaseSource = databaseSource; _readerId = id; _chunkingTable = table; _fetchSize = _databaseChunkedReaderConfig.getFetchSize(); _queryTimeoutSecs = _databaseChunkedReaderConfig.getQueryTimeout(); _maxChunkIndex = _databaseChunkedReaderConfig.getNumChunkBuckets() - 1; _chunkSize = _databaseChunkedReaderConfig.getChunkSize(); _chunkIndex = _databaseChunkedReaderConfig.getChunkIndex(); _connection = source.getConnection(); _hashFunction = _databaseChunkedReaderConfig.getHashFunction(); _concatFunction = _databaseChunkedReaderConfig.getConcatFunction(); _interpreter = _databaseChunkedReaderConfig.getDatabaseInterpreter(); <START> getChunkingKeyInfo(); <END> validateQuery(sourceQuery); }</code><technical_language>I pattern of constructor() : get config parameters start() : do some IO initialize object start processing next() : calling multiple times get data close() : release resources. I suggest move call "getChunkingKeyInfo()" start, some IO</technical_language>

Target:
public DatabaseChunkedReader(Properties props, DataSource source, String sourceQuery, String table, DatabaseSource databaseSource, String id) throws SQLException { _databaseChunkedReaderConfig = new DatabaseChunkedReaderConfig(props); _sourceQuery = sourceQuery; _dataSource = source; _databaseSource = databaseSource; _readerId = id; _chunkingTable = table; _fetchSize = _databaseChunkedReaderConfig.getFetchSize(); _queryTimeoutSecs = _databaseChunkedReaderConfig.getQueryTimeout(); _maxChunkIndex = _databaseChunkedReaderConfig.getNumChunkBuckets() - 1; _chunkSize = _databaseChunkedReaderConfig.getChunkSize(); _chunkIndex = _databaseChunkedReaderConfig.getChunkIndex(); _connection = source.getConnection(); _interpreter = _databaseChunkedReaderConfig.getDatabaseInterpreter(); _chunkedQueryManager = _databaseChunkedReaderConfig.getChunkedQueryManager(); validateQuery(sourceQuery); }
Source:
<code>public void shouldEditConceptAttributeOfConcept() throws Exception { executeDataSet(RestTestConstants2_0.CONCEPT_ATTRIBUTE_DATA_SET); String json = "{ \"uuid\":\"" + RestTestConstants2_0.CONCEPT_UUID + "\"," + "\"attributes\":[{\"uuid\":\"" + RestTestConstants2_0.CONCEPT_ATTRIBUTE_UUID + "\"," + "\"attributeType\":\"" + RestTestConstants2_0.CONCEPT_ATTRIBUTE_TYPE_UUID + "\",\"value\":\"2001-01-01\"}]}"; Concept concept = Context.getConceptService().getConceptByUuid(RestTestConstants2_0.CONCEPT_UUID); int before = concept.getAttributes().size(); <START> Assert.assertEquals(before, concept.getAttributes().size()); <END> ConceptAttribute conceptAttributeBeforeEdit = Context.getConceptService().getConceptAttributeByUuid(RestTestConstants2_0.CONCEPT_ATTRIBUTE_UUID); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Assert.assertEquals("2011-04-25", simpleDateFormat.format(conceptAttributeBeforeEdit.getValue())); handle(newPostRequest(getURI() + "/" + getUuid(), json)); Assert.assertEquals(before, concept.getAttributes().size()); ConceptAttribute actualConceptAttribute = Context.getConceptService().getConceptAttributeByUuid(RestTestConstants2_0.CONCEPT_ATTRIBUTE_UUID); Assert.assertEquals("2001-01-01", simpleDateFormat.format(actualConceptAttribute.getValue())); }</code><technical_language>assertion add? :)</technical_language>

Target:
public void shouldEditConceptAttributeOfConcept() throws Exception { executeDataSet(RestTestConstants2_0.CONCEPT_ATTRIBUTE_DATA_SET); String json = "{ \"uuid\":\"" + RestTestConstants2_0.CONCEPT_UUID + "\"," + "\"attributes\":[{\"uuid\":\"" + RestTestConstants2_0.CONCEPT_ATTRIBUTE_UUID + "\"," + "\"attributeType\":\"" + RestTestConstants2_0.CONCEPT_ATTRIBUTE_TYPE_UUID + "\",\"value\":\"2001-01-01\"}]}"; Concept concept = Context.getConceptService().getConceptByUuid(RestTestConstants2_0.CONCEPT_UUID); int before = concept.getAttributes().size(); ConceptAttribute conceptAttributeBeforeEdit = Context.getConceptService().getConceptAttributeByUuid(RestTestConstants2_0.CONCEPT_ATTRIBUTE_UUID); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Assert.assertEquals("2011-04-25", simpleDateFormat.format(conceptAttributeBeforeEdit.getValue())); handle(newPostRequest(getURI() + "/" + getUuid(), json)); Assert.assertEquals(before, concept.getAttributes().size()); ConceptAttribute actualConceptAttribute = Context.getConceptService().getConceptAttributeByUuid(RestTestConstants2_0.CONCEPT_ATTRIBUTE_UUID); Assert.assertEquals("2001-01-01", simpleDateFormat.format(actualConceptAttribute.getValue())); }
Source:
<code>public void refreshCache() { this.blacklistedPartitions = SystemDistributedKeyspace.getBlacklistedPartitions(); if (DatabaseDescriptor.getBlackListedPartitionsCacheSizeWarnThresholdInMB() > 0) { long cacheSize = 0; for (BlacklistedPartition blacklistedPartition : blacklistedPartitions) { cacheSize += blacklistedPartition.unsharedHeapSize(); } if (cacheSize / (1024 * 1024) >= DatabaseDescriptor.getBlackListedPartitionsCacheSizeWarnThresholdInMB()) { <START> logger.warn(String.format("BlacklistedPartition cache size (%d) MB exceeds threshold size (%d) MB", cacheSize / (1024 * 1024), DatabaseDescriptor.getBlackListedPartitionsCacheSizeWarnThresholdInMB())); <END> } } }</code><technical_language>avoid String.format logger formatting specifiers</technical_language>

Target:
public void refreshCache() { UntypedResultSet results = SystemDistributedKeyspace.getBlacklistedPartitions(); Set<BlacklistedPartition> partitions = new HashSet<>(); if (results != null) { int cacheSizeBytes = 0; for (UntypedResultSet.Row row : results) { try { BlacklistedPartition blacklistedPartition = new BlacklistedPartition(row.getString("keyspace_name"), row.getString("columnfamily_name"), row.getString("partition_key")); cacheSizeBytes += blacklistedPartition.unsharedHeapSize(); if (cacheSizeBytes / (1024 * 1024) > DatabaseDescriptor.getBlackListedPartitionsCacheSizeLimitInMB()) { logger.warn("BlacklistedPartitions cache size limit of MB reached. Unable to load more blacklisted partitions. BlacklistedPartitions cache working in degraded mode.", DatabaseDescriptor.getBlackListedPartitionsCacheSizeLimitInMB()); break; } partitions.add(blacklistedPartition); } catch (IllegalArgumentException ex) { logger.warn("Exception parsing blacklisted partition. {}", ex.getMessage()); } } } this.blacklistedPartitions = partitions; }
Source:
<code>public void open(TableInputSplit split) throws IOException { initTable(); if (table == null) { throw new IOException("The HBase table has not been opened! " + <START> "This needs to be done in configure()."); <END> } if (scan == null) { throw new IOException("Scan has not been initialized! " + "This needs to be done in configure()."); } if (split == null) { throw new IOException("Input split is null!"); } logSplitInfo("opening", split); currentRow = split.getStartRow(); scan.setStartRow(currentRow); scan.setStopRow(split.getEndRow()); resultScanner = table.getScanner(scan); endReached = false; scannedRows = 0; }</code><technical_language>I this (and below) exception messages correct anymore</technical_language>

Target:
public void open(TableInputSplit split) throws IOException { initTable(); if (split == null) { throw new IOException("Input split is null!"); } logSplitInfo("opening", split); currentRow = split.getStartRow(); scan.setStartRow(currentRow); scan.setStopRow(split.getEndRow()); resultScanner = table.getScanner(scan); endReached = false; scannedRows = 0; }
Source:
<code>protected void updateServer(boolean limit) { if (optOut || offline) { return; } if (!uploadingCurrently.getAndSet(true)) { long totalEventCount = dbHelper.getTotalEventCount(); long batchSize = Math.min( limit ? backoffUploadBatchSize : eventUploadMaxBatchSize, totalEventCount ); if (batchSize <= 0) { uploadingCurrently.set(false); return; } try { List<JSONObject> events = dbHelper.getEvents(lastEventId, batchSize); List<JSONObject> identifys = dbHelper.getIdentifys(lastIdentifyId, batchSize); final Pair<Pair<Long, Long>, JSONArray> merged = mergeEventsAndIdentifys( events, identifys, batchSize); final JSONArray mergedEvents = merged.second; if (mergedEvents.length() == 0) { uploadingCurrently.set(false); return; } final long maxEventId = merged.first.first; final long maxIdentifyId = merged.first.second; final String mergedEventsString = merged.second.toString(); httpThread.post(new Runnable() { @Override public void run() { makeEventUploadPostRequest(httpClient, mergedEventsString, maxEventId, maxIdentifyId); } }); } catch (JSONException e) { uploadingCurrently.set(false); logger.e(TAG, e.toString()); } catch (RuntimeException e) { String message = e.getMessage(); <START> if (!TextUtils.isEmpty(message) && message.startsWith("Cursor window")) { <END> uploadingCurrently.set(false); logger.e(TAG, String.format( "Caught Cursor window exception during event upload, deferring upload: %s", message )); } else { throw e; } } } }</code><technical_language>this logic factored a method</technical_language>

Target:
protected void updateServer(boolean limit) { if (optOut || offline) { return; } if (!uploadingCurrently.getAndSet(true)) { long totalEventCount = dbHelper.getTotalEventCount(); long batchSize = Math.min( limit ? backoffUploadBatchSize : eventUploadMaxBatchSize, totalEventCount ); if (batchSize <= 0) { uploadingCurrently.set(false); return; } try { List<JSONObject> events = dbHelper.getEvents(lastEventId, batchSize); List<JSONObject> identifys = dbHelper.getIdentifys(lastIdentifyId, batchSize); final Pair<Pair<Long, Long>, JSONArray> merged = mergeEventsAndIdentifys( events, identifys, batchSize); final JSONArray mergedEvents = merged.second; if (mergedEvents.length() == 0) { uploadingCurrently.set(false); return; } final long maxEventId = merged.first.first; final long maxIdentifyId = merged.first.second; final String mergedEventsString = merged.second.toString(); httpThread.post(new Runnable() { @Override public void run() { makeEventUploadPostRequest(httpClient, mergedEventsString, maxEventId, maxIdentifyId); } }); } catch (JSONException e) { uploadingCurrently.set(false); logger.e(TAG, e.toString()); } catch (CursorWindowAllocationException e) { uploadingCurrently.set(false); logger.e(TAG, String.format( "Caught Cursor window exception during event upload, deferring upload: %s", e.getMessage() )); } } }
Source:
<code>public void configure(JobConf job) { setConf(job); this.scfilters = new ScoringFilters(job); skipTruncated = job.getBoolean(SKIP_TRUNCATED, true); filterflag = job.getBoolean(PARSER_MODELFILTER, true); if (filterflag) { String[] args = new String[2]; args[0] = getConf().get(TRAINFILE_MODELFILTER); args[1] = getConf().get(DICTFILE_MODELFILTER); if (args[0] == null || args[0].trim().length() == 0 || args[1] == null || args[1].trim().length() == 0) { String message = "Model URLFilter: trainfile or wordlist not set in the urlfilter.model.trainfile or urlfilter.model.wordlist"; if (LOG.isErrorEnabled()) { filterflag = false; LOG.error(message); } throw new IllegalArgumentException(message); } else { try { filters = new URLFilters(job); <START> filter = (ModelURLFilterAbstract) filters <END> .getFilter("org.apache.nutch.urlfilter.model.ModelURLFilter"); filter.configure(args); } catch (Exception e) { LOG.warn("There was some problem while getting the model filter or training it. Not using the filter"); filterflag = false; } } } }</code><technical_language>This ties a specific filter, ModelURLFilter, in core Nutch classes. URL filter simply insulated plugin - this touch Nutch core</technical_language>

Target:
public void configure(JobConf job) { setConf(job); this.scfilters = new ScoringFilters(job); skipTruncated = job.getBoolean(SKIP_TRUNCATED, true); }
Source:
<code>private String buildWhereClause(Query query) { <START> String whereClause = Column.has_phone_number + " !=0 AND (" + Column.mimetype + " = ? OR " + Column.mimetype <END> + " = ? ) "; if (query != null) { return (whereClause + " AND " + query.getWhereClause()); } return whereClause; }</code><technical_language>want a StringBuilder Original declared a static final constant</technical_language>

Target:
private String buildWhereClause(Query query) { StringBuilder stringBuilder = new StringBuilder(staticWhereClause); if (query != null) { stringBuilder.append("AND "); stringBuilder.append(query.getWhereClause()); } return stringBuilder.toString(); }
Source:
<code>private void breakModifies(ProgressMonitor pm) throws IOException { if (modifyScore <= 0) return; pm.beginTask(JGitText.get().renamesBreakingModifies, entries.size()); for (int i = 0; i < entries.size(); i++) { DiffEntry e = entries.get(i); if (e.getChangeType() == ChangeType.MODIFY) { if (modifyScore > 100) { List<DiffEntry> tmp = DiffEntry.breakModify(e); deleted.add(tmp.get(0)); added.add(tmp.get(1)); <START> entries.remove(i); <END> i--; } else if (!e.newId.equals(e.oldId)) { if (calculateModifyScore(e) < modifyScore) { List<DiffEntry> tmp = DiffEntry.breakModify(e); deleted.add(tmp.get(0)); added.add(tmp.get(1)); entries.remove(i); i--; } } } pm.update(1); } }</code><technical_language>This is horribly slow entries is ArrayList, shift cell split. Worse splitting in this case. a newEntries add items break into, modify shift existing entries array</technical_language>

Target:
private void breakModifies(ProgressMonitor pm) throws IOException { if (breakScore <= 0) return; ArrayList<DiffEntry> newEntries = new ArrayList<DiffEntry>(entries.size()); pm.beginTask(JGitText.get().renamesBreakingModifies, entries.size()); for (int i = 0; i < entries.size(); i++) { DiffEntry e = entries.get(i); if (e.getChangeType() == ChangeType.MODIFY) { final int score = calculateModifyScore(e); if (score < breakScore) { List<DiffEntry> tmp = DiffEntry.breakModify(e); DiffEntry del = tmp.get(0); del.score = score; deleted.add(del); added.add(tmp.get(1)); i--; } else { newEntries.add(e); } } pm.update(1); } entries = newEntries; }
Source:
<code>public SwaggerInterfaceParser(Class<?> swaggerInterface, SerializerAdapter serializer, String host) { if (!ImplUtils.isNullOrEmpty(host)) { this.host = host; } else { final Host hostAnnotation = swaggerInterface.getAnnotation(Host.class); if (hostAnnotation != null && !hostAnnotation.value().isEmpty()) { this.host = hostAnnotation.value(); } else { <START> throw logger.logExceptionAsError(new MissingRequiredAnnotationException(Host.class, swaggerInterface)); <END> } } ServiceInterface serviceAnnotation = swaggerInterface.getAnnotation(ServiceInterface.class); if (serviceAnnotation != null && !serviceAnnotation.name().isEmpty()) { serviceName = serviceAnnotation.name(); } else { throw logger.logExceptionAsError(new MissingRequiredAnnotationException(ServiceInterface.class, swaggerInterface)); } }</code><technical_language>logs more for a customer right? able do for this. @JonathanGiles want debugging logging</technical_language>

Target:
public SwaggerInterfaceParser(Class<?> swaggerInterface, SerializerAdapter serializer, String host) { if (!ImplUtils.isNullOrEmpty(host)) { this.host = host; } else { final Host hostAnnotation = swaggerInterface.getAnnotation(Host.class); if (hostAnnotation != null && !hostAnnotation.value().isEmpty()) { this.host = hostAnnotation.value(); } else { throw new MissingRequiredAnnotationException(Host.class, swaggerInterface); } } ServiceInterface serviceAnnotation = swaggerInterface.getAnnotation(ServiceInterface.class); if (serviceAnnotation != null && !serviceAnnotation.name().isEmpty()) { serviceName = serviceAnnotation.name(); } else { throw new MissingRequiredAnnotationException(ServiceInterface.class, swaggerInterface); } }
Source:
<code>public static CommandElement entity(Text key, EntityType type) { <START> return new EntityCommandElement(key, false, false, type.getEntityClass()); <END> }</code><technical_language>This work expected. Passing ZOMBIE include PIG_ZOMBIE EntityPigZombie extends EntityZombie</technical_language>

Target:
public static CommandElement entity(Text key, EntityType type) { return new EntityCommandElement(key, false, false, type); }
Source:
<code>public abstract void activate(Context c, XmlWorkflowItem wf) throws SQLException, IOException, AuthorizeException, WorkflowException; public abstract ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request) throws SQLException, AuthorizeException, IOException, WorkflowException; public abstract List<String> getOptions(); <START> protected boolean isInOptions(HttpServletRequest request) { <END> for (String option: this.getOptions()) { if (request.getParameter(option) != null) { return true; } } return false; }</code><technical_language>Renamed</technical_language>

Target:
public abstract void activate(Context c, XmlWorkflowItem wf) throws SQLException, IOException, AuthorizeException, WorkflowException; public abstract ActionResult execute(Context c, XmlWorkflowItem wfi, Step step, HttpServletRequest request) throws SQLException, AuthorizeException, IOException, WorkflowException; public abstract List<String> getOptions(); protected boolean isOptionInParam(HttpServletRequest request) { for (String option: this.getOptions()) { if (request.getParameter(option) != null) { return true; } } return false; }
Source:
<code>private static int getThreadProcessId(String name, @Nullable Object value) { if (value instanceof Number) { return ((Number) value).intValue(); } try { <START> return Integer.parseInt(name); <END> } catch (NumberFormatException e) { } return -1; }</code><technical_language>tryParse</technical_language>

Target:
private static int getThreadProcessId(String name, @Nullable Object value) { if (value instanceof Number) { return ((Number) value).intValue(); } try { return Integer.parseInt(name); } catch (NumberFormatException e) { return UNKNOWN_TID; } }
Source:
<code>public void merge(ClientIOTaskResult.ThreadCountResult result) { <START> mRecordStartMs = result.mRecordStartMs; <END> mEndMs = Math.max(mEndMs, result.mEndMs); mIOBytes += result.mIOBytes; mErrors.addAll(result.mErrors); update(); }</code><technical_language>I understood Math.min'd</technical_language>

Target:
public void merge(ClientIOTaskResult.ThreadCountResult result) { mRecordStartMs = Math.min(mRecordStartMs, result.mRecordStartMs); mEndMs = Math.max(mEndMs, result.mEndMs); mIOBytes += result.mIOBytes; mErrors.addAll(result.mErrors); }
Source:
<code>public boolean isCheckPointCompleted(){ <START> boolean checkPointCompleted = this.status != GeoRepSessionStatus.FAULTY; <END> for (GlusterGeoRepSessionDetails details : getSessionDetails()) { if (details.getStatus() == GeoRepSessionStatus.ACTIVE && !details.isCheckpointCompleted()) { checkPointCompleted = false; } } return checkPointCompleted; }</code><technical_language>delete checkPointCompleted simply return in line 125: this.status != GeoRepSessionStatus.FAULTY</technical_language>

Target:
public boolean isCheckPointCompleted(){ for (GlusterGeoRepSessionDetails details : getSessionDetails()) { if (details.getStatus() == GeoRepSessionStatus.ACTIVE && !details.isCheckpointCompleted()) { return false; } } return this.status != GeoRepSessionStatus.FAULTY; }
Source:
<code>private void serverAboutToStart(FMLServerAboutToStartEvent event) { if (BotaniaAPI.instance().getClass() != BotaniaAPIImpl.class) { String clname = BotaniaAPI.instance().getClass().getName(); throw new IllegalAccessError("The Botania API has been overriden. " + "This will cause crashes and compatibility issues, and that's why it's marked as" + " \"Do not Override\". Whoever had the brilliant idea of overriding it needs to go" + " back to elementary school and learn to read. (Actual classname: " + clname + ")"); } if (Botania.gardenOfGlassLoaded) { <START> WorldTypeUtil.setupForDedicatedServer((DedicatedServer) event.getServer()); <END> } }</code><technical_language>this unsafe, if integrated server</technical_language>

Target:
private void serverAboutToStart(FMLServerAboutToStartEvent event) { if (BotaniaAPI.instance().getClass() != BotaniaAPIImpl.class) { String clname = BotaniaAPI.instance().getClass().getName(); throw new IllegalAccessError("The Botania API has been overriden. " + "This will cause crashes and compatibility issues, and that's why it's marked as" + " \"Do not Override\". Whoever had the brilliant idea of overriding it needs to go" + " back to elementary school and learn to read. (Actual classname: " + clname + ")"); } if (Botania.gardenOfGlassLoaded && event.getServer() instanceof DedicatedServer) { WorldTypeUtil.setupForDedicatedServer((DedicatedServer) event.getServer()); } }
Source:
<code>private void run() { try { boolean valid = connectionSanityCheck.isValid(); if (!valid) { onInvalidConnection.run(); } } catch (Exception e) { <START> logger.warn("Impossible to correctly monitor the Axon Server connection state."); <END> } }</code><technical_language>Add log</technical_language>

Target:
private void run() { try { boolean valid = connectionSanityCheck.isValid(); if (!valid) { onInvalidConnection.run(); } } catch (Exception e) { logger.warn("Impossible to correctly monitor the Axon Server connection state.", e); } }