auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private SortedSet<ActionParameterRequest> buildActionParameters(FormSchemaJson form) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; <START> String displayName; <END> for (FormSchemaQuestionJson question : form.getQuestions()) { ActionParameterRequestBuilder builder = new ActionParameterRequestBuilder(); displayName = ("").equals(question.getQuestionLabel()) ? question.getQuestionValue() : question.getQuestionLabel(); if (displayName.length() > MAX_LABEL_LENGHT) { displayName = displayName.substring(0, MAX_LABEL_LENGHT); } builder.setDisplayName(displayName) .setKey(question.getQuestionValue()) .setOrder(order++); if (question.getOptions() != null && !question.getOptions().isEmpty()) { builder.setType(ParameterType.SELECT.getValue()); builder.setOptions(convertCommcareoptionsToTaskActionOptions(question.getOptions())); } else { builder.setType(ParameterType.UNICODE.getValue()); } parameters.add(builder.createActionParameterRequest()); } return parameters; }</code><technical_language>this declaration for, assignment</technical_language>

Target:
private SortedSet<ActionParameterRequest> buildActionParameters(FormSchemaJson form) { SortedSet<ActionParameterRequest> parameters = new TreeSet<>(); int order = 0; for (FormSchemaQuestionJson question : form.getQuestions()) { ActionParameterRequestBuilder builder = new ActionParameterRequestBuilder(); String displayName = StringUtils.isBlank(question.getQuestionLabel()) ? question.getQuestionValue() : question.getQuestionLabel(); if (displayName.length() > MAX_LABEL_LENGTH) { displayName = displayName.substring(0, MAX_LABEL_LENGTH); } builder.setDisplayName(displayName) .setKey(question.getQuestionValue()) .setOrder(order++); if (question.getOptions() != null && !question.getOptions().isEmpty()) { builder.setType(ParameterType.SELECT.getValue()); builder.setOptions(convertCommcareoptionsToTaskActionOptions(question.getOptions())); } else { builder.setType(ParameterType.UNICODE.getValue()); } parameters.add(builder.createActionParameterRequest()); } return parameters; }
Source:
<code>public void panic(String reason) { <START> LOG.error("PANICKING: {}", reason); <END> }</code><technical_language>call panic(...)below</technical_language>

Target:
public void panic(String reason) { panic(reason, new Throwable("Mock Panicker")); }
Source:
<code>public static FirstWant fromLine(String line) { String wantLine; Set<String> <START> options; <END> if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) { opt = opt.substring(1); } for (String c : opt.split(" ")) { opts.add(c); } wantLine = line.substring(0, 45); options = Collections.unmodifiableSet(opts); } else { wantLine = line; options = Collections.emptySet(); } return new FirstWant(wantLine, options); }</code><technical_language>capabilities</technical_language>

Target:
public static FirstWant fromLine(String line) { String wantLine; Set<String> capabilities; if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) { opt = opt.substring(1); } for (String c : opt.split(" ")) { opts.add(c); } wantLine = line.substring(0, 45); capabilities = Collections.unmodifiableSet(opts); } else { wantLine = line; capabilities = Collections.emptySet(); } return new FirstWant(wantLine, capabilities); }
Source:
<code>public LuceneHdfsDirectory(Path path, FileSystem fs) { this.fs = Preconditions.checkNotNull(fs); <START> dir = path; <END> index_input_list = new ArrayList<HDFSIndexInput>(); }</code><technical_language>correct</technical_language>

Target:
public LuceneHdfsDirectory(Path path, FileSystem fs) { this.fs = Preconditions.checkNotNull(fs); dir = path; }
Source:
<code>public static Collection<Converter<?, ?>> getConvertersToRegister() { List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>(); boolean useISOStringConverterForDate = Boolean.parseBoolean( System.getProperty("org.springframework.data.couchbase.useISOStringConverterForDate", "false")); if (useISOStringConverterForDate) { converters.add(DateToStringConverter.INSTANCE); converters.add(StringToDateConverter.INSTANCE); } else { converters.add(DateToLongConverter.INSTANCE); <START> converters.add(NumberToDateConverter.INSTANCE); <END> } converters.add(CalendarToLongConverter.INSTANCE); converters.add(NumberToCalendarConverter.INSTANCE); if (JODA_TIME_IS_PRESENT) { converters.add(LocalDateToLongConverter.INSTANCE); converters.add(LocalDateTimeToLongConverter.INSTANCE); converters.add(DateTimeToLongConverter.INSTANCE); converters.add(DateMidnightToLongConverter.INSTANCE); converters.add(NumberToLocalDateConverter.INSTANCE); converters.add(NumberToLocalDateTimeConverter.INSTANCE); converters.add(NumberToDateTimeConverter.INSTANCE); converters.add(NumberToDateMidnightConverter.INSTANCE); } return converters; }</code><technical_language>I if adding NumberToDateConverter in case of property set true work? This allow migrate data serialized a long encoding for dates a String based format. ("Be liberal in accept, strict in produce")</technical_language>

Target:
public static Collection<Converter<?, ?>> getConvertersToRegister() { List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>(); boolean useISOStringConverterForDate = Boolean.parseBoolean( System.getProperty("org.springframework.data.couchbase.useISOStringConverterForDate", "false")); if (useISOStringConverterForDate) { converters.add(DateToStringConverter.INSTANCE); } else { converters.add(DateToLongConverter.INSTANCE); } converters.add(SerializedObjectToDateConverter.INSTANCE); converters.add(CalendarToLongConverter.INSTANCE); converters.add(NumberToCalendarConverter.INSTANCE); if (JODA_TIME_IS_PRESENT) { converters.add(LocalDateToLongConverter.INSTANCE); converters.add(LocalDateTimeToLongConverter.INSTANCE); converters.add(DateTimeToLongConverter.INSTANCE); converters.add(DateMidnightToLongConverter.INSTANCE); converters.add(NumberToLocalDateConverter.INSTANCE); converters.add(NumberToLocalDateTimeConverter.INSTANCE); converters.add(NumberToDateTimeConverter.INSTANCE); converters.add(NumberToDateMidnightConverter.INSTANCE); } return converters; }
Source:
<code>public String createGist(final String title, final String extension, final String gist, final GitHubCredentials credentials) throws GitHubServiceException, IOException { PostMethod method = null; try { method = new PostMethod(gistPostURL); final NameValuePair name = new NameValuePair("file_name[gistfile1]", title); final NameValuePair ext = new NameValuePair("file_ext[gistfile1]", extension); final NameValuePair content = new NameValuePair("file_contents[gistfile1]", gist); <START> final NameValuePair login = new NameValuePair("login", credentials.getUsername()); <END> final NameValuePair token = new NameValuePair("token", credentials.getApiToken()); method.addParameters(new NameValuePair[] { name, ext, content, login, token }); executeMethod(method); if (LOG.isDebugEnabled()) { LOG.debug("Response: " + method.getResponseBodyAsString()); LOG.debug("URL: " + method.getURI()); } return method.getResponseHeader("Location").getValue(); } catch (GitHubServiceException e) { throw e; } catch (final RuntimeException runTimeException) { throw runTimeException; } catch (final Exception e) { throw new GitHubServiceException(e); } finally { if (method != null) { method.releaseConnection(); } } }</code><technical_language>setCredentials Basic auth</technical_language>

Target:
public String createGist(final String title, final String extension, final String gist, final GitHubCredentials credentials) throws GitHubServiceException, IOException { PostMethod method = null; try { setCredentials(credentials); method = new PostMethod(gistPostURL); final NameValuePair name = new NameValuePair("file_name[gistfile1]", title); final NameValuePair ext = new NameValuePair("file_ext[gistfile1]", extension); final NameValuePair content = new NameValuePair("file_contents[gistfile1]", gist); method.addParameters(new NameValuePair[] { name, ext, content }); executeMethod(method); return method.getResponseHeader("Location").getValue(); } catch (GitHubServiceException e) { throw e; } catch (final RuntimeException runTimeException) { throw runTimeException; } catch (final Exception e) { throw new GitHubServiceException(e); } finally { if (method != null) { method.releaseConnection(); } } }
Source:
<code>public void init() { DocumentModel domain = session.createDocumentModel("/", "domain", "Domain"); session.createDocument(domain); doc = session.createDocumentModel("/domain", "test", "File"); doc = session.createDocument(doc); <START> domain = session.createDocumentModel("/", "Folder", "Folder"); <END> domain = session.createDocument(domain); DocumentModel fileDoc = session.createDocumentModel(domain.getPathAsString(), "File", "File"); session.createDocument(fileDoc); DocumentModel container = session.createDocumentModel(domain.getPathAsString(), "CommentContainer", "Folder"); session.createDocument(container); session.save(); createUser(AUTHOR_OF_COMMENT); }</code><technical_language>Name folder, reuse doc maybe? domain is misleading</technical_language>

Target:
public void init() { DocumentModel domain = session.createDocumentModel("/", "Folder", "Folder"); domain = session.createDocument(domain); DocumentModel doc = session.createDocumentModel(domain.getPathAsString(), "File", "File"); session.createDocument(doc); DocumentModel container = session.createDocumentModel(domain.getPathAsString(), "CommentContainer", "Folder"); session.createDocument(container); session.save(); createUser(AUTHOR_OF_COMMENT); }
Source:
<code>public List<String> getObjectIdsByAnalysisId(@NonNull String programId, @NonNull String analysisId) { val url = new URL(serverUrl + "/studies/" + programId + "/analysis/" + analysisId + "/files"); <START> log.error("Fetching analysis files from url '{}'", url); <END> val result = MAPPER.readValue(url, ArrayNode.class); val objectIds=new ArrayList<String>(); log.error("Got result {}",result); result.forEach(x-> objectIds.add(x.path("objectId").textValue())); return objectIds; }</code><technical_language>change this debug</technical_language>

Target:
public List<String> getObjectIdsByAnalysisId(@NonNull String programId, @NonNull String analysisId) { val url = new URL(serverUrl + "/studies/" + programId + "/analysis/" + analysisId + "/files"); log.debug("Fetching analysis files from url '{}'", url); return Stream.of(MAPPER.readValue(url, ArrayNode.class)). peek(r -> log.debug("Got result {}", r)). map(x -> x.path("objectId")). map(JsonNode::textValue). collect(toImmutableList()); }
Source:
<code>public void onActivity() { long currentTime = System.currentTimeMillis(); if (currentTime < (lastUpdateTime + threshold)) { activeDuringThreshold.set(true); } else { Thread activityRequestThread = new Thread(this::notifyActivity); <START> activityRequestThread.setDaemon(true); <END> activityRequestThread.start(); lastUpdateTime = currentTime; } }</code><technical_language>give some meaningful name this thread</technical_language>

Target:
public void onActivity() { long currentTime = System.currentTimeMillis(); if (currentTime < (lastUpdateTime + threshold)) { activeDuringThreshold.set(true); } else { Thread activityRequestThread = new Thread(this::notifyActivity); activityRequestThread.setName("WorkspaceActivityRequestThread"); activityRequestThread.setDaemon(true); activityRequestThread.start(); lastUpdateTime = currentTime; } }
Source:
<code>public static FirstWant fromLine(String line) { String <START> realLine; <END> Set<String> options; if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) opt = opt.substring(1); for (String c : opt.split(" ")) opts.add(c); realLine = line.substring(0, 45); options = Collections.unmodifiableSet(opts); } else { realLine = line; options = Collections.emptySet(); } return new FirstWant(realLine, options); }</code><technical_language>maybe: "String wantLine;" "l", "lineWithoutCaps"</technical_language>

Target:
public static FirstWant fromLine(String line) { String wantLine; Set<String> options; if (line.length() > 45) { final HashSet<String> opts = new HashSet<>(); String opt = line.substring(45); if (opt.startsWith(" ")) { opt = opt.substring(1); } for (String c : opt.split(" ")) { opts.add(c); } wantLine = line.substring(0, 45); options = Collections.unmodifiableSet(opts); } else { wantLine = line; options = Collections.emptySet(); } return new FirstWant(wantLine, options); }
Source:
<code>public AdapterFactory createAdapterFactory() { final ComposedAdapterFactory factory = new ComposedAdapterFactory(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { AdapterFactory aFactory = diagramTypeDescriptor.getDiagramDescriptionProvider().getAdapterFactory(); if (aFactory != null) { factory.addAdapterFactory(aFactory); } } factory.addAdapterFactory(new DescriptionItemProviderAdapterFactory()); factory.addAdapterFactory(new DiagramItemProviderAdapterFactory()); factory.addAdapterFactory(new StyleItemProviderAdapterFactory()); factory.addAdapterFactory(new ToolItemProviderAdapterFactory()); <START> factory.addAdapterFactory(new FilterItemProviderAdapterFactory()); <END> factory.addAdapterFactory(new ValidationItemProviderAdapterFactory()); factory.addAdapterFactory(new ConcernItemProviderAdapterFactory()); return factory; }</code><technical_language>ValidationPackage is diagram specifci more. This added in DialectUIManagerImpl here</technical_language>

Target:
public AdapterFactory createAdapterFactory() { final ComposedAdapterFactory factory = new ComposedAdapterFactory(); for (final IDiagramTypeDescriptor diagramTypeDescriptor : DiagramTypeDescriptorRegistry.getInstance().getAllDiagramTypeDescriptors()) { AdapterFactory aFactory = diagramTypeDescriptor.getDiagramDescriptionProvider().getAdapterFactory(); if (aFactory != null) { factory.addAdapterFactory(aFactory); } } factory.addAdapterFactory(new DescriptionItemProviderAdapterFactory()); factory.addAdapterFactory(new DiagramItemProviderAdapterFactory()); factory.addAdapterFactory(new StyleItemProviderAdapterFactory()); factory.addAdapterFactory(new ToolItemProviderAdapterFactory()); factory.addAdapterFactory(new FilterItemProviderAdapterFactory()); factory.addAdapterFactory(new ConcernItemProviderAdapterFactory()); return factory; }
Source:
<code>public void testConcurrentConfigurationReloads() throws InterruptedException, ExecutionException { final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); List<Future<?>> futures = new LinkedList<>(); for (int i = 0; i < TASK_COUNT; i++) { futures.add(threadPool.submit(() -> { Response put = target("configuration") .path("projectsEnabled") .request() <START> .put(Entity.text("true")); <END> Assert.assertEquals(204, put.getStatus()); assertTestedProjects(); })); } threadPool.shutdown(); threadPool.awaitTermination(100, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } }</code><technical_language>set true/false property randomly - in case implements smarter property setting (that no-op if is set)</technical_language>

Target:
public void testConcurrentConfigurationReloads() throws InterruptedException, ExecutionException { final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); List<Future<?>> futures = new LinkedList<>(); for (int i = 0; i < TASK_COUNT; i++) { futures.add(threadPool.submit(() -> { Response put = target("configuration") .path("projectsEnabled") .request() .put(Entity.text("true")); Assert.assertEquals(204, put.getStatus()); assertTestedProjects(); })); } threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } }
Source:
<code>public int readBytesOrFewer(final byte[] buffer, final int offset, final int length) { if (isWriting) { throw new IllegalStateException("Calling read method on BinaryCodec open for write."); } try { <START> if (length == 0) return 0; <END> else return inputStream.read(buffer, offset, length); } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("Read error"), e); } }</code><technical_language>{ } if body</technical_language>

Target:
public int readBytesOrFewer(final byte[] buffer, final int offset, final int length) { if (isWriting) { throw new IllegalStateException("Calling read method on BinaryCodec open for write."); } try { return (length == 0) ? 0 : inputStream.read(buffer, offset, length); } catch (IOException e) { throw new RuntimeIOException(constructErrorMessage("Read error"), e); } }
Source:
<code>private static <R extends BaseResource> BaseResource getParent(R model, Class<?> parentType) { for (Method method : getRelevantMethods(model.getClass())) { try { Object potentialParent = method.invoke(model); if (potentialParent != null && parentType.isAssignableFrom(potentialParent.getClass())) { return (BaseResource)potentialParent; } <START> } catch (Exception e) { <END> continue; } } return null; }</code><technical_language>is OK silently swallow exception. Please send error message log this happens</technical_language>

Target:
private static <R extends BaseResource> BaseResource getParent(R model, Class<?> parentType) { for (Method method : getRelevantMethods(model.getClass())) { try { Object potentialParent = method.invoke(model); if (potentialParent != null && parentType.isAssignableFrom(potentialParent.getClass())) { return (BaseResource)potentialParent; } } catch (Exception e) { log.error("Error invoking method when adding links to an API entity", e); continue; } } return null; }
Source:
<code>private Boolean evaluateBoolean(BinaryOperator statement, Boolean leftBoolean, Boolean rightBoolean) { switch(statement.getOperator()) { case and: return leftBoolean & rightBoolean; case or: if(leftBoolean == null && rightBoolean == null) { return null; <START> } else if (leftBoolean == null) { <END> return rightBoolean; } else if (rightBoolean == null) { return leftBoolean; } return leftBoolean | rightBoolean; case xor: return leftBoolean ^ rightBoolean; default: throw new IllegalArgumentException("Not a boolean operator: " + statement.getOperator()); } }</code><technical_language>&& rightBoolean == true</technical_language>

Target:
private Boolean evaluateBoolean(BinaryOperator statement, Boolean leftBoolean, Boolean rightBoolean) { switch(statement.getOperator()) { case and: return leftBoolean & rightBoolean; case or: if(leftBoolean == null && rightBoolean == null) { return null; } else if (leftBoolean == null) { if(rightBoolean) { return rightBoolean; } return null; } else if (rightBoolean == null) { if(leftBoolean) { return leftBoolean; } return null; } return leftBoolean | rightBoolean; case xor: return leftBoolean ^ rightBoolean; default: throw new IllegalArgumentException("Not a boolean operator: " + statement.getOperator()); } }
Source:
<code>public List<String> getSections() { List<String> sectionNames = new ArrayList<>(); for (String section : bundle.sectionsInCourse()) { if (!section.equals(Const.DEFAULT_SECTION)) { sectionNames.add(section); } } Collections.sort(sectionNames); <START> return sectionNames; <END> }</code><technical_language>Good data bundle. do processing store somewhere</technical_language>

Target:
public List<String> getSections() { return sections; }
Source:
<code>private List<String> getFilterInFromFormData(JSONObject formData) { String stringIn = formData.optString("filterIn"); List<String> filter = null; String[] arrayIn = null; if (!stringIn.equals("null")) { filter = new ArrayList<>(); <START> arrayIn = stringIn.split(" "); <END> filter = Arrays.asList(arrayIn); } return filter; }</code><technical_language>split \\s+ cover white space</technical_language>

Target:
private List<String> getFilterInFromFormData(JSONObject formData) { String stringIn = formData.optString("filterIn", null); List<String> filter = null; String[] arrayIn = null; if (stringIn != null && !stringIn.equals("null")) { filter = new ArrayList<>(); arrayIn = stringIn.split("\\s+"); filter = Arrays.asList(arrayIn); } return filter; }
Source:
<code>public TaskStatus run(final TaskToolbox toolbox) throws Exception { final boolean determineIntervals = !ingestionSchema.getDataSchema() .getGranularitySpec() .bucketIntervals() .isPresent(); final FirehoseFactory delegateFirehoseFactory = ingestionSchema.getIOConfig().getFirehoseFactory(); if (delegateFirehoseFactory instanceof IngestSegmentFirehoseFactory) { ((IngestSegmentFirehoseFactory) delegateFirehoseFactory).setTaskToolbox(toolbox); } <START> final FirehoseFactory firehoseFactory = delegateFirehoseFactory; <END> final Map<Interval, List<ShardSpec>> shardSpecs = determineShardSpecs(toolbox, firehoseFactory); final String version; final DataSchema dataSchema; if (determineIntervals) { Interval interval = JodaUtils.umbrellaInterval(shardSpecs.keySet()); TaskLock lock = toolbox.getTaskActionClient().submit(new LockAcquireAction(interval)); version = lock.getVersion(); dataSchema = ingestionSchema.getDataSchema().withGranularitySpec( ingestionSchema.getDataSchema() .getGranularitySpec() .withIntervals( JodaUtils.condenseIntervals( shardSpecs.keySet() ) ) ); } else { version = Iterables.getOnlyElement(getTaskLocks(toolbox)).getVersion(); dataSchema = ingestionSchema.getDataSchema(); } if (generateAndPublishSegments(toolbox, dataSchema, shardSpecs, version, firehoseFactory)) { return TaskStatus.success(getId()); } else { return TaskStatus.failure(getId()); } }</code><technical_language>call delegateFirehoseFactory firehoseFactory start. renaming useful anymore</technical_language>

Target:
public TaskStatus run(final TaskToolbox toolbox) throws Exception { final boolean determineIntervals = !ingestionSchema.getDataSchema() .getGranularitySpec() .bucketIntervals() .isPresent(); final FirehoseFactory firehoseFactory = ingestionSchema.getIOConfig().getFirehoseFactory(); if (firehoseFactory instanceof IngestSegmentFirehoseFactory) { ((IngestSegmentFirehoseFactory) firehoseFactory).setTaskToolbox(toolbox); } final File firehoseTempDir = toolbox.getFirehoseTemporaryDir(); FileUtils.forceMkdir(firehoseTempDir); final Map<Interval, List<ShardSpec>> shardSpecs = determineShardSpecs(toolbox, firehoseFactory, firehoseTempDir); final String version; final DataSchema dataSchema; if (determineIntervals) { Interval interval = JodaUtils.umbrellaInterval(shardSpecs.keySet()); TaskLock lock = toolbox.getTaskActionClient().submit(new LockAcquireAction(interval)); version = lock.getVersion(); dataSchema = ingestionSchema.getDataSchema().withGranularitySpec( ingestionSchema.getDataSchema() .getGranularitySpec() .withIntervals( JodaUtils.condenseIntervals( shardSpecs.keySet() ) ) ); } else { version = Iterables.getOnlyElement(getTaskLocks(toolbox)).getVersion(); dataSchema = ingestionSchema.getDataSchema(); } if (generateAndPublishSegments(toolbox, dataSchema, shardSpecs, version, firehoseFactory, firehoseTempDir)) { return TaskStatus.success(getId()); } else { return TaskStatus.failure(getId()); } }
Source:
<code>public static Set<IPluginModelBase> parsePlugins(ILaunchConfiguration configuration, String attribute) throws CoreException { HashSet<IPluginModelBase> set = new HashSet<>(); <START> List<String> entries = configuration.getAttribute(attribute, (List<String>) null); <END> if (entries != null) { Map<String, IPluginModelBase> unmatchedEntries = new HashMap<>(); for (int i = 0; i < entries.size(); i++) { String token = entries.get(i); int index = token.indexOf('@'); if (index < 0) { token = token.concat("@default:default"); entries.set(i, token); index = token.indexOf('@'); } String idVersion = token.substring(0, index); int versionIndex = token.indexOf(BundleLauncherHelper.VERSION_SEPARATOR); String id = (versionIndex > 0) ? idVersion.substring(0, versionIndex) : idVersion; String version = (versionIndex > 0) ? idVersion.substring(versionIndex + 1) : null; ModelEntry entry = PluginRegistry.findEntry(id); if (entry != null) { IPluginModelBase matchingModels[] = attribute.equals(IPDELauncherConstants.SELECTED_TARGET_PLUGIN_LIST) ? entry.getExternalModels() : entry.getWorkspaceModels(); for (IPluginModelBase matchingModel : matchingModels) { if (matchingModel.isEnabled()) { if (version == null || matchingModel.getPluginBase().getVersion().equals(version)) { set.add(matchingModel); } else if (matchingModels.length == 1) { if (unmatchedEntries.remove(id) == null) { unmatchedEntries.put(id, matchingModel); } } } } } } set.addAll(unmatchedEntries.values()); } return set; }</code><technical_language>pass emptyList() default skip null check</technical_language>

Target:
public static Set<IPluginModelBase> parsePlugins(ILaunchConfiguration configuration, String attribute) throws CoreException { HashSet<IPluginModelBase> set = new HashSet<>(); Map<String, IPluginModelBase> unmatchedEntries = new HashMap<>(); List<String> entries = configuration.getAttribute(attribute, Collections.emptyList()); for (String token : entries) { int index = token.indexOf('@'); if (index < 0) { token = token.concat("@default:default"); index = token.indexOf('@'); } String idVersion = token.substring(0, index); int versionIndex = token.indexOf(BundleLauncherHelper.VERSION_SEPARATOR); String id = (versionIndex > 0) ? idVersion.substring(0, versionIndex) : idVersion; String version = (versionIndex > 0) ? idVersion.substring(versionIndex + 1) : null; ModelEntry entry = PluginRegistry.findEntry(id); if (entry != null) { IPluginModelBase matchingModels[] = attribute.equals(IPDELauncherConstants.SELECTED_TARGET_BUNDLES) ? entry.getExternalModels() : entry.getWorkspaceModels(); for (IPluginModelBase matchingModel : matchingModels) { if (matchingModel.isEnabled()) { if (version == null || matchingModel.getPluginBase().getVersion().equals(version)) { set.add(matchingModel); } else if (matchingModels.length == 1) { if (unmatchedEntries.remove(id) == null) { unmatchedEntries.put(id, matchingModel); } } } } } } set.addAll(unmatchedEntries.values()); return set; }
Source:
<code>private T waitForCompletionAndThrowIfUploadFailed() throws IOException { try { return uploadOperation.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); uploadOperation.cancel(true); IOException exception = new ClosedByInterruptException(); exception.addSuppressed(e); throw exception; } catch (ExecutionException e) { if (ignoreConditionFailureForUpload(new IOException(e.getCause()))) { logger.atWarning().withCause(e.getCause()).log( "412 Precondition failure was ignored for resource %s.", getResourceString()); return null; } else if (e.getCause() instanceof Error) { throw (Error) e.getCause(); <START> } else { <END> throw new IOException( String.format("Upload failed for '%s'", getResourceString()), e.getCause()); } } }</code><technical_language>Remove else is redundant</technical_language>

Target:
private T waitForCompletionAndThrowIfUploadFailed() throws IOException { try { return uploadOperation.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); uploadOperation.cancel(true); IOException exception = new ClosedByInterruptException(); exception.addSuppressed(e); throw exception; } catch (ExecutionException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new IOException( String.format("Upload failed for '%s'", getResourceString()), e.getCause()); } }
Source:
<code>public void nodeExplicitIndexDrop( String indexName ) throws ExplicitIndexNotFoundKernelException { ktx.assertOpen(); <START> allStoreHolder.explicitIndexTxState().nodeChanges( indexName ).drop(); <END> allStoreHolder.explicitIndexTxState().deleteIndex( IndexEntityType.Node, indexName ); }</code><technical_language>need get explicit index tx state</technical_language>

Target:
public void nodeExplicitIndexDrop( String indexName ) throws ExplicitIndexNotFoundKernelException { ktx.assertOpen(); ExplicitIndexTransactionState txState = allStoreHolder.explicitIndexTxState(); txState.nodeChanges( indexName ).drop(); txState.deleteIndex( IndexEntityType.Node, indexName ); }
Source:
<code>void setSymbols(List<SymbolStyleSearchResult> symbols) { <START> if (symbols.size() > 0) { <END> mSymbols = symbols; setChanged(); notifyObservers(); } }</code><technical_language>!symbols.isEmpty()</technical_language>

Target:
void setSymbols(List<SymbolStyleSearchResult> symbols) { if (!symbols.isEmpty()) { mSymbols = symbols; setChanged(); notifyObservers(); } }
Source:
<code>public ItemStreamWriter<VariantWrapper> vepAnnotationFileWriter(AnnotationParameters annotationParameters, ChunkSizeParameters chunkSizeParameters) { <START> long timeoutInSeconds = 600L; END> return new VepAnnotationFileWriter(annotationParameters, chunkSizeParameters.getChunkSize(), timeoutInSeconds); }</code><technical_language>If TODO DO. code include it</technical_language>

Target:
public ItemWriter<VariantWrapper> vepAnnotationFileWriter(AnnotationParameters annotationParameters, ChunkSizeParameters chunkSizeParameters) { return new VepAnnotationFileWriter(annotationParameters, chunkSizeParameters.getChunkSize(), annotationParameters.getTimeout()); }
Source:
<code>public void setUp() throws Exception { accountsPayableService = Mockito.mock(AccountsPayableService.class); Mockito.when(accountsPayableService.getExpiredOrClosedAccountList(creditMemoDocument)).thenReturn(new HashMap<>()); dataDictionaryService = Mockito.mock(DataDictionaryService.class); Mockito.when(dataDictionaryService.getAttributeMaxLength(DocumentHeader.class, KRADPropertyConstants.DOCUMENT_DESCRIPTION)).thenReturn(200); dateTimeService = new DateTimeServiceImpl(); documentService = buildMockDocumentService(); noteService = Mockito.mock(NoteService.class); purapService = Mockito.mock(PurapService.class); vendorService = new MockVendorServiceImpl(); creditMemoServiceImpl = PowerMockito.spy(new TestCuCreditMemoServiceImpl()); <START> PowerMockito.doNothing().when(creditMemoServiceImpl, "reIndexDocument", Mockito.any()); <END> creditMemoServiceImpl.setDocumentService(documentService); creditMemoServiceImpl.setNoteService(noteService); creditMemoServiceImpl.setPurapService(purapService); creditMemoServiceImpl.setAccountsPayableService(accountsPayableService); creditMemoServiceImpl.setVendorService(vendorService); creditMemoServiceImpl.setDataDictionaryService(dataDictionaryService); creditMemoDocument = setupVendorCreditMemoDocument(); mo14Person = MockPersonUtil.createMockPerson(UserNameFixture.mo14); mo14Session = MockPersonUtil.createMockUserSession(mo14Person); GlobalVariables.setUserSession(mo14Session); }</code><technical_language>Ok, thanks for checking</technical_language>

Target:
public void setUp() throws Exception { accountsPayableService = Mockito.mock(AccountsPayableService.class); Mockito.when(accountsPayableService.getExpiredOrClosedAccountList(Mockito.any())).thenReturn(new HashMap<>()); dataDictionaryService = Mockito.mock(DataDictionaryService.class); Mockito.when(dataDictionaryService.getAttributeMaxLength(DocumentHeader.class, KRADPropertyConstants.DOCUMENT_DESCRIPTION)).thenReturn(200); dateTimeService = new DateTimeServiceImpl(); documentService = buildMockDocumentService(); noteService = Mockito.mock(NoteService.class); purapService = Mockito.mock(PurapService.class); vendorService = new MockVendorServiceImpl(); creditMemoServiceImpl = PowerMockito.spy(new TestCuCreditMemoServiceImpl()); PowerMockito.doNothing().when(creditMemoServiceImpl, "reIndexDocument", Mockito.any()); creditMemoServiceImpl.setDocumentService(documentService); creditMemoServiceImpl.setNoteService(noteService); creditMemoServiceImpl.setPurapService(purapService); creditMemoServiceImpl.setAccountsPayableService(accountsPayableService); creditMemoServiceImpl.setVendorService(vendorService); creditMemoServiceImpl.setDataDictionaryService(dataDictionaryService); creditMemoDocument = setupVendorCreditMemoDocument(); mo14Person = MockPersonUtil.createMockPerson(UserNameFixture.mo14); mo14Session = MockPersonUtil.createMockUserSession(mo14Person); GlobalVariables.setUserSession(mo14Session); }
Source:
<code><START> static SSLFactory getNewInstance(SSLConfig sslConfig) <END> throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { return Utils.getObj(sslConfig.sslFactory, sslConfig); }</code><technical_language>throws Exception</technical_language>

Target:
static SSLFactory getNewInstance(SSLConfig sslConfig) throws Exception { return Utils.getObj(sslConfig.sslFactory, sslConfig); }
Source:
<code>public CommandApi endDate(String endDate) { <START> parameters.put("end_date", String.valueOf(endDate)); <END> return this; }</code><technical_language>endDate is a string -> u need do String.valueOf()</technical_language>

Target:
public CommandApi endDate(String endDate) { parameters.put("end_date", endDate); return this; }
Source:
<code>private void assertValidJson(String snippet) { DU_SCHEMA.validate(new JSONObject(snippet)); assertTrue(true); <START> } <END></code><technical_language>for ease of in debugging test failures, I wrap this in a try/catch explicitly pass/fail good messages, like: private void assertValidJson(String snippet) { try { DU_SCHEMA.validate(new JSONObject(snippet)); assertTrue(true); } catch (ValidationException e) { fail("snippet <" + snippet + "> pass validation: " + e.getMessage()); } }</technical_language>

Target:
private void assertValidJson(String snippet) { try { DU_SCHEMA.validate(new JSONObject(snippet)); assertTrue(true); } catch (ValidationException e) { fail("snippet <" + snippet + "> did not pass validation: " + e.getMessage()); } }
Source:
<code>static Optional<String> getErrorMessageFromTask(String cluster, String taskArn, EcsClient client) { Optional<String> errorMessage; try { final Task task = client.getTask(cluster, taskArn); if (task.getContainers().size() > 0) { <START> errorMessage = Optional.of(task.getContainers().get(0).getReason()); <END> } else { errorMessage = Optional.of("No container information"); } } catch (TaskSetNotFoundException e) { errorMessage = Optional.of(e.getErrorMessage()); } catch (RuntimeException re) { errorMessage = Optional.of(re.getMessage()); } return errorMessage; }</code><technical_language>ECS task 1 container</technical_language>

Target:
static Optional<String> getErrorMessageFromTask(String cluster, String taskArn, EcsClient client) { Optional<String> errorMessage = Optional.absent(); try { final Task task = client.getTask(cluster, taskArn); final List<String> reasons = task.getContainers().stream() .map(c -> c.getReason()) .filter(r -> !Strings.isNullOrEmpty(r)) .collect(Collectors.toList()); if (reasons.size() > 0) { errorMessage = Optional.of(String.join(",", reasons)); } else { errorMessage = Optional.of("No container information"); } } catch (TaskSetNotFoundException e) { errorMessage = Optional.fromNullable(e.getErrorMessage()); } return errorMessage; }
Source:
<code>protected ChannelPool createChannelPool(final String hostString, int count) throws IOException { ChannelPool.ChannelFactory channelFactory = new ChannelPool.ChannelFactory() { @Override public ManagedChannel create() throws IOException { return createNettyChannel(hostString, options.build(), clientInterceptors); } }; return new ChannelPool(channelFactory, count); <START> } <END></code><technical_language>Please re-add createChannelPool(final ChannelPool.ChannelFactory channelFactory, int count) method</technical_language>

Target:
protected ManagedChannel createChannelPool(final String hostString, int count) throws IOException { ChannelPool.ChannelFactory channelFactory = new ChannelPool.ChannelFactory() { @Override public ManagedChannel create() throws IOException { return createNettyChannel(hostString, options.build(), clientInterceptors); } }; return createChannelPool(channelFactory, count); }
Source:
<code>public Future<String> loadNetworkWithPopularTerms() throws QStoreStorageException { String query = env.getProperty("allNetworks"); String queryID = env.getProperty("allNetworks_id"); executeQuery(query, queryID); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(queryID); <START> while (res != null && res.contains("<message>") && res.contains(RUNNING.name())) { <END> try { Thread.sleep(delay); res = getQueryResult(queryID); } catch (InterruptedException e) { throw new QStoreStorageException(e); } } return new AsyncResult<String>(res); }</code><technical_language>parse response parse values for comparison</technical_language>

Target:
public Future<String> loadNetworkWithPopularTerms() throws AsyncExecutionException { String query = env.getProperty("allNetworks"); ResponseEntity<String> response = executeQuery(query); HttpStatus status = response.getStatusCode(); String resbody = response.getBody(); if (status == HttpStatus.BAD_REQUEST || status == HttpStatus.INTERNAL_SERVER_ERROR) { String errorMessage = resbody.substring(resbody.indexOf("<message>"), resbody.indexOf("</message>")); throw new AsyncExecutionException(errorMessage); } QStoreAsyncResult asyncResult = getResponseFromXML(resbody); String pollURL = asyncResult.getPollurl(); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); while (asyncResult != null && asyncResult.getQueryStatus().equals(RUNNING.name())) { try { Thread.sleep(delay); res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); } catch (InterruptedException e) { throw new AsyncExecutionException(e); } } return new AsyncResult<String>(asyncResult.getResult()); }
Source:
<code>public GroupWait(TimePeriod timeout, WaitWrapper... waitings) { remainingTimeout = timeout; if (waitings == null || waitings.length == 0) { throw new IllegalArgumentException("There are no waiting to wait for, pass one or more waitings " + "as a constructor arguments to start waiting"); } for (WaitWrapper waitWrapper: waitings) { if (WaitType.WHILE.equals(waitWrapper.getWaitType())) { <START> long startTimeOfWait = System.currentTimeMillis(); <END> new WaitWhile(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); remainingTimeout = getRemainingTimeoutPeriod(remainingTimeout, startTimeOfWait); } else { if (WaitType.UNTIL.equals(waitWrapper.getWaitType())) { long startTimeOfWait = System.currentTimeMillis(); new WaitUntil(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); remainingTimeout = getRemainingTimeoutPeriod(remainingTimeout, startTimeOfWait); } } } }</code><technical_language>this moved if condition</technical_language>

Target:
public GroupWait(TimePeriod timeout, WaitWrapper... waitings) { remainingTimeout = timeout; if (waitings == null || waitings.length == 0) { throw new IllegalArgumentException("There are no waiting to wait for, pass one or more waitings " + "as a constructor arguments to start waiting"); } for (WaitWrapper waitWrapper: waitings) { long startTimeOfWait = System.currentTimeMillis(); if (WaitType.WHILE.equals(waitWrapper.getWaitType())) { new WaitWhile(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); } else if (WaitType.UNTIL.equals(waitWrapper.getWaitType())) { new WaitUntil(waitWrapper.getWaitCondition(), remainingTimeout, waitWrapper.throwRuntimeException()); } remainingTimeout = getRemainingTimeoutPeriod(remainingTimeout, startTimeOfWait); } }
Source:
<code>public Session getSession() { Session session = null; if (sessionRef == null || <START> sessionRef.get() == <END> null) { URI sessionModelURI = getURI().trimFragment(); if (sessionResourceURI != null) { sessionModelURI = sessionResourceURI; } Session newSession = getSession(sessionModelURI); if (newSession != null) { session = newSession; this.sessionRef = new WeakReference<Session>(newSession); } } else { session = sessionRef.get(); } return session; }</code><technical_language>session removed calls sessionRef.get(). Session session = sessionRef != null ? sessionRef.get() : null; if(session == null)</technical_language>

Target:
public Session getSession() { Session session = sessionRef != null ? sessionRef.get() : null; if (session == null) { URI sessionModelURI = getURI().trimFragment(); if (sessionResourceURI != null) { sessionModelURI = sessionResourceURI; } session = getSession(sessionModelURI); if (session != null) { this.sessionRef = new WeakReference<Session>(session); } } return session; }
Source:
<code>public void returnsExplicitCollections() throws IOException { JiraSession session = mock(JiraSession.class); JiraSite site = mock(JiraSite.class); <START> when(site.getSession(null)).thenReturn(session); <END> ExplicitIssueSelector jqlUpdaterIssueSelector = new ExplicitIssueSelector( Collections.singletonList(TEST_KEY)); Set<String> foundIssueIds = jqlUpdaterIssueSelector.findIssueIds(null, site, null); assertThat(foundIssueIds, hasSize(1)); assertThat(foundIssueIds.iterator().next(), equalTo(TEST_KEY)); }</code><technical_language>Tests need context-aware unfortunately, end testing globally defined sites</technical_language>

Target:
public void returnsExplicitCollections() throws IOException { ExplicitIssueSelector jqlUpdaterIssueSelector = new ExplicitIssueSelector(Collections.singletonList(TEST_KEY)); Set<String> foundIssueIds = jqlUpdaterIssueSelector.findIssueIds(null, null, null); assertThat(foundIssueIds, hasSize(1)); assertThat(foundIssueIds.iterator().next(), equalTo(TEST_KEY)); }
Source:
<code>public Collection<Locator> getLocators(long shard) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); final Collection<Locator> locators = new ArrayList<Locator>(); try { RowQuery<Long, Locator> query = AstyanaxIO.getKeyspace() .prepareQuery(CassandraModel.CF_METRICS_LOCATOR) .getKey(shard); ColumnList<Locator> columns = query.execute().getResult(); for (Column<Locator> column: columns) { <START> locators.add(column.getName().withLastUpdatedTimestamp(column.getTimestamp() / 1000)); <END> } if (locators.size() == 0) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } } catch (NotFoundException e) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } catch (ConnectionException ex) { Instrumentation.markReadError(ex); LOG.error("Connection exception during getLocators(" + Long.toString(shard) + " )", ex); throw new IOException("Error reading locators", ex); } finally { ctx.stop(); } return locators; }</code><technical_language>Locator's updated timestamp in granularity Cassandra's timestamp? I.e: miliseconds</technical_language>

Target:
public Collection<Locator> getLocators(long shard) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); final Collection<Locator> locators = new ArrayList<Locator>(); try { RowQuery<Long, Locator> query = AstyanaxIO.getKeyspace() .prepareQuery(CassandraModel.CF_METRICS_LOCATOR) .getKey(shard); ColumnList<Locator> columns = query.execute().getResult(); for (Column<Locator> column: columns) { locators.add(column.getName() .withLastUpdatedTimestamp(TimeUnit.MILLISECONDS.convert(column.getTimestamp(), TimeUnit.MICROSECONDS))); } if (locators.size() == 0) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } } catch (NotFoundException e) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } catch (ConnectionException ex) { Instrumentation.markReadError(ex); LOG.error("Connection exception during getLocators(" + Long.toString(shard) + " )", ex); throw new IOException("Error reading locators", ex); } finally { ctx.stop(); } return locators; }
Source:
<code>public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } String bootStr = str.toString(); if (!bootStr.equals("")) { return BootSequence.valueOf(bootStr); } <START> return null; <END> }</code><technical_language>Is for replacing ternary if? is better</technical_language>

Target:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } return !str.toString().equals("") ? BootSequence.valueOf(str.toString()) : null; }
Source:
<code>public boolean add(TileEntity te) { ChunkPos pos = getChunkPos(te); List<TileEntity> list = getChunkTEList(pos); <START> if(list == null) <END> { list = new ArrayList<>(); list.add(te); content.put(pos, list); return true; } else return list.add(te); }</code><technical_language>computeIfAbsent</technical_language>

Target:
public boolean add(TileEntity te) { ChunkPos pos = getChunkPos(te); List<TileEntity> list = content.get(pos); totalCount++; modCount++; if (list == null) { list = new ArrayList<>(); list.add(te); content.put(pos, list); return true; } else return list.add(te); }
Source:
<code>public FlowLoader createFlowLoader(final File projectDir) throws ProjectManagerException { final File[] projectFileList = projectDir.listFiles(new SuffixFilter(Constants .PROJECT_FILE_SUFFIX)); <START> if (projectFileList != null && projectFileList.length > 0) { <END> if (projectFileList.length > 1) { throw new ProjectManagerException("Duplicate project YAML files found in the project " + "directory. Only one is allowed."); } final Map<String, Object> projectYamlParser; try { projectYamlParser = (Map<String, Object>) new Yaml() .load(new FileInputStream(projectFileList[0])); } catch (final FileNotFoundException e) { throw new ProjectManagerException("Error reading project YAML file.", e); } if (!projectYamlParser.containsKey(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION)) { throw new ProjectManagerException("Azkaban-Flow-Version is not specified in the project " + "YAML file."); } if (projectYamlParser.get(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION).equals (Constants.VERSION_2_0)) { return new DirectoryYamlFlowLoader(this.props); } else { throw new ProjectManagerException("Invalid Azkaban-Flow-Version in the project YAML file."); } } else { return new DirectoryFlowLoader(this.props); } }</code><technical_language>consider ArrayUtils.isNotEmpty</technical_language>

Target:
public FlowLoader createFlowLoader(final File projectDir) throws ProjectManagerException { final File[] projectFileList = projectDir.listFiles(new SuffixFilter(Constants .PROJECT_FILE_SUFFIX)); if (projectFileList == null) { throw new ProjectManagerException("Error reading project directory. Input is not a " + "directory or IO error happens."); } if (ArrayUtils.isNotEmpty(projectFileList)) { if (projectFileList.length > 1) { throw new ProjectManagerException("Duplicate project YAML files found in the project " + "directory. Only one is allowed."); } final Map<String, Object> azkabanProject; try (FileInputStream fis = new FileInputStream(projectFileList[0])) { azkabanProject = (Map<String, Object>) new Yaml().load(fis); } catch (final IOException e) { throw new ProjectManagerException("Error reading project YAML file.", e); } if (azkabanProject == null || !azkabanProject .containsKey(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION)) { throw new ProjectManagerException("azkaban-flow-version is not specified in the project " + "YAML file."); } if (azkabanProject.get(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION).equals (Constants.AZKABAN_FLOW_VERSION_2_0)) { return new DirectoryYamlFlowLoader(this.props); } else { throw new ProjectManagerException("Invalid azkaban-flow-version in the project YAML file."); } } else { return new DirectoryFlowLoader(this.props); } }
Source:
<code>public void validate() { super.validate(); if (!this.containsMacro("filesystemURI")) { <START> if (!filesystemURI.startsWith("s3a://")) { <END> throw new IllegalArgumentException("URI for S3 source must start with s3a://"); } } }</code><technical_language>s3n is older, supported scheme. allow too</technical_language>

Target:
public void validate() { super.validate(); if (!this.containsMacro("filesystemURI")) { URI fsUri = URI.create(filesystemURI); if (!fsUri.getScheme().equals("s3a") && !fsUri.getScheme().equals("s3n")) { throw new IllegalArgumentException("URI scheme for S3 source must be s3a or s3n"); } } }