auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean performOperation(final IComment comment) { final IReviewItem item = reviewitem; final AtomicReference<IStatus> result = new AtomicReference<IStatus>(); if (isSave == true || isDiscard == true) { final Job job = new Job(Messages.CommandServerOperation) { @Override protected IStatus run(IProgressMonitor monitor) { IStatus status = null; <START> if (isSave == true) { <END> status = reviewBehavior.addComment(item, comment, monitor); if (status.isOK()) { result.set(status); updateClient(comment, item); return Status.OK_STATUS; } } else if (isDiscard == true) { status = reviewBehavior.discardComment(item, comment, monitor); if (status.isOK()) { result.set(status); updateClient(comment, item); return Status.OK_STATUS; } } processServerError(status.getException().getCause().toString()); return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } return true; }</code><technical_language>"if (isSave)" enough</technical_language>

Target:
private boolean performOperation(final IComment comment) { final IReviewItem item = reviewitem; final AtomicReference<IStatus> result = new AtomicReference<IStatus>(); if (isSave || isDiscard) { final Job job = new Job(Messages.CommandServerOperation) { @Override protected IStatus run(IProgressMonitor monitor) { IStatus status = null; if (isSave) { status = reviewBehavior.addComment(item, comment, monitor); if (status.isOK()) { result.set(status); updateClient(comment, item); return Status.OK_STATUS; } } else if (isDiscard) { status = reviewBehavior.discardComment(item, comment, monitor); if (status.isOK()) { result.set(status); updateClient(comment, item); return Status.OK_STATUS; } } processServerError(status.getException().getCause().toString()); return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } return true; }
Source:
<code>public ClusterSpectator getClusterSpectator(CloudConfig cloudConfig, ClusterMapConfig clusterMapConfig) { <START> return new VcrHelixClusterSpectator(cloudConfig, clusterMapConfig); <END> }</code><technical_language>Name inconsistency: HelixClusterSpectatorFactory create HelixClusterSpectator</technical_language>

Target:
public ClusterSpectator getClusterSpectator(CloudConfig cloudConfig, ClusterMapConfig clusterMapConfig) { return new HelixClusterSpectator(cloudConfig, clusterMapConfig); }
Source:
<code>public void dispose() { Iterator<AbstractAttributeEditor> editorIterator = editors.iterator(); while (editorIterator.hasNext()) { AbstractAttributeEditor editor = editorIterator.next(); <START> editor.getControl().dispose(); <END> editorIterator.remove(); } }</code><technical_language>I undeprecate AbstractAttributeEditor.dispose dispose control labelControl. call dispose here</technical_language>

Target:
public void dispose() { Iterator<AbstractAttributeEditor> editorIterator = editors.iterator(); while (editorIterator.hasNext()) { AbstractAttributeEditor editor = editorIterator.next(); editor.dispose(); } }
Source:
<code>private static String truncateText(String text, int length, int lastWordAllowance) { if (length < 0) { throw new IndexOutOfBoundsException(); } if (text == null || text.length() <= length) { return text; } String truncated; if (length < text.length()) { truncated = text.substring(0, length); } else { truncated = text; } if (truncated.length() > lastWordAllowance * LAST_WORD_ALLOWANCE_MIN_LENGTH_FACTOR) { String[] parts = truncated.split("\\b(?=\\w*$)"); if (parts.length > 1) { <START> int lastBoundryIndex = parts[0].length(); <END> if (truncated.length() - lastBoundryIndex < lastWordAllowance) { truncated = parts[0].trim(); } } } return truncated; }</code><technical_language>"boundaryIndex"</technical_language>

Target:
private static String truncateText(String text, int length, int lastWordAllowance) { if (length < 0) { throw new IndexOutOfBoundsException(); } if (text == null || text.length() <= length) { return text; } String truncated; if (length < text.length()) { truncated = text.substring(0, length); } else { truncated = text; } if (truncated.length() > lastWordAllowance * LAST_WORD_ALLOWANCE_MIN_LENGTH_FACTOR) { String[] parts = truncated.split("\\b(?=\\w*$)"); if (parts.length > 1) { int lastBoundaryIndex = parts[0].length(); if (truncated.length() - lastBoundaryIndex < lastWordAllowance) { truncated = parts[0].trim(); } } } return truncated; }
Source:
<code>private void visitClassOrInterface(String name, FunctionType ftype) { final boolean emitInstance = !ftype.isInterface(); if (emitInstance) { emit("class"); emit(name); visitTemplateTypes(ftype); emit("extends"); emit(name + INSTANCE_CLASS_SUFFIX); visitTemplateTypes(ftype); emit("{"); indent(); emitBreak(); visitProperties(ftype, true); unindent(); emit("}"); emitBreak(); } if (ftype.isConstructor()) { emit("class"); } else if (ftype.isInterface()) { emit("interface"); } else { checkState(false, "Unexpected function type " + ftype); } emit(emitInstance ? name + INSTANCE_CLASS_SUFFIX : name); visitTemplateTypes(ftype); if (ftype.getExtendedInterfacesCount() > 0) { emit("extends"); Iterator<ObjectType> it = ftype.getExtendedInterfaces().iterator(); emitCommaSeparatedInterfaces(it); } ObjectType superType = getSuperType(ftype); if (superType != null) { emit("extends"); if (isPrivate(superType.getJSDocInfo())) { emit(Constants.INTERNAL_NAMESPACE + ".PrivateClass"); } else { <START> boolean emitInstanceForObject = emitInstance && <END> (opts.allowPlatformExterns || !isDefinedInPlatformExterns(superType)); Visitor<Void> visitor = new ExtendsImplementsTypeVisitor(emitInstanceForObject); superType.visit(visitor); } } Iterator<ObjectType> it = ftype.getOwnImplementedInterfaces().iterator(); if (it.hasNext()) { emit("implements"); emitCommaSeparatedInterfaces(it); } boolean implementsIArrayLike = any(ftype.getAllImplementedInterfaces(), IS_IARRYLIKE); visitObjectType(ftype, ftype.getPrototype(), implementsIArrayLike || ftype.isDict()); }</code><technical_language>whitespace is a bit</technical_language>

Target:
private void visitClassOrInterface(String name, FunctionType ftype) { final boolean emitInstance = !ftype.isInterface(); if (emitInstance) { emit("class"); emit(name); visitTemplateTypes(ftype); emit("extends"); emit(name + INSTANCE_CLASS_SUFFIX); visitTemplateTypes(ftype); emit("{"); indent(); emitBreak(); visitProperties(ftype, true); unindent(); emit("}"); emitBreak(); } if (ftype.isConstructor()) { emit("class"); } else if (ftype.isInterface()) { emit("interface"); } else { checkState(false, "Unexpected function type " + ftype); } emit(emitInstance ? name + INSTANCE_CLASS_SUFFIX : name); visitTemplateTypes(ftype); if (ftype.getExtendedInterfacesCount() > 0) { emit("extends"); Iterator<ObjectType> it = ftype.getExtendedInterfaces().iterator(); emitCommaSeparatedInterfaces(it); } ObjectType superType = getSuperType(ftype); if (superType != null) { emit("extends"); if (isPrivate(superType.getJSDocInfo())) { emit(Constants.INTERNAL_NAMESPACE + ".PrivateClass"); } else { boolean emitInstanceForObject = emitInstance && (opts.emitPlatformExterns || !isDefinedInPlatformExterns(superType)); Visitor<Void> visitor = new ExtendsImplementsTypeVisitor(emitInstanceForObject); superType.visit(visitor); } } Iterator<ObjectType> it = ftype.getOwnImplementedInterfaces().iterator(); if (it.hasNext()) { emit("implements"); emitCommaSeparatedInterfaces(it); } boolean implementsIArrayLike = any(ftype.getAllImplementedInterfaces(), IS_IARRYLIKE); visitObjectType(ftype, ftype.getPrototype(), implementsIArrayLike || ftype.isDict()); }
Source:
<code>private void updateHoverBehavior() { SourceViewerConfiguration configuration = getSourceViewerConfiguration(); String[] types = configuration.getConfiguredContentTypes(getSourceViewer()); for (int i = 0; i < types.length; i++) { String t = types[i]; ISourceViewer sourceViewer = getSourceViewer(); <START> if (sourceViewer == null) { <END> return; } if (sourceViewer instanceof ITextViewerExtension2) { ((ITextViewerExtension2) sourceViewer).removeTextHovers(t); int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); if (stateMasks != null) { for (int j = 0; j < stateMasks.length; j++) { int stateMask = stateMasks[j]; ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover = configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else { sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } }</code><technical_language>I this this method, this for loop</technical_language>

Target:
private void updateHoverBehavior() { ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer == null) { return; } SourceViewerConfiguration configuration = getSourceViewerConfiguration(); String[] types = configuration.getConfiguredContentTypes(getSourceViewer()); for (int i = 0; i < types.length; i++) { String t = types[i]; if (sourceViewer instanceof ITextViewerExtension2) { ((ITextViewerExtension2) sourceViewer).removeTextHovers(t); int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); if (stateMasks != null) { for (int j = 0; j < stateMasks.length; j++) { int stateMask = stateMasks[j]; ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover = configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else { sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } }
Source:
<code>private static <T> T writeAtomically(final File file, final File tmpDir, OutputStreamConsumer<T> f) throws IOException { final File tmpFile = new File(tmpDir, StringUtils.format(".%s.%s", file.getName(), UUID.randomUUID())); try { final T retVal; <START> try (final FileOutputStream out = new FileOutputStream(tmpFile)) { <END> retVal = f.apply(uncloseable(out)); out.flush(); out.getChannel().force(true); } java.nio.file.Files.move( tmpFile.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING ); try (final FileChannel directory = FileChannel.open(file.getParentFile().toPath(), StandardOpenOption.READ)) { directory.force(true); } return retVal; } finally { if (tmpFile.exists()) { if (!tmpFile.delete()) { log.warn("Could not delete tmpFile[%s]", tmpFile); } } } }</code><technical_language>Please FileChannel.open(...) Channels.newOutputStream()</technical_language>

Target:
private static <T> T writeAtomically(final File file, final File tmpDir, OutputStreamConsumer<T> f) throws IOException { final File tmpFile = new File(tmpDir, StringUtils.format(".%s.%s", file.getName(), UUID.randomUUID())); try (final Closeable deleter = () -> java.nio.file.Files.deleteIfExists(tmpFile.toPath())) { final T retVal; try ( final FileChannel fileChannel = FileChannel.open( tmpFile.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW ); final OutputStream out = Channels.newOutputStream(fileChannel) ) { retVal = f.apply(uncloseable(out)); fileChannel.force(true); } java.nio.file.Files.move( tmpFile.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING ); try (final FileChannel directory = FileChannel.open(file.getParentFile().toPath(), StandardOpenOption.READ)) { directory.force(true); } return retVal; } }
Source:
<code>public OAuth2RequestAuthenticator(ClientCredentials<OAuth2AccessToken> clientCredentials) { <START> this.clientCredentials = clientCredentials; <END> }</code><technical_language>If client credentials is managed method below, do need pass constructor? Removing this resolve question I</technical_language>

Target:
public OAuth2RequestAuthenticator(ClientCredentials<OAuth2AccessToken> clientCredentials) { Assert.notNull(clientCredentials, "clientCredentials may not be null"); this.clientCredentials = clientCredentials; }
Source:
<code>public CRAMFileReader(final File cramFile, final InputStream inputStream, final CRAMReferenceSource referenceSource) { if (cramFile == null && inputStream == null) { throw new IllegalArgumentException("Either file or input stream is required."); } if (referenceSource == null) { throw new IllegalArgumentException("A reference is required for CRAM readers"); } this.cramFile = cramFile; this.inputStream = inputStream; this.referenceSource = referenceSource; <START> if (cramFile != null) initIndexFile(null); <END> getIterator(); }</code><technical_language>initIndexFile is called in middle of constructors, I static (you'll pass in cramFile well) return updated indexFile, constructors initialize member variable. rename (maybe "findIndexForFile" ?)</technical_language>

Target:
public CRAMFileReader(final File cramFile, final InputStream inputStream, final CRAMReferenceSource referenceSource) { if (cramFile == null && inputStream == null) { throw new IllegalArgumentException("Either file or input stream is required."); } if (referenceSource == null) { throw new IllegalArgumentException("A reference is required for CRAM readers"); } this.cramFile = cramFile; this.inputStream = inputStream; this.referenceSource = referenceSource; if (cramFile != null) { mIndexFile = findIndexForFile(null, cramFile); } getIterator(); }
Source:
<code>private boolean isWordWrapPreferenceAllowed() { return <START> Boolean.getBoolean("eclipse.workaround.bug488162"); <END> }</code><technical_language>I a "negative" name, e.g. "eclipse.show.wrapByDefaultPreference"</technical_language>

Target:
private boolean isWordWrapPreferenceAllowed() { return Boolean.getBoolean("eclipse.show.wrapByDefaultPreference"); }
Source:
<code>public static RepositoryMapping getMapping(final IResource resource) { if (isNonWorkspace(resource)) return null; if (resource.isLinked(IResource.CHECK_ANCESTORS)) <START> return getMapping(resource.getRawLocation()); <END> IProject project = resource.getProject(); if (project == null) return null; final RepositoryProvider rp = RepositoryProvider.getProvider(project); if (!(rp instanceof GitProvider)) return null; if (((GitProvider)rp).getData() == null) return null; return ((GitProvider)rp).getData().getRepositoryMapping(resource); }</code><technical_language>getRawLocation getLocation here</technical_language>

Target:
public static RepositoryMapping getMapping(final IResource resource) { if (isNonWorkspace(resource)) return null; if (resource.isLinked(IResource.CHECK_ANCESTORS)) return getMapping(resource.getLocation()); IProject project = resource.getProject(); if (project == null) return null; final RepositoryProvider rp = RepositoryProvider.getProvider(project); if (!(rp instanceof GitProvider)) return null; if (((GitProvider)rp).getData() == null) return null; return ((GitProvider)rp).getData().getRepositoryMapping(resource); }
Source:
<code>private IVersionedApiResource endpointFor(String version, String kind) { String[] split = StringUtils.isBlank(version) ? new String[] : version.split(FWD_SLASH); Optional<? extends IVersionedApiResource> result = null; if (split.length <= 1) { <START> result = resourceEndpoints.stream().filter(e -> { <END> return e.getName().equals(ResourceKind.pluralize(kind, true, true)) && (split.length == 0 || e.getVersion().equals(split[split.length - 1])) && (split.length < 2 || e.getApiGroupName().equals(split[0])); }).findFirst(); } else { result = Optional.of(formatEndpointFor(API_GROUPS_API, version, kind)); } if (result.isPresent()) { int index = resourceEndpoints.indexOf(result.get()); if (index > -1) { return resourceEndpoints.get(index); } } return null; }</code><technical_language>replaced a simpler lambda: .filter(e -> e.getName().equals(ResourceKind.pluralize(kind, true, true)) && (split.length == 0 || e.getVersion().equals(split[split.length - 1])) && (split.length < 2 || e.getApiGroupName().equals(split[0])) ) lambda is difficult understand. extract this lambda method a speaking name</technical_language>

Target:
private IVersionedApiResource endpointFor(String version, String kind) { String[] split = StringUtils.isBlank(version) ? new String[] : version.split(FWD_SLASH); Optional<? extends IVersionedApiResource> result = null; if (split.length <= 1) { result = resourceEndpoints.stream().filter(e -> isResourceCompatible(kind, split, e) ).findFirst(); } else { result = Optional.of(formatEndpointFor(API_GROUPS_API, version, kind)); } if (result.isPresent()) { int index = resourceEndpoints.indexOf(result.get()); if (index > -1) { return resourceEndpoints.get(index); } } return null; }
Source:
<code>private static AWSCredentialsProvider overwriteBasicCredentials(AwsCredentialsConfig task, final AWSCredentials creds) { <START> task.setAuthMethod("default"); <END> task.setAccessKeyId(Optional.of(creds.getAWSAccessKeyId())); task.setSecretAccessKey(Optional.of(creds.getAWSSecretKey())); return new AWSCredentialsProvider() { public AWSCredentials getCredentials() { return creds; } public void refresh() { } }; }</code><technical_language>"basic" here</technical_language>

Target:
private static AWSCredentialsProvider overwriteBasicCredentials(AwsCredentialsConfig task, final AWSCredentials creds) { task.setAuthMethod("basic"); task.setAccessKeyId(Optional.of(creds.getAWSAccessKeyId())); task.setSecretAccessKey(Optional.of(creds.getAWSSecretKey())); return new AWSCredentialsProvider() { public AWSCredentials getCredentials() { return creds; } public void refresh() { } }; }
Source:
<code>private void testAddTemplateQuestionLink() throws Exception { ______TS("add template question link"); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.clickTemplateModalButton(); feedbackEditPage.verifyHtmlPart(By.id("addTemplateQuestionModal"), "/instructorFeedbackTemplateQuestionExpandedModal.html"); <START> assertFalse("Unable to submit when there is no question selected", <END> feedbackEditPage.isAddTemplateQuestionButtonEnabled()); }</code><technical_language>able submit is question selected</technical_language>

Target:
private void testAddTemplateQuestionLink() throws Exception { ______TS("add template question link"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.clickTemplateModalButton(); feedbackEditPage.verifyHtmlPart(By.id("addTemplateQuestionModal"), "/instructorFeedbackTemplateQuestionExpandedModal.html"); assertFalse("Should not be able to submit when there is no question selected", feedbackEditPage.isAddTemplateQuestionButtonEnabled()); }
Source:
<code>protected void okPressed() { if (!isCommitWithoutFilesAllowed()) { MessageDialog.openWarning(getShell(), UIText.CommitDialog_ErrorNoItemsSelected, UIText.CommitDialog_ErrorNoItemsSelectedToBeCommitted); return; } if (!commitMessageComponent.checkCommitInfo()) return; <START> if (!getSeverityItems().isEmpty()) { <END> int warnings = 0; int errors = 0; if ((getSeverityItems().get(IMarker.SEVERITY_WARNING) != null)) { warnings = getSeverityItems().get(IMarker.SEVERITY_WARNING) .size(); } if (getSeverityItems().get(IMarker.SEVERITY_ERROR) != null) { errors = getSeverityItems().get(IMarker.SEVERITY_ERROR).size(); } CommitWarningDialog dialog = new CommitWarningDialog(PlatformUI .getWorkbench().getActiveWorkbenchWindow().getShell(), warnings, errors); if (dialog.open() == Window.CANCEL) { return; } } Object[] checkedElements = filesViewer.getCheckedElements(); selectedFiles.clear(); for (Object obj : checkedElements) selectedFiles.add(((CommitItem) obj).path); amending = commitMessageComponent.isAmending(); commitMessage = commitMessageComponent.getCommitMessage(); author = commitMessageComponent.getAuthor(); committer = commitMessageComponent.getCommitter(); createChangeId = changeIdItem.getSelection(); IDialogSettings settings = org.eclipse.egit.ui.Activator .getDefault().getDialogSettings(); settings.put(SHOW_UNTRACKED_PREF, showUntracked); CommitMessageHistory.saveCommitHistory(getCommitMessage()); super.okPressed(); }</code><technical_language>Please check if settings require a dialog shhown</technical_language>

Target:
protected void okPressed() { if (!isCommitWithoutFilesAllowed()) { MessageDialog.openWarning(getShell(), UIText.CommitDialog_ErrorNoItemsSelected, UIText.CommitDialog_ErrorNoItemsSelectedToBeCommitted); return; } if (!commitMessageComponent.checkCommitInfo()) return; if (!getSeverityItems().isEmpty() && getPreferenceStore() .getBoolean(UIPreferences.CHECK_BEFORE_COMMITTING)) { CommitWarningDialog dialog = new CommitWarningDialog(PlatformUI .getWorkbench().getActiveWorkbenchWindow().getShell(), getSeverityItems()); if (dialog.open() == Window.CANCEL) { return; } } Object[] checkedElements = filesViewer.getCheckedElements(); selectedFiles.clear(); for (Object obj : checkedElements) selectedFiles.add(((CommitItem) obj).path); amending = commitMessageComponent.isAmending(); commitMessage = commitMessageComponent.getCommitMessage(); author = commitMessageComponent.getAuthor(); committer = commitMessageComponent.getCommitter(); createChangeId = changeIdItem.getSelection(); IDialogSettings settings = org.eclipse.egit.ui.Activator .getDefault().getDialogSettings(); settings.put(SHOW_UNTRACKED_PREF, showUntracked); CommitMessageHistory.saveCommitHistory(getCommitMessage()); super.okPressed(); }
Source:
<code>protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { stderr.println("The Jenkins instance has not been started, or was already shut down!"); return -1; } final HashSet<String> hs = new HashSet<String>(); hs.addAll(jobs); for (String job_s: hs) { AbstractItem job = null; try { <START> job = (AbstractItem) jenkins.getItemByFullName(job_s); <END> if(job == null) { AbstractProject project = AbstractProject.findNearest(job_s); if(project == null) { stderr.format("No such job \u2018%s\u2019 exists.\n", job_s); } else { stderr.format("No such job ‘%s’ exists. Perhaps you meant ‘never_created’?", job_s, project.getFullName()); } errorOccurred = true; continue; } try { job.checkPermission(AbstractItem.CONFIGURE); } catch (Exception e) { stderr.println(e.getMessage()); errorOccurred = true; continue; } job.doReload(); } catch (Exception e) { final String errorMsg = String.format("Unexpected exception occurred during reloading of job '%s': %s", job == null ? "(null)" : job.getFullName(), e.getMessage()); stderr.println(errorMsg); LOGGER.warning(errorMsg); errorOccurred = true; continue; } } return errorOccurred ? 1 : 0; }</code><technical_language>Unchecked Cast. I suppose <code>Item</code> (there other public implementations, exist in closed source plugins)</technical_language>

Target:
protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { stderr.println("The Jenkins instance has not been started, or was already shut down!"); return -1; } final HashSet<String> hs = new HashSet<String>(); hs.addAll(jobs); for (String job_s: hs) { AbstractItem job = null; try { Item item = jenkins.getItemByFullName(job_s); if (item instanceof AbstractItem) { job = (AbstractItem) item; } else if (item != null) { LOGGER.log(Level.WARNING, "Unsupported item type: {0}", item.getClass().getName()); } if(job == null) { AbstractProject project = AbstractProject.findNearest(job_s); if(project == null) { stderr.format("No such job \u2018%s\u2019 exists.\n", job_s); } else { stderr.format("No such job \u2018%s\u2019 exists. Perhaps you meant \u2018%s\u2019?", job_s, project.getFullName()); } errorOccurred = true; continue; } try { job.checkPermission(AbstractItem.CONFIGURE); } catch (Exception e) { stderr.println(e.getMessage()); errorOccurred = true; continue; } job.doReload(); } catch (Exception e) { final String errorMsg = String.format("Unexpected exception occurred during reloading of job '%s': %s", job == null ? "(null)" : job.getFullName(), e.getMessage()); stderr.println(errorMsg); LOGGER.warning(errorMsg); errorOccurred = true; continue; } } return errorOccurred ? 1 : 0; }
Source:
<code>private byte[] convertXMLToHTML(InputStream xml, InputStream xsl) { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(xsl)); <START> transformer.transform(new javax.xml.transform.stream.StreamSource(xml), <END> new javax.xml.transform.stream.StreamResult(output)); } catch (TransformerException e) { LOG.error("Exception in transforming from xml to html", e); } return output.toByteArray(); }</code><technical_language>import StreamSource</technical_language>

Target:
private byte[] convertXMLToHTML(InputStream xml, InputStream xsl) { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(xsl)); transformer.transform(new javax.xml.transform.stream.StreamSource(xml), new javax.xml.transform.stream.StreamResult(output)); } catch (TransformerException e) { LOG.error("Exception in transforming from xml to html", e); } return output.toByteArray(); }
Source:
<code>public static long crc32(String data) { if (data == null) { return -1; } try { byte bytes[] = data.getBytes("UTF-8"); Checksum checksum = new CRC32(); checksum.update(bytes, 0, bytes.length); return checksum.getValue(); } catch (UnsupportedEncodingException e) { <START> return -1; <END> } }</code><technical_language>catch exception ? pass ? I is a thin chance this happen. in case. Also, do a default data.getBytes() if UTF-8 fails UnsupportedEncodingException</technical_language>

Target:
public static long crc32(String data) { if (data == null) { return -1; } try { byte bytes[] = data.getBytes("UTF-8"); Checksum checksum = new CRC32(); checksum.update(bytes, 0, bytes.length); return checksum.getValue(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
<code>public Optional<ImmutableWorkerInfo> findWorkerForTask( WorkerTaskRunnerConfig config, ImmutableMap<String, ImmutableWorkerInfo> zkWorkers, Task task ) { final TreeSet<ImmutableWorkerInfo> sortedWorkers = Sets.newTreeSet( new Comparator<ImmutableWorkerInfo>() { @Override public int compare( ImmutableWorkerInfo zkWorker, ImmutableWorkerInfo zkWorker2 ) { <START> int retVal = Ints.compare(zkWorker2.getWorker().getCapacity() - zkWorker2.getCurrCapacityUsed(), <END> zkWorker.getWorker().getCapacity() - zkWorker.getCurrCapacityUsed()); if(retVal == 0) { retVal = zkWorker2.getWorker().getVersion().compareTo(zkWorker.getWorker().getVersion()); } return retVal; } } ); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableWorkerInfo zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }</code><technical_language>Suggested factor getWorker().getCapacity() - getCurrCapacityUsed() a method in ImmutableWorkerInfo, i. e. called "getAvailableCapacity". Comparator.comparing(ImmutableWorkerInfo::getAvailableCapacity).reversed() .thenComparing(zkWorker -> zkWorker.getWorker().getVersion()) Instead of anonymous Comparator subclass</technical_language>

Target:
public Optional<ImmutableWorkerInfo> findWorkerForTask( WorkerTaskRunnerConfig config, ImmutableMap<String, ImmutableWorkerInfo> zkWorkers, Task task ) { final TreeSet<ImmutableWorkerInfo> sortedWorkers = Sets.newTreeSet( Comparator.comparing(ImmutableWorkerInfo::getAvailableCapacity).reversed() .thenComparing(zkWorker -> zkWorker.getWorker().getVersion())); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableWorkerInfo zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }
Source:
<code>public List<String> getSearchDomains() { Object serviceLabels = ServiceDiscoveryUtil.getLaunchConfigObject(service, launchConfigName, InstanceConstants.FIELD_LABELS); if (serviceLabels != null) { String setSearchDomain = ((Map<String, String>) serviceLabels) .get(SystemLabels.LABEL_RANCHER_CONTAINER_DNS_PRIORITY); <START> if (setSearchDomain != null && !setSearchDomain.isEmpty() && StringUtils.equals(setSearchDomain.trim(), "None")) { <END> return Arrays.asList(); } } String stackNamespace = ServiceDiscoveryDnsUtil.getStackNamespace(this.stack, this.service); String serviceNamespace = ServiceDiscoveryDnsUtil .getServiceNamespace(this.stack, this.service); return Arrays.asList(stackNamespace, serviceNamespace); }</code><technical_language>Case insensitive comparison is needed</technical_language>

Target:
public List<String> getSearchDomains() { Object serviceLabels = ServiceDiscoveryUtil.getLaunchConfigObject(service, launchConfigName, InstanceConstants.FIELD_LABELS); if (serviceLabels != null) { String setSearchDomain = ((Map<String, String>) serviceLabels) .get(SystemLabels.LABEL_RANCHER_CONTAINER_DNS_PRIORITY); if (setSearchDomain != null && !setSearchDomain.isEmpty() && StringUtils.equalsIgnoreCase(setSearchDomain.trim(), "None")) { return Arrays.asList(); } } String stackNamespace = ServiceDiscoveryDnsUtil.getStackNamespace(this.stack, this.service); String serviceNamespace = ServiceDiscoveryDnsUtil .getServiceNamespace(this.stack, this.service); return Arrays.asList(stackNamespace, serviceNamespace); }
Source:
<code>public BreakIteratorSentenceDetector(Locale locale) { <START> breakIterator = BreakIterator.getSentenceInstance(Locale.US); <END> }</code><technical_language>local is supplied used, no</technical_language>

Target:
public BreakIteratorSentenceDetector(Locale locale) { breakIterator = BreakIterator.getSentenceInstance(locale); }
Source:
<code>public Set<String> getFreeVariables() { <START> return new HashSet<String>(); <END> }</code><technical_language>return variables referenced in right hand side of effect declaration, e.g. start of path in Effect in effectSet</technical_language>

Target:
public Set<String> getFreeVariables() { Set<String> freeVars = new HashSet<String>(); for (Effect e : effectSet) { freeVars.add(e.getPath().getName()); } return freeVars; }
Source:
<code>private void testChangeFeedbackRecipient() { ______TS("click on Edit visibility then change recipient"); feedbackEditPage = getFeedbackEditPage(); WebElement editLabel = feedbackEditPage.getEditLabel(1); WebElement previewLabel = feedbackEditPage.getPreviewLabel(1); feedbackEditPage.clickQuestionEditForQuestion1(); editLabel.click(); feedbackEditPage.selectRecipientTypeForQuestion1("Other teams in the course"); boolean isPreviewButtonActive = previewLabel.getAttribute("class").contains("active"); <START> assertTrue(!isPreviewButtonActive); <END> boolean isEditButtonActive = editLabel.getAttribute("class").contains("active"); assertTrue(isEditButtonActive); WebElement visibilityMessage = feedbackEditPage.getVisibilityMessage(1); assertTrue(!visibilityMessage.isDisplayed()); WebElement visibilityOptions = feedbackEditPage.getVisibilityOptions(1); assertTrue(visibilityOptions.isDisplayed()); }</code><technical_language>assertFalse instead. import it. for lines below. Also, do asserts clicking edit button changing recipient type, states correct then</technical_language>

Target:
private void testChangeFeedbackRecipient() { ______TS("click on Edit visibility then change recipient"); feedbackEditPage = getFeedbackEditPage(); assertTrue(feedbackEditPage.verifyPreviewLabelIsActive(1)); assertFalse(feedbackEditPage.verifyEditLabelIsActive(1)); assertTrue(feedbackEditPage.verifyVisibilityMessageIsDisplayed(1)); assertFalse(feedbackEditPage.verifyVisibilityOptionsIsDisplayed(1)); feedbackEditPage.clickQuestionEditForQuestion1(); feedbackEditPage.clickEditLabel(1); feedbackEditPage.selectRecipientTypeForQuestion1("Other teams in the course"); assertFalse(feedbackEditPage.verifyPreviewLabelIsActive(1)); assertTrue(feedbackEditPage.verifyEditLabelIsActive(1)); assertFalse(feedbackEditPage.verifyVisibilityMessageIsDisplayed(1)); assertTrue(feedbackEditPage.verifyVisibilityOptionsIsDisplayed(1)); }
Source:
<code><START> private String removeUserInfo(String url) { <END> String userInfo = ""; try { userInfo = new URL(url).getUserInfo(); } catch (MalformedURLException e) { logger.warn("Suppressed exception", e); } return url.replace(userInfo, "XXXX:XXXX"); }</code><technical_language>public static</technical_language>

Target:
public static String removeUserInfo(String url) { Logger logger = LoggerFactory.getLogger("HttpClient"); String userInfo = ""; try { userInfo = new URL(url).getUserInfo(); } catch (MalformedURLException e) { logger.warn("Suppressed exception", e); } if (null == userInfo || userInfo.isEmpty()){ return url; } return url.replace(userInfo, "XXXX:XXXX"); }
Source:
<code><START> public EnergyNet(@Nonnull Location l) { <END> super(SlimefunPlugin.getNetworkManager(), l); }</code><technical_language>Making this public sound a good idea, public static accessor method is provided</technical_language>

Target:
protected EnergyNet(@Nonnull Location l) { super(SlimefunPlugin.getNetworkManager(), l); }
Source:
<code><START> private static boolean isSamsungS5() { <END> return (Build.MANUFACTURER.equals("Samsung") && (((Build.DEVICE.startsWith("k") || Build.DEVICE.startsWith("l")) && (Build.MODEL.contains("SM-G"))) || (Build.DEVICE.contains("SCL23")))); }</code><technical_language>issue other device while opening closing always</technical_language>

Target:
private static boolean isSamsungS5() { return (Build.MANUFACTURER.equalsIgnoreCase("samsung") && (((Build.DEVICE.startsWith("k") || Build.DEVICE.startsWith("l")) && (Build.MODEL.contains("SM-G"))) || (Build.DEVICE.contains("SCL23")))); }
Source:
<code>protected static LicenseInfoParsingResult getLicenseInfoFromSpdx(AttachmentContent attachmentContent, SpdxDocument doc) { LicenseInfo licenseInfo = new LicenseInfo().setFilenames(Arrays.asList(attachmentContent.getFilename())); <START> if(! licenseInfo.isSetLicenseNamesWithTexts()){ <END> licenseInfo.setLicenseNamesWithTexts(new HashSet<>()); } if(! licenseInfo.isSetCopyrights()){ licenseInfo.setCopyrights(new HashSet<>()); } try { for (SpdxItem spdxItem : doc.getDocumentDescribes()) { licenseInfo.getLicenseNamesWithTexts() .addAll(getAllLicenseTexts(spdxItem, true) .collect(Collectors.toSet())); licenseInfo.getCopyrights() .addAll(getAllCopyrights(spdxItem) .collect(Collectors.toSet())); } } catch (UncheckedInvalidSPDXAnalysisException e) { return new LicenseInfoParsingResult() .setStatus(LicenseInfoRequestStatus.FAILURE) .setMessage(e.getInvalidSPDXAnalysisExceptionCause().getMessage()); } catch (InvalidSPDXAnalysisException e) { return new LicenseInfoParsingResult() .setStatus(LicenseInfoRequestStatus.FAILURE) .setMessage(e.getMessage()); } return new LicenseInfoParsingResult() .setLicenseInfo(licenseInfo) .setStatus(LicenseInfoRequestStatus.SUCCESS); }</code><technical_language>remove this</technical_language>

Target:
protected static LicenseInfoParsingResult getLicenseInfoFromSpdx(AttachmentContent attachmentContent, SpdxDocument doc) { LicenseInfo licenseInfo = new LicenseInfo().setFilenames(Arrays.asList(attachmentContent.getFilename())); licenseInfo.setLicenseNamesWithTexts(new HashSet<>()); licenseInfo.setCopyrights(new HashSet<>()); try { for (SpdxItem spdxItem : doc.getDocumentDescribes()) { licenseInfo.getLicenseNamesWithTexts() .addAll(getAllLicenseTexts(spdxItem, true) .collect(Collectors.toSet())); licenseInfo.getCopyrights() .addAll(getAllCopyrights(spdxItem) .collect(Collectors.toSet())); } } catch (UncheckedInvalidSPDXAnalysisException e) { return new LicenseInfoParsingResult() .setStatus(LicenseInfoRequestStatus.FAILURE) .setMessage(e.getInvalidSPDXAnalysisExceptionCause().getMessage()); } catch (InvalidSPDXAnalysisException e) { return new LicenseInfoParsingResult() .setStatus(LicenseInfoRequestStatus.FAILURE) .setMessage(e.getMessage()); } return new LicenseInfoParsingResult() .setLicenseInfo(licenseInfo) .setStatus(LicenseInfoRequestStatus.SUCCESS); }
Source:
<code>AbstractBuilder(int initialCapacity) { <START> this.list = new ArrayList<T>(initialCapacity); <END> }</code><technical_language>minor: need add explicit type argument</technical_language>

Target:
AbstractBuilder(int initialCapacity) { this.list = new ArrayList<>(initialCapacity); }
Source:
<code>public static ObjectId read(InputStream in) throws IOException { switch (in.read()) { case 0: return null; case 1: final byte[] b = new <START> byte[20]; <END> IO.readFully(in, b, 0, 20); return ObjectId.fromRaw(b); default: throw new IOException("Invalid flag before ObjectId"); } }</code><technical_language>Constants.OBJECT_ID_LENGTH</technical_language>

Target:
public static ObjectId read(InputStream in) throws IOException { switch (in.read()) { case 0: return null; case 1: final byte[] b = new byte[OBJECT_ID_LENGTH]; IO.readFully(in, b, 0, OBJECT_ID_LENGTH); return ObjectId.fromRaw(b); default: throw new IOException("Invalid flag before ObjectId"); } }
Source:
<code>protected boolean canDoAction() { <START> if (getParameters() == null || (getParameters().getQuotaId() == null)) { <END> return false; } return true; }</code><technical_language>add a canDoAction message if fail canDoAction</technical_language>

Target:
protected boolean canDoAction() { if (getParameters() == null || (getParameters().getQuotaId() == null)) { return false; } Quota quota = getQuotaDAO().getById(getParameters().getQuotaId()); if (getStoragePool().getQuotaEnforcementType() == QuotaEnforcmentTypeEnum.DISABLED && quota.getIsDefaultQuota()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_CAN_NOT_HAVE_DEFAULT_INDICATION); } List<Quota> quotaList = getQuotaDAO().getQuotaByStoragePoolGuid(getParameters().getStoragePoolId()); if (quotaList.size() <= 1) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_MUST_HAVE_AT_LEAST_ONE_QUOTA); } return true; }
Source:
<code>private void handleSecurityException(Exception e) { sslInfrastructureService.invalidateAgentCertificate(); LOG.error("There has been a problem with one of Go's SSL certificates." + <START> " This can be caused by a man-in-the-middle attack, or by pointing the agent to a new e, or by" + <END> " deleting and re-installing Go Server. Go will ask for a new certificate. If this" + " fails to solve the problem, try deleting config/trust.jks in Go Agent's home directory.", e); }</code><technical_language>Typo : 'server' replaced 'e' :)</technical_language>

Target:
private void handleSecurityException(Exception e) { sslInfrastructureService.invalidateAgentCertificate(); LOG.error("There has been a problem with one of Go's SSL certificates." + " This can be caused by a man-in-the-middle attack, or by pointing the agent to a new server, or by" + " deleting and re-installing Go Server. Go will ask for a new certificate. If this" + " fails to solve the problem, try deleting config/trust.jks in Go Agent's home directory.", e); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recent_notifications); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation)); setSupportActionBar(toolbar); setupActionBar(); <START> Fragment fragment = new RecentNotificationsFragmentV2(); <END> getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in_support, R.anim.fade_out_support).replace(R.id.container, fragment, MAIN_FRAGMENT_TAG).commit(); }</code><technical_language>If fragment is good, rename RecentNotificationsFragment remove one</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recent_notifications); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); ViewCompat.setElevation(toolbar, getResources().getDimension(R.dimen.toolbar_elevation)); setSupportActionBar(toolbar); setupActionBar(); Fragment fragment = new RecentNotificationsFragment(); getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in_support, R.anim.fade_out_support).replace(R.id.container, fragment, MAIN_FRAGMENT_TAG).commit(); }
Source:
<code>public boolean isInstalled() { try { Project project = getFaceted(); <START> project.getFacet(MavenFacet.class); <END> return getRootTemplateDirectory().exists(); } catch (FacetNotFoundException e) { return false; } }</code><technical_language>project.hasFacet(MavenFacet.class) preferred instead</technical_language>

Target:
public boolean isInstalled() { Project project = getFaceted(); return project.hasFacet(MavenFacet.class) && getRootTemplateDirectory().exists(); }
Source:
<code>public static String getClientIp(final String ip, final String xff) { if (xff == null || xff.isEmpty() || xff.equals("-")) { return ip; } else { String[] proxiedIps = xff.split(","); try { for (String proxiedIp : proxiedIps) { int ipVersion = getIpVersion(proxiedIp); if ((!( <START> proxiedIp.startsWith("127.0") || <END> proxiedIp.startsWith("192.168") || proxiedIp.startsWith("10.") || proxiedIp.startsWith("169.254") )) && ( ipVersion == 4 || ipVersion == 6 ) ) { return proxiedIp; } } return ip; } catch (ArrayIndexOutOfBoundsException e) { return ip; } } }</code><technical_language>Do want trim() string.startsWith()</technical_language>

Target:
public static String getClientIp(final String ip, final String xff) { if (xff == null || xff.isEmpty() || xff.equals("-")) { return ip; } else { String[] proxiedIps = xff.split(","); try { for (String proxiedIp : proxiedIps) { proxiedIp = proxiedIp.trim(); int ipVersion = getIpVersion(proxiedIp); if ((!( proxiedIp.startsWith("127.0") || proxiedIp.startsWith("192.168") || proxiedIp.startsWith("10.") || proxiedIp.startsWith("169.254") )) && ( ipVersion == 4 || ipVersion == 6 ) ) { return proxiedIp; } } return ip; } catch (ArrayIndexOutOfBoundsException e) { return ip; } } }
Source:
<code>protected <T> T get(Class<T> clazz, String path, String ...params) { path = getPath(path, params); try { HttpGet get = new HttpGet(); setupCommonHeaders(get); get.setURI(uri.resolve(path)); String json = getJSON(get); <START> return gson.fromJson(json, clazz); <END> } catch (IOException e) { throw new HttpClientException(e); } }</code><technical_language>gson instead of jackson? curious, matter</technical_language>

Target:
protected <T> T get(Class<T> clazz, String path, String ...params) { path = getPath(path, params); try { HttpGet get = new HttpGet(); setupCommonHeaders(get); get.setURI(uri.resolve(path)); String json = getJSON(get); return mapper.readValue(json, clazz); } catch (IOException e) { throw new HttpClientException(e); } }
Source:
<code>public void testGetErrors() { HttpCodesUtil.HttpCode code200 = new HttpCodesUtil.HttpCode(200, "Ok"); HttpCodesUtil.HttpCode code302 = new HttpCodesUtil.HttpCode(302, "Found"); HttpCodesUtil.HttpCode code400 = new HttpCodesUtil.HttpCode(400, "Bad Request"); HttpCodesUtil.HttpCode code501 = new HttpCodesUtil.HttpCode(501, "Not Implemented"); List<HttpCodesUtil.HttpCode> codeList = Arrays.asList(code200, code400, code400, code302, code501); List<HttpCodesUtil.HttpCode> clientOrServerErrors = HttpCodesUtil.getClientOrServerErrors(codeList); Assert.assertEquals(3, clientOrServerErrors.size()); <START> Assert.assertEquals(Arrays.asList(code400, code400, code501), clientOrServerErrors); <END> }</code><technical_language>Is this assertion "order dependent"? If I change order codeList, test break? more importantly: _should_ test break</technical_language>

Target:
public void testGetErrors() { HttpCodesUtil.HttpCode code200 = new HttpCodesUtil.HttpCode(200, "Ok"); HttpCodesUtil.HttpCode code302 = new HttpCodesUtil.HttpCode(302, "Found"); HttpCodesUtil.HttpCode code400 = new HttpCodesUtil.HttpCode(400, "Bad Request"); HttpCodesUtil.HttpCode code501 = new HttpCodesUtil.HttpCode(501, "Not Implemented"); List<HttpCodesUtil.HttpCode> codeList = Arrays.asList(code200, code400, code400, code302, code501); List<HttpCodesUtil.HttpCode> clientOrServerErrors = HttpCodesUtil.getClientOrServerErrors(codeList); Assert.assertEquals( Arrays.asList(new HttpCodesUtil.HttpCode(400, "400"), new HttpCodesUtil.HttpCode(400, "400"), new HttpCodesUtil.HttpCode(501, "501")), clientOrServerErrors); Assert.assertEquals(Arrays.asList(code400, code400, code501), clientOrServerErrors); }
Source:
<code>public static Path getJavaExecutablePath() { String javaHome = System.getenv(JAVA_HOME); <START> if (javaHome == null) { <END> throw new NullPointerException(String.format("'%s' is not set", JAVA_HOME)); } return Paths.get(javaHome).resolve("bin/java"); }</code><technical_language>is commons-lang3 in classpath? Validate.notNull(...)</technical_language>

Target:
public static Path getJavaExecutablePath() { Path javaHome = PROPERTIES.getJavaHome(); if (javaHome == null) { throw new NullPointerException("'java.home' is not set"); } return PROPERTIES.getJavaHome().resolve("bin/java"); }
Source:
<code><START> public static void addBundleToMap(Bundle bundle, List<String> keys, Map<String, String> map) { <END> if (bundle == null || keys == null || bundle.isEmpty() || keys.isEmpty()) { return; } if (map == null) { map = new HashMap<>(); } for (final String key : keys) { if (!TextUtils.isEmpty(key)) { map.put(key, bundle.getString(key)); } } }</code><technical_language>thanks for thorough</technical_language>

Target:
public static Map<String, String> addBundleToMap(Bundle bundle, List<String> keys, Map<String, String> map) { if (bundle == null || keys == null || bundle.isEmpty() || keys.isEmpty()) { return map; } if (map == null) { map = new HashMap<>(); } for (final String key : keys) { if (!TextUtils.isEmpty(key)) { map.put(key, bundle.getString(key)); } } return map; }
Source:
<code>final <E extends Throwable> E expectError(Class<E> clazz, final long totalTimeoutMillis, long pollTimeoutMillis, String errorMsg) throws Exception { long totalTimeoutRemainingMillis = totalTimeoutMillis; long timeStampA = System.nanoTime(); long timeStampB; for (;;) { Thread.sleep(Math.min(pollTimeoutMillis, totalTimeoutRemainingMillis)); if (env.asyncErrors.isEmpty()) { timeStampB = System.nanoTime(); <START> totalTimeoutRemainingMillis =- timeStampB - timeStampA; <END> timeStampA = timeStampB; if (totalTimeoutRemainingMillis <= 0) { return env.flopAndFail(String.format("%s within %d ms", errorMsg, totalTimeoutMillis)); } } else { Throwable thrown = env.asyncErrors.remove(0); if (clazz.isInstance(thrown)) { return (E) thrown; } else { return env.flopAndFail(String.format("%s within %d ms; Got %s but expected %s", errorMsg, totalTimeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName())); } } } }</code><technical_language>@Scottmitch nanotime() is in millis</technical_language>

Target:
final <E extends Throwable> E expectError(Class<E> clazz, final long totalTimeoutMillis, long pollTimeoutMillis, String errorMsg) throws Exception { long totalTimeoutRemainingNs = MILLISECONDS.toNanos(totalTimeoutMillis); long timeStampANs = System.nanoTime(); long timeStampBNs; for (;;) { Thread.sleep(Math.min(pollTimeoutMillis, NANOSECONDS.toMillis(totalTimeoutRemainingNs))); if (env.asyncErrors.isEmpty()) { timeStampBNs = System.nanoTime(); totalTimeoutRemainingNs =- timeStampBNs - timeStampANs; timeStampANs = timeStampBNs; if (totalTimeoutRemainingNs <= 0) { return env.flopAndFail(String.format("%s within %d ms", errorMsg, totalTimeoutMillis)); } } else { Throwable thrown = env.asyncErrors.remove(0); if (clazz.isInstance(thrown)) { return (E) thrown; } else { return env.flopAndFail(String.format("%s within %d ms; Got %s but expected %s", errorMsg, totalTimeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName())); } } } }