auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected VDS getVds(Guid id) { <START> return DbFacade.getInstance().getVdsDao().get(id); <END> }</code><technical_language>need for that..you getVdsDao() method</technical_language>

Target:
protected VDS getVds(Guid id) { return getVdsDAO().get(id); }
Source:
<code><START> public void lock(BindContext context) { <END> log.debug("Requesting locks"); context.lockPools(); log.debug("Successfully achieved locks"); }</code><technical_language>method protected (private if isolated in tests)</technical_language>

Target:
private void lock(BindContext context) { log.debug("Requesting locks"); context.lockPools(); log.debug("Successfully achieved locks"); }
Source:
<code>public void roundtripBase58_invalidCompressed() { String base58 = "5Kg5shEQWrf1TojaHTdc2kLuz5Mfh4uvp3cYu8uJHaHgfTGUbTD"; byte[] bytes = Base58.decodeChecked(base58); <START> bytes = Arrays.concatenate(bytes, new byte[]{0}); <END> base58 = Base58.encode(bytes); DumpedPrivateKey.fromBase58(null, base58); }</code><technical_language>I is alternative this spongycastle method</technical_language>

Target:
public void roundtripBase58_invalidCompressed() { String base58 = "5Kg5shEQWrf1TojaHTdc2kLuz5Mfh4uvp3cYu8uJHaHgfTGUbTD"; byte[] bytes = Base58.decodeChecked(base58); bytes = Arrays.copyOf(bytes, bytes.length+1); bytes[bytes.length-1] = 0; base58 = Base58.encode(bytes); DumpedPrivateKey.fromBase58(null, base58); }
Source:
<code>public boolean isUsableByPlayer(EntityPlayer player) { <START> return true; END> }</code><technical_language>How? This is kind of necessary open GUIs map</technical_language>

Target:
public boolean isUsableByPlayer(EntityPlayer player) { return adapter.isUsableByPlayer(player); }
Source:
<code><START> private boolean isHostLocal(EndpointDetails details, HostLocation myLocation) { <END> return details.isSetDatacenter() && details.isSetRack() && details.isSetHost() && myLocation.equals(HostLocation.of(details.getDatacenter(), details.getRack())); }</code><technical_language>nit: This static. Also, check details.isSetHost() is intentionally included (since involved in equals comparison)</technical_language>

Target:
private static boolean isHostLocal(EndpointDetails details, HostLocation myLocation) { return details.isSetDatacenter() && details.isSetRack() && details.isSetHost() && myLocation.equals(HostLocation.of(details.getDatacenter(), details.getRack())); }
Source:
<code>public void startTimer() { SwingUtilities.invokeLater( new Runnable() { public void run() { <START> remaining = new JLabel(timeLimit+" sec"); timer = new Timer(1000, listener); phaseDisplay.getClientgui().getMenuBar().add(display); timer.start(); display.setLayout(new FlowLayout()); display.add(remaining); display.add(progressBar); display.setVisible(true); <END> } }); }</code><technical_language>need rebuild timer panel time displayed. initialized in constructor set visible invisible needed</technical_language>

Target:
public void startTimer() { SwingUtilities.invokeLater( new Runnable() { public void run() { timer = new Timer(1000, listener); phaseDisplay.getClientgui().getMenuBar().add(display); timer.start(); display.setVisible(true); } }); }
Source:
<code>private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext context) { String pkgName = getDeserializerPackageName(targetType); final String simpleName = getDeserializerSimpleName(targetType); final PrintWriter pw; final ClassSourceFileComposerFactory cf; pw = context.tryCreate(logger, pkgName, simpleName); <START> if (pw == null) return null; <END> cf = new ClassSourceFileComposerFactory(pkgName, simpleName); cf.addImport(JavaScriptObject.class.getCanonicalName()); cf.addImport(ResultDeserializer.class.getCanonicalName()); cf.setSuperclass(ArrayResultDeserializer.class.getCanonicalName()); cf.addImplementedInterface(ResultDeserializer.class.getCanonicalName() + "<" + targetType.getQualifiedSourceName() + ">"); return cf.createSourceWriter(context, pw); }</code><technical_language>Again, cuddling</technical_language>

Target:
private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext context) { String pkgName = getDeserializerPackageName(targetType); final String simpleName = getDeserializerSimpleName(targetType); final PrintWriter pw; final ClassSourceFileComposerFactory cf; pw = context.tryCreate(logger, pkgName, simpleName); if (pw == null) { return null; } cf = new ClassSourceFileComposerFactory(pkgName, simpleName); cf.addImport(JavaScriptObject.class.getCanonicalName()); cf.addImport(ResultDeserializer.class.getCanonicalName()); cf.setSuperclass(ArrayResultDeserializer.class.getCanonicalName()); cf.addImplementedInterface(ResultDeserializer.class.getCanonicalName() + "<" + targetType.getQualifiedSourceName() + ">"); return cf.createSourceWriter(context, pw); }
Source:
<code><START> private void removeNmMdAndUqTags(final SAMRecord rec) { <END> rec.setAttribute(SAMTag.NM.name(), null); rec.setAttribute(SAMTag.MD.name(), null); rec.setAttribute(SAMTag.UQ.name(), null); }</code><technical_language>static</technical_language>

Target:
private static void removeNmMdAndUqTags(final SAMRecord rec) { rec.setAttribute(SAMTag.NM.name(), null); rec.setAttribute(SAMTag.MD.name(), null); rec.setAttribute(SAMTag.UQ.name(), null); }
Source:
<code>public void open() throws CatalogException { if (client == null) { client = HiveMetastoreClientFactory.create(hiveConf, hiveVersion); <START> if (client == null) { <END> throw new CatalogException("Can not open hive catalog because create hive metastore client failed."); } LOG.info("Connected to Hive metastore"); } if (!databaseExists(getDefaultDatabase())) { throw new CatalogException(String.format("Configured default database %s doesn't exist in catalog %s.", getDefaultDatabase(), getName())); } }</code><technical_language>This happen</technical_language>

Target:
public void open() throws CatalogException { if (client == null) { client = HiveMetastoreClientFactory.create(hiveConf, hiveVersion); LOG.info("Connected to Hive metastore"); } if (!databaseExists(getDefaultDatabase())) { throw new CatalogException(String.format("Configured default database %s doesn't exist in catalog %s.", getDefaultDatabase(), getName())); } }
Source:
<code>public void parsesHttpBody() throws IOException { final String body = "40 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( "form-data; name=\"t4\"" ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); try { MatcherAssert.assertThat( new RqHeaders.Base( multi.part("t4").iterator().next() ).header(RqMultipartTest.DISPOSITION), Matchers.hasItem("form-data; name=\"t4\"") ); MatcherAssert.assertThat( new RqPrint( new RqHeaders.Base( multi.part("t4").iterator().next() ) ).printBody(), Matchers.allOf( Matchers.startsWith("40 N"), Matchers.endsWith("CA 94085") ) ); } finally { <START> multi.body().close(); <END> multi.part("t4").iterator().next().body().close(); } }</code><technical_language>@raphaelln do need close of requests</technical_language>

Target:
public void parsesHttpBody() throws IOException { final String body = "40 N Wolfe Rd, Sunnyvale, CA 94085"; final String part = "t4"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( String.format("form-data; name=\"%s\"", part) ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); try { MatcherAssert.assertThat( new RqHeaders.Base( multi.part(part).iterator().next() ).header(RqMultipartTest.DISPOSITION), Matchers.hasItem("form-data; name=\"t4\"") ); MatcherAssert.assertThat( new RqPrint( new RqHeaders.Base( multi.part(part).iterator().next() ) ).printBody(), Matchers.allOf( Matchers.startsWith("40 N"), Matchers.endsWith("CA 94085") ) ); } finally { multi.part(part).iterator().next().body().close(); } }
Source:
<code>private void setAlternate(FileRepository from, FileRepository to) throws IOException { File alt = new File(from.getObjectDatabase().getDirectory(), <START> Constants.INFO_ALTERNATES); <END> alt.getParentFile().mkdirs(); File fromDir = from.getObjectDatabase().getDirectory(); File toDir = to.getObjectDatabase().getDirectory(); Path relative = fromDir.toPath().relativize(toDir.toPath()); write(alt, relative.toString() + "\n"); }</code><technical_language>optional: "import static"</technical_language>

Target:
private void setAlternate(FileRepository from, FileRepository to) throws IOException { File alt = new File(from.getObjectDatabase().getDirectory(), INFO_ALTERNATES); alt.getParentFile().mkdirs(); File fromDir = from.getObjectDatabase().getDirectory(); File toDir = to.getObjectDatabase().getDirectory(); Path relative = fromDir.toPath().relativize(toDir.toPath()); write(alt, relative.toString() + "\n"); }
Source:
<code>void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messageList = new ArrayList<>(); IntStream.range(0, count).forEach(index -> { final ServiceBusMessage message = new ServiceBusMessage(contents); <START> Assertions.assertTrue(messageList.add(message)); <END> }); when(asyncSender.send(messageList)).thenReturn(Mono.empty()); sender.send(messageList); verify(asyncSender, times(1)).send(messageList); verify(asyncSender).send(messageListCaptor.capture()); final List<ServiceBusMessage> sentMessages = messageListCaptor.getValue(); Assertions.assertEquals(count, sentMessages.size()); sentMessages.forEach(sentMessage -> { Assertions.assertArrayEquals(contents, sentMessage.getBody()); }); }</code><technical_language>assertion here? testing code</technical_language>

Target:
void sendMessageList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString(), contents); when(asyncSender.send(messages)).thenReturn(Mono.empty()); sender.send(messages); verify(asyncSender, times(1)).send(messages); verify(asyncSender).send(messageListCaptor.capture()); final List<ServiceBusMessage> sentMessages = messageListCaptor.getValue(); Assertions.assertEquals(count, sentMessages.size()); sentMessages.forEach(serviceBusMessage -> Assertions.assertArrayEquals(contents, serviceBusMessage.getBody())); }
Source:
<code>private void extractDetectors(Set<FractionMetadata> fractions) { Path buildDir = Paths.get(this.project.getBuild().getOutputDirectory()); Set<FractionMetadata> fractionsWithDetectors = fractions.stream() .filter(f -> f.getDetectorClasses().size() > 0) .collect(Collectors.toSet()); fractionsWithDetectors .forEach(f -> { f.getDetectorClasses().forEach((relative, full) -> { try { Path target = buildDir.resolve(relative); File targetFile = target.toFile(); if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); } copy(full, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { getLog().error(e); } }); }); String servicesFile = "META-INF" + File.separator + "services" + File.separator + "org.wildfly.swarm.spi.meta.FractionDetector"; File outFile = new File(this.project.getBuild().getOutputDirectory(), servicesFile); if (!outFile.exists()) { outFile.getParentFile().mkdirs(); } try (FileWriter writer = new FileWriter(outFile)) { fractionsWithDetectors .stream() .flatMap(f -> f.getDetectorClasses().keySet().stream()) .map(p -> p.toString().substring(0, p.toString().lastIndexOf('.'))) .map(s -> s.replace(File.separatorChar, '.')) .forEach(p -> { try { writer.write(p); writer.write("\n"); } catch (IOException e) { getLog().error(e); } }); writer.flush(); <START> writer.close(); <END> } catch (IOException e) { getLog().error(e); } }</code><technical_language>need close explicitly, in a try-with-resources block</technical_language>

Target:
private void extractDetectors(Set<FractionMetadata> fractions) { Path buildDir = Paths.get(this.project.getBuild().getOutputDirectory()); Set<FractionMetadata> fractionsWithDetectors = fractions.stream() .filter(f -> f.getDetectorClasses().size() > 0) .collect(Collectors.toSet()); fractionsWithDetectors .forEach(f -> { f.getDetectorClasses().forEach((relative, full) -> { try { Path target = buildDir.resolve(relative); File targetFile = target.toFile(); if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); } copy(full, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { getLog().error(e); } }); }); String servicesFile = "META-INF" + File.separator + "services" + File.separator + "org.wildfly.swarm.spi.meta.FractionDetector"; File outFile = new File(this.project.getBuild().getOutputDirectory(), servicesFile); if (!outFile.exists()) { outFile.getParentFile().mkdirs(); } try (FileWriter writer = new FileWriter(outFile)) { fractionsWithDetectors .stream() .flatMap(f -> f.getDetectorClasses().keySet().stream()) .map(p -> p.toString().substring(0, p.toString().lastIndexOf('.'))) .map(s -> s.replace(File.separatorChar, '.')) .forEach(p -> { try { writer.write(p); writer.write("\n"); } catch (IOException e) { getLog().error(e); } }); writer.flush(); } catch (IOException e) { getLog().error(e); } }
Source:
<code>private Object replaceObjects(Environment context) { if(!context.data.isPresent()) { throw new BadRequestException("REPLACE must include data argument"); } if(context.ids.isPresent()) { throw new BadRequestException("REPLACE must not include ids argument"); } Set<PersistentResource> existingObjects = (Set<PersistentResource>) fetchObjects(context); Set<PersistentResource> upsertedObjects = upsertObjects(context); Set<PersistentResource> toDelete = Sets.difference(existingObjects, upsertedObjects); if(!context.isRoot()) { toDelete.forEach(item -> context.parentResource.removeRelation(context.field.getName(), item)); } else { toDelete.forEach(PersistentResource::deleteResource); } <START> return toDelete; <END> }</code><technical_language>This return remains - deleted</technical_language>

Target:
private Object replaceObjects(Environment context) { if(!context.data.isPresent()) { throw new BadRequestException("REPLACE must include data argument"); } if(context.ids.isPresent()) { throw new BadRequestException("REPLACE must not include ids argument"); } Set<PersistentResource> existingObjects = (Set<PersistentResource>) fetchObjects(context); Set<PersistentResource> upsertedObjects = upsertObjects(context); Set<PersistentResource> toDelete = Sets.difference(existingObjects, upsertedObjects); if(!context.isRoot()) { toDelete.forEach(item -> context.parentResource.removeRelation(context.field.getName(), item)); } else { toDelete.forEach(PersistentResource::deleteResource); } return upsertedObjects; }
Source:
<code>private String localize(final Node elem) { <START> String ret = null; <END> String localized; if (elem != null) { try { Node contentNode = (Node) XPATH_CHARACTER_STRING.evaluate(elem, XPathConstants.NODE); ret = getText(contentNode); if (pathToLocalizedValue != null){ final Node localeNode = (Node) pathToLocalizedValue.evaluate(contentNode, XPathConstants.NODE); localized = getText(localeNode); if (localized != null && !localized.isEmpty()) { ret = localized; } } } catch (Exception e) { log.warn("Error parsing localized value for:", elem.getLocalName(), ". Message:", e.getMessage()); } } return ret; }</code><technical_language>easier read if instead of if (elem != null) call if (elem == null) { return null; }</technical_language>

Target:
private String localize(final Node elem) { String ret = null; String localized; if (elem == null) { return null; } try { Node contentNode = (Node) XPATH_CHARACTER_STRING.evaluate(elem, XPathConstants.NODE); ret = getText(contentNode); if (pathToLocalizedValue != null){ final Node localeNode = (Node) pathToLocalizedValue.evaluate(contentNode, XPathConstants.NODE); localized = getText(localeNode); if (localized != null && !localized.isEmpty()) { ret = localized; } } } catch (Exception e) { log.warn("Error parsing localized value for:", elem.getLocalName(), ". Message:", e.getMessage()); } return ret; }
Source:
<code>public XmlStringBuilder toXML() { <START> XmlStringBuilder xml = new XmlStringBuilder(this, getNamespace()); <END> xml.attribute(ID_TAG, getIdInitialMessage()); xml.attribute("xmlns", getNamespace()); xml.append('/'); xml.rightAngleBracket(); return xml; }</code><technical_language>new XmlStringBuilder(this) do right thing, i.e. adding opening tag xmlns attribute</technical_language>

Target:
public XmlStringBuilder toXML() { XmlStringBuilder xml = new XmlStringBuilder(this); xml.attribute(ID_TAG, getIdInitialMessage()); xml.closeEmptyElement(); return xml; }
Source:
<code>public Set<String> getCustomAttributes() { <START> return Collections.emptySet(); <END> }</code><technical_language>a type-checking warning here? Collections.EMPTY_SET type inference, older .emptySet() not. (or do Collections.<String> emptySet() too)</technical_language>

Target:
public Set<String> getCustomAttributes() { return Collections.<String>emptySet(); }
Source:
<code><START> public List<String> getDependencies(@NotNull String filePath) { <END> return myPathsToDependenciesMap.get(filePath); }</code><technical_language>declared this method nullable, null - not-null instead</technical_language>

Target:
public List<String> getDependencies(@NotNull String filePath) { List<String> dependencies = myPathsToDependenciesMap.get(filePath); assert dependencies != null; return dependencies; }
Source:
<code>protected void initialize(Map conf, String localDir) throws Exception { <START> <END> setConfig(conf); setLocalState(new LocalState(localDir)); _allowedHosts = listIntoSet((List<String>)conf.get(CONF_MESOS_ALLOWED_HOSTS)); _disallowedHosts = listIntoSet((List<String>)conf.get(CONF_MESOS_DISALLOWED_HOSTS)); setScheduler(new NimbusScheduler()); createLocalServerPort(); setupHttpServer(); }</code><technical_language>Please kill this new line</technical_language>

Target:
protected void initialize(Map conf, String localDir) throws Exception { _conf = conf; _state = new LocalState(localDir); _allowedHosts = listIntoSet((List<String>)conf.get(CONF_MESOS_ALLOWED_HOSTS)); _disallowedHosts = listIntoSet((List<String>)conf.get(CONF_MESOS_DISALLOWED_HOSTS)); _scheduler = new NimbusScheduler(); createLocalServerPort(); setupHttpServer(); }
Source:
<code><START> XPathEvaluationException(Throwable cause) { <END> super(cause); }</code><technical_language>is package-private intended visibility? missed access modifier</technical_language>

Target:
public XPathEvaluationException(Throwable cause) { super(cause); }
Source:
<code>public DefaultUrlSanitizer() { this(new ArrayList<String>() {{ add("http"); add("https"); add("mailto"); <START> }}); <END> }</code><technical_language>Arrays.asList instead</technical_language>

Target:
public DefaultUrlSanitizer() { this(Arrays.asList("http", "https", "mailto")); }
Source:
<code>private static Object readObjectTillTheEnd(final StringTokenizer tokenizer) { final JSONObject result = new JSONObject(); boolean finished = false; boolean allowObjectEnd = true; while (!finished) { final char nameStart = tokenizer.nextUnskippable(); if (nameStart == '}') { if (!allowObjectEnd) { throw syntaxError("Not allowed to finish object with comma", tokenizer); } finished = true; } else { if (nameStart != '"') { throw syntaxError("Unexpected symbol '" + nameStart + "'", tokenizer); } final String name = readStringTillTheEnd(tokenizer); final char separator = tokenizer.nextUnskippable(); if (separator != ':') { throw syntaxError("Waiting for name-value separator : while parsing object", tokenizer); } final Object value = parse(tokenizer); result.putOnce(name, value); final char nextToken = tokenizer.nextUnskippable(); if (nextToken == '}') { finished = true; } else if (nextToken != ',') { <START> throw syntaxError("Unexpected symbol " + nextToken + " while parsing object", tokenizer); <END> } } allowObjectEnd = false; } return result; }</code><technical_language>please put symbol in single quotes</technical_language>

Target:
private static Object readObjectTillTheEnd(final StringTokenizer tokenizer) { final JSONObject result = new JSONObject(); boolean finished = false; boolean allowObjectEnd = true; while (!finished) { final char nameStart = tokenizer.nextUnskippable(); if (nameStart == '}') { if (!allowObjectEnd) { throw syntaxError("Not allowed to finish object with comma", tokenizer); } finished = true; } else { if (nameStart != '"') { throw syntaxError("Unexpected symbol '" + nameStart + "'", tokenizer); } final String name = readStringTillTheEnd(tokenizer); final char separator = tokenizer.nextUnskippable(); if (separator != ':') { throw syntaxError("Waiting for name-value separator : while parsing object", tokenizer); } final Object value = parse(tokenizer); result.putOnce(name, value); final char nextToken = tokenizer.nextUnskippable(); if (nextToken == '}') { finished = true; } else if (nextToken != ',') { throw syntaxError("Unexpected symbol '" + nextToken + "' while parsing object", tokenizer); } } allowObjectEnd = false; } return result; }
Source:
<code><START> public void setLineVerticalIndent(int lineIndex, int verticalLineIndent) { <END> checkWidget(); if (isListening(ST.LineGetStyle)) return; if (lineIndex < 0 || lineIndex > content.getLineCount()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } if (verticalLineIndent == renderer.getLineVerticalIndent(lineIndex, 0)) { return; } setVariableLineHeight(); int oldBottom = getLinePixel(lineIndex + 1); renderer.setLineVerticalIndent(lineIndex, verticalLineIndent); resetCache(lineIndex, 1); int newBottom = getLinePixel(lineIndex + 1); redrawLines(lineIndex, 1, oldBottom != newBottom); int caretLine = getCaretLine(); if (lineIndex <= caretLine && caretLine < lineIndex + 1) { setCaretLocation(); } }</code><technical_language>Throws AIOOB exception called index = line count</technical_language>

Target:
public void setLineVerticalIndent(int lineIndex, int verticalLineIndent) { checkWidget(); if (isListening(ST.LineGetStyle)) return; if (lineIndex < 0 || lineIndex > content.getLineCount()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } if (verticalLineIndent == renderer.getLineVerticalIndent(lineIndex)) { return; } setVariableLineHeight(); int oldBottom = getLinePixel(lineIndex + 1); renderer.setLineVerticalIndent(lineIndex, verticalLineIndent); resetCache(lineIndex, 1); int newBottom = getLinePixel(lineIndex + 1); redrawLines(lineIndex, 1, oldBottom != newBottom); int caretLine = getCaretLine(); if (lineIndex <= caretLine && caretLine < lineIndex + 1) { setCaretLocation(); } }
Source:
<code>public Attachment getAttachment(AttachmentId attachmentId) throws AttachmentNotFoundException { <START> Preconditions.checkArgument(attachmentId != null); <END> return Optional.ofNullable(getEntityManager().find(JPAAttachment.class, attachmentId.getId())) .orElseThrow(() -> new AttachmentNotFoundException(attachmentId.getId())).toAttachment(); }</code><technical_language>more clear reading error log if error message in Precondition check! Similar other places</technical_language>

Target:
public Attachment getAttachment(AttachmentId attachmentId) throws AttachmentNotFoundException { Preconditions.checkArgument(attachmentId != null, "AttachmentId can't be null when trying to get attachment!"); return Optional.ofNullable(getEntityManager().find(JPAAttachment.class, attachmentId.getId())) .orElseThrow(() -> new AttachmentNotFoundException(attachmentId.getId())).toAttachment(); }
Source:
<code>private void testUUID() { long maxHigh = 0, maxLow = 0, minHigh = -1L, minLow = -1L; for (int i = 0; i < 100; i++) { ValueUuid uuid = ValueUuid.getNewRandom(); maxHigh |= uuid.getHigh(); maxLow |= uuid.getLow(); minHigh &= uuid.getHigh(); minLow &= uuid.getLow(); } ValueUuid max = ValueUuid.get(maxHigh, maxLow); assertEquals("ffffffff-ffff-4fff-bfff-ffffffffffff", max.getString()); ValueUuid min = ValueUuid.get(minHigh, minLow); assertEquals("00000000-0000-4000-8000-000000000000", min.getString()); ValueJavaObject vo_uuid = ValueJavaObject.getNoCopy(UUID.randomUUID(), null, null); <START> assertTrue(vo_uuid.convertTo(Value.UUID) instanceof ValueUuid); <END> ValueJavaObject vo_string = ValueJavaObject.getNoCopy(new String("This is not a ValueUuid object"), null, null); assertThrows(DbException.class, vo_string).convertTo(Value.UUID); }</code><technical_language>I guess assert UUID get ValueUuid instance equal initially passed value</technical_language>

Target:
private void testUUID() { long maxHigh = 0, maxLow = 0, minHigh = -1L, minLow = -1L; for (int i = 0; i < 100; i++) { ValueUuid uuid = ValueUuid.getNewRandom(); maxHigh |= uuid.getHigh(); maxLow |= uuid.getLow(); minHigh &= uuid.getHigh(); minLow &= uuid.getLow(); } ValueUuid max = ValueUuid.get(maxHigh, maxLow); assertEquals("ffffffff-ffff-4fff-bfff-ffffffffffff", max.getString()); ValueUuid min = ValueUuid.get(minHigh, minLow); assertEquals("00000000-0000-4000-8000-000000000000", min.getString()); String uuidStr = "12345678-1234-4321-8765-123456789012"; UUID origUUID = UUID.fromString(uuidStr); ValueJavaObject valObj = ValueJavaObject.getNoCopy(origUUID, null, null); Value valUUID = valObj.convertTo(Value.UUID); assertTrue(valUUID instanceof ValueUuid); assertTrue((valUUID.getString().equals(uuidStr))); assertTrue(valUUID.getObject().equals(origUUID)); ValueJavaObject vo_string = ValueJavaObject.getNoCopy(new String("This is not a ValueUuid object"), null, null); assertThrows(DbException.class, vo_string).convertTo(Value.UUID); }
Source:
<code>public void execute(FunctionContext<Object[]> context) { RegionFunctionContextImpl regionFunctionContext = (RegionFunctionContextImpl) context; ByteArrayWrapper key = (ByteArrayWrapper) regionFunctionContext.getFilter().iterator().next(); Region<ByteArrayWrapper, RedisSet> localRegion = regionFunctionContext.getLocalDataSet(regionFunctionContext.getDataSet()); Object[] args = context.getArguments(); RedisCommandType command = (RedisCommandType) args[0]; <START> Object result = compute(regionFunctionContext.getDataSet(), key, command, args); <END> context.getResultSender().lastResult(result); }</code><technical_language>this change made? getLocalDataSet want</technical_language>

Target:
public void execute(FunctionContext<Object[]> context) { RegionFunctionContextImpl regionFunctionContext = (RegionFunctionContextImpl) context; ByteArrayWrapper key = (ByteArrayWrapper) regionFunctionContext.getFilter().iterator().next(); Region<ByteArrayWrapper, RedisSet> localRegion = regionFunctionContext.getLocalDataSet(regionFunctionContext.getDataSet()); Object[] args = context.getArguments(); RedisCommandType command = (RedisCommandType) args[0]; Runnable computation = () -> { Object result = compute(localRegion, key, command, args); context.getResultSender().lastResult(result); }; computeWithPrimaryLocked(key, (LocalDataSet) localRegion, computation); }
Source:
<code><START> public void setStatistic(EntityPlayer player, StatBase statistic, int newValue, CallbackInfo ci, int oldValue) { <END> final Text message = Text.of(defaultAchievementTranslation, player.getDisplayName(), statistic.getStatName()); final MessageChannel targetSink; if (this.mcServer.isAnnouncingPlayerAchievements()) { targetSink = MessageChannel.TO_ALL; } else { targetSink = MessageChannel.TO_NONE; } final MessageEvent.MessageFormatter formatter = new MessageEvent.MessageFormatter(message); final GrantAchievementEvent event = SpongeEventFactory.createGrantAchievementEventTargetPlayer(Cause.of(NamedCause.of(NamedCause.SOURCE,player)), targetSink, Optional.of(targetSink), (Achievement) statistic, formatter, (Player) player, false); SpongeImpl.getGame().getEventManager().post(event); if (event.isCancelled()) { super.unlockAchievement(player, statistic, oldValue); } else { final Optional<MessageChannel> optChannel = event.getChannel(); if (optChannel.isPresent()) { final MessageChannel channel = optChannel.get(); channel.send(event.getMessage()); } } ci.cancel(); }</code><technical_language>reason for this injection public</technical_language>

Target:
private void setStatistic(EntityPlayer player, StatBase statistic, int newValue, CallbackInfo ci, int oldValue) { final Text message = Text.of(defaultAchievementTranslation, player.getDisplayName(), statistic.getStatName()); final MessageChannel targetSink; if (this.mcServer.isAnnouncingPlayerAchievements()) { targetSink = MessageChannel.TO_ALL; } else { targetSink = MessageChannel.TO_NONE; } final MessageEvent.MessageFormatter formatter = new MessageEvent.MessageFormatter(message); final GrantAchievementEvent event = SpongeEventFactory.createGrantAchievementEventTargetPlayer(Cause.of(NamedCause.of(NamedCause.SOURCE,player)), targetSink, Optional.of(targetSink), (Achievement) statistic, formatter, (Player) player, false); SpongeImpl.getGame().getEventManager().post(event); if (event.isCancelled()) { super.unlockAchievement(player, statistic, oldValue); } else { final Optional<MessageChannel> optChannel = event.getChannel(); if (optChannel.isPresent()) { final MessageChannel channel = optChannel.get(); channel.send(event.getMessage()); } } ci.cancel(); }
Source:
<code>public void deleteMetadata(String name, String metadataName) throws EntityNotFoundException { Product product = null; try { <START> product = productManager.load(name); <END> } catch (EntityNotFoundException e) { log.warning("EntityNotFoundException: " + e.getMessage()); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } try { product.deleteMetadata(metadataName); productManager.update(product); } catch (Exception e) { log.warning("Metadata not found : " + metadataName); throw new APIException(new EntityNotFoundException(Metadata.class, "Metadata not found : " + metadataName, metadataName)); } }</code><technical_language>coding style lines, I impression lots of code lines duplicates</technical_language>

Target:
public void deleteMetadata(String name, String metadataName) throws APIException { Product product = null; try { product = productManager.load(name); } catch (EntityNotFoundException e) { log.warning("EntityNotFoundException: " + e.getMessage()); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } try { product.deleteMetadata(metadataName); productManager.update(product); } catch (Exception e) { log.warning("Metadata not found : " + metadataName); throw new APIException(new EntityNotFoundException(Metadata.class, "Metadata not found : " + metadataName, metadataName)); } }
Source:
<code>public void testLostEventsTotalInRange() { <START> long start = 1376592664900000000L; <END> long end = 1376592665000000000L; long realEventsInRange = backend.getEventsInRange(start, end); assertEquals(11209L, realEventsInRange); }</code><technical_language>extracted constants in tests</technical_language>

Target:
public void testLostEventsTotalInRange() { long realEventsInRange = backend.getEventsInRange(rangeStart, rangeEnd); assertEquals(11209L, realEventsInRange); }
Source:
<code>public boolean isStethoEnabled() { <START> return isStethoPresent() && mHolder.impl.isStethoActive(); <END> }</code><technical_language>throughout, consider checking (mHolder != null) calling isStethoPresent() sIsStethoPresent. implementation robust called active, main goal of this check is avoid NPE. This intention clearer null check</technical_language>

Target:
public boolean isStethoEnabled() { return mHolder != null && mHolder.impl.isStethoActive(); }
Source:
<code>public void release(Throwable cause) { for (SlotExecutionVertexAssignment assignment : requestedLogicalSlots.values()) { ExecutionVertexID executionVertexId = assignment.getExecutionVertexId(); LOG.debug("Release {}", getLogicalSlotString(requestedLogicalSlots.getKeyBByKeyA(executionVertexId), executionVertexId)); <START> assignment <END> .getLogicalSlotFuture() .thenAccept(logicalSlot -> ((PhysicalSlot.Payload) logicalSlot).release(cause)); } }</code><technical_language>SharedSlot#release(...) is invoked, physical slot successfully allocated, shared slot is assigned payload yet. This means logical slot futures completed normally. This is I understand assumption. If do assumption logical slot futures completed normally, need cancel slotContextFuture pending logical slot futures in this release() method</technical_language>

Target:
public void release(Throwable cause) { Preconditions.checkState( slotContextFuture.isDone(), "Releasing of the shared slot is expected only from its successfully allocated physical slot ({})", physicalSlotRequestId); for (ExecutionVertexID executionVertexId : requestedLogicalSlots.keySetA()) { LOG.debug("Release {}", getLogicalSlotString(executionVertexId)); CompletableFuture<SingleLogicalSlot> logicalSlotFuture = requestedLogicalSlots.getValueByKeyA(executionVertexId); Preconditions.checkNotNull(logicalSlotFuture); Preconditions.checkState( logicalSlotFuture.isDone(), "Logical slot future must already done when release call comes from the successfully allocated physical slot ({})", physicalSlotRequestId); logicalSlotFuture.thenAccept(logicalSlot -> logicalSlot.release(cause)); } }
Source:
<code>public void testComputeJointSegmentCost() { <START> DateTime referenceTime = DateTime.now(DateTimeZone.UTC); <END> CostBalancerStrategy strategy = new CostBalancerStrategy(referenceTime, 4); double segmentCost = strategy.computeJointSegmentCosts( getSegment( 100, "DUMMY", new Interval( referenceTime, referenceTime.plusHours(1) ) ), getSegment( 101, "DUMMY", new Interval( referenceTime.minusDays(2), referenceTime.minusDays(2).plusHours(1) ) ) ); Assert.assertEquals(138028.62811791385d, segmentCost, 0); }</code><technical_language>I prefer if specific timestamps in tests ensure deterministic</technical_language>

Target:
public void testComputeJointSegmentCost() { DateTime referenceTime = new DateTime("2014-01-01T00:00:00"); CostBalancerStrategy strategy = new CostBalancerStrategy(referenceTime, 4); double segmentCost = strategy.computeJointSegmentCosts( getSegment( 100, "DUMMY", new Interval( referenceTime, referenceTime.plusHours(1) ) ), getSegment( 101, "DUMMY", new Interval( referenceTime.minusDays(2), referenceTime.minusDays(2).plusHours(1) ) ) ); Assert.assertEquals(138028.62811791385d, segmentCost, 0); }
Source:
<code>public CacheGroupPageScanner(GridKernalContext ctx) { this.ctx = ctx; log = ctx.log(getClass()); encrCfg = ctx.config().getDataStorageConfiguration().getEncryptionConfiguration(); <START> execSvc = new IgniteThreadPoolExecutor(REENCRYPT_THREAD_PREFIX, <END> ctx.igniteInstanceName(), encrCfg.getReencryptionThreadCnt(), encrCfg.getReencryptionThreadCnt(), IgniteConfiguration.DFLT_THREAD_KEEP_ALIVE_TIME, new LinkedBlockingQueue<>(), GridIoPolicy.SYSTEM_POOL, new OomExceptionHandler(ctx)); execSvc.allowCoreThreadTimeOut(true); DataStorageConfiguration dsCfg = ctx.config().getDataStorageConfiguration(); limiter = CU.isPersistenceEnabled(dsCfg) && encrCfg.getReencryptionRateLimit() > 0 ? new BasicRateLimiter(encrCfg.getReencryptionRateLimit() * MB / dsCfg.getPageSize()) : null; }</code><technical_language>single thread executor</technical_language>

Target:
public CacheGroupPageScanner(GridKernalContext ctx) { this.ctx = ctx; log = ctx.log(getClass()); DataStorageConfiguration dsCfg = ctx.config().getDataStorageConfiguration(); if (ctx.clientNode() || !CU.isPersistenceEnabled(dsCfg)) { batchSize = -1; limiter = null; singleExecSvc = null; return; } double rateLimit = dsCfg.getEncryptionConfiguration().getReencryptionRateLimit(); limiter = rateLimit > 0 ? new BasicRateLimiter(rateLimit * MB / (dsCfg.getPageSize() == 0 ? DataStorageConfiguration.DFLT_PAGE_SIZE : dsCfg.getPageSize())) : null; batchSize = dsCfg.getEncryptionConfiguration().getReencryptionBatchSize(); singleExecSvc = new IgniteThreadPoolExecutor(REENCRYPT_THREAD_PREFIX, ctx.igniteInstanceName(), 1, 1, IgniteConfiguration.DFLT_THREAD_KEEP_ALIVE_TIME, new LinkedBlockingQueue<>(), GridIoPolicy.SYSTEM_POOL, new OomExceptionHandler(ctx)); singleExecSvc.allowCoreThreadTimeOut(true); }
Source:
<code>public void saveBootstrapConfig(BootstrapConfig bootstrapConfig) { <START> configLocationFileStore.add(bootstrapConfig.getMotechDir()); <END> File defaultBootstrapFile = ConfigPropertiesUtils.getDefaultPropertiesFile(ConfigLocation.FileAccessType.WRITABLE, configLocationFileStore.getAll(true), BOOTSTRAP_PROPERTIES); ConfigPropertiesUtils.saveConfig(defaultBootstrapFile, BootstrapConfigPropertyMapper.toProperties(bootstrapConfig)); }</code><technical_language>config location is ~/.motech , ~/.motech/config - in Tomcat config of this</technical_language>

Target:
public void saveBootstrapConfig(BootstrapConfig bootstrapConfig) { configLocationFileStore.add(new File(bootstrapConfig.getMotechDir(), "config").getAbsolutePath()); File defaultBootstrapFile = ConfigPropertiesUtils.getDefaultPropertiesFile(ConfigLocation.FileAccessType.WRITABLE, configLocationFileStore.getAll(), BOOTSTRAP_PROPERTIES); ConfigPropertiesUtils.saveConfig(defaultBootstrapFile, BootstrapConfigPropertyMapper.toProperties(bootstrapConfig)); }
Source:
<code>private static void usage(PrintStream writer) { final String cmdName = "dumpapp " + NAME; final String usagePrefix = "Usage: " + cmdName + " "; writer.println(usagePrefix + "<command> [command-options]"); writer.print(usagePrefix + CMD_LIST); writer.println(); writer.print(usagePrefix + CMD_CLEAR); writer.println(); <START> writer.print(usagePrefix + CMD_REMOVE_ROW + " <row id>"); <END> writer.println(); writer.print(usagePrefix + CMD_REFRESH); writer.println(); }</code><technical_language><rowid> <row-id>. spaces :)</technical_language>

Target:
private static void usage(PrintStream writer) { final String cmdName = "dumpapp " + NAME; final String usagePrefix = "Usage: " + cmdName + " "; writer.println(usagePrefix + "<command> [command-options]"); writer.print(usagePrefix + CMD_LIST); writer.println(); writer.print(usagePrefix + CMD_CLEAR); writer.println(); writer.print(usagePrefix + CMD_DELETE + " <rowId>"); writer.println(); writer.print(usagePrefix + CMD_REFRESH); writer.println(); }
Source:
<code>public void reconcileTrackedClients(Set<UUID> trackedClients) { <START> messageTrackers.entrySet().removeIf(x -> !trackedClients.contains(x)); <END> }</code><technical_language>This work - incompatible types. is missing testing ..</technical_language>

Target:
public void reconcileTrackedClients(Set<UUID> trackedClients) { messageTrackers.keySet().retainAll(trackedClients); }
Source:
<code>public String getName() { <START> return "Echo Off"; <END> }</code><technical_language>This is true</technical_language>

Target:
public String getName() { return "Headers disabled"; }
Source:
<code>public MethodHandle getMethod() { if (currentMethod.get() == null) return super.getMethod(); else <START> return currentMethod.get(); <END> }</code><technical_language>nit: missing curly braces one-line blocks</technical_language>

Target:
public MethodHandle getMethod() { if (currentMethod.get() == null) { return super.getMethod(); } else { return currentMethod.get(); } }
Source:
<code>public void testListEmptyPrefixDelimiter() throws Exception { final String container = getContainerName(); BlobStore blobStore = view.getBlobStore(); try { blobStore.createContainerInLocation(null, container); ImmutableList<String> blobs = ImmutableList.of("a", "b", "c"); for (String blob : blobs) { blobStore.putBlob(container, blobStore.blobBuilder(blob).payload("").build()); } ListContainerOptions options = ListContainerOptions.Builder.delimiter("") .prefix("").afterMarker(""); PageSet<? extends StorageMetadata> rs = blobStore.list(container, options); <START> assertEquals(rs.size(), 3); <END> ImmutableList.Builder<String> builder = ImmutableList.builder(); for (StorageMetadata sm : rs) { builder.add(sm.getName()); } assertThat(builder.build()).containsExactlyElementsOf(blobs); } finally { returnContainer(container); } }</code><technical_language>This is necessary assertThat call checks length</technical_language>

Target:
public void testListEmptyPrefixDelimiter() throws Exception { final String container = getContainerName(); BlobStore blobStore = view.getBlobStore(); blobStore.createContainerInLocation(null, container); try { ImmutableList<String> blobs = ImmutableList.of("a", "b", "c"); for (String blob : blobs) { blobStore.putBlob(container, blobStore.blobBuilder(blob).payload("").build()); } ListContainerOptions options = ListContainerOptions.Builder.delimiter("") .prefix("").afterMarker(""); PageSet<? extends StorageMetadata> rs = blobStore.list(container, options); ImmutableList.Builder<String> builder = ImmutableList.builder(); for (StorageMetadata sm : rs) { builder.add(sm.getName()); } assertThat(builder.build()).containsExactlyElementsOf(blobs); } finally { returnContainer(container); } }
Source:
<code>protected boolean verifyAddVM() { <START> final MacPoolManagerStrategy macPool = getMacPoolForVm(); <END> final List<String> reasons = getReturnValue().getCanDoActionMessages(); final int nicsCount = getParameters().getVmsCount() * getVmNicDao().getAllForTemplate(getVmTemplateId()).size(); final int priority = getParameters().getVmStaticData().getPriority(); return VmHandler.verifyAddVm(reasons, nicsCount, priority, macPool); }</code><technical_language>This generates a null pointer exception in MacPoolPerDc.poolForVm() I try create a new VM pool</technical_language>

Target:
protected boolean verifyAddVM() { final List<String> reasons = getReturnValue().getCanDoActionMessages(); final int nicsCount = getParameters().getVmsCount() * getVmNicDao().getAllForTemplate(getVmTemplateId()).size(); final int priority = getParameters().getVmStaticData().getPriority(); return VmHandler.verifyAddVm(reasons, nicsCount, priority, getMacPool()); }
Source:
<code>public void testDNRestart() throws Exception { BlockReaderTestUtil.enableShortCircuitShmTracing(); TemporarySocketDirectory sockDir = new TemporarySocketDirectory(); Configuration conf = createShortCircuitConf("testDNRestart", sockDir); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); <START> DistributedFileSystem fs = cluster.getFileSystem(); <END> final ShortCircuitCache cache = fs.getClient().getClientContext().getShortCircuitCache(); DomainPeer peer = getDomainPeerToDn(conf); MutableBoolean usedPeer = new MutableBoolean(false); ExtendedBlockId blockId = new ExtendedBlockId(123, "xyz"); final DatanodeInfo datanode = new DatanodeInfo.DatanodeInfoBuilder() .setNodeID(cluster.getDataNodes().get(0).getDatanodeId()).build(); Slot slot1 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); cluster.getDataNodes().get(0).getShortCircuitRegistry() .registerSlot(blockId, slot1.getSlotId(), false); cluster.restartDataNode(0); Thread.sleep(1000); cache.scheduleSlotReleaser(slot1); Slot slot2 = null; try { slot2 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); } catch (ClosedChannelException ce) { } cache.scheduleSlotReleaser(slot2); Thread.sleep(2000); Assert.assertTrue(cluster.getDataNodes().get(0).getShortCircuitRegistry() .getShmNum() == 0); Assert.assertTrue(cache.getDfsClientShmManager().getShmNum() == 0); cluster.shutdown(); }</code><technical_language>is mini cluster required? starting a mini cluster takes time prone flaky failures. nice avoid it</technical_language>

Target:
public void testDNRestart() throws Exception { TemporarySocketDirectory sockDir = new TemporarySocketDirectory(); Configuration conf = createShortCircuitConf("testDNRestart", sockDir); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); try { cluster.waitActive(); DistributedFileSystem fs = cluster.getFileSystem(); final ShortCircuitCache cache = fs.getClient().getClientContext().getShortCircuitCache(); DomainPeer peer = getDomainPeerToDn(conf); MutableBoolean usedPeer = new MutableBoolean(false); ExtendedBlockId blockId = new ExtendedBlockId(123, "xyz"); final DatanodeInfo datanode = new DatanodeInfo.DatanodeInfoBuilder() .setNodeID(cluster.getDataNodes().get(0).getDatanodeId()).build(); Slot slot1 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); cluster.getDataNodes().get(0).getShortCircuitRegistry() .registerSlot(blockId, slot1.getSlotId(), false); cluster.restartDataNode(0); Thread.sleep(1000); cache.scheduleSlotReleaser(slot1); Slot slot2 = null; try { slot2 = cache.allocShmSlot(datanode, peer, usedPeer, blockId, "testReleaseSlotReuseDomainSocket_client"); } catch (ClosedChannelException ce) { } cache.scheduleSlotReleaser(slot2); Thread.sleep(2000); Assert.assertEquals(0, cluster.getDataNodes().get(0).getShortCircuitRegistry().getShmNum()); Assert.assertEquals(0, cache.getDfsClientShmManager().getShmNum()); } finally { cluster.shutdown(); } }
Source:
<code>public void onStart() { super.onStart(); if (getActivity().getClass() == PreferenceActivity.class) { ((PreferenceActivity) getActivity()).getSupportActionBar().setTitle(R.string.statistics_label); <START> } <END> refreshStatistics(); }</code><technical_language>Oh, I lines removed. title in settings is handled StatisticsFragment (where added a similar change). a leftover statistics screen single tab</technical_language>

Target:
public void onStart() { super.onStart(); refreshStatistics(); }
Source:
<code>public void adsVuapTimeProgressingFandom(String pageType, String pageName, String slotName) throws InterruptedException { AdsFandomObject fandomPage = loadPage(pageName, pageType); AutoplayVuap videoFanTakeover = prepareSlot(slotName, fandomPage); <START> networkTrafficInterceptor.startIntercepting(); <END> videoFanTakeover.playVideoFor(Duration.ofSeconds(1)); double firstPause = videoFanTakeover.getCurrentTime(); videoFanTakeover.playVideoFor(Duration.ofSeconds(1)); double currentTime = videoFanTakeover.getCurrentTime(); Assert.assertTrue( firstPause < currentTime, String.format( "Video time is not progressing, first pause time %s is not smaller than current %s", firstPause, currentTime) ); }</code><technical_language>do need NTI in this test</technical_language>

Target:
public void adsVuapTimeProgressingFandom(String pageType, String pageName, String slotName) throws InterruptedException { AdsFandomObject fandomPage = loadPage(pageName, pageType); AutoplayVuap vuap = prepareSlot(slotName, fandomPage); playVideoAndCheckTimeProgressing(vuap, DESKTOP_VIDEO_TRIGGER_AREA); }