auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void compile(Definition javaDef) throws IOException { String fileSep = System.getProperty("file.separator"); String endl = System.getProperty("line.separator"); LatexFilter lf; if(makeDocument) lf = new DocumentationFilter(context); else lf = new LatexFilter(context); javaDef.accept(lf); String kLatexStyle = KPaths.getKBase(false) + fileSep + "include" + fileSep + "latex" + fileSep + "k.sty"; latexStyleFile = new File(context.dotk.getAbsolutePath() + fileSep + "k.sty"); FileUtils.writeStringToFile(latexStyleFile, FileUtil.getFileContent(kLatexStyle)); String latexified = "\\nonstopmode" + endl + "\\PassOptionsToPackage{pdftex,usenames,dvipsnames,svgnames,x11names}{xcolor}"+ endl + "\\PassOptionsToPackage{pdftex}{hyperref}"+ endl + "\\documentclass{article}" + endl + "\\usepackage[" + options.docStyle() + "]{k}" + endl; String preamble = lf.getPreamble().toString(); latexified += preamble + "\\begin{document}" + endl + lf.getResult() + "\\end{document}" + endl; <START> File canonicalFile = options.definition(); <END> String latexFilePath; if(makeDocument) latexFilePath= context.dotk.getAbsolutePath() + fileSep + FilenameUtils.removeExtension(canonicalFile.getName()) + "-doc.tex"; else latexFilePath = context.dotk.getAbsolutePath() + fileSep + FilenameUtils.removeExtension(canonicalFile.getName()) + ".tex"; latexFile = new File(latexFilePath); FileUtils.writeStringToFile(latexFile, latexified); sw.printIntermediate("Latex Generation"); }</code><technical_language>name for main file of a definition please</technical_language>

Target:
public void compile(Definition javaDef) throws IOException { String fileSep = System.getProperty("file.separator"); String endl = System.getProperty("line.separator"); LatexFilter lf; if(makeDocument) lf = new DocumentationFilter(context); else lf = new LatexFilter(context); javaDef.accept(lf); String kLatexStyle = KPaths.getKBase(false) + fileSep + "include" + fileSep + "latex" + fileSep + "k.sty"; latexStyleFile = new File(context.dotk.getAbsolutePath() + fileSep + "k.sty"); FileUtils.writeStringToFile(latexStyleFile, FileUtil.getFileContent(kLatexStyle)); String latexified = "\\nonstopmode" + endl + "\\PassOptionsToPackage{pdftex,usenames,dvipsnames,svgnames,x11names}{xcolor}"+ endl + "\\PassOptionsToPackage{pdftex}{hyperref}"+ endl + "\\documentclass{article}" + endl + "\\usepackage[" + options.docStyle() + "]{k}" + endl; String preamble = lf.getPreamble().toString(); latexified += preamble + "\\begin{document}" + endl + lf.getResult() + "\\end{document}" + endl; File canonicalFile = options.mainDefinitionFile(); String latexFilePath; if(makeDocument) latexFilePath= context.dotk.getAbsolutePath() + fileSep + FilenameUtils.removeExtension(canonicalFile.getName()) + "-doc.tex"; else latexFilePath = context.dotk.getAbsolutePath() + fileSep + FilenameUtils.removeExtension(canonicalFile.getName()) + ".tex"; latexFile = new File(latexFilePath); FileUtils.writeStringToFile(latexFile, latexified); sw.printIntermediate("Latex Generation"); }
Source:
<code>private void waitUntilFlowPreparationFinish() { while (this.preparingFlowCount.intValue() != 0) { try { logger.info(this.preparingFlowCount + " flow(s) is/are still being setup before complete " + "deactivation."); Thread.sleep(Duration.ofSeconds(5).toMillis()); } catch (final InterruptedException ex) { <START> logger.debug(ex); <END> } } }</code><technical_language>Interrupts re-raised</technical_language>

Target:
private void waitUntilFlowPreparationFinish() throws InterruptedException { final Duration SLEEP_INTERVAL = Duration.ofSeconds(5); while (this.preparingFlowCount.intValue() != 0) { logger.info(this.preparingFlowCount + " flow(s) is/are still being setup before complete " + "deactivation."); Thread.sleep(SLEEP_INTERVAL.toMillis()); } }
Source:
<code>private void pollTxnStream() throws Exception { if (subscription.isStopped()) { return; } txnStream.seek(lastReadAddress + 1L); <START> List<ILogData> updates = txnStream.remaining(); <END> if (updates.isEmpty()) { TimeUnit.MILLISECONDS.sleep(IDLE_WAIT_TIME_MS.toMillis()); pollingExecutor.submit(this); return; } long remainingBlockTime = QUEUE_FULL_BLOCK_TIME_MS.toNanos(); for (ILogData update : updates) { if (subscription.isStopped()) { return; } long startTime = System.nanoTime(); if (!subscription.enqueueStreamEntry(update, remainingBlockTime)) { break; } remainingBlockTime -= System.nanoTime() - startTime; lastReadAddress = update.getGlobalAddress(); } pollingExecutor.submit(this); }</code><technical_language>of remaining() is OOM scenario. more selectivity, this result in OOM if is a lot of distance lastAddress tail</technical_language>

Target:
private void pollTxnStream() throws Exception { if (subscription.isStopped()) { return; } txnStream.seek(lastReadAddress + 1L); List<ILogData> updates = txnStream.remainingAtMost(subscription.getStreamBufferSize()); if (updates.isEmpty()) { TimeUnit.MILLISECONDS.sleep(IDLE_WAIT_TIME_MS.toMillis()); pollingExecutor.submit(this); return; } long remainingBlockTime = QUEUE_FULL_BLOCK_TIME_MS.toNanos(); for (ILogData update : updates) { if (subscription.isStopped()) { return; } long startTime = System.nanoTime(); if (!subscription.enqueueStreamEntry(update, remainingBlockTime)) { break; } remainingBlockTime -= System.nanoTime() - startTime; lastReadAddress = update.getGlobalAddress(); } pollingExecutor.submit(this); }
Source:
<code>public String resetRoute(String id) throws Exception { ManagedRouteMBean managedRouteMBean = camelContext.getManagedRoute(id, ManagedRouteMBean.class); if (managedRouteMBean != null) { managedRouteMBean.reset(true); } else { String description = "The provided route id does not exists :" + camelContext.getRoute(id); ResponseEntity<?> responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(description); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(responseEntity); } <START> return null; <END> }</code><technical_language>if this method return in fact in Mvc endpoint return is for logging purpose</technical_language>

Target:
public void resetRoute(String id) throws Exception { ManagedRouteMBean managedRouteMBean = camelContext.getManagedRoute(id, ManagedRouteMBean.class); if (managedRouteMBean != null) { managedRouteMBean.reset(true); } }
Source:
<code>public Response deletePropertyByPath(@PathParam("clusterId") String clusterId, @PathParam("path") String path) { path = "/" + path; if (!ZkValidationUtil.isPathValid(path)) { LOG.info("The propertyStore path is invalid for cluster {}", path, clusterId); return badRequest( <START> "Invalid path string. Valid path strings use slash as the directory separator and names the location of ZNode"); <END> } final String recordPath = PropertyPathBuilder.propertyStore(clusterId) + path; ZkBaseDataAccessor<byte[]> propertyStoreDataAccessor = getByteArrayDataAccessor(); if (!propertyStoreDataAccessor.remove(recordPath, AccessOption.PERSISTENT)) { return serverError("Failed to delete PropertyStore record in path: " + path); } return OK(); }</code><technical_language>Nit, long line? split strings concatenation</technical_language>

Target:
public Response deletePropertyByPath(@PathParam("clusterId") String clusterId, @PathParam("path") String path) { path = "/" + path; if (!ZkValidationUtil.isPathValid(path)) { LOG.info("The propertyStore path is invalid for cluster {}", path, clusterId); return badRequest( "Invalid path string. Valid path strings use slash as the directory separator and names the location of ZNode"); } final String recordPath = PropertyPathBuilder.propertyStore(clusterId) + path; BaseDataAccessor<byte[]> propertyStoreDataAccessor = getByteArrayDataAccessor(); if (!propertyStoreDataAccessor.remove(recordPath, AccessOption.PERSISTENT)) { return serverError("Failed to delete PropertyStore record in path: " + path); } return OK(); }
Source:
<code>private boolean needClearCache(IResource resource) { boolean cacheUpdated = false; <START> String resourceExtension = resource.getFileExtension().toUpperCase(); <END> if (WorkspaceImageFigure.isSvgImage(resourceExtension)) { String svgUri = resource.getFullPath().toString(); Option<String> removed = SVGWorkspaceImageFigure.removeFromCache(svgUri); if (removed.some()) { cacheUpdated = true; } } else { URL url; try { url = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().append(resource.getFullPath()).toOSString()).toURI().toURL(); } catch (MalformedURLException e) { DiagramPlugin.getDefault().logError("Invalid uri : " + e.getMessage()); return false; } ImageDescriptor bundledImageDescriptor = ImageDescriptor.createFromURL(url); boolean removed = DiagramUIPlugin.getPlugin().removeCacheImage(bundledImageDescriptor); if (removed) { cacheUpdated = true; } } return cacheUpdated; }</code><technical_language>toUpperCase() useless is done in "WorkspaceImageFigure.isSvgImage(resourceExtension)"</technical_language>

Target:
private boolean needClearCache(IResource resource) { boolean cacheUpdated = false; String resourceExtension = resource.getFileExtension(); if (WorkspaceImageFigure.isSvgImage(resourceExtension)) { String svgUri = resource.getFullPath().toString(); Option<String> removed = SVGWorkspaceImageFigure.removeFromCache(svgUri); if (removed.some()) { cacheUpdated = true; } } else { URL url; try { url = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().append(resource.getFullPath()).toOSString()).toURI().toURL(); } catch (MalformedURLException e) { DiagramPlugin.getDefault().logError("Invalid uri : " + e.getMessage()); return false; } ImageDescriptor bundledImageDescriptor = ImageDescriptor.createFromURL(url); boolean removed = DiagramUIPlugin.getPlugin().removeCacheImage(bundledImageDescriptor); if (removed) { cacheUpdated = true; } } return cacheUpdated; }
Source:
<code>public Bullet shoot() { final SpriteSheet spritesheet = new SpriteSheet(getGame().getSpriteSheet()); final Bullet newBullet = new Bullet(getX() + 5, getY() + 2, spritesheet); <START> Game.logfile.writeShoot("Alien", getX(), getY()); <END> newBullet.setDownSpeed(4.4); newBullet.setSpritesheet(172,605,6,16); return newBullet; }</code><technical_language>add type of alien logfile</technical_language>

Target:
public Bullet shoot() { final SpriteSheet spritesheet = new SpriteSheet(getGame().getSpriteSheet()); final Bullet newBullet = new Bullet(getX() + 5, getY() + 2, spritesheet); Game.logfile.writeShoot("AlienType2", getX(), getY()); newBullet.setDownSpeed(4.4); newBullet.setSpritesheet(172,605,6,16); return newBullet; }
Source:
<code>public void htmlFlag(){ String results = (String) Eclim.execute(new String[]{ "java_element_doc", "-p", Jdt.TEST_PROJECT, "-f", TEST_FILE, "-o", "255", "-l", "11", "-e", "utf-8", "-h", "true" }); <START> Assert.assertTrue("HTML Format expected", results.startsWith("<html><head>")); <END> }</code><technical_language>stick existing coding style omit Assert. prefix here</technical_language>

Target:
public void htmlFlag(){ String results = (String) Eclim.execute(new String[]{ "java_element_doc", "-p", Jdt.TEST_PROJECT, "-f", TEST_FILE, "-o", "255", "-l", "11", "-e", "utf-8", "-h", "true" }); assertTrue("HTML Format expected", results.startsWith("<html><head>")); }
Source:
<code>private String createCanonicalRequestHash( Map<String, String> headers, List<String> sortedHeaderNames) { <START> StringBuilder sb = new StringBuilder(httpMethod).append(NEW_LINE); <END> String urlPath = uri.getRawPath().isEmpty() ? "/" : uri.getRawPath(); sb.append(urlPath).append(NEW_LINE); String actionQueryString = uri.getRawQuery() != null ? uri.getRawQuery() : ""; sb.append(actionQueryString).append(NEW_LINE); StringBuilder canonicalHeaders = new StringBuilder(); for (String headerName : sortedHeaderNames) { canonicalHeaders.append(headerName + ":" + headers.get(headerName)).append(NEW_LINE); } sb.append(canonicalHeaders).append(NEW_LINE); sb.append(Joiner.on(';').join(sortedHeaderNames)).append(NEW_LINE); sb.append(DigestUtils.sha256Hex(requestPayload)); return DigestUtils.sha256Hex(sb.toString()); }</code><technical_language>Google style is abbreviations sb. url</technical_language>

Target:
private String createCanonicalRequestHash( Map<String, String> headers, List<String> sortedHeaderNames) { StringBuilder canonicalRequest = new StringBuilder(httpMethod).append("\n"); String urlPath = uri.getRawPath().isEmpty() ? "/" : uri.getRawPath(); canonicalRequest.append(urlPath).append("\n"); String actionQueryString = uri.getRawQuery() != null ? uri.getRawQuery() : ""; canonicalRequest.append(actionQueryString).append("\n"); StringBuilder canonicalHeaders = new StringBuilder(); for (String headerName : sortedHeaderNames) { canonicalHeaders.append(headerName).append(":").append(headers.get(headerName)).append("\n"); } canonicalRequest.append(canonicalHeaders).append("\n"); canonicalRequest.append(Joiner.on(';').join(sortedHeaderNames)).append("\n"); canonicalRequest.append(getHexEncodedSha256Hash(requestPayload.getBytes(UTF_8))); return getHexEncodedSha256Hash(canonicalRequest.toString().getBytes(UTF_8)); }
Source:
<code>public Page<Alert> getAlerts(String tenantId, AlertsCriteria criteria, Pager pager) throws Exception { if (isEmpty(tenantId)) { throw new IllegalArgumentException("TenantId must be not null"); } List<Alert> alerts = getAlerts(tenantId, criteria); <START> if (alerts.isEmpty()) { <END> return new Page<>(alerts, pager, 0); } else { return preparePage(alerts, pager); } }</code><technical_language>chain here? return getAlerts(Collections.singleton(tenantId), criteria, pager);</technical_language>

Target:
public Page<Alert> getAlerts(String tenantId, AlertsCriteria criteria, Pager pager) throws Exception { return getAlerts(Collections.singleton(tenantId), criteria, pager); }
Source:
<code><START> private Boolean isExecutionCalendarGIDefined(String jobDescriptor) { <END> Document dom = XMLParser.parse(jobDescriptor); dom.getDocumentElement().normalize(); Boolean exists = false; Boolean executionCalendarDefined = false; NodeList genericInfo = dom.getElementsByTagName("genericInformation"); Node root = genericInfo.item(0); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node.getNodeName() == "info" && node.hasAttributes()) { NamedNodeMap attributes = node.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { Node attribute = attributes.item(j); if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("name") && attribute.getNodeValue().equals("EXECUTION_CALENDARS")) { exists = true; } if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("value") && exists) { if (attribute.getNodeValue() != null) { executionCalendarDefined = true; } else { displayErrorMessage("EXECUTION_CALENDAR value is empty."); } } } } } return executionCalendarDefined; }</code><technical_language>This method is long 3 nested levels. break smaller methods. file is long. refactor functionality new classes stop growing this file, ideally shrink ;)</technical_language>

Target:
private Boolean isExecutionCalendarGIDefined(String jobDescriptor) { Document dom = XMLParser.parse(jobDescriptor); dom.getDocumentElement().normalize(); Boolean exists = false; Boolean executionCalendarDefined = false; NodeList genericInfo = dom.getElementsByTagName("genericInformation"); Node root = genericInfo.item(0); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node.getNodeName().equals("info") && node.hasAttributes()) { NamedNodeMap attributes = node.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { Node attribute = attributes.item(j); if (attribute.getNodeType() == Node.ATTRIBUTE_NODE && attribute.getNodeName().equals("name") && attribute.getNodeValue().equals("EXECUTION_CALENDARS")) { exists = true; } if (isAttributeExecCalendarValueDefined(attribute, "value") && exists) { if (!attribute.getNodeValue().isEmpty() && exists) { executionCalendarDefined = true; if (!attribute.getNodeValue().isEmpty()) { isExecCalendarValueNull = false; } else { isExecCalendarValueNull = true; } } } } } } return executionCalendarDefined; }
Source:
<code>private String getCaCertPath() { <START> return "/etc/pki/vdsm/libvirt-spice/ca-cert.pem"; <END> }</code><technical_language>replaced ConfigValue / local constant</technical_language>

Target:
private String getCaCertPath() { return CA_CERT_PATH; }
Source:
<code>protected void executeVdsBrokerCommand() { if (getParameters().getAction() == FenceActionType.STATUS || !isAlreadyInRequestedStatus()) { _result = fenceNode( getParameters().getAction(), <START> getParameters().getAction() != <END> FenceActionType.STATUS); getVDSReturnValue().setSucceeded(false); if (getParameters().getAction() == FenceActionType.STATUS && _result.power != null) { String stat = _result.power.toLowerCase(); String msg = _result.mStatus.mMessage; if ("on".equals(stat) || "off".equals(stat)) { getVDSReturnValue().setSucceeded(true); } else { if (!getParameters().getTargetVdsID().equals(Guid.Empty)) { alertPowerManagementStatusFailed(msg); } } FenceStatusReturnValue fenceStatusReturnValue = new FenceStatusReturnValue(stat, msg); setReturnValue(fenceStatusReturnValue); } else { FenceStatusReturnValue fenceStatusReturnValue = new FenceStatusReturnValue( _result.operationStatus, _result.mStatus.mMessage != null ? _result.mStatus.mMessage : "" ); setReturnValue(fenceStatusReturnValue); getVDSReturnValue().setSucceeded(_result.mStatus.mCode == 0); } } else { alertActionSkippedAlreadyInStatus(); getVDSReturnValue().setSucceeded(true); setReturnValue(new FenceStatusReturnValue(FenceStatusReturnValue.SKIPPED_DUE_TO_STATUS, "")); } }</code><technical_language>redundant? providing 'Action' fenceNode(); method check for if [action!=FenceActionType.STATUS] (no need provide another parameter)</technical_language>

Target:
protected void executeVdsBrokerCommand() { if (getParameters().getAction() == FenceActionType.STATUS || !isAlreadyInRequestedStatus()) { _result = fenceNode(getParameters().getAction()); getVDSReturnValue().setSucceeded(false); if (getParameters().getAction() == FenceActionType.STATUS && _result.power != null) { String stat = _result.power.toLowerCase(); String msg = _result.mStatus.mMessage; if ("on".equals(stat) || "off".equals(stat)) { getVDSReturnValue().setSucceeded(true); } else { if (!getParameters().getTargetVdsID().equals(Guid.Empty)) { alertPowerManagementStatusFailed(msg); } } FenceStatusReturnValue fenceStatusReturnValue = new FenceStatusReturnValue(stat, msg); setReturnValue(fenceStatusReturnValue); } else { FenceStatusReturnValue fenceStatusReturnValue = new FenceStatusReturnValue( _result.operationStatus, _result.mStatus.mMessage != null ? _result.mStatus.mMessage : "" ); setReturnValue(fenceStatusReturnValue); getVDSReturnValue().setSucceeded(_result.mStatus.mCode == 0); } } else { alertActionSkippedAlreadyInStatus(); getVDSReturnValue().setSucceeded(true); setReturnValue(new FenceStatusReturnValue(FenceStatusReturnValue.SKIPPED_DUE_TO_STATUS, "")); } }
Source:
<code>public static String mapToJsonUnchecked(Map<String, Object> input) { try { return mapToJson(input); } catch (IOException e) { throw new RuntimeException(String.format("Object \"%s\" cannot be serialized to JSON.", <START> e)); <END> } }</code><technical_language>I print content of 'input' pass 'e' (exception) a argument of RuntimeExeption c'tor call</technical_language>

Target:
public static String mapToJsonUnchecked(Map<String, Object> input) { try { return mapToJson(input); } catch (IOException e) { throw new RuntimeException(String.format("Object \"%s\" cannot be serialized to JSON.", input), e); } }
Source:
<code>public void changeDetail(final Change.Id id, final AsyncCallback<ChangeDetail> callback) { run(callback, new Action<ChangeDetail>() { public ChangeDetail run(final ReviewDb db) throws OrmException, Failure { final Account.Id me = Common.getAccountId(); final Change change = db.changes().get(id); final PatchSet patch = db.patchSets().get(change.currentPatchSetId()); final Project proj = db.projects().get(change.getDest().getParentKey()); <START> if (change == null || patch == null || proj == null) { <END> throw new Failure(new NoSuchEntityException()); } assertCanRead(change); final boolean anon; boolean canAbandon = false; if (me == null) { anon = true; } else { anon = canRead(null, change.getDest().getParentKey()); canAbandon = me.equals(change.getOwner()) || me.equals(patch.getUploader()) || Common.getGroupCache().isAdministrator(me) || Common.getGroupCache().isInGroup(me, proj.getOwnerGroupId()); } final ChangeDetail d = new ChangeDetail(); d.load(db, new AccountInfoCacheFactory(db), change, anon, canAbandon); return d; } }); }</code><technical_language>change==null test is pointless, line 39 NPE'd if change null current patch set</technical_language>

Target:
public void changeDetail(final Change.Id id, final AsyncCallback<ChangeDetail> callback) { run(callback, new Action<ChangeDetail>() { public ChangeDetail run(final ReviewDb db) throws OrmException, Failure { final Account.Id me = Common.getAccountId(); final Change change = db.changes().get(id); if (change == null) { throw new Failure(new NoSuchEntityException()); } final PatchSet patch = db.patchSets().get(change.currentPatchSetId()); final Project proj = db.projects().get(change.getDest().getParentKey()); if (patch == null || proj == null) { throw new Failure(new NoSuchEntityException()); } assertCanRead(change); final boolean anon; boolean canAbandon = false; if (me == null) { anon = true; } else { anon = canRead(null, change.getDest().getParentKey()); canAbandon = me.equals(change.getOwner()) || me.equals(patch.getUploader()) || Common.getGroupCache().isAdministrator(me) || Common.getGroupCache().isInGroup(me, proj.getOwnerGroupId()); } final ChangeDetail d = new ChangeDetail(); d.load(db, new AccountInfoCacheFactory(db), change, anon, canAbandon); return d; } }); }
Source:
<code>public String produceDts(Compiler compiler) { Set<String> provides = new HashSet<>(); for (CompilerInput compilerInput : compiler.getInputsById().values()) { provides.addAll(compilerInput.getProvides()); } out = new StringWriter(); TypedScope topScope = compiler.getTopScope(); for (String provide : provides) { <START> emitNoSpace("declare module "); <END> emitNoSpace(INTERNAL_NAMESPACE); emitNoSpace(provide); emitNoSpace(" {"); indent(); emitBreak(); TypedVar symbol = topScope.getOwnSlot(provide); checkArgument(symbol != null, "goog.provide not defined: %s", provide); if (symbol.getType() != null) { walkScope(symbol, true); } else { String prefix = provide + "."; for (TypedVar other : topScope.getAllSymbols()) { String otherName = other.getName(); if (otherName.startsWith(prefix) && other.getType() != null && !other.getType().isFunctionPrototypeType()) { walkScope(other, false); } } } unindent(); emit("}"); emitBreak(); defineExternalModule(provide); } checkState(indent == 0, "indent must be zero after printing, but is %s", indent); return out.toString(); }</code><technical_language>declare namespace work yet</technical_language>

Target:
public String produceDts(Compiler compiler) { Set<String> provides = new HashSet<>(); for (CompilerInput compilerInput : compiler.getInputsById().values()) { provides.addAll(compilerInput.getProvides()); } out = new StringWriter(); TypedScope topScope = compiler.getTopScope(); for (String provide : provides) { TypedVar symbol = topScope.getOwnSlot(provide); checkArgument(symbol != null, "goog.provide not defined: %s", provide); String namespace = provide; boolean isDefault = false; if (symbol.getType() != null) { if (!symbol.getType().isObject() || symbol.getType().isInterface() || symbol.getType().isFunctionType()) { int lastDot = symbol.getName().lastIndexOf('.'); namespace = lastDot >= 0 ? symbol.getName().substring(0, lastDot) : ""; isDefault = true; } } emitNoSpace("declare namespace "); emitNoSpace(INTERNAL_NAMESPACE); if (!namespace.isEmpty()) { emitNoSpace("." + namespace); } emitNoSpace(" {"); indent(); emitBreak(); if (symbol.getType() != null) { walkScope(symbol, isDefault); } else { String prefix = provide + "."; for (TypedVar other : topScope.getAllSymbols()) { String otherName = other.getName(); if (otherName.startsWith(prefix) && other.getType() != null && !other.getType().isFunctionPrototypeType()) { walkScope(other, false); } } } unindent(); emit("}"); emitBreak(); declareModule(provide, isDefault); } checkState(indent == 0, "indent must be zero after printing, but is %s", indent); return out.toString(); }
Source:
<code>public static SecorConfig load() throws ConfigurationException { Properties systemProperties = System.getProperties(); String configProperty = systemProperties.getProperty("config"); PropertiesConfiguration properties = new PropertiesConfiguration(configProperty); <START> for (final Object key : systemProperties.keySet()) { <END> properties.setProperty(key.toString(), systemProperties.get(key)); } return new SecorConfig(properties); }</code><technical_language>Consider iterating systemProperties.entrySet() instead. This eliminate need for key lookups in iteration</technical_language>

Target:
public static SecorConfig load() throws ConfigurationException { Properties systemProperties = System.getProperties(); String configProperty = systemProperties.getProperty("config"); PropertiesConfiguration properties = new PropertiesConfiguration(configProperty); for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) { properties.setProperty(entry.getKey().toString(), entry.getValue()); } return new SecorConfig(properties); }
Source:
<code>public ObjectStream<SentenceSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); InputStreamFactory inFactory = CmdLineUtil.createInputStreamFactory(params.getData()); <START> try { <END> return new ConlluSentenceSampleStream(new ConlluStream(inFactory), 25); } catch (IOException e) { CmdLineUtil.handleCreateObjectStreamError(e); } return null; }</code><technical_language>25 configurable user</technical_language>

Target:
public ObjectStream<SentenceSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); InputStreamFactory inFactory = CmdLineUtil.createInputStreamFactory(params.getData()); try { return new ConlluSentenceSampleStream(new ConlluStream(inFactory), Integer.parseInt(params.getSentencesPerSample())); } catch (IOException e) { CmdLineUtil.handleCreateObjectStreamError(e); } return null; }
Source:
<code>private Map<String, ResourceAssignment> calculateAssignment( ResourceControllerDataProvider clusterData, Map<HelixConstants.ChangeType, Set<String>> clusterChanges, Map<String, Resource> resourceMap, Set<String> activeNodes, Map<String, ResourceAssignment> baseline, Map<String, ResourceAssignment> prevBestPossibleAssignment) throws HelixRebalanceException { long startTime = System.currentTimeMillis(); LOG.info("Start calculating for an assignment"); ClusterModel clusterModel; try { clusterModel = ClusterModelProvider.generateClusterModel(clusterData, resourceMap, activeNodes, clusterChanges, baseline, prevBestPossibleAssignment); } catch (Exception ex) { throw new HelixRebalanceException("Failed to generate cluster model.", HelixRebalanceException.Type.INVALID_CLUSTER_STATUS, ex); } OptimalAssignment optimalAssignment = _rebalanceAlgorithm.calculate(clusterModel); Map<String, ResourceAssignment> newAssignment = optimalAssignment.getOptimalResourceAssignment(); <START> LOG.info("Finish calculating. Time spent: {}ms.", System.currentTimeMillis() - startTime); <END> asyncReportBaselineDivergenceGauge(clusterData, baseline, newAssignment); return newAssignment; }</code><technical_language>Nit: I find more helpful say: "Finish calculateAssignment(). Took: ms.". consistent other logs</technical_language>

Target:
private Map<String, ResourceAssignment> calculateAssignment( ResourceControllerDataProvider clusterData, Map<HelixConstants.ChangeType, Set<String>> clusterChanges, Map<String, Resource> resourceMap, Set<String> activeNodes, Map<String, ResourceAssignment> baseline, Map<String, ResourceAssignment> prevBestPossibleAssignment) throws HelixRebalanceException { long startTime = System.currentTimeMillis(); LOG.info("Start calculating for an assignment"); ClusterModel clusterModel; try { clusterModel = ClusterModelProvider.generateClusterModel(clusterData, resourceMap, activeNodes, clusterChanges, baseline, prevBestPossibleAssignment); } catch (Exception ex) { throw new HelixRebalanceException("Failed to generate cluster model.", HelixRebalanceException.Type.INVALID_CLUSTER_STATUS, ex); } OptimalAssignment optimalAssignment = _rebalanceAlgorithm.calculate(clusterModel); Map<String, ResourceAssignment> newAssignment = optimalAssignment.getOptimalResourceAssignment(); LOG.info("Finish calculating an assignment. Took: ms.", System.currentTimeMillis() - startTime); return newAssignment; }
Source:
<code>private int getMaxDataVolumesSupported(UserVmVO vm) { Long hostId = vm.getHostId(); if (hostId == null) { hostId = vm.getLastHostId(); } HostVO host = _hostDao.findById(hostId); Integer maxDataVolumesSupported = null; if (host != null) { _hostDao.loadDetails(host); maxDataVolumesSupported = _hypervisorCapabilitiesDao.getMaxDataVolumesLimit(host.getHypervisorType(), host.getDetail("product_version")); } else { List<HypervisorType> supportingDefaultHV = Arrays.asList(HypervisorType.XenServer, HypervisorType.VMware, HypervisorType.KVM, HypervisorType.Ovm, HypervisorType.LXC); HypervisorType hypervisorType = vm.getHypervisorType(); if (hypervisorType != null && supportingDefaultHV.contains(hypervisorType)) { <START> maxDataVolumesSupported = _hypervisorCapabilitiesDao.getMaxDataVolumesLimit(hypervisorType, "default"); <END> } } if (maxDataVolumesSupported == null || maxDataVolumesSupported.intValue() <= 0) { maxDataVolumesSupported = 6; } return maxDataVolumesSupported.intValue(); }</code><technical_language>version specific values regression bug</technical_language>

Target:
private int getMaxDataVolumesSupported(UserVmVO vm) { Long hostId = vm.getHostId(); if (hostId == null) { hostId = vm.getLastHostId(); } HostVO host = _hostDao.findById(hostId); Integer maxDataVolumesSupported = null; if (host != null) { _hostDao.loadDetails(host); maxDataVolumesSupported = _hypervisorCapabilitiesDao.getMaxDataVolumesLimit(host.getHypervisorType(), host.getDetail("product_version")); } else { HypervisorType hypervisorType = vm.getHypervisorType(); if (hypervisorType != null && CollectionUtils.isNotEmpty(supportingDefaultHV) && supportingDefaultHV.contains(hypervisorType)) { maxDataVolumesSupported = _hypervisorCapabilitiesDao.getMaxDataVolumesLimit(hypervisorType, "default"); } } if (maxDataVolumesSupported == null || maxDataVolumesSupported.intValue() <= 0) { maxDataVolumesSupported = 6; } return maxDataVolumesSupported.intValue(); }
Source:
<code>public void testBuilderWithDefaultKinesisProxy() { IRecordProcessorFactory recordProcessorFactory = mock(IRecordProcessorFactory.class); Worker.Builder builder = new Worker.Builder() .recordProcessorFactory(recordProcessorFactory) .config(config); builder.build(); assertNotNull(builder.getKinesisProxy()); <START> assertTrue(builder.getKinesisProxy() instanceof KinesisProxy); <END> }</code><technical_language>This is correct test proxy is set. need worker is proxy expect use</technical_language>

Target:
public void testBuilderWithDefaultKinesisProxy() { IRecordProcessorFactory recordProcessorFactory = mock(IRecordProcessorFactory.class); Worker worker = new Worker.Builder() .recordProcessorFactory(recordProcessorFactory) .config(config) .build(); Assert.assertNotNull(worker.getStreamConfig().getStreamProxy()); Assert.assertTrue(worker.getStreamConfig().getStreamProxy() instanceof KinesisProxy); }
Source:
<code><START> public static ByteString getFixedByteString(Text key) { <END> ByteString value = fixedByteStringCache.get(key); if (value == null) { value = ByteString.copyFromUtf8(key.toString()); fixedByteStringCache.put(new Text(key.copyBytes()), value); } return value; }</code><technical_language>Is risk this grow a size a problem? If not, a guava cache is overkill, if is a risk yes, need</technical_language>

Target:
public static ByteString getFixedByteString(Text key) { ByteString value = FIXED_BYTESTRING_CACHE.get(key); if (value == null) { value = ByteString.copyFromUtf8(key.toString()); FIXED_BYTESTRING_CACHE.put(new Text(key.copyBytes()), value); } return value; }
Source:
<code>public void handleEvent(Event event) { EventContext eventContext = event.getContext(); if (!(eventContext instanceof DocumentEventContext)) { return; } DocumentModel previousDocument = (DocumentModel) eventContext.getProperty( CoreEventConstants.PREVIOUS_DOCUMENT_MODEL); <START> if (previousDocument.hasFacet(FacetNames.COLD_STORAGE)) { if (previousDocument.getPropertyValue(ColdStorageHelper.COLD_STORAGE_CONTENT_PROPERTY) != null) { <END> DocumentModel document = ((DocumentEventContext) eventContext).getSourceDocument(); Property mainContent = document.getProperty(ColdStorageHelper.FILE_CONTENT_PROPERTY); if (mainContent.isDirty()) { event.markBubbleException(); throw new NuxeoException(String.format( "The main content of document: %s cannot be updated. It's already in cold storage.", document), SC_FORBIDDEN); } } } }</code><technical_language>if merged</technical_language>

Target:
public void handleEvent(Event event) { EventContext eventContext = event.getContext(); if (!(eventContext instanceof DocumentEventContext)) { return; } DocumentModel previousDocument = (DocumentModel) eventContext.getProperty( CoreEventConstants.PREVIOUS_DOCUMENT_MODEL); if (previousDocument.hasFacet(FacetNames.COLD_STORAGE) && previousDocument.getPropertyValue(ColdStorageHelper.COLD_STORAGE_CONTENT_PROPERTY) != null) { DocumentModel document = ((DocumentEventContext) eventContext).getSourceDocument(); Property mainContent = document.getProperty(ColdStorageHelper.FILE_CONTENT_PROPERTY); if (mainContent.isDirty()) { event.markBubbleException(); throw new NuxeoException(String.format( "The main content of document: %s cannot be updated. It's already in cold storage.", document), SC_FORBIDDEN); } } }
Source:
<code>private void showDomainCreditsCheckProgressDialog() { if (mCheckingDomainCreditsProgressDialog == null) { mCheckingDomainCreditsProgressDialog = new ProgressDialog(this); <START> mCheckingDomainCreditsProgressDialog.setCancelable(false); <END> mCheckingDomainCreditsProgressDialog.setIndeterminate(true); mCheckingDomainCreditsProgressDialog .setMessage(getString(R.string.plugin_check_domain_credits_progress_dialog_message)); } if (!mCheckingDomainCreditsProgressDialog.isShowing()) { mCheckingDomainCreditsProgressDialog.show(); } }</code><technical_language>I setting cancelable false result in infinite dialog OnPlansFetched event get lost a configuration change. I this handled in places in app, I wanted mention it. want consider allowing user cancel dialog setting @Subscribe(sticky=true,..) handle appropriately. Wdyt</technical_language>

Target:
private void showDomainCreditsCheckProgressDialog() { if (mCheckingDomainCreditsProgressDialog == null) { mCheckingDomainCreditsProgressDialog = new ProgressDialog(this); mCheckingDomainCreditsProgressDialog.setCancelable(true); mCheckingDomainCreditsProgressDialog.setIndeterminate(true); mCheckingDomainCreditsProgressDialog .setMessage(getString(R.string.plugin_check_domain_credits_progress_dialog_message)); } if (!mCheckingDomainCreditsProgressDialog.isShowing()) { mCheckingDomainCreditsProgressDialog.show(); } }
Source:
<code>private Repository openRepo() throws TransportException { try { <START> final RepositoryBuilder <END> builder = new RepositoryBuilder(); builder.setGitDir(remoteGitDir); if (local != null) { builder.setFS(local.getFS()); } return builder.build(); } catch (IOException err) { throw new TransportException(uri, JGitText.get().notAGitDirectory); } }</code><technical_language>need final</technical_language>

Target:
private Repository openRepo() throws TransportException { try { RepositoryBuilder builder = new RepositoryBuilder() .setGitDir(remoteGitDir); if (local != null) { builder.setFS(local.getFS()); } return builder.build(); } catch (IOException err) { throw new TransportException(uri, JGitText.get().notAGitDirectory); } }
Source:
<code>public void trim() { for (Iterator<SlimAnnotatedTypeContext<?>> iterator = annotatedTypes.iterator(); iterator.hasNext(); ) { <START> if (!AnnotatedTypes.hasBeanDefiningAnnotation(iterator.next().getAnnotatedType())) { <END> iterator.remove(); } } }</code><technical_language>pseudo scopes? E.g. javax.inject.Singleton</technical_language>

Target:
public void trim() { for (Iterator<SlimAnnotatedTypeContext<?>> iterator = annotatedTypes.iterator(); iterator.hasNext(); ) { if (!AnnotatedTypes.hasBeanDefiningAnnotation(iterator.next().getAnnotatedType(), AnnotatedTypes.TRIM_META_ANNOTATIONS)) { iterator.remove(); } } }
Source:
<code>private static List<Map<String, Object>> getAllWorkDefinitionsMap(String directory, String widName) { List<Map<String, Object>> workDefinitions = new ArrayList<Map<String, Object>>(); if(widName != null) { workDefinitions.addAll(getWorkDefinitionsMapForSingleDir(directory, widName)); } else { for (String s: getDirectories(directory)) { try { workDefinitions.addAll(getAllWorkDefinitionsMap(directory + "/" + s, null)); } catch (Throwable t) { <START> t.printStackTrace(); <END> } workDefinitions.addAll(getWorkDefinitionsMap(directory, s)); } } return workDefinitions; }</code><technical_language>logger</technical_language>

Target:
private static List<Map<String, Object>> getAllWorkDefinitionsMap(String directory, String widName) { List<Map<String, Object>> workDefinitions = new ArrayList<Map<String, Object>>(); if(widName != null) { workDefinitions.addAll(getWorkDefinitionsMapForSingleDir(directory, widName)); } else { for (String s: getDirectories(directory)) { try { workDefinitions.addAll(getAllWorkDefinitionsMap(directory + "/" + s, null)); } catch (Throwable t) { logger.error("Error retrieving work definitions: " + t.getMessage()); } workDefinitions.addAll(getWorkDefinitionsMap(directory, s)); } } return workDefinitions; }
Source:
<code>public List<BibEntry> performSearch(BibEntry entry) throws FetcherException { Optional<String> entryTitle = entry.getLatexFreeField(StandardField.TITLE); <START> if(entryTitle.isPresent()){ <END> String xmlResponse = makeOpenSearchRequest(entryTitle.get()); WorldcatImporter importer = new WorldcatImporter(); ParserResult parserResult; try{ if(importer.isRecognizedFormat(xmlResponse)){ parserResult = importer.importDatabase(xmlResponse); } else{ BibDatabase errorBibDataBase = new BibDatabase(); parserResult = new ParserResult(errorBibDataBase); } return parserResult.getDatabase().getEntries(); } catch(IOException e){ throw new FetcherException("IO Exception " + e.getMessage(), e); } } else { return new ArrayList<>(); } }</code><technical_language>Checkstyle violations. spaces braces. Please check tests</technical_language>

Target:
public List<BibEntry> performSearch(BibEntry entry) throws FetcherException { Optional<String> entryTitle = entry.getLatexFreeField(StandardField.TITLE); if (entryTitle.isPresent()) { String openSearchXMLResponse = makeOpenSearchRequest(entryTitle.get()); Document openSearchDocument = parse(openSearchXMLResponse); Document detailedXML = parseOpenSearchXML(openSearchDocument); String detailedXMLString; try (StringWriter sw = new StringWriter()) { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(detailedXML), new StreamResult(sw)); detailedXMLString = sw.toString(); } catch (TransformerException e) { throw new FetcherException("Could not transform XML", e); } catch (IOException e) { throw new FetcherException("Could not close StringWriter", e); } WorldcatImporter importer = new WorldcatImporter(); ParserResult parserResult; try { if (importer.isRecognizedFormat(detailedXMLString)) { parserResult = importer.importDatabase(detailedXMLString); } else { BibDatabase errorBibDataBase = new BibDatabase(); parserResult = new ParserResult(errorBibDataBase); } return parserResult.getDatabase().getEntries(); } catch (IOException e) { throw new FetcherException("Could not perform search (Worldcat) ", e); } } else { return new ArrayList<>(); } }
Source:
<code>protected static void loadAd(UnityAdapterDelegate delegate) { UnityAds.load(delegate.getPlacementId()); if (!UnityAds.isInitialized()) { <START> initializeUnityAds(Activity activity, String gameId); <END> } if (UnityAds.isReady(delegate.getPlacementId())) { delegate.onUnityAdsReady(delegate.getPlacementId()); } if (mPlacementsInUse.containsKey(delegate.getPlacementId()) && mPlacementsInUse.get(delegate.getPlacementId()).get() != null) { Log.e(UnityMediationAdapter.TAG, "An ad is already loading for placement ID: " + delegate.getPlacementId()); delegate.onUnityAdsError(UnityAds.UnityAdsError.INTERNAL_ERROR, delegate.getPlacementId()); return; } mPlacementsInUse.put(delegate.getPlacementId(), new WeakReference<>(delegate)); }</code><technical_language>gameID ? resolve gameId. parameter in API, 'activity'</technical_language>

Target:
protected static void loadAd(UnityAdapterDelegate delegate) { UnityAds.load(delegate.getPlacementId()); if (!UnityAds.isInitialized()) { initializeUnityAds(UnitySingleton.activity.get(), currentGameID); } if (UnityAds.isReady(delegate.getPlacementId())) { delegate.onUnityAdsReady(delegate.getPlacementId()); } if (mPlacementsInUse.containsKey(delegate.getPlacementId()) && mPlacementsInUse.get(delegate.getPlacementId()).get() != null) { delegate.onUnityAdsError(UnityAds.UnityAdsError.INTERNAL_ERROR, delegate.getPlacementId()); return; } mPlacementsInUse.put(delegate.getPlacementId(), new WeakReference<>(delegate)); }
Source:
<code>public void binaryPubSubChannelWithPingPongWithArgument() { final CountDownLatch latchUnsubscribed = new CountDownLatch(1); final CountDownLatch latchReceivedPong = new CountDownLatch(1); final List<byte[]> pongPatterns = new ArrayList<>(); jedis.subscribe(new BinaryJedisPubSub() { @Override public void onSubscribe(byte[] channel, int subscribedChannels) { publishOne("testchan1", "hello"); } @Override public void onMessage(byte[] channel, byte[] message) { <START> this.ping("hi!".getBytes()); <END> } @Override public void onPong(byte[] pattern) { pongPatterns.add(pattern); latchReceivedPong.countDown(); unsubscribe(); } @Override public void onUnsubscribe(byte[] channel, int subscribedChannels) { latchUnsubscribed.countDown(); } }, SafeEncoder.encode("testchan1")); assertEquals(0L, latchReceivedPong.getCount()); assertEquals(0L, latchUnsubscribed.getCount()); assertEquals("hi!", new String(pongPatterns.get(0))); }</code><technical_language>Instread of String.getBytes(), SafeEncoder.encode(String). Alternate idea, SafeEncoder.encode(message) in variable want</technical_language>

Target:
public void binaryPubSubChannelWithPingPongWithArgument() throws InterruptedException { final CountDownLatch latchUnsubscribed = new CountDownLatch(1); final CountDownLatch latchReceivedPong = new CountDownLatch(1); final List<byte[]> pongPatterns = new ArrayList<>(); final byte[] pingMessage = SafeEncoder.encode("hi!"); jedis.subscribe(new BinaryJedisPubSub() { @Override public void onSubscribe(byte[] channel, int subscribedChannels) { publishOne("testchan1", "hello"); } @Override public void onMessage(byte[] channel, byte[] message) { this.ping(pingMessage); } @Override public void onPong(byte[] pattern) { pongPatterns.add(pattern); latchReceivedPong.countDown(); unsubscribe(); } @Override public void onUnsubscribe(byte[] channel, int subscribedChannels) { latchUnsubscribed.countDown(); } }, SafeEncoder.encode("testchan1")); assertEquals(0L, latchReceivedPong.getCount()); assertEquals(0L, latchUnsubscribed.getCount()); assertArrayEquals(pingMessage, pongPatterns.get(0)); }
Source:
<code><START> private boolean hasDeadlineExpired(final Date deadline) { <END> if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } }</code><technical_language>deadline-related methods static</technical_language>

Target:
private static boolean hasDeadlineExpired(final Date deadline) { if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } }
Source:
<code>private static LockAndTimestampServices withRequestBatchingTimestampService( java.util.function.Supplier<TimestampClientConfig> timestampClientConfigSupplier, LockAndTimestampServices lockAndTimestampServices, String userAgent) { TimelockService timelockServiceWithBatching = ServiceCreator.createInstrumentedService( DecoratedTimelockServices.createTimelockServiceWithTimestampBatching( lockAndTimestampServices.timelock(), timestampClientConfigSupplier), <START> TimelockService.class, userAgent); <END> return ImmutableLockAndTimestampServices.builder() .from(lockAndTimestampServices) .timestamp(new TimelockTimestampServiceAdapter(timelockServiceWithBatching)) .timelock(timelockServiceWithBatching) .build(); }</code><technical_language>I instrument TimelockService (line 497), metrics handle TimelockService interfaces. @schlosna is this ok</technical_language>

Target:
private static LockAndTimestampServices withRequestBatchingTimestampService( java.util.function.Supplier<TimestampClientConfig> timestampClientConfigSupplier, LockAndTimestampServices lockAndTimestampServices, String userAgent) { TimelockService timelockServiceWithBatching = DecoratedTimelockServices .createTimelockServiceWithTimestampBatching( lockAndTimestampServices.timelock(), timestampClientConfigSupplier, userAgent); return ImmutableLockAndTimestampServices.builder() .from(lockAndTimestampServices) .timestamp(new TimelockTimestampServiceAdapter(timelockServiceWithBatching)) .timelock(timelockServiceWithBatching) .build(); }
Source:
<code>private void updateResourceType(Policy policy, ScopePermissionRepresentation representation) { if (representation != null) { if (ScopePermissionRepresentation.class.equals(representation.getClass())) { <START> ScopePermissionRepresentation resourcePermission = ScopePermissionRepresentation.class.cast(representation); <END> Map<String, String> config = new HashMap(policy.getConfig()); config.compute("defaultResourceType", (key, value) -> { String resourceType = resourcePermission.getResourceType(); return resourceType != null ? resourcePermission.getResourceType() : null; }); policy.setConfig(config); } } }</code><technical_language>Is this if statement necessary</technical_language>

Target:
private void updateResourceType(Policy policy, ScopePermissionRepresentation representation) { if (representation != null) { Map<String, String> config = new HashMap(policy.getConfig()); config.compute("defaultResourceType", (key, value) -> { String resourceType = representation.getResourceType(); return resourceType != null ? representation.getResourceType() : null; }); policy.setConfig(config); } }