auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private IRegion computeHeaderComment(FoldingStructureComputationContext ctx) throws JavaModelException { ISourceRange range= ctx.getFirstType().getSourceRange(); if (range == null) return null; int start= 0; int end= range.getOffset(); IScanner scanner= ctx.getScanner(); scanner.resetTo(start, end); int headerStart= -1; int headerEnd= -1; try { boolean foundComment= false; int terminal= scanner.getNextToken(); while (terminal != ITerminalSymbols.TokenNameEOF <START> && ((((terminal <END> != ITerminalSymbols.TokenNameclass) && (terminal != ITerminalSymbols.TokenNameinterface)) && (terminal != ITerminalSymbols.TokenNameenum)) && (!foundComment || ((terminal != ITerminalSymbols.TokenNameimport) && (terminal != ITerminalSymbols.TokenNamepackage))))) { if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK || terminal == ITerminalSymbols.TokenNameCOMMENT_LINE) { if (!foundComment) headerStart= scanner.getCurrentTokenStartPosition(); headerEnd= scanner.getCurrentTokenEndPosition(); foundComment= true; } terminal= scanner.getNextToken(); } } catch (InvalidInputException ex) { return null; } if (headerEnd != -1) { return new Region(headerStart, headerEnd - headerStart); } return null; }</code><technical_language>I start of this in a new line</technical_language>

Target:
private IRegion computeHeaderComment(FoldingStructureComputationContext ctx) throws JavaModelException { ISourceRange range= ctx.getFirstType().getSourceRange(); if (range == null) return null; int start= 0; int end= range.getOffset(); IScanner scanner= ctx.getScanner(); scanner.resetTo(start, end); int headerStart= -1; int headerEnd= -1; try { boolean foundComment= false; int terminal= scanner.getNextToken(); while (terminal != ITerminalSymbols.TokenNameEOF && (terminal != ITerminalSymbols.TokenNameclass) && (terminal != ITerminalSymbols.TokenNameinterface) && (terminal != ITerminalSymbols.TokenNameenum) && (!foundComment || ((terminal != ITerminalSymbols.TokenNameimport) && (terminal != ITerminalSymbols.TokenNamepackage)))) { if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || terminal == ITerminalSymbols.TokenNameCOMMENT_BLOCK || terminal == ITerminalSymbols.TokenNameCOMMENT_LINE) { if (!foundComment) headerStart= scanner.getCurrentTokenStartPosition(); headerEnd= scanner.getCurrentTokenEndPosition(); foundComment= true; } terminal= scanner.getNextToken(); } } catch (InvalidInputException ex) { return null; } if (headerEnd != -1) { return new Region(headerStart, headerEnd - headerStart); } return null; }
Source:
<code>private boolean appendValue(final StringBuilder rval, final Long value, final String key, final boolean nonzeroFragmentVisited) { boolean append = nonzeroFragmentVisited; if (value == null) { return nonzeroFragmentVisited; } <START> if (!nonzeroFragmentVisited && value.longValue() > 0) { <END> append = true; } if (append) { rval.append(value.longValue()).append(key); return true; } return false; }</code><technical_language>Is boolean append necessary? nozeroFragmentVisited || value.longValue() > 0 more simple. Please check</technical_language>

Target:
private boolean appendValue(final StringBuilder rval, final Long value, final String key, final boolean nonzeroFragmentVisited) { if (value == null) { return nonzeroFragmentVisited; } if (nonzeroFragmentVisited || value.longValue() > 0) { rval.append(value.longValue()).append(key); return true; } return false; }
Source:
<code>public void mappingFunctionReturnsIterableOfEntriesForEachInputEntry() throws Exception { Set<K> inputKeys = new HashSet<K>(); int nbElements = 10; for (long i = 0; i < nbElements; i++) { K k = factory.createKey(i); V v = factory.createValue(i); inputKeys.add(k); kvStore.put(k, v); } try { kvStore.bulkComputeIfAbsent(inputKeys, entries -> { assertThat(entries.iterator().hasNext(), is(false)); <START> return new HashMap<K, V>().entrySet(); <END> } ); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } }</code><technical_language>Collections.emptySet() I</technical_language>

Target:
public void mappingFunctionReturnsIterableOfEntriesForEachInputEntry() throws Exception { Set<K> inputKeys = new HashSet<K>(); int nbElements = 10; for (long i = 0; i < nbElements; i++) { K k = factory.createKey(i); V v = factory.createValue(i); inputKeys.add(k); kvStore.put(k, v); } try { kvStore.bulkComputeIfAbsent(inputKeys, entries -> { assertThat(entries.iterator().hasNext(), is(false)); return emptySet(); } ); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } }
Source:
<code>public static ThirdPartyContext singleTenant(String name) { <START> checkNotNull(name); <END> return newContext(name, false); }</code><technical_language>check for empty string too, please</technical_language>

Target:
public static ThirdPartyContext singleTenant(String name) { return newContext(name, false); }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { View vwRet = convertView; if (null == vwRet) { vwRet = LayoutInflater.from(context).inflate(R.layout.list_language_row, null); } Button delBtn = (Button) vwRet.findViewById(R.id.button_delete); Button dldBtn = (Button) vwRet.findViewById(R.id.button_download); Button optBtn = (Button) vwRet.findViewById(R.id.button_options); <START> delBtn.setText(IconFontUtils.get(IconFontUtils.REMOVE) + " " <END> + context.getString(R.string.button_delete)); dldBtn.setText(IconFontUtils.get(IconFontUtils.DOWNLOAD) + " " + context.getString(R.string.button_download)); optBtn.setText(IconFontUtils.get(IconFontUtils.WRENCH) + " " + context.getString(R.string.button_options)); delBtn.setTypeface(Settings.iconFont); dldBtn.setTypeface(Settings.iconFont); optBtn.setTypeface(Settings.iconFont); delBtn.setOnClickListener(this); dldBtn.setOnClickListener(this); optBtn.setOnClickListener(this); delBtn.setVisibility(View.GONE); dldBtn.setVisibility(View.GONE); optBtn.setVisibility(View.GONE); delBtn.setTag(SUPPORTED_LANGUAGES[position]); dldBtn.setTag(SUPPORTED_LANGUAGES[position]); optBtn.setTag(SUPPORTED_LANGUAGES[position]); if (null != this.customizer) { this.customizer.customizeUI(vwRet, SUPPORTED_LANGUAGES[position]); } return vwRet; }</code><technical_language>create a function concat white space string time? Like: IconFontUtils.get(IconFontUtils.REMOVE, context.getString(R.string.button_delete)); whitespace concatenation is a bit ugly</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { View vwRet = convertView; if (null == vwRet) { vwRet = LayoutInflater.from(context).inflate(R.layout.list_language_row, null); } Button delBtn = (Button) vwRet.findViewById(R.id.button_delete); Button dldBtn = (Button) vwRet.findViewById(R.id.button_download); Button optBtn = (Button) vwRet.findViewById(R.id.button_options); delBtn.setText(IconFontUtils.get(IconFontUtils.REMOVE, context.getString(R.string.button_delete))); dldBtn.setText(IconFontUtils.get(IconFontUtils.DOWNLOAD, context.getString(R.string.button_download))); optBtn.setText(IconFontUtils.get(IconFontUtils.WRENCH, context.getString(R.string.button_options))); delBtn.setTypeface(Settings.iconFont); dldBtn.setTypeface(Settings.iconFont); optBtn.setTypeface(Settings.iconFont); delBtn.setOnClickListener(this); dldBtn.setOnClickListener(this); optBtn.setOnClickListener(this); delBtn.setVisibility(View.GONE); dldBtn.setVisibility(View.GONE); optBtn.setVisibility(View.GONE); delBtn.setTag(SUPPORTED_LANGUAGES[position]); dldBtn.setTag(SUPPORTED_LANGUAGES[position]); optBtn.setTag(SUPPORTED_LANGUAGES[position]); if (null != this.customizer) { this.customizer.customizeUI(vwRet, SUPPORTED_LANGUAGES[position]); } return vwRet; }
Source:
<code>protected Optional<ExampleProjectError> getError(Path projectPath) { POM pom = this.getPom(pomService, projectPath); <START> if (pom.getModules().isEmpty() || pom.getModules() == null) { <END> return Optional.empty(); } else { return Optional.of(new ExampleProjectError(CheckModulesValidator.class.getCanonicalName(), "")); } }</code><technical_language>need swap order of nullcheck / isEmpty, lead NPE (if getModules returns null, possible) this validator fail</technical_language>

Target:
protected Optional<ExampleProjectError> getError(Path projectPath) { POM pom = this.getPom(pomService, projectPath); if (pom.getModules() == null || pom.getModules().isEmpty()) { return Optional.empty(); } else { return Optional.of(new ExampleProjectError(CheckModulesValidator.class.getCanonicalName(), "")); } }
Source:
<code>public static void configureRepositories(Project project) { project.getRepositories().all(repository -> { <START> if (repository instanceof MavenArtifactRepository) { <END> final MavenArtifactRepository maven = (MavenArtifactRepository) repository; assertRepositoryURIIsSecure(maven.getName(), project.getPath(), maven.getUrl()); for (URI uri : maven.getArtifactUrls()) { assertRepositoryURIIsSecure(maven.getName(), project.getPath(), uri); } } else if (repository instanceof IvyArtifactRepository) { final IvyArtifactRepository ivy = (IvyArtifactRepository) repository; assertRepositoryURIIsSecure(ivy.getName(), project.getPath(), ivy.getUrl()); } }); RepositoryHandler repos = project.getRepositories(); if (System.getProperty("repos.mavenLocal") != null) { repos.mavenLocal(); } repos.jcenter(); String luceneVersion = VersionProperties.getLucene(); if (luceneVersion.contains("-snapshot")) { Matcher matcher = LUCENE_SNAPSHOT_REGEX.matcher(luceneVersion); if (matcher.find() == false) { throw new GradleException("Malformed lucene snapshot version: " + luceneVersion); } String revision = matcher.group(1); MavenArtifactRepository luceneRepo = repos.maven(repo -> { repo.setName("lucene-snapshots"); repo.setUrl("<LINK_0>" + revision); }); repos.exclusiveContent(exclusiveRepo -> { exclusiveRepo.filter(descriptor -> { descriptor.includeVersionByRegex("org\\.apache\\.lucene", ".*", ".*-snapshot-" + revision); }); exclusiveRepo.forRepositories(luceneRepo); }); } }</code><technical_language>I replace of this introduced in Gradle 6.0. if (repository instanceof UrlArtifactRepository) { ((UrlArtifactRepository) repository).setAllowInsecureProtocol(false); }</technical_language>

Target:
public static void configureRepositories(Project project) { project.getRepositories().all(repository -> { if (repository instanceof MavenArtifactRepository) { final MavenArtifactRepository maven = (MavenArtifactRepository) repository; assertRepositoryURIIsSecure(maven.getName(), project.getPath(), maven.getUrl()); for (URI uri : maven.getArtifactUrls()) { assertRepositoryURIIsSecure(maven.getName(), project.getPath(), uri); } } else if (repository instanceof IvyArtifactRepository) { final IvyArtifactRepository ivy = (IvyArtifactRepository) repository; assertRepositoryURIIsSecure(ivy.getName(), project.getPath(), ivy.getUrl()); } }); RepositoryHandler repos = project.getRepositories(); if (System.getProperty("repos.mavenLocal") != null) { repos.mavenLocal(); } repos.jcenter(); String luceneVersion = VersionProperties.getLucene(); if (luceneVersion.contains("-snapshot")) { Matcher matcher = LUCENE_SNAPSHOT_REGEX.matcher(luceneVersion); if (matcher.find() == false) { throw new GradleException("Malformed lucene snapshot version: " + luceneVersion); } String revision = matcher.group(1); MavenArtifactRepository luceneRepo = repos.maven(repo -> { repo.setName("lucene-snapshots"); repo.setUrl("<LINK_0>" + revision); }); repos.exclusiveContent(exclusiveRepo -> { exclusiveRepo.filter( descriptor -> descriptor.includeVersionByRegex("org\\.apache\\.lucene", ".*", ".*-snapshot-" + revision) ); exclusiveRepo.forRepositories(luceneRepo); }); } }
Source:
<code>public static Repository getRepository(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); <START> IEditorInput editorInput = HandlerUtil.getActiveEditorInput(event); <END> return getRepository(selection, editorInput); }</code><technical_language>getActiveEditorInput is "since 3.7". AFAIK support 3.5. I making code more complicated for compatibility, in this case I bad copy implementation getVariable. do think</technical_language>

Target:
public static Repository getRepository(ExecutionEvent event) { ISelection selection = HandlerUtil.getCurrentSelection(event); IEditorInput editorInput = getActiveEditorInput(event); return getRepository(selection, editorInput); }
Source:
<code>public String toString() { <START> if (this.equals(ANY_VALUE)) { <END> return "ANY_VALUE"; } else if (this.equals(NO_POSSIBLE_VALUE)) { return "NO_POSSIBLE_VALUE"; } else if (this.equals(TRUTHY)) { return "TRUTHY"; } else if (this.equals(FALSY)) { return "FALSY"; } else { StringBuilder result = new StringBuilder(); for (SubConstraint subConstraint : SubConstraint.values()) { if ((this.bitSet & subConstraint.bitSet) == subConstraint.bitSet) { result.append("|").append(subConstraint.toString()); } } return result.substring(1); } }</code><technical_language>@vilchik-elena solution: a Map</technical_language>

Target:
public String toString() { String name = COMMON_CONSTRAINT_NAMES.get(this); if (name != null) { return name; } StringBuilder result = new StringBuilder(); for (ValueSubSet subSet : ValueSubSet.values()) { if ((this.bitSet & subSet.bitSet()) == subSet.bitSet()) { result.append("|").append(subSet); } } return result.substring(1); }
Source:
<code>protected void deallocate(Event event) { log.info("Deallocating [{}:{}]", event.getResourceType(), event.getResourceId()); AllocationRequest request = new AllocationRequest(event); try { allocator.deallocate(request); log.info("Deallocator handled request [{}]", allocator, request); eventService.publish(EventVO.reply(event)); } catch (AllocationException e) { String errorMessage = "Failed to deallocate: " + e.getMessage(); eventService.publish(EventVO.reply(event).withTransitioningMessage(errorMessage).withTransitioning(Event.TRANSITIONING_ERROR)); } <START> eventService.publish(EventVO.reply(event)); <END> }</code><technical_language>In error situation double reply</technical_language>

Target:
protected void deallocate(Event event) { log.info("Deallocating [{}:{}]", event.getResourceType(), event.getResourceId()); AllocationRequest request = new AllocationRequest(event); try { allocator.deallocate(request); log.info("Deallocator handled request [{}]", allocator, request); eventService.publish(EventVO.reply(event)); } catch (FailedToAllocate e) { String errorMessage = "Failed to deallocate: " + e.getMessage(); eventService.publish(EventVO.reply(event).withTransitioningMessage(errorMessage).withTransitioning(Event.TRANSITIONING_ERROR)); } }
Source:
<code>public void edit(final VnicProfileModel model) { driver.edit(model); publicInfo.setVisible(model.getPublicUse().getIsAvailable()); nameEditor.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { ValueChangeEvent.fire(nameEditor.asValueBox(), nameEditor.asValueBox().getValue()); } }); } }); nameEditor.asValueBox().addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { ValueChangeEvent.fire(VnicProfileWidget.this, model); } }); <START> model.getName().getEntityChangedEvent().addListener(new IEventListener() { <END> @Override public void eventRaised(Event ev, Object sender, EventArgs args) { ValueChangeEvent.fire(VnicProfileWidget.this, model); } }); }</code><technical_language>I understand do need this listener. model fire change event widget? is changed widget side model listens valueChanged event widget. model fire event widget</technical_language>

Target:
public void edit(final VnicProfileModel model) { driver.edit(model); publicInfo.setVisible(model.getPublicUse().getIsAvailable()); nameEditor.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { ValueChangeEvent.fire(nameEditor.asValueBox(), nameEditor.asValueBox().getValue()); } }); } }); nameEditor.asValueBox().addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { ValueChangeEvent.fire(VnicProfileWidget.this, model); } }); }
Source:
<code>public ListenableFuture<AckingContainer> poll(boolean forcePollSchema) { final SettableFuture<AckingContainer> fut = SettableFuture.create(false); PollTask pollTask = new PollTask(fut, forcePollSchema); try { m_es.execute(new Runnable() { @Override public void run() { if (!m_mastershipAccepted.get()) { try { pollTask.clear(); } catch (RejectedExecutionException rej) { } m_pollTask = null; return; } try { <START> if (m_pollTask != null) { <END> fut.setException(new ReentrantPollException("Reentrant poll detected: InCat = " + m_isInCatalog + " In " + ExportDataSource.this.toString())); return; } if (!m_es.isShutdown()) { pollImpl(pollTask); } } catch (Exception e) { exportLog.error("Exception polling export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error polling export buffer", true, e); } } }); } catch (RejectedExecutionException rej) { exportLog.info("Polling from export data source rejected."); } return fut; }</code><technical_language>Move this check beginning of runnable</technical_language>

Target:
public ListenableFuture<AckingContainer> poll(boolean forcePollSchema) { final SettableFuture<AckingContainer> fut = SettableFuture.create(false); PollTask pollTask = new PollTask(fut, forcePollSchema); try { m_es.execute(new Runnable() { @Override public void run() { if (m_pollTask != null) { try { pollTask.setException( new ReentrantPollException("Reentrant poll detected: InCat = " + m_isInCatalog + " In " + ExportDataSource.this.toString())); } catch (RejectedExecutionException reex) { } return; } if (!m_mastershipAccepted.get()) { try { pollTask.clear(); } catch (RejectedExecutionException rej) { } return; } try { if (!m_es.isShutdown()) { pollImpl(pollTask); } } catch (Exception e) { exportLog.error("Exception polling export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error polling export buffer", true, e); } } }); } catch (RejectedExecutionException rej) { exportLog.info("Polling from export data source rejected."); } return fut; }
Source:
<code>private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs) { <START> if ("POST".equals(requestLogInfo.method) && requestLogInfo.path.startsWith("/event-types/") && <END> requestLogInfo.path.contains("/events")) { final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } else if (requestLogInfo.contentLength > 50000) { sloBucket = ">50K"; } GlobalTracer.get() .buildSpan("publish_events") .withStartTimestamp(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime)) .start() .setTag("client_id", requestLogInfo.user) .setTag("event_type", eventType) .setTag("error", statusCode == 207 || statusCode >= 500) .setTag("http.status_code", statusCode) .setTag("http.url", requestLogInfo.path + requestLogInfo.query) .setTag("http.header.content_encoding", requestLogInfo.contentEncoding) .setTag("http.header.accept_encoding", requestLogInfo.acceptEncoding) .setTag("http.header.user_agent", requestLogInfo.userAgent) .setTag("slo_bucket", sloBucket) .setTag("content_length", requestLogInfo.contentLength) .finish(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime + timeSpentMs)); } }</code><technical_language>Is path guaranteed null</technical_language>

Target:
private void traceRequest(final RequestLogInfo requestLogInfo, final int statusCode, final Long timeSpentMs) { if (requestLogInfo.path != null && "POST".equals(requestLogInfo.method) && requestLogInfo.path.startsWith("/event-types/") && requestLogInfo.path.contains("/events")) { final String eventType = requestLogInfo.path.substring("/event-types/".length(), requestLogInfo.path.lastIndexOf("/events")); String sloBucket = "5K-50K"; if (requestLogInfo.contentLength < 5000) { sloBucket = "<5K"; } else if (requestLogInfo.contentLength > 50000) { sloBucket = ">50K"; } GlobalTracer.get() .buildSpan("publish_events") .withStartTimestamp(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime)) .start() .setTag("client_id", requestLogInfo.user) .setTag("event_type", eventType) .setTag("error", statusCode == 207 || statusCode >= 500) .setTag("http.status_code", statusCode) .setTag("http.url", requestLogInfo.path + requestLogInfo.query) .setTag("http.header.content_encoding", requestLogInfo.contentEncoding) .setTag("http.header.accept_encoding", requestLogInfo.acceptEncoding) .setTag("http.header.user_agent", requestLogInfo.userAgent) .setTag("slo_bucket", sloBucket) .setTag("content_length", requestLogInfo.contentLength) .finish(TimeUnit.MILLISECONDS.toMicros(requestLogInfo.requestTime + timeSpentMs)); } }
Source:
<code>protected List<VmStatic> filterVmsInClusterNeedUpdate() { List<VmStatic> allVms = vmStaticDao.getAllByCluster(getCluster().getId()); Set<VmStatic> vmSet = allVms.stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null) <START> .collect(Collectors.toSet()); <END> try { if (FeatureSupported.isBiosTypeSupported(getCluster().getCompatibilityVersion()) && oldCluster.getBiosType() != getCluster().getBiosType()) { allVms.stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL) .filter(vm -> vm.getBiosType() == BiosType.CLUSTER_DEFAULT) .forEach(vmSet::add); } } catch (IllegalArgumentException e) { } return vmSet.stream() .sorted() .collect(Collectors.toList()); }</code><technical_language>Creating a new set unnecessary. check for bios type done in filter() method. For example: boolean clusterBiosChanged = false; try { clusterBiosChanged = FeatureSupported.isBiosTypeSupported(getCluster().getCompatibilityVersion()) && oldCluster.getBiosType() != getCluster().getBiosType(); } catch (IllegalArgumentException e) final boolean biosChanged = clusterBiosChanged; vmStaticDao.getAllByCluster(getCluster().getId()).stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null || (biosChanged && vm.getBiosType() == BiosType.CLUSTER_DEFAULT)) .collect(Collectors.toList());</technical_language>

Target:
protected List<VmStatic> filterVmsInClusterNeedUpdate() { final boolean biosTypeChanged = isBiosTypeChanged(); return vmStaticDao.getAllByCluster(getCluster().getId()).stream() .filter(vm -> vm.getOrigin() != OriginType.EXTERNAL && !vm.isHostedEngine()) .filter(vm -> vm.getCustomCompatibilityVersion() == null || biosTypeChanged && vm.getBiosType() == BiosType.CLUSTER_DEFAULT) .sorted() .collect(Collectors.toList()); }
Source:
<code>private void handleLogReplicationEntry(CorfuPayloadMsg<LogReplicationEntry> msg, ChannelHandlerContext ctx, IServerRouter r) { <START> log.info("Log Replication Entry received by Server."); <END> if (isLeader(msg, r)) { LogReplicationEntry ack = sinkManager.receive(msg.getPayload()); if (ack != null) { long ts = ack.getMetadata().getMessageMetadataType().equals(MessageType.LOG_ENTRY_REPLICATED) ? ack.getMetadata().getTimestamp() : ack.getMetadata().getSnapshotTimestamp(); log.info("Sending ACK on to Client ", ack.getMetadata(), ts); r.sendResponse(msg, CorfuMsgType.LOG_REPLICATION_ENTRY.payloadMsg(ack)); } } }</code><technical_language>Log level trace? LOG_REPLICATION_ENTRY message is pretty common</technical_language>

Target:
private void handleLogReplicationEntry(CorfuPayloadMsg<LogReplicationEntry> msg, ChannelHandlerContext ctx, IServerRouter r) { log.trace("Log Replication Entry received by Server."); if (isLeader(msg, r)) { LogReplicationEntry ack = sinkManager.receive(msg.getPayload()); if (ack != null) { long ts = ack.getMetadata().getMessageMetadataType().equals(MessageType.LOG_ENTRY_REPLICATED) ? ack.getMetadata().getTimestamp() : ack.getMetadata().getSnapshotTimestamp(); log.info("Sending ACK on to Client ", ack.getMetadata(), ts); r.sendResponse(msg, CorfuMsgType.LOG_REPLICATION_ENTRY.payloadMsg(ack)); } } }
Source:
<code>private void render(DiffInfo diff) { JsArray<Region> regions = diff.content(); int lineA = 0, lineB = 0; for (int i = 0; i < regions.length(); i++) { Region current = regions.get(i); if (current.ab() != null) { lineA += current.ab().length(); lineB += current.ab().length(); } else if (current.a() == null && current.b() != null) { int delta = current.b().length(); padLines(cmA, delta, lineA - 1); lineB = colorLine(delta, lineA, lineB, true); } else if (current.a() != null && current.b() == null) { int delta = current.a().length(); padLines(cmB, delta, lineB - 1); lineA = colorLine(delta, lineA, lineB, false); } else { lineA = colorLine(current.a().length(), lineA, lineB, false); <START> lineB = colorLine(current.b().length(), lineA, lineB, true); <END> } } }</code><technical_language>a.length != b.length, need pad lines of shorter side</technical_language>

Target:
private void render(DiffInfo diff) { JsArray<Region> regions = diff.content(); int lineA = 0, lineB = 0; for (int i = 0; i < regions.length(); i++) { Region current = regions.get(i); if (current.ab() != null) { lineA += current.ab().length(); lineB += current.ab().length(); } else if (current.a() == null && current.b() != null) { int delta = current.b().length(); padLines(cmA, delta, lineA - 1); lineB = colorLine(delta, lineB, true); } else if (current.a() != null && current.b() == null) { int delta = current.a().length(); padLines(cmB, delta, lineB - 1); lineA = colorLine(delta, lineA, false); } else { lineA = colorLine(current.a().length(), lineA, false); lineB = colorLine(current.b().length(), lineB, true); } } }
Source:
<code>private static void printPowerSources(PowerSource[] powerSources) { StringBuilder sb = new StringBuilder("Power: "); if (powerSources.length == 0) { sb.append("Unknown"); } else { double timeRemaining = powerSources[0].getTimeRemaining(); if (timeRemaining < -1d) { sb.append("Charging"); } else if (timeRemaining < 0d) { sb.append("Calculating time remaining"); } else { sb.append(String.format("%d:%02d remaining", (int) (timeRemaining / 3600), (int) (timeRemaining / 60) % 60)); } } for (PowerSource powerSource : powerSources) { <START> sb.append(powerSource.toString()); <END> } oshi.add(sb.toString()); }</code><technical_language>Append "\n " here</technical_language>

Target:
private static void printPowerSources(PowerSource[] powerSources) { StringBuilder sb = new StringBuilder("Power: "); if (powerSources.length == 0) { sb.append("Unknown"); } for (PowerSource powerSource : powerSources) { sb.append("\n ").append(powerSource.toString()); } oshi.add(sb.toString()); }
Source:
<code>public void testInterfaceDefaultMethodBreakpoint() throws Exception { Listener listener = new Listener(); IBreakpointManager manager = getBreakpointManager(); manager.addBreakpointListener(listener); try { Path path = new Path("java8/EvalTestIntf18.java"); <START> toggleBreakpoint(path, <END> 20); IBreakpoint added = listener.getAdded(); assertTrue("Should be a method breakpoint", added instanceof IJavaMethodBreakpoint); IJavaMethodBreakpoint breakpoint = (IJavaMethodBreakpoint) added; assertEquals("Wrong type name", "Intf18", breakpoint.getTypeName()); assertEquals("Wrong method name", "test2", breakpoint.getMethodName()); assertEquals("Wrong signature", "()I", breakpoint.getMethodSignature()); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT); } finally { manager.removeBreakpointListener(listener); removeAllBreakpoints(); } }</code><technical_language>waitForJobs here? Reason: if test fails in asserts below, wait executed silly errors again</technical_language>

Target:
public void testInterfaceDefaultMethodBreakpoint() throws Exception { Listener listener = new Listener(); IBreakpointManager manager = getBreakpointManager(); manager.addBreakpointListener(listener); try { Path path = new Path("java8/EvalTestIntf18.java"); toggleBreakpoint(path, 20); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT); IBreakpoint added = listener.getAdded(); assertTrue("Should be a method breakpoint", added instanceof IJavaMethodBreakpoint); IJavaMethodBreakpoint breakpoint = (IJavaMethodBreakpoint) added; assertEquals("Wrong type name", "Intf18", breakpoint.getTypeName()); assertEquals("Wrong method name", "test2", breakpoint.getMethodName()); assertEquals("Wrong signature", "()I", breakpoint.getMethodSignature()); } finally { manager.removeBreakpointListener(listener); removeAllBreakpoints(); } }
Source:
<code>public double[] getTargetFactors() { final double[] values = file.readDoubleArray(TARGET_FACTORS_PATH); if (values.length != targetNames.get().size()) { throw new GATKException(String.format("Wrong number of elements in the target factors recovered " + <START> "from file '%s': %d != %d", file.getFile(), values.length, targetNames.get().size())); <END> } return values; }</code><technical_language>more informative replace "%d != %d" in exception message "(from file) %d != (number of targets) %d"</technical_language>

Target:
public double[] getTargetFactors() { final double[] values = file.readDoubleArray(TARGET_FACTORS_PATH); if (values.length != targetNames.get().size()) { throw new GATKException(String.format("Wrong number of elements in the target factors recovered " + "from file '%s': number of target factors found in file (%d) != number of target names (%d)", file.getFile(), values.length, targetNames.get().size())); } return values; }
Source:
<code><START> public void addContent(String content) { <END> driver.switchTo().frame(iframe); contentInput.clear(); contentInput.sendKeys(content); driver.switchTo().defaultContent(); }</code><technical_language>logging</technical_language>

Target:
public void addContent(String content) { driver.switchTo().frame(iframe); contentInput.clear(); contentInput.sendKeys(content); driver.switchTo().defaultContent(); PageObjectLogging.log("addContent", "content " + content + " added to the article", true); }
Source:
<code>public static String parseSessionId(String legend) { if (legend.startsWith("#")) { return legend.substring(legend.indexOf('#'), legend.indexOf(':')); } return ""; <START> } <END></code><technical_language>LegendProvider requires re-factoring: 1. private String generatePlotHeader(String sessionId, String taskName, String plotName) is 2. public String getPlotHeader(Set<Long> taskIds, String plotName) is strange, in place, is called necessary data is available, instead of this data DB please refactor create issue for this</technical_language>

Target:
public static String parseSessionId(String legend) { if (legend.startsWith(SESSION_PREFIX)) { return legend.substring(legend.indexOf(SESSION_PREFIX), legend.indexOf(LEGEND_DESCRIPTION_SEPARATOR)); } return ""; }
Source:
<code>public Response getAllRefunds(UriInfo uriInfo, SearchParams searchParams) { <START> RefundSearchStrategy refundSearchStrategy = new RefundSearchStrategy(refundDao); <END> return refundSearchStrategy.search(searchParams, uriInfo); }</code><technical_language>I a change RefundSearchStrategy a field initialise in @Inject method, eliminating need store RefundDao a field: java @Inject public SearchRefundsService(RefundDao refundDao) { this.refundSearchStrategy = new RefundSearchStrategy(refundDao); } (It's a good assign refundSearchStrategy method invocation, especially multiple threads do this time.)</technical_language>

Target:
public Response getAllRefunds(UriInfo uriInfo, SearchParams searchParams) { refundSearchStrategy = new RefundSearchStrategy(refundDao); return refundSearchStrategy.search(searchParams, uriInfo); }
Source:
<code>private Map<String, DashboardInfo> allDashboardsFor(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); do { dashboards = addProjectDashboards(projectState, dashboards); <START> parent = projectState.getProject().getParent(); <END> if (parent == null || !seen.add(parent)) { break; } projectState = projectCache.get(parent); } while (projectState != null); projectState = projectCache.getAllProjects(); parent = projectState.getProject().getNameKey(); if (seen.add(parent)) { dashboards = addProjectDashboards(projectState, dashboards); } return dashboards; }</code><technical_language>projectState.getProject().getParent(allProjectsName) here? need special handling for All-Projects project below</technical_language>

Target:
private Map<String, DashboardInfo> allDashboardsFor(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; Map<String, DashboardInfo> dashboards = Maps.newTreeMap(); Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); do { dashboards = addProjectDashboards(projectState, dashboards); parent = projectState.getProject().getParent(allProjects); projectState = projectCache.get(parent); } while (projectState != null && seen.add(parent)); return dashboards; }
Source:
<code>public boolean apply(BlockRayHit lastHit) { <START> return !lastHit.getBlockPosition().equals(this.target); <END> }</code><technical_language>I save object created here</technical_language>

Target:
public boolean apply(BlockRayHit lastHit) { return lastHit.getBlockX() != this.target.getX() || lastHit.getBlockY() != this.target.getY() || lastHit.getBlockZ() != this.target.getZ(); }
Source:
<code>public List<Statement> createAttributeStatements(final CallbackProperties properties, final Subject subject) { final List<Statement> statements = new ArrayList<>(); statements.add(createAuthenicationStatements(properties)); statements.add(createSubjectIdAttributeStatement(properties)); statements.add(createOrganizationAttributeStatements(properties)); statements.add(createSubjectRoleStatement(properties)); statements.add(createPurposeOfUseStatements(properties)); statements.add(createHomeCommunityIdAttributeStatement(properties)); statements.add(createOrganizationIdAttributeStatement(properties)); <START> statements.add(createResourceIdAttributeStatement(properties)); <END> statements.add(createNPIAttributeStatement(properties)); statements.addAll(createAcpAttributeStatements(properties)); if (isAcpOrIacpExists(properties)) { statements.add(createAuthorizationDecisionStatements(properties, subject)); } return statements; }</code><technical_language>methods for optional fields return a null instead of empty list, null check adding list</technical_language>

Target:
public List<Statement> createAttributeStatements(final CallbackProperties properties, final Subject subject) { final List<Statement> statements = new ArrayList<>(); addOptionalStatement(statements, createAuthenicationStatements(properties)); addOptionalStatement(statements, createSubjectIdAttributeStatement(properties)); addOptionalStatement(statements, createOrganizationAttributeStatement(properties)); addOptionalStatement(statements, createSubjectRoleStatement(properties)); addOptionalStatement(statements, createPurposeOfUseStatement(properties)); addOptionalStatement(statements, createHomeCommunityIdAttributeStatement(properties)); addOptionalStatement(statements, createOrganizationIdAttributeStatement(properties)); addOptionalStatement(statements, createResourceIdAttributeStatement(properties)); addOptionalStatement(statements, createNPIAttributeStatement(properties)); addOptionalAttributeStatements(statements, createAcpAttributeStatements(properties)); if (isAcpOrIacpExists(properties)) { addOptionalStatement(statements, createAuthorizationDecisionStatement(properties, subject)); } return statements; }
Source:
<code>public void handleForeignKeyAdd(DDLChange ddlChange, long onConglomerateNumber) { TentativeFK tentativeFKAdd = ddlChange.getTentativeFK(); if (onConglomerateNumber == tentativeFKAdd.getReferencedConglomerateNumber()) { addParentInterceptWriteFactory(tentativeFKAdd.getReferencedTableName(), ImmutableList.of(tentativeFKAdd.getReferencingConglomerateNumber()), <START> ImmutableList.of(tentativeFKAdd.getFkConstraintInfo().getTable().getConglomerate()),ImmutableList.of(tentativeFKAdd.getFkConstraintInfo())); <END> } if (onConglomerateNumber == tentativeFKAdd.getReferencingConglomerateNumber()) { addChildIntercept(tentativeFKAdd.getReferencedConglomerateNumber(), tentativeFKAdd.getFkConstraintInfo()); } }</code><technical_language>argument built fourth. Is build function signature cleaner</technical_language>

Target:
public void handleForeignKeyAdd(DDLChange ddlChange, long onConglomerateNumber) { TentativeFK tentativeFKAdd = ddlChange.getTentativeFK(); if (onConglomerateNumber == tentativeFKAdd.getReferencedConglomerateNumber()) { addParentInterceptWriteFactory(tentativeFKAdd.getReferencedTableName(), ImmutableList.of(tentativeFKAdd.getReferencingConglomerateNumber()), ImmutableList.of(tentativeFKAdd.getFkConstraintInfo())); } if (onConglomerateNumber == tentativeFKAdd.getReferencingConglomerateNumber()) { addChildIntercept(tentativeFKAdd.getReferencedConglomerateNumber(), tentativeFKAdd.getFkConstraintInfo()); } }
Source:
<code>protected List<MethodHandle> getMethodHandles(RowType type, FunctionManager functionManager, OperatorType operatorType) { ImmutableList.Builder<MethodHandle> argumentMethods = ImmutableList.builder(); for (Type parameterType : type.getTypeParameters()) { <START> FunctionHandle operator = functionManager.resolveOperator(operatorType, ImmutableList.of(parameterType, parameterType)); <END> argumentMethods.add(functionManager.getScalarFunctionImplementation(operator).getMethodHandle()); } return argumentMethods.build(); }</code><technical_language>operatorHandle</technical_language>

Target:
protected List<MethodHandle> getMethodHandles(RowType type, FunctionManager functionManager, OperatorType operatorType) { ImmutableList.Builder<MethodHandle> argumentMethods = ImmutableList.builder(); for (Type parameterType : type.getTypeParameters()) { FunctionHandle operatorHandle = functionManager.resolveOperator(operatorType, ImmutableList.of(parameterType, parameterType)); argumentMethods.add(functionManager.getScalarFunctionImplementation(operatorHandle).getMethodHandle()); } return argumentMethods.build(); }
Source:
<code>public EditionLimiter(TextViewer viewer) { this.textViewer = viewer; textViewer.getTextWidget().addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { <START> if (((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'd')) { <END> triggeredFromWidget = true; Point currentlocation = e.widget.getDisplay().getCursorLocation(); Control currentcontrol = e.widget.getDisplay().getCursorControl(); StyledText txt = (StyledText) e.getSource(); int lineLength = 0; int caretOffset = txt.getCaretOffset(); if (document == null) { initialize(); } try { int lineNo = document.getLineOfOffset(caretOffset); lineLength = document.getLineLength(lineNo); } catch (BadLocationException e1) { e1.printStackTrace(); } isDeleteLine = true; doit(txt.getCaretOffset(), lineLength, "", true, true); try { document.replace(txt.getCaretOffset(), lineLength, ""); } catch (BadLocationException e1) { e1.printStackTrace(); } isDeleteLine = false; lastTextForShortCircuiting = null; triggeredFromWidget = false; } } @Override public void keyReleased(KeyEvent e) { } }); }</code><technical_language>I CTRL is platform specific. need equivalent for Mac (don't remember is though)</technical_language>

Target:
public EditionLimiter(TextViewer viewer) { this.textViewer = viewer; textViewer.getTextWidget().addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (((e.stateMask & SWT.CTRL) == SWT.CTRL) && (e.keyCode == 'd')) { triggeredFromWidget = true; StyledText txt = (StyledText) e.getSource(); int lineLength = 0; int lineNo = 0; int caretOffset = txt.getCaretOffset(); if (document == null) { initialize(); } try { lineNo = document.getLineOfOffset(caretOffset); lineLength = document.getLineLength(lineNo); } catch (BadLocationException e1) { logger.debug("Exception inserting " + "Could not obtain line info", e1); } try { if (!isEditableLine(document.getLineOffset(lineNo), 1)) { return; } } catch (BadLocationException e2) { logger.debug("Exception inserting " + "Could not check if editable", e2); } isDeleteLine = true; doit(caretOffset, lineLength, "", false, true); try { document.replace(document.getLineOffset(lineNo), lineLength, ""); } catch (BadLocationException e1) { logger.debug("Exception inserting " + "Could not replace text", e1); } isDeleteLine = false; lastTextForShortCircuiting = null; triggeredFromWidget = false; } } @Override public void keyReleased(KeyEvent e) { } }); }
Source:
<code>protected Set<RunningInstance> createNodesInRegionAndZone(String region, String zone, String group, int count, Template template, RunInstancesOptions instanceOptions) { int countStarted = 0; int tries = 0; Set<RunningInstance> started = ImmutableSet.<RunningInstance> of(); int maxCount = EC2TemplateOptions.class.cast(template.getOptions()).getMaxCount(); <START> int provCount; <END> if (maxCount == 0) { maxCount = count; provCount = 1; } else { provCount = count; } while (countStarted < count && tries++ < count) { if (logger.isDebugEnabled()) logger.debug(">> running %d instance region(%s) zone(%s) ami(%s) params(%s)", count - countStarted, region, zone, template.getImage().getProviderId(), instanceOptions.buildFormParameters()); started = ImmutableSet.copyOf(concat( started, client.getInstanceApi().get().runInstancesInRegion(region, zone, template.getImage().getProviderId(), provCount, maxCount - countStarted, instanceOptions))); countStarted = size(started); if (countStarted < count) logger.debug(">> not enough instances (%d/%d) started, attempting again", countStarted, count); } return started; }</code><technical_language>is "provCount" supposed stand for? figure out logic for setting below... ;-)</technical_language>

Target:
protected Set<RunningInstance> createNodesInRegionAndZone(String region, String zone, String group, int count, Template template, RunInstancesOptions instanceOptions) { int countStarted = 0; int tries = 0; Set<RunningInstance> started = ImmutableSet.<RunningInstance> of(); int maxCount = EC2TemplateOptions.class.cast(template.getOptions()).getMaxCount(); int countToProvision; if (maxCount == 0) { maxCount = count; countToProvision = 1; } else { countToProvision = count; } while (countStarted < count && tries++ < count) { if (logger.isDebugEnabled()) logger.debug(">> running %d instance region(%s) zone(%s) ami(%s) params(%s)", count - countStarted, region, zone, template.getImage().getProviderId(), instanceOptions.buildFormParameters()); started = ImmutableSet.copyOf(concat( started, client.getInstanceApi().get().runInstancesInRegion(region, zone, template.getImage().getProviderId(), countToProvision, maxCount - countStarted, instanceOptions))); countStarted = size(started); if (countStarted < count) logger.debug(">> not enough instances (%d/%d) started, attempting again", countStarted, count); } return started; }
Source:
<code>public static boolean hasPermission( final String owner, final String activity, final String target) { <START> logger.warn("BEACH Test: in hasPermission and the upAuth helper is: " + authorizationHelper.getClass()); <END> return authorizationHelper.hasPermission(owner, activity, target); }</code><technical_language>warning: Left test log</technical_language>

Target:
public static boolean hasPermission( final String owner, final String activity, final String target) { return authorizationHelper.hasPermission(owner, activity, target); }
Source:
<code>public void initializeOfferings() { File metaDirectory = ufg.getMetaDirectory(); File[] files = metaDirectory.listFiles(); for (File file : files) { if (file.getName().startsWith("offer_") == false) continue; String offeringId = this.ufg.extractUniqueCode(file.getName()); try { String json = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath()))); Offering offering = Offering.fromJSON(json); offeringNameToOfferingId.put(offering.getName(), offering.getId()); <START> } catch (Exception e) { <END> this.removeOffering(offeringId); } } }</code><technical_language>practices do recommend catching Exception</technical_language>

Target:
public void initializeOfferings() { File metaDirectory = ufg.getMetaDirectory(); File[] files = metaDirectory.listFiles(); for (File file : files) { if (file.getName().startsWith("offer_") == false) continue; String offeringId = this.ufg.extractUniqueCode(file.getName()); try { String json = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath()))); Offering offering = Offering.fromJSON(json); offeringNameToOfferingId.put(offering.getName(), offering.getId()); } catch (IOException e) { this.removeOffering(offeringId); } } }
Source:
<code>private QName getPortTypeName(Class<?> serviceEndpointInterface) { Class<?> seiClass = serviceEndpointInterface; if (!serviceEndpointInterface.isAnnotationPresent(WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, serviceEndpointInterface .getCanonicalName()); throw new WebServiceException(msg.toString()); } if (!serviceEndpointInterface.isInterface()) { WebService webService = serviceEndpointInterface.getAnnotation(WebService.class); String epi = webService.endpointInterface(); if (epi.length() > 0) { try { seiClass = Thread.currentThread().getContextClassLoader().loadClass(epi); } catch (ClassNotFoundException e) { <START> Message msg = new Message("COULD_NOT_LOAD_CLASS", BUNDLE, api); <END> throw new WebServiceException(msg.toString()); } if (!seiClass.isAnnotationPresent(javax.jws.WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, seiClass.getCanonicalName()); throw new WebServiceException(msg.toString()); } } } WebService webService = seiClass.getAnnotation(WebService.class); String name = webService.name(); if (name.length() == 0) { name = seiClass.getSimpleName(); } String tns = webService.targetNamespace(); if (tns.length() == 0) { tns = URIParserUtil.getNamespace(PackageUtils.getPackageName(seiClass)); } return new QName(tns, name); }</code><technical_language>epi api</technical_language>

Target:
private QName getPortTypeName(Class<?> serviceEndpointInterface) { Class<?> seiClass = serviceEndpointInterface; if (!serviceEndpointInterface.isAnnotationPresent(WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, serviceEndpointInterface .getCanonicalName()); throw new WebServiceException(msg.toString()); } if (!serviceEndpointInterface.isInterface()) { WebService webService = serviceEndpointInterface.getAnnotation(WebService.class); String epi = webService.endpointInterface(); if (epi.length() > 0) { try { seiClass = Thread.currentThread().getContextClassLoader().loadClass(epi); } catch (ClassNotFoundException e) { Message msg = new Message("COULD_NOT_LOAD_CLASS", BUNDLE, epi); throw new WebServiceException(msg.toString()); } if (!seiClass.isAnnotationPresent(javax.jws.WebService.class)) { Message msg = new Message("SEI_NO_WEBSERVICE_ANNOTATION", BUNDLE, seiClass.getCanonicalName()); throw new WebServiceException(msg.toString()); } } } WebService webService = seiClass.getAnnotation(WebService.class); String name = webService.name(); if (name.length() == 0) { name = seiClass.getSimpleName(); } String tns = webService.targetNamespace(); if (tns.length() == 0) { tns = URIParserUtil.getNamespace(PackageUtils.getPackageName(seiClass)); } return new QName(tns, name); }