auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Iterable<XeSource> bouts(final Request req, final String query) throws IOException { final Iterable<Bout> bouts; <START> if (StringUtils.isBlank(query)) { <END> long since = Inbox.NEVER; final Iterator<String> param = new RqHref.Base(req).href() .param("since").iterator(); if (param.hasNext()) { since = Long.parseLong(param.next()); } bouts = Iterables.limit(new RqAlias(this.base, req).alias().inbox() .jump(since).iterate(), Inbox.PAGE ); } else { bouts = new RqAlias(this.base, req).alias().inbox().search(query); } return new XeTransform<>( bouts, new XeTransform.Func<Bout>() { @Override public XeSource transform(final Bout bout) throws IOException { return TkInbox.source(bout); } } ); }</code><technical_language>@erimerturk this method changed a lot, implement some more tests cover bouts searching (pdd maybe?)</technical_language>

Target:
private Iterable<XeSource> bouts(final Request req, final String query) throws IOException { final Iterable<Bout> bouts; final Inbox inbox = new RqAlias(this.base, req).alias().inbox(); if (StringUtils.isBlank(query)) { long since = Inbox.NEVER; final Iterator<String> param = new RqHref.Base(req).href() .param("since").iterator(); if (param.hasNext()) { since = Long.parseLong(param.next()); } bouts = inbox.jump(since).iterate(); } else { bouts = inbox.search(query); } return new XeTransform<>( Iterables.limit(bouts, Inbox.PAGE), new XeTransform.Func<Bout>() { @Override public XeSource transform(final Bout bout) throws IOException { return TkInbox.source(bout); } } ); }
Source:
<code>private Session getOrOpenTargetSession(final URI sessionResourceUri) { Session session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); if (session == null) { ModelingProjectManager.INSTANCE.loadAndOpenRepresentationsFile(sessionResourceUri, true); try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { <START> throw new RuntimeException(e); <END> } session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); } return session; }</code><technical_language>Before, waitOtherJobs, "Do nothing" in case of InterruptedException. do change that? test difference</technical_language>

Target:
private Session getOrOpenTargetSession(final URI sessionResourceUri) { Session session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); if (session == null) { ModelingProjectManager.INSTANCE.loadAndOpenRepresentationsFile(sessionResourceUri, true); try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { } session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); } return session; }
Source:
<code>public <T> T readObject(Class<T> clazz) throws IOException, ClassNotFoundException { int classNameLength = dis.readInt(); int bytesLength = dis.readInt(); if (classNameLength < 0 || bytesLength < 0) { throw new IOException(); } byte[] classNameBytes = new byte[classNameLength]; dis.read(classNameBytes, 0, classNameLength); byte[] bytes = new byte[bytesLength]; dis.read(bytes, 0, bytesLength); T result; if (Utils.WRAPPER_SET.contains(clazz) || clazz.isArray() || clazz.isEnum()) { Schema<Wrapper> schema = RuntimeSchema.getSchema(Wrapper.class); Wrapper wrapper = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, wrapper, schema); result = (T) wrapper.getData(); } else { Schema<T> schema = RuntimeSchema.getSchema(clazz); result = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, result, schema); } <START> return result; <END> }</code><technical_language>advice refactor method extraction is a lot of replicated codes</technical_language>

Target:
public <T> T readObject(Class<T> clazz) throws IOException, ClassNotFoundException { int classNameLength = dis.readInt(); int bytesLength = dis.readInt(); if (classNameLength < 0 || bytesLength < 0) { throw new IOException(); } byte[] classNameBytes = new byte[classNameLength]; dis.read(classNameBytes, 0, classNameLength); byte[] bytes = new byte[bytesLength]; dis.read(bytes, 0, bytesLength); T result; if (WrapperUtils.needWrapper(clazz)) { Schema<Wrapper> schema = RuntimeSchema.getSchema(Wrapper.class); Wrapper wrapper = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, wrapper, schema); result = (T) wrapper.getData(); } else { Schema<T> schema = RuntimeSchema.getSchema(clazz); result = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, result, schema); } return result; }
Source:
<code>private void _startTimeout() { ClockModel pc = getClockModel(Clock.ID_PERIOD); ClockModel tc = getClockModel(Clock.ID_TIMEOUT); <START> requestBatchStart(); <END> if (tc.isRunning()) { if (getTimeoutOwner()=="") { setTimeoutOwner("O"); } else { setTimeoutOwner(""); } return; } pc.stop(); _endLineup(); _endJam(false); _endIntermission(false); setInPeriod(true); tc.startNext(); }</code><technical_language>close this batch, early return mess this too. This break WS least</technical_language>

Target:
private void _startTimeout() { ClockModel pc = getClockModel(Clock.ID_PERIOD); ClockModel tc = getClockModel(Clock.ID_TIMEOUT); requestBatchStart(); if (tc.isRunning()) { if (getTimeoutOwner()==TIMEOUT_OWNER_NONE) { setTimeoutOwner(TIMEOUT_OWNER_OTO); } else { setTimeoutOwner(TIMEOUT_OWNER_NONE); } requestBatchEnd(); return; } pc.stop(); _endLineup(); _endJam(false); _endIntermission(false); setInPeriod(true); tc.startNext(); requestBatchEnd(); }
Source:
<code>public void testResponseStreamConsumedByReadingStream() throws Exception { final RestResponse response = getStreamTestResponse(); <START> try (InputStream in = response.asInputStream()) { <END> inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } final RestResponse anotherResponse = getStreamTestResponse(); assertNotNull(anotherResponse); }</code><technical_language>above, other try block</technical_language>

Target:
public void testResponseStreamConsumedByReadingStream() throws Exception { final RestResponse response = getStreamTestResponse(); try { InputStream in = response.asInputStream(); inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } final RestResponse anotherResponse = getStreamTestResponse(); assertNotNull(anotherResponse); }
Source:
<code>private InputStream fakeBody(final String... dispositions) { final String boundary = "AaB02x"; final Collection<String> parts = new LinkedList<String>(); for (final String disposition : dispositions) { parts.add(String.format("--%s", boundary)); parts.add(disposition); } parts.add("Content-Transfer-Encoding: utf-8"); parts.add(""); parts.add("the start\r\t\n\u20ac\n\n\n\t\r\t\n\n\n\r\n the end"); parts.add(String.format("--%s--", boundary)); return new ByteArrayInputStream( <START> RqMultipart.Fake.join(parts.iterator()).getBytes() <END> ); }</code><technical_language>@erimerturk Joiner.on(RqMultipartTest.CRLF).join(parts) in RqMultipartTest</technical_language>

Target:
private static InputStream fakeBody(final String... dispositions) { final StringBuilder builder = new StringBuilder(); for (final String disposition : dispositions) { builder.append(String.format("--%s%s", BOUNDARY, "\r\n")) .append(disposition) .append("\r\n"); } builder.append("Content-Transfer-Encoding: utf-8\r\n") .append(String.format("--%s--", BOUNDARY)); return new ByteArrayInputStream( builder.toString().getBytes() ); }
Source:
<code>public static ImageDescriptor[] getImages(String value, Bundle definingBundle) { URL[] urls = getURLs(value, definingBundle); if (urls == null || urls.length <= 0) { <START> return null; <END> } ImageDescriptor[] images = new ImageDescriptor[urls.length]; for (int i = 0; i < images.length; ++i) { images[i] = ImageDescriptor.createFromURL(urls[i]); } return images; }</code><technical_language>returning null is bad, returng null instead of array/collection is worse</technical_language>

Target:
protected static List<ImageDescriptor> getImages(String value, Bundle definingBundle) { List<URL> urls = getURLs(value, definingBundle); if (urls == null || urls.isEmpty()) { return Collections.emptyList(); } List<ImageDescriptor> images = new ArrayList<>(urls.size()); urls.forEach(u -> images.add(ImageDescriptor.createFromURL(u))); return images; }
Source:
<code>public void getFile( @NotBlank(message = "Source file path cannot be empty.") final String srcRemotePath, @NotBlank(message = "Destination local path cannot be empty") final String dstLocalPath ) throws GenieException { final long start = System.nanoTime(); log.debug("Called with src path and destination path {}", srcRemotePath, dstLocalPath); final File outputFile = new File(dstLocalPath); <START> try (final FileOutputStream fos = new FileOutputStream(outputFile)) { <END> this.restTemplate.execute( srcRemotePath, HttpMethod.GET, requestEntity -> requestEntity.getHeaders().setAccept(Lists.newArrayList(MediaType.ALL)), new ResponseExtractor<Void>() { @Override public Void extractData(final ClientHttpResponse response) throws IOException { ByteStreams.copy(response.getBody(), fos); return null; } } ); } catch (final IOException e) { throw new GenieServerException(e); } finally { this.downloadTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }</code><technical_language>commons-io FileUtils.copyURLToFile(URL source, File destination,int connectionTimeout, int readTimeout)</technical_language>

Target:
public void getFile( @NotBlank(message = "Source file path cannot be empty.") final String srcRemotePath, @NotBlank(message = "Destination local path cannot be empty") final String dstLocalPath ) throws GenieException { final long start = System.nanoTime(); log.debug("Called with src path and destination path {}", srcRemotePath, dstLocalPath); try { final File outputFile = new File(dstLocalPath); if (!this.isValid(srcRemotePath)) { throw new GenieServerException("Unable to download " + srcRemotePath + " not a valid URL"); } this.restTemplate.execute( srcRemotePath, HttpMethod.GET, requestEntity -> requestEntity.getHeaders().setAccept(Lists.newArrayList(MediaType.ALL)), new ResponseExtractor<Void>() { @Override public Void extractData(final ClientHttpResponse response) throws IOException { FileUtils.copyInputStreamToFile(response.getBody(), outputFile); return null; } } ); } finally { this.downloadTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }
Source:
<code>public void parse(byte[] vmdkFileContent) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmdkFileContent),"UTF-8")); String line; while ((line = in.readLine()) != null) { line = line.trim(); if (line.isEmpty()) { continue; } if (line.charAt(0) == '#') { continue; } final String[] tokens = line.split("="); if (tokens.length == 2) { final String name = tokens[0].trim(); String value = tokens[1].trim(); if (value.charAt(0) == '\"') { value = value.substring(1, value.length() - 1); } _properties.put(name, value); } else { if (line.startsWith("RW")) { final int startPos = line.indexOf('\"'); final int endPos = line.lastIndexOf('\"'); assert startPos > 0; <START> assert endPos > 0; <END> _baseFileName = line.substring(startPos + 1, endPos); } else { s_logger.warn("Unrecognized vmdk line content: " + line); } } } } finally { if (in != null) { in.close(); } } }</code><technical_language>endPos greater equal startPos? If so, sense add assertion for condition. Also, CloudStack run assertions enabled. Consider Guava's Preconditions.checkState throw IllegalStateException assertion fails</technical_language>

Target:
public void parse(byte[] vmdkFileContent) throws IOException { try (BufferedReader in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(vmdkFileContent),"UTF-8"));) { String line; while ((line = in.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.charAt(0) == '#') { continue; } final String[] tokens = line.split("="); if (tokens.length == 2) { final String name = tokens[0].trim(); String value = tokens[1].trim(); if (value.charAt(0) == '\"') { value = value.substring(1, value.length() - 1); } _properties.put(name, value); } else { if (line.startsWith("RW")) { final int startPos = line.indexOf('\"'); final int endPos = line.lastIndexOf('\"'); Preconditions.checkState(startPos > 0); Preconditions.checkState(startPos < endPos); _baseFileName = line.substring(startPos + 1, endPos); } else { s_logger.warn("Unrecognized vmdk line content: " + line); } } } } }
Source:
<code>public static int compareValues(Object value1, Object value2) { if (value1 instanceof Comparable && value2 instanceof Comparable && <START> value2 != null) { <END> return ((Comparable) value1).compareTo(value2); } else if (value1 != null && value2 != null) { return value1.toString().compareTo(value2.toString()); } else if (value1 != null && value2 == null) { return 1; } else if (value1 == null && value2 != null) { return -1; } return 0; }</code><technical_language>this null check is redundant: if value2 is instance of something, null in Java</technical_language>

Target:
public static int compareValues(Object value1, Object value2) { if (value1 instanceof Comparable && value2 instanceof Comparable) { return ((Comparable) value1).compareTo(value2); } else if (value1 != null && value2 != null) { return value1.toString().compareTo(value2.toString()); } else if (value1 != null) { return 1; } else if (value2 != null) { return -1; } return 0; }
Source:
<code>public void returnsA500ForViewsWithBadTemplatePaths() throws Exception { try { target("/test/bad").request().get(String.class); assertThat(1 == 0).isTrue(); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatus()) .isEqualTo(500); final String responseStr = e.getResponse().readEntity(String.class); <START> assertThat(responseStr) <END> .isEqualTo("<html><head><title>Missing Template</title></head><body><h1>Missing Template</h1><p>Template /woo-oo-ahh.txt.mustache not found.</p></body></html>"); } }</code><technical_language>responseStr inlined sole of this variable readable before</technical_language>

Target:
public void returnsA500ForViewsWithBadTemplatePaths() throws Exception { try { target("/test/bad").request().get(String.class); failBecauseExceptionWasNotThrown(WebApplicationException.class); } catch (WebApplicationException e) { assertThat(e.getResponse().getStatus()) .isEqualTo(500); assertThat(e.getResponse().readEntity(String.class)) .isEqualTo("<html><head><title>Missing Template</title></head><body><h1>Missing Template</h1><p>Template /woo-oo-ahh.txt.mustache not found.</p></body></html>"); } }
Source:
<code>public void reset() { view.reset(); <START> if (!saveEnabled) { <END> view.getSaveButton().removeFromParent(); } settingsScenarioSimulationDropdown.clear(); }</code><technical_language>A small suggestion: if !saveEnabled time, worth saveDisabled</technical_language>

Target:
public void reset() { view.reset(); if (!saveEnabled) { view.removeSaveButton(); } settingsScenarioSimulationDropdown.clear(); }
Source:
<code>public boolean isApplicable(IPerson p) { boolean isApplicable = false; if (LOG.isInfoEnabled()) LOG.info(">>>> calling " + name + ".isApplicable( " + p.getAttribute("username") + " )"); try { if (evaluators == null) { if (LOG.isDebugEnabled()) { LOG.debug("isApplicable()=false due to evaluators collection being null"); } } else { for (Evaluator v : evaluators) { if (v.isApplicable(p)) { isApplicable = true; break; } } } } catch (Exception e) { throw new RuntimeException("Failed to evaluate whether fragment '" + this.getName() <START> + "' is applicable to user '" + p.getUserName() + "'"); <END> } if (LOG.isInfoEnabled()) { LOG.info("---- " + name + ".isApplicable( " + p.getAttribute( "username" ) + " )=" + isApplicable); } return isApplicable; }</code><technical_language>new RuntimeException wrap e retain detail caught Exception</technical_language>

Target:
public boolean isApplicable(IPerson p) { boolean isApplicable = false; if (LOG.isInfoEnabled()) LOG.info(">>>> calling " + name + ".isApplicable( " + p.getAttribute("username") + " )"); try { if (evaluators == null) { LOG.debug("isApplicable()=false due to evaluators collection being null"); } else { for (Evaluator v : evaluators) { if (v.isApplicable(p)) { isApplicable = true; break; } } } } catch (Exception e) { throw new RuntimeException("Failed to evaluate whether fragment '" + this.getName() + "' is applicable to user '" + p.getUserName() + "'", e); } if (LOG.isInfoEnabled()) { LOG.info("---- " + name + ".isApplicable( " + p.getAttribute( "username" ) + " )=" + isApplicable); } return isApplicable; }
Source:
<code>protected String getCachedString(String str) { <START> WeakReference<String> internedString = stringCache.get(str); <END> if ( internedString == null ) { internedString = new WeakReference<>(str); stringCache.put(str, internedString); } return internedString.get(); }</code><technical_language>I thought need check referenced string of WeakReference GC'ed...shouldn't if statement if ( internedString == null || internedString.get()==null) ??</technical_language>

Target:
protected String getCachedString(String str) { if (!vcfCodecUseStringsCache) return str; WeakReference<String> stringWeakReference = stringCache.get(str); if ( stringWeakReference != null) { String ret = stringWeakReference.get(); if (ret != null) return ret; } stringWeakReference = new WeakReference<>(str); stringCache.put(str, stringWeakReference); return str; }
Source:
<code>public String getInstallationAccessTokenFromCache(String installationId) { try { CacheStats cacheStats = installationAccessTokenCache.stats(); LOG.info(cacheStats.toString()); return installationAccessTokenCache.get(installationId); } catch (Exception ex) { <START> LOG.error("Error retrieving token " + ex.getMessage()); <END> } return null; }</code><technical_language>Log actual exception a parameter</technical_language>

Target:
public String getInstallationAccessTokenFromCache(String installationId) { try { CacheStats cacheStats = installationAccessTokenCache.stats(); LOG.info(cacheStats.toString()); return installationAccessTokenCache.get(installationId); } catch (Exception ex) { LOG.error("Error retrieving token", ex); } return null; }
Source:
<code>public void shouldRemoveRepeatedContributorsWhenAdding() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setProperty("dublincore", "creator", "Administrator"); doc.setProperty("dublincore", "lastContributor", "Administrator"); doc.setProperty("dublincore", "contributors", new String[] { "user:Administrator", "user:Administrator", "user:Administrator", "user:Administrator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = new HashSet<>(); expectedChangedProperties.add("dc:contributors"); Event event = getEvent(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); <START> assertTrue(!contributors.contains("user:Administrator")); <END> assertTrue(contributors.contains(principalName)); }</code><technical_language>change assertTrue assertFalse</technical_language>

Target:
public void shouldRemoveRepeatedContributorsWhenAdding() { DocumentModel doc = session.createDocumentModel("/", "file", "File"); doc.setPropertyValue("dc:creator", "Administrator"); doc.setPropertyValue("dc:lastContributor", "Administrator"); doc.setPropertyValue("dc:contributors", new String[] { "user:Administrator", "user:Administrator", "user:Administrator", "user:Administrator" }); Map<String, Object> originalProperties = new HashMap<>(doc.getProperties("dublincore")); Set<String> expectedChangedProperties = Collections.singleton("dc:contributors"); Event event = getEventFromDocumentContext(BEFORE_DOC_UPDATE, session, session.getPrincipal()); storageService.addContributor(doc, event); assertDocumentPropertiesChanges(doc, originalProperties, expectedChangedProperties); String principalName = session.getPrincipal().getName(); List<String> contributors = Arrays.asList((String[]) doc.getPropertyValue("dc:contributors")); assertEquals(1, contributors.size()); assertFalse(contributors.contains("user:Administrator")); assertTrue(contributors.contains(principalName)); }
Source:
<code>public KafkaMessageContentsBuilder appendIntBigEndian(int v) { for (int i = 3; i >= 0; --i) { <START> contents.write((v & 0xff << i * 8) >> (i + 1) * 8); <END> } return this; }</code><technical_language>Is this correct? For i=0 (v & 0xff) (low 8 bits) >> 8, i.e. 0...? shift v >> (i * 8)) & 0xff</technical_language>

Target:
public KafkaMessageContentsBuilder appendIntBigEndian(int v) { for (int i = 3; i >= 0; --i) { contents.write((v >> (i * 8)) & 0xff); } return this; }
Source:
<code>public void processOutStream(int type, final BinaryRawWriterEx writer) throws IgniteCheckedException { if (type == OP_GET_FIELD_NAMES) { FieldsQueryCursor fq = (FieldsQueryCursor) cursor(); int cnt = fq.getColumnsCount(); writer.writeInt(cnt); for (int i = 0; i < cnt; i++) { writer.writeString(fq.getFieldName(i)); } } else if (type == OP_GET_FIELDS_META) { QueryCursorEx<List<?>> cursor = cursor(); List<GridQueryFieldMetadata> metadatas = cursor.fieldsMeta(); <START> writer.writeInt(metadatas.size()); <END> for (GridQueryFieldMetadata metadata: metadatas){ writer.writeString(metadata.fieldName()); writer.writeString(metadata.fieldTypeName()); } } else { super.processOutStream(type, writer); } }</code><technical_language>cursor.fieldsMeta() is guaranteed return a non-null result, add a check</technical_language>

Target:
@Override public void processOutStream(int type, final BinaryRawWriterEx writer) throws IgniteCheckedException { if (type == OP_GET_FIELD_NAMES) { FieldsQueryCursor fq = (FieldsQueryCursor) cursor(); int cnt = fq.getColumnsCount(); writer.writeInt(cnt); for (int i = 0; i < cnt; i++) { writer.writeString(fq.getFieldName(i)); } } else if (type == OP_GET_FIELDS_META) { QueryCursorEx<List<?>> cursor = cursor(); List<GridQueryFieldMetadata> metas = cursor.fieldsMeta(); if (metas == null) { writer.writeInt(0); } else { writer.writeInt(metas.size()); for (GridQueryFieldMetadata meta : metas) { writer.writeString(meta.fieldName()); writer.writeString(meta.fieldTypeName()); } } } else { super.processOutStream(type, writer); } }
Source:
<code>public void testResolveMappedEntryNumber() { final Map<Integer, Integer> designExpectedEntriesMap = new HashMap<>(); <START> designExpectedEntriesMap.put(9, 3); <END> designExpectedEntriesMap.put(10, 5); final Integer result1 = experimentDesignGenerator.resolveMappedEntryNumber(9, designExpectedEntriesMap); Assert.assertEquals("Lookup value 9 should return 3", Integer.valueOf(3), result1); final Integer result2 = experimentDesignGenerator.resolveMappedEntryNumber(10, designExpectedEntriesMap); Assert.assertEquals("Lookup value 10 should return 5", Integer.valueOf(5), result2); final Integer result5 = experimentDesignGenerator.resolveMappedEntryNumber(9999, designExpectedEntriesMap); Assert.assertEquals("9999 is not in map of checks, the return value should be the same number", Integer.valueOf(9999), result5); }</code><technical_language>Please numbers constants</technical_language>

Target:
public void testResolveMappedEntryNumber() { final Map<Integer, Integer> designExpectedEntriesMap = new HashMap<>(); designExpectedEntriesMap.put(ENTRY_NO_9, ENTRY_NO_3); designExpectedEntriesMap.put(ENTRY_NO_10, ENTRY_NO_5); final Integer result1 = experimentDesignGenerator.resolveMappedEntryNumber(9, designExpectedEntriesMap); Assert.assertEquals("Lookup value 9 should return 3", Integer.valueOf(3), result1); final Integer result2 = experimentDesignGenerator.resolveMappedEntryNumber(10, designExpectedEntriesMap); Assert.assertEquals("Lookup value 10 should return 5", Integer.valueOf(5), result2); final Integer result5 = experimentDesignGenerator.resolveMappedEntryNumber(9999, designExpectedEntriesMap); Assert.assertEquals("9999 is not in map of checks, the return value should be the same number", Integer.valueOf(9999), result5); }
Source:
<code>private void scrollCommentAndDiff(Point location, int lineHeight) { Rectangle size = commentAndDiffScrolledComposite.getBounds(); ScrollBar bar = commentAndDiffScrolledComposite.getVerticalBar(); <START> if (bar != null) { size.width = Math.max(0, size.width - bar.getSize().x); } bar = commentAndDiffScrolledComposite.getHorizontalBar(); if (bar != null) { <END> size.height = Math.max(0, size.height - bar.getSize().y); } Point topLeft = commentAndDiffScrolledComposite.getOrigin(); size.x = topLeft.x; size.y = topLeft.y; if (location.y >= size.y) { location.y += lineHeight; } if (!size.contains(location)) { int left = size.x; int top = size.y; if (location.x < left) { left = location.x; } else if (location.x > left + size.width) { left = Math.max(0, location.x - size.width); } if (location.y < top) { top = location.y; } else if (location.y > top + size.height) { top = Math.max(0, location.y - size.height); } commentAndDiffScrolledComposite.setOrigin(left, top); } }</code><technical_language>bars need checked for "isVisible" additionally. I scrolling cursor in second-last line instead of last. (I checked in debugger, bar objects non-null, I any)</technical_language>

Target:
private void scrollCommentAndDiff(Point location, int lineHeight) { Rectangle size = commentAndDiffScrolledComposite.getBounds(); ScrollBar bar = commentAndDiffScrolledComposite.getVerticalBar(); if (bar != null && bar.isVisible()) { size.width = Math.max(0, size.width - bar.getSize().x); } bar = commentAndDiffScrolledComposite.getHorizontalBar(); if (bar != null && bar.isVisible()) { size.height = Math.max(0, size.height - bar.getSize().y); } Point topLeft = commentAndDiffScrolledComposite.getOrigin(); size.x = topLeft.x; size.y = topLeft.y; if (location.y >= size.y) { location.y += lineHeight; } if (!size.contains(location)) { int left = size.x; int top = size.y; int minScroll = size.width / 4; if (location.x < left) { left = Math.max(0, left - Math.max(left - location.x, minScroll)); } else if (location.x > left + size.width) { int maxWidth = commentAndDiffComposite.getSize().x; int right = Math.max(location.x, left + size.width + minScroll); left = Math.min(right, maxWidth) - size.width; } if (location.y < top) { top = location.y; } else if (location.y > top + size.height) { top = location.y - size.height; } commentAndDiffScrolledComposite.setOrigin(left, top); } }
Source:
<code>private @Nullable ByteBuffer parsePacketHeader() throws IOException, BadPcapFileException { ByteBuffer pcapPacketHeader; SeekableByteChannel fFileChannel = getFileChannel(); if (fFileChannel.size() - fFileChannel.position() == 0) { return null; } if (fFileChannel.size() - fFileChannel.position() < <START> PcapFileValues.PCAPNG_PACKET_HEADER_SIZE) { <END> throw new BadPcapFileException("A pcapng header is invalid."); } pcapPacketHeader = ByteBuffer.allocate(PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); pcapPacketHeader.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); fFileChannel.read(pcapPacketHeader); pcapPacketHeader.flip(); return pcapPacketHeader; }</code><technical_language>If this method called a block is smaller packet header size (28), get exception. parsing blocks instead of packets</technical_language>

Target:
private @Nullable ByteBuffer parsePacketHeader() throws IOException, BadPcapFileException { ByteBuffer pcapPacketHeader; SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() == 0) { return null; } if (fileChannel.size() - fileChannel.position() < PcapFileValues.PCAPNG_PACKET_HEADER_SIZE) { throw new BadPcapFileException("A pcapng header is invalid."); } pcapPacketHeader = ByteBuffer.allocate(PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); pcapPacketHeader.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); fileChannel.read(pcapPacketHeader); pcapPacketHeader.flip(); return pcapPacketHeader; }
Source:
<code>public void queryUpdateConvertsExceptions() throws Exception { ConstraintViolationException cve = new ConstraintViolationException( "Duplicate entry 'studyTest-email@email.com' for key 'Accounts-StudyId-Email-Index'", null, null); PersistenceException ex = new PersistenceException(cve); reset(helper); doThrow(ex).when(mockSessionFactory).openSession(); HibernateAccount account = new HibernateAccount(); account.setStudyId("testStudy"); <START> helper.update(account); <END> }</code><technical_language>This test is called queryUpdate(), calls update()</technical_language>

Target:
public void queryUpdateConvertsExceptions() throws Exception { ConstraintViolationException cve = new ConstraintViolationException( "Duplicate entry 'studyTest-email@email.com' for key 'Accounts-StudyId-Email-Index'", null, null); PersistenceException ex = new PersistenceException(cve); reset(helper); doThrow(ex).when(mockSessionFactory).openSession(); HibernateAccount account = new HibernateAccount(); account.setStudyId("testStudy"); when(mockExceptionConverter.convert(ex, null)).thenReturn(TEST_EXCEPTION); try { helper.queryUpdate("query string", ImmutableMap.of()); fail("Should have thrown exception"); } catch(Exception e) { assertSame(TEST_EXCEPTION, e); } verify(mockExceptionConverter).convert(ex, null); }
Source:
<code>public int getVisibility(IBinding member) { if (member instanceof ICPPSpecialization) { return getSpecializedBinding().getVisibility(((ICPPSpecialization)member).getSpecializedBinding()); } try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); <START> throw new IllegalArgumentException(member.getName() + " is not a member of " + getName()); END> } }</code><technical_language>A CoreException necessarily member is owned class. Logging re-throwing exception double reporting re-thrown exception logged reported some other elsewhere</technical_language>

Target:
public int getVisibility(IBinding member) { if (member instanceof ICPPSpecialization) { return getSpecializedBinding().getVisibility(((ICPPSpecialization)member).getSpecializedBinding()); } try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); return v_public; } }
Source:
<code>public void loginAsync_errorHandlerThrows() { SyncCredentials credentials = SyncCredentials.usernamePassword("IWantToHackYou", "GeneralPassword", false); SyncUser.loginAsync(credentials, Constants.AUTH_URL, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.INVALID_CREDENTIALS, error.getErrorCode()); <START> looperThread.testComplete(); <END> } }); }</code><technical_language>purpose of this test is throw onError block. I understand removed IAE</technical_language>

Target:
public void loginAsync_errorHandlerThrows() throws InterruptedException { final AtomicBoolean errorThrown = new AtomicBoolean(false); Thread t = new Thread(new Runnable() { private volatile Handler handler; @Override public void run() { Looper.prepare(); try { handler = new Handler(); handler.post(new Runnable() { @Override public void run() { SyncCredentials credentials = SyncCredentials.usernamePassword("IWantToHackYou", "GeneralPassword", false); SyncUser.loginAsync(credentials, Constants.AUTH_URL, new SyncUser.Callback() { @Override public void onSuccess(SyncUser user) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.INVALID_CREDENTIALS, error.getErrorCode()); throw new IllegalArgumentException("BOOM"); } }); } }); Looper.loop(); } catch (IllegalArgumentException e) { errorThrown.set(true); } } }); t.start(); t.join(TimeUnit.SECONDS.toMillis(10)); assertTrue(errorThrown.get()); }
Source:
<code>public static DataWord of(byte[] data) { if (data == null || data.length == 0) { return DataWord.ZERO; } <START> boolean allExceptLastIsZero = true; <END> for (int i = 0; i < (data.length - 1); ++i) { if (data[i] != 0) { allExceptLastIsZero = false; break; } } if (allExceptLastIsZero) { if (data[data.length - 1] == 0) return DataWord.ZERO; if (data[data.length - 1] == 1) return DataWord.ONE; } if (data.length == 32) return new DataWord(Arrays.copyOf(data, data.length)); else if (data.length <= 32) { byte[] bytes = new byte[32]; System.arraycopy(data, 0, bytes, 32 - data.length, data.length); return new DataWord(bytes); } else { throw new RuntimeException(String.format("Data word can't exceed 32 bytes: 0x%s", ByteUtil.toHexString(data))); } }</code><technical_language>8 * data.length - ByteUtil.numberOfLeadingZeros(data). check residual 0 1</technical_language>

Target:
public static DataWord of(byte[] data) { if (data == null || data.length == 0) { return DataWord.ZERO; } int leadingZeroBits = numberOfLeadingZeros(data); int valueBits = 8 * data.length - leadingZeroBits; if (valueBits <= 8) { if (data[data.length - 1] == 0) return DataWord.ZERO; if (data[data.length - 1] == 1) return DataWord.ONE; } if (data.length == 32) return new DataWord(Arrays.copyOf(data, data.length)); else if (data.length <= 32) { byte[] bytes = new byte[32]; System.arraycopy(data, 0, bytes, 32 - data.length, data.length); return new DataWord(bytes); } else { throw new RuntimeException(String.format("Data word can't exceed 32 bytes: 0x%s", ByteUtil.toHexString(data))); } }
Source:
<code>private void setBackgroundText() { OCFileListFragment listFragment = getListOfFilesFragment(); if (listFragment != null) { int message = R.string.file_list_loading; if (!mSyncInProgress) { message = R.string.file_list_empty_moving; <START> if (listFragment.getProgressBar() != null && listFragment.getShadowView() != null) { <END> listFragment.getProgressBar().setVisibility(View.GONE); listFragment.getShadowView().setVisibility(View.VISIBLE); } } listFragment.setMessageForEmptyList(getString(message)); } else { Timber.e("OCFileListFragment is null"); } }</code><technical_language>Is listFragment.getProgressBar() is null while listFragment.getShadowView() is null properly setting progressBar visibility in case</technical_language>

Target:
private void setBackgroundText() { OCFileListFragment listFragment = getListOfFilesFragment(); if (listFragment != null) { int message = R.string.file_list_loading; if (!mSyncInProgress) { message = R.string.file_list_empty_moving; if (listFragment.getProgressBar() != null) { listFragment.getProgressBar().setVisibility(View.GONE); } if (listFragment.getShadowView() != null) { listFragment.getShadowView().setVisibility(View.VISIBLE); } } listFragment.setMessageForEmptyList(getString(message)); } else { Timber.e("OCFileListFragment is null"); } }
Source:
<code>public void tagPicture(View view) { MapleApplication app = (MapleApplication) getApplication(); <START> <END> companyTag = companySuggest.getText().toString(); app.setCurrentCompany(companyTag); ((TextView) this.findViewById(R.id.header)) .setText("Customize Your Ad"); ((Button) findViewById(R.id.changeTag)).setText(companyTag); toggleOptions(); }</code><technical_language>nit: This need a private instance variable in future. functionality grows for MapleApplication want get in <code>onCreate</code> function</technical_language>

Target:
public void tagPicture(View view) { companyTag = companySuggest.getText().toString(); app.setCurrentCompany(companyTag); ((TextView) this.findViewById(R.id.header)) .setText("Customize Your Ad"); ((Button) findViewById(R.id.changeTag)).setText(companyTag); toggleOptions(); }
Source:
<code>public void addApplicationDataForDeferredProcessing(RawData outgoingMessage) { <START> int max = maxDeferredProcessedOutgoingApplicationDataMessages == 0 ? 1 : maxDeferredProcessedOutgoingApplicationDataMessages; <END> if (deferredApplicationData.size() < max) { deferredApplicationData.add(outgoingMessage); } }</code><technical_language>is a default > 0, do need this compatibility stuff</technical_language>

Target:
public void addApplicationDataForDeferredProcessing(RawData outgoingMessage) { if (deferredApplicationData.size() < maxDeferredProcessedOutgoingApplicationDataMessages) { deferredApplicationData.add(outgoingMessage); } }
Source:
<code>public void testFieldsBinding() throws Exception { Handle h = dbRule.openHandle(); Update s = h.createUpdate("insert into something (id, name) values (:id, :name)"); s.bindFields(new Object() { @SuppressWarnings("unused") public int id = 0; @SuppressWarnings("unused") public String name = "Keith"; }); int insert_count = s.execute(); <START> assertThat(insert_count).isEqualTo(1); <END> }</code><technical_language>For completeness, this test select data out of table, verify expected</technical_language>

Target:
public void testFieldsBinding() throws Exception { Handle h = dbRule.openHandle(); Update s = h.createUpdate("insert into something (id, name) values (:id, :name)"); s.bindFields(new Object() { @SuppressWarnings("unused") public int id = 0; @SuppressWarnings("unused") public String name = "Keith"; }); int insert_count = s.execute(); Query q = h.createQuery("select * from something where id = :id").bind("id", 0); final Something fromDb = q.mapToBean(Something.class).findOnly(); assertThat(insert_count).isEqualTo(1); assertThat(fromDb).extracting(Something::getId, Something::getName).containsExactly(0, "Keith"); }
Source:
<code>public static UserSqlSandbox getStaticStorage(String username, String path) { <START> System.out.println("Get STatic storage path: " + path); <END> return new UserSqlSandbox(username, path); }</code><technical_language>This shoudln't</technical_language>

Target:
public static UserSqlSandbox getStaticStorage(String username, String path) { return new UserSqlSandbox(username, path); }
Source:
<code>public static void warn() { if (PORT > 0) { <START> LOGGER.warning("UDP broadcast capability has been removed from Jenkins."); <END> } }</code><technical_language>suggestion LOGGER.warning("UDP broadcast capability removed Jenkins. More information: <LINK_0>");</technical_language>

Target:
public static void warn() { if (PORT > 0) { LOGGER.warning("UDP broadcast capability has been removed from Jenkins. More information: <LINK_0>"); } }
Source:
<code>public BlockPlacementData(Vector3ic blockPosition, Side attachmentSide, Vector3fc viewingDirection, Vector2fc relativeAttachmentPosition) { <START> this.blockPosition = new Vector3i(blockPosition); <END> this.attachmentSide = attachmentSide; this.viewingDirection = new Vector3f(viewingDirection); this.relativeAttachmentPosition = new Vector2f(relativeAttachmentPosition); }</code><technical_language>Good question. tending null-checks ensure values non-null usage side accesses them. I suspect a null-check there.... Guava's Preconditions here</technical_language>

Target:
public BlockPlacementData(Vector3ic blockPosition, Side attachmentSide, Vector3fc viewingDirection, Vector2fc relativeAttachmentPosition) { this.blockPosition = new Vector3i(Preconditions.checkNotNull(blockPosition)); this.attachmentSide = Preconditions.checkNotNull(attachmentSide); this.viewingDirection = new Vector3f(Preconditions.checkNotNull(viewingDirection)); this.relativeAttachmentPosition = new Vector2f(Preconditions.checkNotNull(relativeAttachmentPosition)); }
Source:
<code>public void setupToC(final Page page, Site site, boolean firstPage) { funnel = new ToCInteractionFunnel((WikipediaApp)slidingPane.getContext().getApplicationContext(), site); tocProgress.setVisibility(View.GONE); <START> tocList.setLayoutDirection(isLangRTL(site.getLanguageCode()) ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR); <END> tocList.setVisibility(View.VISIBLE); headerView.setText(Html.fromHtml(page.getDisplayTitle())); headerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scrollToSection(page.getSections().get(0)); wasClicked = true; funnel.logClick(); hide(); } }); tocList.setAdapter(new ToCAdapter(page)); tocList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Section section = (Section) parent.getAdapter().getItem(position); scrollToSection(section); wasClicked = true; funnel.logClick(); hide(); } }); if (!page.isMainPage() && !firstPage) { if (WikipediaApp.getInstance().getOnboardingStateMachine().isTocTutorialEnabled()) { showTocOnboarding(); } } }</code><technical_language>instead set textDirection textAlignment (like RtlAwareTextView) in xml</technical_language>

Target:
public void setupToC(final Page page, Site site, boolean firstPage) { funnel = new ToCInteractionFunnel((WikipediaApp)slidingPane.getContext().getApplicationContext(), site); tocProgress.setVisibility(View.GONE); setLayoutDirection(tocList, site.getLanguageCode()); tocList.setVisibility(View.VISIBLE); headerView.setText(Html.fromHtml(page.getDisplayTitle())); headerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { scrollToSection(page.getSections().get(0)); wasClicked = true; funnel.logClick(); hide(); } }); tocList.setAdapter(new ToCAdapter(page)); tocList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Section section = (Section) parent.getAdapter().getItem(position); scrollToSection(section); wasClicked = true; funnel.logClick(); hide(); } }); if (!page.isMainPage() && !firstPage) { if (WikipediaApp.getInstance().getOnboardingStateMachine().isTocTutorialEnabled()) { showTocOnboarding(); } } }
Source:
<code>private boolean isMessageLoggedWithAdditionalContext() { if (loggingMethodInvocations.isEmpty()) { return false; } for (MethodInvocationTree mit : loggingMethodInvocations) { if (hasGetMessageInvocation(mit) && hasDynamicExceptionMessageUsage(mit)) { return true; } } <START> return false; <END> }</code><technical_language>This method replaced a anyMatch call : <LINK_0> return loggingMethodInvocations.stream().anyMatch(mit -> hasGetMessageInvocation(mit) && hasDynamicExceptionMessageUsage(mit));</technical_language>

Target:
private boolean isMessageLoggedWithAdditionalContext() { return loggingMethodInvocations.stream().anyMatch(mit -> hasGetMessageInvocation(mit) && hasDynamicExceptionMessageUsage(mit)); }
Source:
<code>MergingIterator() { this.queue = new TreeSet<>(new PeekFileRecordIteratorComparator()); int n = 0; log.info(String.format("Creating merging iterator from %d files", files.size())); int suggestedBufferSize = checkMemoryAndAdjustBuffer(files.size(), Defaults.BUFFER_SIZE); for (final Path f : files) { final FileRecordIterator it = new FileRecordIterator(f, suggestedBufferSize); if (it.hasNext()) { this.queue.add(new PeekFileRecordIterator(it, n++)); } else { <START> it.close(); <END> } } }</code><technical_language>This skipped if previous lines throw, try-with-resources fix</technical_language>

Target:
MergingIterator() { this.queue = new TreeSet<>(new PeekFileRecordIteratorComparator()); int n = 0; log.info(String.format("Creating merging iterator from %d files", files.size())); int suggestedBufferSize = checkMemoryAndAdjustBuffer(files.size()); for (final Path f : files) { final FileRecordIterator it = new FileRecordIterator(f, suggestedBufferSize); if (it.hasNext()) { this.queue.add(new PeekFileRecordIterator(it, n++)); } else { it.close(); } } }
Source:
<code>public void verifyNoDomainForMemoryWhenDomainHasLowSpace() { when(validStorageDomainValidator.isDomainWithinThresholds()) .thenReturn(new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)); <START> verifyNoDomainForMemory(Arrays.asList(validStorageDomain)); <END> }</code><technical_language>Please Collections.singletonList()</technical_language>

Target:
public void verifyNoDomainForMemoryWhenDomainHasLowSpace() { when(validStorageDomainValidator.isDomainWithinThresholds()) .thenReturn(new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)); verifyNoDomainForMemory(Collections.singletonList(validStorageDomain)); }
Source:
<code>private List<ThemeModel> filter(@NonNull List<ThemeModel> themes) { if (TextUtils.isEmpty(mLastSearch)) { return themes; } List<ThemeModel> filteredThemes = new ArrayList<>(); for (ThemeModel theme : themes) { <START> if (theme.getName().toLowerCase().contains(mLastSearch.toLowerCase())) { <END> filteredThemes.add(theme); } } return filteredThemes; }</code><technical_language>more efficient create a string variable for mLastSearch.toLowerCase() do case conversion iteration. More importantly, I matching theme name is enough - match description well. So: String lcSearch = mLastSearch.toLowerCase(); for (ThemeModel theme : themes) { if (theme.getName().toLowerCase().contains(lcSearch) || (theme.getDescription() != null && theme.getDescription().toLowerCase().contains(lcSearch))) { filteredThemes.add(theme); } }</technical_language>

Target:
private List<ThemeModel> filter(@NonNull List<ThemeModel> themes) { if (TextUtils.isEmpty(mLastSearch)) { return themes; } List<ThemeModel> filteredThemes = new ArrayList<>(); String lcSearch = mLastSearch.toLowerCase(); for (ThemeModel theme : themes) { if (theme.getName().toLowerCase().contains(lcSearch) || (theme.getDescription() != null && theme.getDescription().toLowerCase().contains(lcSearch))) { filteredThemes.add(theme); } } return filteredThemes; }
Source:
<code>public boolean supports(final RepositoryPath repositoryPath) { if (repositoryPath == null) { return false; } if (!MetadataHelper.MAVEN_METADATA_XML.equals(repositoryPath.getFileName().toString())) { return false; } Repository repository = repositoryPath.getRepository(); RepositoryProvider provider = repositoryProviderRegistry.getProvider(repository.getType()); <START> return provider instanceof ProxyRepositoryProvider; <END> }</code><technical_language>I check other instead: repository.getRemoteRepository() != null</technical_language>

Target:
public boolean supports(final RepositoryPath repositoryPath) { if (repositoryPath == null) { return false; } try { if (!RepositoryFiles.isMetadata(repositoryPath)) { return false; } } catch (IOException e) { throw new UndeclaredThrowableException(e); } Repository repository = repositoryPath.getRepository(); return repository.getRemoteRepository() != null; }
Source:
<code><START> public ValidationResult isReadOnlyPropertyCompatibleWithLunInterface() { <END> if (Boolean.TRUE.equals(disk.getReadOnly()) && disk.getDiskInterface() == DiskInterface.VirtIO_SCSI && disk.getDiskStorageType() == DiskStorageType.LUN) { return new ValidationResult( VdcBllMessages.ACTION_TYPE_FAILED_VIRT_IO_SCSI_INTERFACE_FOR_LUN_DISKS_DOES_NOT_SUPPORT_READ_ONLY_ATTR); } return ValidationResult.VALID; }</code><technical_language>reason combine this method isReadOnlyPropertyCompatibleWithInterface</technical_language>

Target:
public ValidationResult isReadOnlyPropertyCompatibleWithLunInterface() { if (Boolean.TRUE.equals(disk.getReadOnly()) && disk.getDiskInterface() == DiskInterface.VirtIO_SCSI) { return new ValidationResult( VdcBllMessages.ACTION_TYPE_FAILED_VIRT_IO_SCSI_INTERFACE_FOR_LUN_DISKS_DOES_NOT_SUPPORT_READ_ONLY_ATTR); } return ValidationResult.VALID; }