auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void checkVariantInformation(Variant variant, String fileId, String studyId) throws NonVariantException, IncompleteInformationException { VariantSourceEntry variantSourceEntry = variant.getSourceEntry(fileId, studyId); <START> if (isNonVariant(variantSourceEntry)) { <END> throw new NonVariantException("The variant " + variant + " has allele frequency or counts '0'"); } else if (!canAlleleFrequenciesBeCalculated(variantSourceEntry)) { throw new IncompleteInformationException(variant); } }</code><technical_language>I I suggested it, a bit inconsistent check is written affirmatively (canAlleleFrequenciesBeCalculated) other negatively (isNonVariant). Affirmative easier understand</technical_language>

Target:
protected void checkVariantInformation(Variant variant, String fileId, String studyId) throws NonVariantException, IncompleteInformationException { super.checkVariantInformation(variant, fileId, studyId); VariantSourceEntry variantSourceEntry = variant.getSourceEntry(fileId, studyId); if (!canAlleleFrequenciesBeCalculated(variantSourceEntry)) { throw new IncompleteInformationException(variant); } else if (variantFrequencyIsZero(variantSourceEntry)) { throw new NonVariantException("The variant " + variant + " has allele frequency or counts '0'"); } }
Source:
<code>public void generate(Model model) { model.types() .filter(StructType.class::isInstance) .map(StructType.class::cast) .forEach(this::generateClasses); model.types() <START> <END> .filter(EnumType.class::isInstance) .map(EnumType.class::cast) .forEach(this::generateClasses); }</code><technical_language>indentation in rest of code</technical_language>

Target:
public void generate(Model model) { model.types() .filter(StructType.class::isInstance) .map(StructType.class::cast) .forEach(this::generateStructSupportClasses); model.types() .filter(EnumType.class::isInstance) .map(EnumType.class::cast) .forEach(this::generateEnumSupportClasses); }
Source:
<code>public static String parseHostFromOldLog(Path p) { try { String n = p.getName(); int idx = n.lastIndexOf(LOGNAME_SEPARATOR); String s = URLDecoder.decode(n.substring(0, idx), "UTF8"); <START> return ServerName.valueOf(s).getHostname() + ":" + ServerName.valueOf(s).getPort(); <END> } catch (Exception e) { LOG.warn("Skip log file (can't parse): " + p); return null; } }</code><technical_language>Store valueOf result a local variable call getHostname getPort save parsing</technical_language>

Target:
public static String parseHostFromOldLog(Path p) { try { String n = p.getName(); int idx = n.lastIndexOf(LOGNAME_SEPARATOR); String s = URLDecoder.decode(n.substring(0, idx), "UTF8"); return ServerName.valueOf(s).getAddress().toString(); } catch (Exception e) { LOG.warn("Skip log file (can't parse): {}", p); return null; } }
Source:
<code>private void assertMultipleIssue(Set<AnalyzerMessage> issues) throws AssertionError { Preconditions.checkState(!issues.isEmpty(), "At least one issue expected"); List<Integer> unexpectedLines = Lists.newLinkedList(); Multimap<Integer, Expectations.Issue> expected = expectations.issues; flowAssertions = new SoftAssertions(); for (AnalyzerMessage issue : issues) { validateIssue(expected, unexpectedLines, issue); } <START> flowAssertions.assertAll(); <END> if (!expected.isEmpty() || !unexpectedLines.isEmpty()) { Collections.sort(unexpectedLines); String expectedMsg = !expected.isEmpty() ? ("Expected " + expected) : ""; String unexpectedMsg = !unexpectedLines.isEmpty() ? ((expectedMsg.isEmpty() ? "" : ", ") + "Unexpected at " + unexpectedLines) : ""; fail(expectedMsg + unexpectedMsg); } assertSuperfluousFlows(); }</code><technical_language>If blocker issues FP (as I suspect) please create ticket handle them</technical_language>

Target:
private void assertMultipleIssue(Set<AnalyzerMessage> issues) throws AssertionError { Preconditions.checkState(!issues.isEmpty(), "At least one issue expected"); List<Integer> unexpectedLines = Lists.newLinkedList(); Multimap<Integer, Expectations.Issue> expected = expectations.issues; for (AnalyzerMessage issue : issues) { validateIssue(expected, unexpectedLines, issue); } if (!expected.isEmpty() || !unexpectedLines.isEmpty()) { Collections.sort(unexpectedLines); String expectedMsg = !expected.isEmpty() ? ("Expected " + expected) : ""; String unexpectedMsg = !unexpectedLines.isEmpty() ? ((expectedMsg.isEmpty() ? "" : ", ") + "Unexpected at " + unexpectedLines) : ""; fail(expectedMsg + unexpectedMsg); } assertSuperfluousFlows(); }
Source:
<code>public String toString() { String info = ""; <START> info += "ModuleName= " + this.moduleName <END> + " RespTime= " + this.respTime + " Availability= " + this.availability + " Host= " + this.host.getHostName() + " DeploymentType= " + this.host.getDeploymentType() + " isJavaApp= " + this.isJavaApp; return info; }</code><technical_language>StringBuilder for multiple string concatenation</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(300); return sb.append("ModuleName= ").append(this.moduleName) .append(" RespTime= ").append(this.respTime) .append(" Availability= ").append(this.availability) .append(" Host= ").append(this.host.getHostName()) .append(" DeploymentType= ").append(this.host.getDeploymentType()) .append(" isJavaApp= ").append(this.isJavaApp) .toString(); }
Source:
<code>public DmxTransmitter(DmxService service) { this.service = service; <START> lastTransmit = 0; <END> }</code><technical_language>lastTransmit initialized 0 above, instead of private member initialized way, other initialized in constructor</technical_language>

Target:
public DmxTransmitter(DmxService service) { this.service = service; }
Source:
<code>public void startTimelineUpdate(final String eventType, final long timeoutMs) throws InterruptedException { LOG.info("Starting timeline update for event type with timeout ms", eventType, timeoutMs); final String etZkPath = toZkPath("/locked_et/" + eventType); <START> boolean successfull = false; <END> try { zooKeeperHolder.get().create().withMode(CreateMode.EPHEMERAL) .forPath(etZkPath, thisId.getBytes(Charsets.UTF_8)); updateVersionAndWaitForAllNodes(timeoutMs); successfull = true; } catch (final InterruptedException ex) { throw ex; } catch (final Exception e) { throw new RuntimeException(e); } finally { if (!successfull) { try { zooKeeperHolder.get().delete().forPath(etZkPath); } catch (final Exception e) { LOG.error("Failed to delete node {}", etZkPath, e); } } } }</code><technical_language>rename successfull successful</technical_language>

Target:
public void startTimelineUpdate(final String eventType, final long timeoutMs) throws InterruptedException { LOG.info("Starting timeline update for event type with timeout ms", eventType, timeoutMs); final String etZkPath = toZkPath("/locked_et/" + eventType); boolean successful = false; try { zooKeeperHolder.get().create().withMode(CreateMode.EPHEMERAL) .forPath(etZkPath, nodeId.getBytes(Charsets.UTF_8)); updateVersionAndWaitForAllNodes(timeoutMs); successful = true; } catch (final KeeperException.NodeExistsException ex) { throw new IllegalStateException(ex); } catch (final InterruptedException ex) { throw ex; } catch (final Exception e) { throw new RuntimeException(e); } finally { if (!successful) { try { zooKeeperHolder.get().delete().forPath(etZkPath); } catch (final Exception e) { LOG.error("Failed to delete node {}", etZkPath, e); } } } }
Source:
<code>protected boolean isUserRespondentOfSession() { <START> return hasValidResponse; <END> }</code><technical_language>Need consider case questions shown user, leading cases depend submitted form. e.g. user is student instructor</technical_language>

Target:
protected boolean isUserRespondentOfSession() { return hasValidResponse || logic.hasGiverRespondedForSession(getUserEmailForCourse(), feedbackSessionName, courseId); }
Source:
<code>public void shouldAcceptMnv() throws Exception { <START> Variant input = new Variant("1", 1000, 1003, "ATG", "CGT"); <END> Variant output = processor.process(input); assertEquals(Variant.VariantType.MNV, input.getType()); assertNotNull(output); assertEquals(input, output); }</code><technical_language>coordinates 1000, 1002</technical_language>

Target:
public void shouldAcceptMnv() throws Exception { Variant input = new Variant("1", 1000, 1002, "ATG", "CGT"); Variant output = processor.process(input); assertEquals(Variant.VariantType.MNV, input.getType()); assertNotNull(output); assertEquals(input, output); }
Source:
<code><START> public StringResourceModel(final String resourceKey, final Component component) <END> { Args.notNull(resourceKey, "resource key"); this.resourceKey = resourceKey; this.component = component; }</code><technical_language>migration easier I good more constructor: public StringResourceModel(final String resourceKey, final Component component, final IModel<?> model)</technical_language>

Target:
public StringResourceModel(final String resourceKey, final Component component) { this(resourceKey, component, null); }
Source:
<code>public void createCollectionObserver() { cCollectionObserver = new Observer() { @Override public void update(Observable o, Object arg) { Collection collection = (Collection) arg; Gdx.app.log(this.getClass().getName(), "Received Collection update: " + collection.toString()); if (collection.isEmpty()) { notifyUserEmptyContainerReceived(); } <START> for (Collectible c : collection) { <END> addCollectibleRendererItem(c); } for (CollectibleRenderer cr : cInitialSet) { if (!isInDisplaySet(cr)) { cDisplayRendererSet.add(cr); cStage.addActor(cr.getActor()); } } } }; }</code><technical_language>2 for loops in else case of collection.isEmpty() check, I assume</technical_language>

Target:
public void createCollectionObserver() { cCollectionObserver = new Observer() { @Override public void update(Observable o, Object arg) { Collection collection = (Collection) arg; Gdx.app.log(this.getClass().getName(), "Received Collection update: " + collection.toString()); if (collection.isEmpty()) { notifyUserEmptyContainerReceived(); } else { for (Collectible c : collection) { addCollectibleRendererItem(c); } for (CollectibleRenderer cr : cInitialSet) { if (!isInDisplaySet(cr)) { cDisplayRendererSet.add(cr); cStage.addActor(cr.getActor()); } } } } }; }
Source:
<code><START> public HttpRequest populateHttpRequest(HttpProducerContext producerContext, IncomingMessage incomingMessage) throws Exception { <END> String uri = getURI(producerContext.getHost(), producerContext.getPort(), incomingMessage); URI requestUri = new URI(uri); producerContext.host(requestUri.getHost()); String scheme = requestUri.getScheme(); if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); } HttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, incomingMessage.getMethod(), requestUri.getRawPath()); populateHeader(request, requestUri.getHost(), incomingMessage); populateCookies(request, incomingMessage); populateQueryParameters(request, incomingMessage); return request; }</code><technical_language>Line character count limit is 120 in a source file</technical_language>

Target:
public HttpRequest populateHttpRequest(HttpProducerContext producerContext, IncomingMessage incomingMessage) throws Exception { String uri = getURI(producerContext.getHost(), producerContext.getPort(), incomingMessage); URI requestUri = new URI(uri); producerContext.host(requestUri.getHost()); String scheme = requestUri.getScheme(); if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { log.error("Only HTTP(S) is supported."); } HttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, incomingMessage.getMethod(), requestUri.getRawPath()); populateHeader(request, requestUri.getHost(), incomingMessage); populateCookies(request, incomingMessage); return request; }
Source:
<code>public synchronized void onTimer(CruiseConfigProvider provider) { CruiseConfig currentConfig = provider.getCurrentConfig(); getAllValidLogs(currentConfig); <START> LOG.info("Recomputing material to pipeline mappings."); <END> HashMap<ServerHealthState, Set<String>> erroredPipelines = new HashMap<>(); for (Map.Entry<HealthStateType, ServerHealthState> entry : serverHealth.entrySet()) { erroredPipelines.put(entry.getValue(), entry.getValue().getPipelineNames(currentConfig)); } pipelinesWithErrors = erroredPipelines; LOG.info("Done recomputing material to pipeline mappings."); }</code><technical_language>this INFO level DEBUG? I guess ok default log level for appender is WARN, a user care a regular basis</technical_language>

Target:
public synchronized void onTimer(CruiseConfigProvider provider) { CruiseConfig currentConfig = provider.getCurrentConfig(); getAllValidLogs(currentConfig); LOG.debug("Recomputing material to pipeline mappings."); HashMap<ServerHealthState, Set<String>> erroredPipelines = new HashMap<>(); for (Map.Entry<HealthStateType, ServerHealthState> entry : serverHealth.entrySet()) { erroredPipelines.put(entry.getValue(), entry.getValue().getPipelineNames(currentConfig)); } pipelinesWithErrors = erroredPipelines; LOG.debug("Done recomputing material to pipeline mappings."); }
Source:
<code>private void setDynamicPreferredSize() { int maxNameLength = 0; <START> if (chat != null) { <END> final FontMetrics fontMetrics = this.getFontMetrics(UIManager.getFont("TextField.font")); for (final UserName onlinePlayer : chat.getOnlinePlayers()) { maxNameLength = Math.max(maxNameLength, fontMetrics.stringWidth(onlinePlayer.getValue())); } } int iconCounter = 0; if (setCellRenderer instanceof PlayerChatRenderer) { iconCounter = ((PlayerChatRenderer) setCellRenderer).getMaxIconCounter(); } setPreferredSize(new Dimension(maxNameLength + 40 + iconCounter * 14, 80)); }</code><technical_language>I thinking this for a while, I this right fix for this. stacktrace in #7034 clear this NullPointerException occurs shutting a game, adjusting preffered size game is closed sense me. recommend making this method no-op if chat is null i.e. java if (chat == null) { return; } start if method</technical_language>

Target:
private void setDynamicPreferredSize() { if (chat == null) { return; } int maxNameLength = 0; final FontMetrics fontMetrics = this.getFontMetrics(UIManager.getFont("TextField.font")); for (final UserName onlinePlayer : chat.getOnlinePlayers()) { maxNameLength = Math.max(maxNameLength, fontMetrics.stringWidth(onlinePlayer.getValue())); } int iconCounter = 0; if (setCellRenderer instanceof PlayerChatRenderer) { iconCounter = ((PlayerChatRenderer) setCellRenderer).getMaxIconCounter(); } setPreferredSize(new Dimension(maxNameLength + 40 + iconCounter * 14, 80)); }
Source:
<code>public <V> Callable<V> wrap(Callable<V> command) { if (command == null) { return null; } <START> serverSpanThreadBinder.setCurrentSpan(null); <END> return () -> { if (serverSpan != null) { serverSpanThreadBinder.setCurrentSpan(serverSpan); } return command.call(); }; }</code><technical_language>that. this: final ServerSpan spanToUse = serverSpanThreadBinder.getCurrentSpan(); if (spanToUse == null) { spanToUse = serverSpan; } span for current thread affected anyhow. call wrap times want, span propagated wrapped runnables/callables. do think</technical_language>

Target:
public <V> Callable<V> wrap(Callable<V> command) { if (command == null) { return null; } final ServerSpan current = getCurrentServerSpan(); final ServerSpan serverSpan = getFromExchange(); return () -> { try { if (current == null) { serverSpanThreadBinder.setCurrentSpan(serverSpan); } return command.call(); } finally { serverSpanThreadBinder.setCurrentSpan(current); } }; }
Source:
<code>private void processTokens() { try { DataParser.Token token; while ((token = _parser.nextToken()) != null) { switch (token) { case START_OBJECT: validate(START_OBJECT); if (_currDataMapBuilder.inUse()) { _currDataMapBuilder = new DataMapBuilder(); } _currDataMapBuilder.setInUse(true); push(_currDataMapBuilder, false); break; case END_OBJECT: validate(END_OBJECT); pop(); break; case START_ARRAY: validate(START_ARRAY); push(new DataList(), true); break; case END_ARRAY: validate(END_ARRAY); pop(); break; case STRING: validate(STRING); if (!_isCurrList && _currField == null) { _currField = _parser.getString(); _expectedTokens = VALUE; } else { addValue(_parser.getString()); } break; <START> case INTEGER: <END> addValue(_parser.getIntValue()); break; case LONG: addValue(_parser.getLongValue()); break; case FLOAT: addValue(_parser.getFloatValue()); break; case DOUBLE: addValue(_parser.getDoubleValue()); break; case BOOL_TRUE: validate(BOOL_TRUE); addValue(Boolean.TRUE); break; case BOOL_FALSE: validate(BOOL_FALSE); addValue(Boolean.FALSE); break; case NULL: validate(NULL); addValue(Data.NULL); break; case NOT_AVAILABLE: readNextChunk(); return; default: handleException(new Exception("Unexpected token " + token + " from data parser")); } } } catch (IOException e) { handleException(e); } }</code><technical_language>is validate missing for these? I this simplified calling validate(token) switch statement mapping parsers underlying token DataParser.Token is done</technical_language>

Target:
private void processTokens() { try { NonBlockingDataParser.Token token; while ((token = _parser.nextToken()) != EOF_INPUT) { validate(token); switch (token) { case START_OBJECT: push(createDataObject(_parser), false); break; case START_ARRAY: push(createDataList(_parser), true); break; case END_OBJECT: case END_ARRAY: pop(); break; case STRING: if (!_isCurrList && _currField == null) { _currField = _parser.getString(); _expectedTokens = VALUE; } else { addValue(_parser.getString()); } break; case RAW_BYTES: addValue(_parser.getRawBytes()); break; case INTEGER: addValue(_parser.getIntValue()); break; case LONG: addValue(_parser.getLongValue()); break; case FLOAT: addValue(_parser.getFloatValue()); break; case DOUBLE: addValue(_parser.getDoubleValue()); break; case BOOL_TRUE: addValue(Boolean.TRUE); break; case BOOL_FALSE: addValue(Boolean.FALSE); break; case NULL: addValue(Data.NULL); break; case NOT_AVAILABLE: readNextChunk(); return; default: handleException(new Exception("Unexpected token " + token + " from data parser")); } } } catch (IOException e) { handleException(e); } }
Source:
<code>public IInformationControlCreator getHoverControlCreator() { return new AbstractReusableInformationControlCreator() { @Override protected IInformationControl doCreateInformationControl(Shell parent) { <START> return new DefaultInformationControl(parent, true); <END> } }; }</code><technical_language>'EditorsUI.getTooltipAffordanceString()' instead of 'true'? add label info F2 focus. Hover needs resizable focus gained</technical_language>

Target:
public IInformationControlCreator getHoverControlCreator() { return new AbstractReusableInformationControlCreator() { @Override protected IInformationControl doCreateInformationControl(Shell parent) { return new DefaultInformationControl(parent, EditorsUI.getTooltipAffordanceString()); } }; }
Source:
<code>private void checkPrivateMethodInvocations(CtModel model) { List<CtMethod<?>> methods = model.getElements(new TypeFilter<>(CtMethod.class)); methods.removeIf(v -> !v.isPrivate()); <START> methods.removeIf(v -> v.getSimpleName().matches("(readObject)|(readResolve)|(getTypeName)")); <END> List<CtInvocation<?>> methodInvocations = model.getElements(new TypeFilter<>(CtInvocation.class)); methodInvocations.removeIf(v -> v.getExecutable().getExecutableDeclaration() == null); List<CtExecutableReferenceExpression<?, ?>> executableReferences = model.getElements(new TypeFilter<>(CtExecutableReferenceExpression.class)); HashSet<CtExecutable<?>> lookUp = methodInvocations.stream() .map(CtInvocation::getExecutable) .map(v -> v.getExecutableDeclaration()) .collect(Collectors.toCollection(HashSet::new)); executableReferences.stream() .map(v -> v.getExecutable().getExecutableDeclaration()) .filter(Objects::nonNull) .forEach(lookUp::add); List<CtMethod<?>> methodsWithInvocation = methods.stream() .filter(method -> lookUp.contains(method)) .collect(Collectors.toList()); methods.removeAll(methodsWithInvocation); assertEquals("Some methods have no invocation", Collections.emptyList(), methods); }</code><technical_language>getTypeName removed</technical_language>

Target:
private void checkPrivateMethodInvocations(CtModel model) { List<CtMethod<?>> methods = model.getElements(new TypeFilter<>(CtMethod.class)); methods.removeIf(v -> !v.isPrivate()); methods.removeIf(v -> v.getSimpleName().matches("(readObject)|(readResolve)")); List<CtInvocation<?>> methodInvocations = model.getElements(new TypeFilter<>(CtInvocation.class)); methodInvocations.removeIf(v -> v.getExecutable().getExecutableDeclaration() == null); List<CtExecutableReferenceExpression<?, ?>> executableReferences = model.getElements(new TypeFilter<>(CtExecutableReferenceExpression.class)); HashSet<CtExecutable<?>> lookUp = methodInvocations.stream() .map(CtInvocation::getExecutable) .map(v -> v.getExecutableDeclaration()) .collect(Collectors.toCollection(HashSet::new)); executableReferences.stream() .map(v -> v.getExecutable().getExecutableDeclaration()) .filter(Objects::nonNull) .forEach(lookUp::add); List<CtMethod<?>> methodsWithInvocation = methods.stream() .filter(method -> lookUp.contains(method)) .collect(Collectors.toList()); methods.removeAll(methodsWithInvocation); assertEquals("Some methods have no invocation", Collections.emptyList(), methods); }
Source:
<code>private void addIcon(final ArtResource image, final int index) { if (image.getType() != ArtResourceType.ALPHA <START> || image.getType() != ArtResourceType.ADDITIVE_ALPHA <END> || image.getType() != ArtResourceType.SPRITE) { throw new UnsupportedOperationException("Not supported yet."); } addIcon(image.getName(), index); }</code><technical_language>I && operator</technical_language>

Target:
private void addIcon(final ArtResource image, final int index) { if (image.getType() != ArtResourceType.ALPHA && image.getType() != ArtResourceType.ADDITIVE_ALPHA && image.getType() != ArtResourceType.SPRITE) { throw new UnsupportedOperationException("Not supported yet."); } addIcon(image.getName(), index); }
Source:
<code><START> public long getLastExchangeFailureTimestamp() { <END> return 1573285945806L; }</code><technical_language>This a Date</technical_language>

Target:
public Date getLastExchangeFailureTimestamp() { return new Date((long)(EXPECTED_SECONDS * 1000)); }
Source:
<code><START> private void onCommentVote(final String resultMessage) { <END> Log.d(TAG, "output => " + resultMessage); }</code><technical_language>is purpose of this method</technical_language>

Target:
private void onCommentVote(final String resultMessage) { final Bundle data = getArguments(); data.putBoolean(FLAG_SHOW_LOADING, false); getLoaderManager().restartLoader(ID_LOADER_REFRESH_ARTICLE, data, this); }
Source:
<code>public void checkInitializingAfterFirstStarting() { projectExplorer.openItemByPath(PROJECT_NAME + "/Program.cs"); try { editor.waitMarkerInPosition(INFO, 1); editor.waitMarkerInPosition(INFO, 2); } catch (TimeoutException ex) { <START> fail("<LINK_0>"); <END> } }</code><technical_language>Error message is unclear</technical_language>

Target:
public void checkInitializingAfterFirstStarting() { projectExplorer.openItemByPath(PROJECT_NAME + "/Program.cs"); try { editor.waitMarkerInPosition(INFO, 1); editor.waitMarkerInPosition(INFO, 2); } catch (TimeoutException ex) { fail("Known issue: <LINK_0>", ex); } }
Source:
<code>public void stopped() { <START> HtmlFormEntryService hfes = Context.getService(HtmlFormEntryService.class); <END> if (hfes != null) hfes.getHandlers().remove("encounterProviderAndRole"); log.info("Stopped HTML Form Entry Module"); }</code><technical_language>This removed too, add handler moduleApplicationContext</technical_language>

Target:
public void stopped() { log.info("Stopped HTML Form Entry Module"); }
Source:
<code>protected Integer computeNext() { if (current >= 0) { int retval = current; <START> current -= 1; <END> return retval; } return endOfData(); }</code><technical_language>I understand prefer int retval = current--;, replace current -= 1 line current--;</technical_language>

Target:
protected Integer computeNext() { if (current >= 0) { int retval = current; current--; return retval; } return endOfData(); }
Source:
<code><START> public static ClientBuilder account(String account) throws MalformedURLException { <END> return new ClientBuilder(account); }</code><technical_language>this a MalformedURLException? Constructing a client account name a MalformedURLException, building URL name provided. IllegalArugmentException more in event Cloudant Account provided form a valid URL</technical_language>

Target:
public static ClientBuilder account(String account) { try { URL url = new URL(String.format("<LINK_0>", account)); return ClientBuilder.url(url); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not generate url from account name.", e); } }
Source:
<code>public void setReplicaDisabledState(ReplicaId replicaId, boolean disable) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } synchronized (helixAdministrationLock) { List<String> disabledReplicas = new ArrayList<>(getDisabledReplicas()); String partitionName = replicaId.getPartitionId().toPathString(); if (!disable && disabledReplicas.contains(partitionName)) { logger.info("Removing the partition from disabledReplicas list", partitionName); disabledReplicas.remove(partitionName); setDisabledReplicas(disabledReplicas); } else if (disable && !disabledReplicas.contains(partitionName)) { logger.info("Adding the partition to disabledReplicas list", partitionName); disabledReplicas.add(partitionName); setDisabledReplicas(disabledReplicas); } InstanceConfig instanceConfig = getInstanceConfig(); String resourceNameForPartition = getResourceNameOfPartition(helixAdmin, clusterName, partitionName); <START> instanceConfig.setInstanceEnabledForPartition(resourceNameForPartition, partitionName, !disable); <END> logger.info("Disabled state of partition is updated", partitionName); } }</code><technical_language>this method updates ZnRecord java object. Do need call HelixAdmin.setInstanceConfig done in setDisabledReplicas. Also, I wondering if need additional disabledReplicas field if HELIX_DISABLED_PARTITION? I missing something, hold set of information updated time</technical_language>

Target:
public void setReplicaDisabledState(ReplicaId replicaId, boolean disable) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } synchronized (helixAdministrationLock) { List<String> disabledReplicas = new ArrayList<>(getDisabledReplicas()); String partitionName = replicaId.getPartitionId().toPathString(); InstanceConfig instanceConfig = getInstanceConfig(); String resourceNameForPartition = getResourceNameOfPartition(helixAdmin, clusterName, partitionName); logger.info("{} replica on current node", disable ? "Disabling" : "Enabling", partitionName); instanceConfig.setInstanceEnabledForPartition(resourceNameForPartition, partitionName, !disable); if (!disable && disabledReplicas.contains(partitionName)) { logger.info("Removing the partition from disabledReplicas list", partitionName); disabledReplicas.remove(partitionName); } else if (disable && !disabledReplicas.contains(partitionName)) { logger.info("Adding the partition to disabledReplicas list", partitionName); disabledReplicas.add(partitionName); } logger.info("Setting InstanceConfig with list of disabled replicas: {}", disabledReplicas.toArray()); instanceConfig.getRecord().setListField(DISABLED_REPLICAS_STR, disabledReplicas); helixAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); logger.info("Disabled state of partition is updated", partitionName); } }
Source:
<code>public Object[] getChildren(Object o) { if (o instanceof IContainer) { IContainer container = (IContainer) o; if (!showLinkedResources && container.isLinked(IResource.CHECK_ANCESTORS)) { return <START> new Object[0]; <END> } IResource[] members = null; try { members = container.members(); } catch (CoreException e) { return new Object[0]; } ArrayList results = new ArrayList(); for (int i = 0; i < members.length; i++) { IResource resource = members[i]; if (!showLinkedResources && resource.isLinked()) { continue; } if ((resource.getType() & resourceType) > 0) { results.add(resource); } } return results.toArray(); } if (o instanceof ArrayList) { return ((ArrayList) o).toArray(); } return new Object[0]; }</code><technical_language>Extract a constant for new Object[0]</technical_language>

Target:
public Object[] getChildren(Object o) { if (o instanceof IContainer) { IContainer container = (IContainer) o; if (!showLinkedResources && container.isLinked(IResource.CHECK_ANCESTORS)) { return EMPTY; } IResource[] members = null; try { members = container.members(); } catch (CoreException e) { return EMPTY; } List<IResource> results = new ArrayList<>(); for (int i = 0; i < members.length; i++) { IResource resource = members[i]; if (!showLinkedResources && resource.isLinked()) { continue; } if ((resource.getType() & resourceType) > 0) { results.add(resource); } } return results.toArray(); } if (o instanceof ArrayList) { return ((List<?>) o).toArray(); } return EMPTY; }
Source:
<code>public void onOffline(@Nonnull final Computer c, @CheckForNull OfflineCause cause) { <START> if (Boolean.getBoolean(SupportPlugin.class.getName() + ".generateOnOfflineNode")) { <END> Timer.get().schedule(new java.util.concurrent.Callable<Void>() { @Override public Void call() throws Exception { boolean locked = false; try { locked = lock.tryLock(); if (locked) { PeriodicWork.all().get(PeriodicWorkImpl.class).doRun(); Logger.getLogger(SupportPlugin.class.getName()) .log(Level.INFO, "Node: " + c.getDisplayName() + " went offline. A new support bundle" + " was generated. Please check: " + SupportPlugin.getRootDirectory().getAbsolutePath() + " at this time."); } } catch (Exception e) { Logger.getLogger(SupportPlugin.class.getName()) .log(Level.WARNING, "Error when generating support bundle while on offline node", e); } finally { if (locked) lock.unlock(); } return null; } }, 1, TimeUnit.MINUTES); } }</code><technical_language>sense generate bundles is null RestartCause (which means termination is abnormal). <LINK_0> . RestartCause produce flood Jenkins performs restart. Kinda</technical_language>

Target:
public void onOffline(@Nonnull final Computer c, @CheckForNull OfflineCause cause) { if (Boolean.getBoolean(SupportPlugin.class.getName() + ".generateOnOfflineNode") && cause != null && !cause.getClass().getName().contains("RestartCause")) { Timer.get().schedule(new java.util.concurrent.Callable<Void>() { @Override public Void call() throws Exception { boolean locked = false; try { locked = lock.tryLock(); if (locked) { PeriodicWork.all().get(PeriodicWorkImpl.class).doRun(); Logger.getLogger(SupportPlugin.class.getName()) .log(Level.INFO, "Node: " + c.getDisplayName() + " went offline. A new support bundle" + " was generated. Please check: " + SupportPlugin.getRootDirectory().getAbsolutePath() + " at this time."); } } catch (Exception e) { Logger.getLogger(SupportPlugin.class.getName()) .log(Level.WARNING, "Error when generating support bundle while on offline node", e); } finally { if (locked) lock.unlock(); } return null; } }, 1, TimeUnit.MINUTES); } }
Source:
<code>protected AuditLogType getAuditLogForMigrationFailure() { if (getVds().getStatus() == VDSStatus.PreparingForMaintenance) { return getDestinationVds() != null ? AuditLogType.VM_MIGRATION_FAILED_DURING_MOVE_TO_MAINTENANCE : AuditLogType.VM_MIGRATION_FAILED_DURING_MOVE_TO_MAINTENANCE_SINCE_NO_VDS_TO_MIGRATE_TO; } else { if (getDestinationVds() == null) { auditLogDirector.log(this, AuditLogType.VM_MIGRATION_NO_VDS_TO_MIGRATE_TO); } return AuditLogType.VM_MIGRATION_FAILED; } <START> } <END></code><technical_language>a matter of styling really, return if-block, avoid else-block (less indentation level is supposed code more readable)</technical_language>

Target:
protected AuditLogType getAuditLogForMigrationFailure() { if (getDestinationVds() == null) { auditLogDirector.log(this, AuditLogType.VM_MIGRATION_NO_VDS_TO_MIGRATE_TO); } if (getVds().getStatus() == VDSStatus.PreparingForMaintenance) { return getDestinationVds() != null ? AuditLogType.VM_MIGRATION_FAILED_DURING_MOVE_TO_MAINTENANCE : AuditLogType.VM_MIGRATION_FAILED_DURING_MOVE_TO_MAINTENANCE_NO_DESTINATION_VDS; } return AuditLogType.VM_MIGRATION_FAILED; }
Source:
<code>public Builder hostname(final String hostname) { <START> if (hostname != null && !hostname.isEmpty()) { <END> this.hostname = hostname; } return this; }</code><technical_language>This means .hostname("").hostname("wonka") .hostname("wonka").hostname("") result in hostname "wonka" ? inconsistent. is this needed</technical_language>

Target:
public Builder hostname(final String hostname) { this.hostname = hostname; return this; }
Source:
<code>public Map<String, Integer> getStats() { int in = 0; int out = 0; for (Connection conn : connections.values()) { if (conn.direction == Connection.Direction.OUT) { out++; } else { in++; } } <START> Map<String, Integer> result = new HashMap<>(2); <END> result.put("connections.in", in); result.put("connections.out", out); return result; }</code><technical_language>Unfortunately, passing 2 constructor allow map hold 2 entries re-sizing (have account for load factor, is 0.75 default). like: public static int hashMapCapacity(int size) { return (size * 4 + 2) / 3; } // for load factor of 0.75 ... new HashMap(hashMapCapacity(2), 0.75f);</technical_language>

Target:
public Map<String, Integer> getStats() { int in = 0; int out = 0; for (Connection conn : connections.values()) { if (conn.direction == Connection.Direction.OUT) { out++; } else { in++; } } Map<String, Integer> result = new HashMap<>(3); result.put("connections.in", in); result.put("connections.out", out); return result; }
Source:
<code>private TurnType attachTurnLanesData(boolean leftSide, RouteSegmentResult prevSegm, TurnType t) { <START> int lanes = prevSegm.getObject().getLanes(); <END> String turnLanes = getTurnLanesString(prevSegm); if (turnLanes == null) { return t; } String[] splitLaneOptions = turnLanes.split("\\|", -1); if (splitLaneOptions.length != lanes) { return t; } if (t.getLanes().length != lanes) { return t; } assignTurns(splitLaneOptions, t); return t; }</code><technical_language>is qute confusing return 't' before. I suggest for return type void put "return;"</technical_language>

Target:
private void attachTurnLanesData(boolean leftSide, RouteSegmentResult prevSegm, TurnType t) { int lanes = prevSegm.getObject().getLanes(); String turnLanes = getTurnLanesString(prevSegm); if (turnLanes == null) { return; } String[] splitLaneOptions = turnLanes.split("\\|", -1); if (splitLaneOptions.length != lanes) { return; } if (t.getLanes().length != lanes) { return; } assignTurns(splitLaneOptions, t); }
Source:
<code><START> private static boolean isXterm() { <END> String term = System.getenv("TERM"); return term != null && term.equals("xterm"); }</code><technical_language>this is example a good change: yes, implementation, this method renamed! +1</technical_language>

Target:
private static boolean isXterm() { return "xterm".equals(System.getenv("TERM")); }
Source:
<code>public TopicThreads call() throws Exception { try { if (courseId != null) { int pageSize = pagination.pageSize(); int page = pagination.numOfPagesLoaded() + 1; return environment.getDiscussionAPI().getThreadList(courseId, topicIds, filter.getQueryParamValue(), orderBy.getQueryParamValue(), pageSize, page); } } catch (Exception ex) { <START> handle(ex); <END> logger.error(ex, true); } return null; }</code><technical_language>Instead of catching generic Exception, RetroHttpException caught here. I other exception thrown in this block. logic refactored in Task some point automatically calls handle() onException(), I guess leave for now</technical_language>

Target:
public TopicThreads call() throws Exception { try { if (courseId != null) { int pageSize = pagination.pageSize(); int page = pagination.numOfPagesLoaded() + 1; return environment.getDiscussionAPI().getThreadList(courseId, topicIds, filter.getQueryParamValue(), orderBy.getQueryParamValue(), pageSize, page); } } catch (RetroHttpException ex) { handle(ex); logger.error(ex, true); } return null; }
Source:
<code>protected int getDefaultPort() { <START> return JigasiBundleActivator.getConfigurationService().getInt( <END> P_NAME_TRANSCRIPT_PORT, TRANSCRIPT_PORT_DEFAULT_VALUE); }</code><technical_language>return -1 (and in getDefaultTlsPort), AbstractJettyBundleActivator pick configuration if is set: <LINK_0></technical_language>

Target:
protected int getDefaultPort() { return -1; }
Source:
<code>public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { if (delegate instanceof X509ExtendedTrustManager) { <START> ((X509ExtendedTrustManager)delegate).checkClientTrusted(chain, authType, socket); <END> } else { throw new UnsupportedOperationException(); } verifier.checkChain(chain); }</code><technical_language>IMHO copy-paste bug - checkServerTrusted instead</technical_language>

Target:
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { if (delegate instanceof X509ExtendedTrustManager) { ((X509ExtendedTrustManager)delegate).checkServerTrusted(chain, authType, socket); } else { throw new UnsupportedOperationException(); } verifier.checkChain(chain); }
Source:
<code>public void testStartsInLegacySpecifiedDirectory() { String dir1 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); String dir2 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); shutdown(); LocalManagementContext mgmt = new LocalManagementContext(); ((BrooklynProperties)mgmt.getConfig()).put("brooklyn.dirs.install", dir1); ((BrooklynProperties)mgmt.getConfig()).put("brooklyn.dirs.run", dir2); app = ApplicationBuilder.newManagedApp(TestApplication.class, mgmt); app.setConfig(BrooklynConfigKeys.RUN_DIR, dir2); doTestSpecifiedDirectory(dir1, dir2); <START> Os.tryDeleteDirectory(dir1); <END> Os.tryDeleteDirectory(dir2); }</code><technical_language>do tryDeleteDirectory in a finally block, in case test fails</technical_language>

Target:
public void testStartsInLegacySpecifiedDirectory() { String dir1 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); String dir2 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); shutdown(); LocalManagementContext mgmt = new LocalManagementContext(); mgmt.getBrooklynProperties().put("brooklyn.dirs.install", dir1); mgmt.getBrooklynProperties().put("brooklyn.dirs.run", dir2); app = ApplicationBuilder.newManagedApp(TestApplication.class, mgmt); app.setConfig(BrooklynConfigKeys.RUN_DIR, dir2); doTestSpecifiedDirectory(dir1, dir2); Os.tryDeleteDirectory(dir1); Os.tryDeleteDirectory(dir2); }
Source:
<code>private static Workpiece readWorkpiece(FileManagementInterface fileManagement, URI metsFileUri, LockResult lockResult) throws IOException { <START> try (InputStream in = fileManagement.read(metsFileUri, lockResult)) { <END> return createMetsXmlElementAccess().read(in, (uri, unusedBecauseAccessIsReadOnly) -> { try { Map<URI, LockingMode> requested = new HashMap<>(2); requested.put(uri, LockingMode.IMMUTABLE_READ); Map<URI, Collection<String>> conflicts = lockResult.tryLock(requested); if (conflicts.isEmpty()) { return fileManagement.read(uri, lockResult); } else { throw new IOException(createLockErrorMessage(uri, conflicts)); } } catch (IOException e) { throw new UncheckedIOException(e); } }); } }</code><technical_language>please change variable name "inputStream"</technical_language>

Target:
private static Workpiece readWorkpiece(FileManagementInterface fileManagement, URI metsFileUri, LockResult lockResult) throws IOException { try (InputStream inputStream = fileManagement.read(metsFileUri, lockResult)) { Workpiece result = createMetsXmlElementAccess().read(inputStream, (uri, unusedBecauseAccessIsReadOnly) -> { try { Map<URI, LockingMode> requested = new HashMap<>(2); requested.put(uri, LockingMode.IMMUTABLE_READ); Map<URI, Collection<String>> conflicts = lockResult.tryLock(requested); if (conflicts.isEmpty()) { return fileManagement.read(uri, lockResult); } else { throw new IOException(createLockErrorMessage(uri, conflicts)); } } catch (IOException e) { throw new UncheckedIOException(e); } }); return result; } }
Source:
<code>protected void checkGLevelMD( final PreparedVerifier verifier ) { final Content content = getNexusClient().getSubsystem( Content.class ); final File target = util.createTempFile(); FileInputStream fis = null; try { content.download( Location.repositoryLocation( getTargetedRepositoryId(), "/" + getClass().getPackage().getName().replaceAll( "\\.", "/" ) + "/maven-metadata.xml" ), target ); fis = new FileInputStream( target ); final Metadata md = new MetadataXpp3Reader().read( fis ); assertThat( md.getPlugins(), not( empty() ) ); for ( Plugin plugin : md.getPlugins() ) { if ( StringUtils.equals( plugin.getArtifactId(), verifier.getProjectArtifactId() ) && StringUtils.equals( plugin.getPrefix(), verifier.getProjectArtifactId() ) ) { return; } } throw new AssertionError( "The maven-plugin with artifact ID " + verifier.getProjectArtifactId() + " should be contained in this Plugin list: " + Lists.transform( md.getPlugins(), new Function<Plugin, String>() { @Override public String apply( @Nullable Plugin input ) { <START> return input.getArtifactId(); <END> } } ) ); } catch ( XmlPullParserException e ) { throw new AssertionError( "The metadata parse failed: " + e.getMessage() ); } catch ( IOException e ) { throw new AssertionError( "The metadata download failed: " + e.getMessage() ); } finally { IOUtil.close( fis ); } }</code><technical_language>If is @Nullable need handle null case</technical_language>

Target:
protected void checkGLevelMD( final PreparedVerifier verifier ) { final Content content = getNexusClient().getSubsystem( Content.class ); final File target = util.createTempFile(); FileInputStream fis = null; try { content.download( Location.repositoryLocation( getTargetedRepositoryId(), "/" + getClass().getPackage().getName().replaceAll( "\\.", "/" ) + "/maven-metadata.xml" ), target ); fis = new FileInputStream( target ); final Metadata md = new MetadataXpp3Reader().read( fis ); assertThat( md.getPlugins(), not( empty() ) ); for ( Plugin plugin : md.getPlugins() ) { if ( StringUtils.equals( plugin.getArtifactId(), verifier.getProjectArtifactId() ) && StringUtils.equals( plugin.getPrefix(), verifier.getProjectArtifactId() ) ) { return; } } throw new AssertionError( "The maven-plugin with artifact ID " + verifier.getProjectArtifactId() + " should be contained in this Plugin list: " + Lists.transform( md.getPlugins(), new Function<Plugin, String>() { @Override public String apply( Plugin input ) { if ( null == input ) { return "invalid-plugin-null-value"; } return input.getArtifactId(); } } ) ); } catch ( XmlPullParserException e ) { throw new AssertionError( "The metadata parse failed: " + e.getMessage() ); } catch ( IOException e ) { throw new AssertionError( "The metadata download failed: " + e.getMessage() ); } finally { IOUtil.close( fis ); } }
Source:
<code>private DeclaredType getProviderInterface(AnnotationMirror providerAnnotation) { <START> Map<? extends ExecutableElement, ? extends AnnotationValue> values = <END> providerAnnotation.getElementValues(); log("annotation values: " + values); AnnotationValue value = values.values().iterator().next(); return (DeclaredType) value.getValue(); }</code><technical_language>values->valuesIndex. values.values() is cute, slightly confusing read</technical_language>

Target:
private DeclaredType getProviderInterface(AnnotationMirror providerAnnotation) { Map<? extends ExecutableElement, ? extends AnnotationValue> valueIndex = providerAnnotation.getElementValues(); log("annotation values: " + valueIndex); AnnotationValue value = valueIndex.values().iterator().next(); return (DeclaredType) value.getValue(); }
Source:
<code>private void copyOriginalURL() { ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData urlClipData = ClipData.newPlainText("article URL", articleUrl); clipboardManager.setPrimaryClip(urlClipData); <START> Toast toast = new Toast(this); <END> toast.makeText(this, R.string.txtUrlCopied, Toast.LENGTH_SHORT).show(); }</code><technical_language>need for this. Toast.makeText(). Other ok me</technical_language>

Target:
private void copyOriginalURL() { ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData urlClipData = ClipData.newPlainText("article URL", articleUrl); clipboardManager.setPrimaryClip(urlClipData); Toast.makeText(this, R.string.txtUrlCopied, Toast.LENGTH_SHORT).show(); }
Source:
<code><START> private static List<EObject> getSupersetReferences(EReference reference) { <END> EAnnotation annotation = Iterables.find(reference.getEAnnotations(), new Predicate<EAnnotation>() { public boolean apply(EAnnotation input) { return input.getSource().equals(UMLUtilForCompare.getAnnotationSubsetsID()); } }, null); if (annotation != null) { return annotation.getReferences(); } return Lists.newArrayList(); }</code><technical_language>Properly type returned iterable if is meant EReferences</technical_language>

Target:
private static Iterable<EReference> getSupersetReferences(EReference reference) { EAnnotation subsetsAnnotation = Iterables.find(reference.getEAnnotations(), UMLUtilForCompare .isSubsetsAnnotation(), null); if (subsetsAnnotation != null) { return Iterables.filter(subsetsAnnotation.getReferences(), EReference.class); } return Collections.emptyList(); }
Source:
<code><START> public MultiDataSet next() { <END> if (minibatchCount < terminationPoint) { minibatchCount++; return underlyingIterator.next(); } else { throw new RuntimeException("Calls to next have exceeded termination point."); } }</code><technical_language>Answered raver</technical_language>

Target:
public MultiDataSet next() { if (minibatchCount < terminationPoint) { minibatchCount++; return underlyingIterator.next(); } else { throw new RuntimeException("Calls to next have exceeded the allotted number of minibatches."); } }
Source:
<code>public void resetPassword_shouldResetUserPasswordIfActivationKeyIsCorrect() throws Exception { <START> User u = new User(); <END> u.setPerson(new Person()); u.addName(new PersonName("Benjamin", "A", "Wolfe")); u.setUsername("bwolfe"); u.getPerson().setGender("M"); User createdUser = userService.createUser(u, "Openmr5xy"); String key = "h4ph0fpNzQCIPSw8plJI"; int validTime = 10 * 60 * 1000; Long tokenTime = System.currentTimeMillis() + validTime; LoginCredential credentials = dao.getLoginCredential(createdUser); credentials .setActivationKey("b071c88d6d877922e35af2e6a90dd57d37ac61143a03bb986c5f353566f3972a86ce9b2604c31a22dfa467922dcfd54fa7d18b0a7c7648d94ca3d97a88ea2fd0:" + tokenTime); dao.updateLoginCredential(credentials); String newPassword = "newPasswordString123"; MockHttpServletResponse response = handle(newPostRequest(RESET_PASSWORD_URI + "/" + key, "{\"newPassword\":\"" + newPassword + "\"}")); assertEquals(200, response.getStatus()); }</code><technical_language>existing user</technical_language>

Target:
public void resetPassword_shouldResetUserPasswordIfActivationKeyIsCorrect() throws Exception { User user = userService.getUserByUuid("c98a1558-e131-11de-babe-001e378eb67e"); String key = "h4ph0fpNzQCIPSw8plJI"; int validTime = 10 * 60 * 1000; Long tokenTime = System.currentTimeMillis() + validTime; LoginCredential credentials = dao.getLoginCredential(user); credentials .setActivationKey("b071c88d6d877922e35af2e6a90dd57d37ac61143a03bb986c5f353566f3972a86ce9b2604c31a22dfa467922dcfd54fa7d18b0a7c7648d94ca3d97a88ea2fd0:" + tokenTime); dao.updateLoginCredential(credentials); String newPassword = "newPasswordString123"; MockHttpServletResponse response = handle(newPostRequest(RESET_PASSWORD_URI + "/" + key, "{\"newPassword\":\"" + newPassword + "\"}")); assertEquals(200, response.getStatus()); Context.authenticate(user.getUsername(), newPassword); }