auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void startGroup() { if (DEBUG) log("startGroup()"); GroupColumnIO group = (GroupColumnIO) currentColumnIO; <START> if (hasNullCache(group)) <END> flushCachedNulls(group); ++currentLevel; r[currentLevel] = r[currentLevel - 1]; int fieldsCount = ((GroupColumnIO) currentColumnIO).getChildrenCount(); fieldsWritten[currentLevel].reset(fieldsCount); if (DEBUG) printState(); }</code><technical_language>curly braces for 1 line if statements</technical_language>

Target:
public void startGroup() { if (DEBUG) log("startGroup()"); GroupColumnIO group = (GroupColumnIO) currentColumnIO; if (hasNullCache(group)) { flushCachedNulls(group); } ++currentLevel; r[currentLevel] = r[currentLevel - 1]; int fieldsCount = ((GroupColumnIO) currentColumnIO).getChildrenCount(); fieldsWritten[currentLevel].reset(fieldsCount); if (DEBUG) printState(); }
Source:
<code>public void testGetChildrenOfFolder() throws Exception { String uniqueId = this.commonTestProject.getUniqueID(); DmsProject mainFolder = this.studyTDI.createFolderTestData(uniqueId); int subFolderID = this.manager.addSubFolder(mainFolder.getProjectId(), "Sub folder", "Sub Folder", uniqueId); List<Reference> childrenNodes = this.manager.getChildrenOfFolder(mainFolder.getProjectId(), this.commonTestProject.getUniqueID(), StudyType.nurseriesAndTrials()); Assert.assertNotNull(childrenNodes); <START> Assert.assertTrue("The size should be one.", childrenNodes.size() == 1); <END> Assert.assertTrue("The id of the subFolder should be " + subFolderID, subFolderID == childrenNodes.get(0).getId()); }</code><technical_language>assert equals</technical_language>

Target:
public void testGetChildrenOfFolder() throws Exception { final String uniqueId = this.commonTestProject.getUniqueID(); final DmsProject mainFolder = this.studyTDI.createFolderTestData(uniqueId); final int subFolderID = this.manager.addSubFolder(mainFolder.getProjectId(), "Sub folder", "Sub Folder", uniqueId); final List<Reference> childrenNodes = this.manager.getChildrenOfFolder(mainFolder.getProjectId(), this.commonTestProject.getUniqueID(), StudyType.nurseriesAndTrials()); Assert.assertNotNull(childrenNodes); Assert.assertEquals("The size should be one.", 1, childrenNodes.size()); Assert.assertTrue("The id of the subFolder should be " + subFolderID, subFolderID == childrenNodes.get(0).getId()); }
Source:
<code>private boolean removeVm() { VM vm = getVm(); hasImages = vm.getDiskList().size() > 0; final List<DiskImage> diskImages = ImagesHandler.filterImageDisks(getVm().getDiskList(), true, false); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { removeVmFromDb(); if (getParameters().isRemoveDisks()) { for (DiskImage image : diskImages) { getCompensationContext().snapshotEntityStatus(image.getImage(), ImageStatus.ILLEGAL); } ImagesHandler.updateDiskImagesStatus(diskImages, ImageStatus.LOCKED); getCompensationContext().stateChanged(); } return null; } }); <START> if (getParameters().isRemoveDisks() && hasImages) { <END> Collection<DiskImage> unremovedDisks = (Collection<DiskImage>)removeVmImages(diskImages).getActionReturnValue(); if (!unremovedDisks.isEmpty()) { processUnremovedDisks(unremovedDisks); setSucceeded(false); } } return true; }</code><technical_language>do I need check hasImages() here? optimization</technical_language>

Target:
private boolean removeVm() { final List<DiskImage> diskImages = ImagesHandler.filterImageDisks(getVm().getDiskList(), true, false); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { removeVmFromDb(); if (getParameters().isRemoveDisks()) { for (DiskImage image : diskImages) { getCompensationContext().snapshotEntityStatus(image.getImage(), ImageStatus.ILLEGAL); ImagesHandler.updateImageStatus(image.getImage().getId(), ImageStatus.LOCKED); } getCompensationContext().stateChanged(); } return null; } }); if (getParameters().isRemoveDisks() && !diskImages.isEmpty()) { Collection<DiskImage> unremovedDisks = (Collection<DiskImage>)removeVmImages(diskImages).getActionReturnValue(); if (!unremovedDisks.isEmpty()) { processUnremovedDisks(unremovedDisks); return false; } } return true; }
Source:
<code>public void done(IJobChangeEvent event) { final Map<Repository, Object> res = new HashMap<Repository, Object>( PullOperationUI.this.results); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { <START> Shell shell = PlatformUI.getWorkbench() <END> .getActiveWorkbenchWindow().getShell(); for (Entry<Repository, Object> entry : res.entrySet()) { Object result = entry.getValue(); if (result instanceof PullResult) { PullResult pullResult = (PullResult) result; if (pullResult.getRebaseResult() != null && RebaseResult.Status.UNCOMMITTED_CHANGES == pullResult .getRebaseResult().getStatus()) { boolean handledSeparately = handleUncommittedChanges( entry.getKey(), pullResult .getRebaseResult() .getUncommittedChanges(), shell); if (handledSeparately) tasksToWaitFor.incrementAndGet(); } } } if (tasksToWaitFor.decrementAndGet() == 0 && !results.isEmpty()) showResults(shell); } }); }</code><technical_language>extract body of this method? readable here</technical_language>

Target:
public void done(IJobChangeEvent event) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { Map<Repository, Object> res = new HashMap<Repository, Object>( PullOperationUI.this.results); Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); handlePullResults(res, shell); } }); }
Source:
<code>public void process(final Exchange exchange) throws Exception { final Message in = exchange.getIn(); String fcrepoBinaryUri = (String) in.getHeader(FCREPO_URI); if (fcrepoBinaryUri == null) { Document msgBody = MessageUtil.getDocumentBody(in); Element body = msgBody.getRootElement(); String pidValue = body.getChild("pid", ATOM_NS).getTextTrim(); PID objPid = PIDs.get(pidValue); try { RepositoryObject repoObj = repoObjLoader.getRepositoryObject(objPid); log.info("Adding enhancement headers for " + pidValue); in.setHeader(FCREPO_URI, pidValue); <START> if (repoObj instanceof CollectionObject) { <END> in.setHeader(FCREPO_RESOURCE_TYPE, repoObj.getTypes()); } else { in.setHeader(FCREPO_RESOURCE_TYPE, Binary.getURI()); } } catch (ObjectTypeMismatchException e) { log.warn("{} is not a repository object. No enhancement headers added", objPid.getURI()); } } }</code><technical_language>call getTypes() for objects. I for binaries work, want able process AdminUnits folders too</technical_language>

Target:
public void process(final Exchange exchange) throws Exception { final Message in = exchange.getIn(); String fcrepoBinaryUri = (String) in.getHeader(FCREPO_URI); if (fcrepoBinaryUri == null) { Document msgBody = MessageUtil.getDocumentBody(in); Element body = msgBody.getRootElement(); Element enhancementsEl = body.getChild(RUN_ENHANCEMENTS.getName(), CDR_MESSAGE_NS); if (enhancementsEl != null) { String pidValue = enhancementsEl.getChild("pid", CDR_MESSAGE_NS).getTextTrim(); PID objPid = PIDs.get(pidValue); try { RepositoryObject repoObj = repoObjLoader.getRepositoryObject(objPid); log.info("Adding enhancement headers for " + pidValue); in.setHeader(FCREPO_URI, pidValue); in.setHeader(FCREPO_RESOURCE_TYPE, String.join(",", repoObj.getTypes())); } catch (ObjectTypeMismatchException e) { log.warn("{} is not a repository object. No enhancement headers added", objPid.getURI()); } } } }
Source:
<code>public Mono<Void> createOrReplaceOrder(Order order) { return this.throwRandomError() .then(Mono.fromRunnable(() -> { if (order.getId() == null) { Order newOrder = new Order(); newOrder.setId(UUID.randomUUID().toString()); newOrder.setContent(order.getContent()); logger.info(String.format("Order created: %s", newOrder)); } else { logger.info(String.format("Order updated %s", order)); } <START> })).then(this.throwRandomError()); <END> }</code><technical_language>do want throw a random error order creation</technical_language>

Target:
public Mono<Void> createOrReplaceOrder(Order order) { return this.throwRandomError() .then(Mono.delay(Duration.ofMillis(50))) .then(Mono.fromRunnable(() -> { if (order.getId() == null) { Order newOrder = new Order(); newOrder.setId(UUID.randomUUID().toString()); newOrder.setContent(order.getContent()); logger.info(String.format("Order created: %s", newOrder)); } else { logger.info(String.format("Order updated %s", order)); } })).then(this.throwRandomError()); }
Source:
<code>public void configure(final MapperFactory mapperFactory) { mapperFactory.getConverterFactory().registerConverter(new AlarmRegisterConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsGasResponseConverter()); mapperFactory.getConverterFactory().registerConverter(AmrProfileStatusCodeConverter.CONVERTER_ID, <START> new AmrProfileStatusCodeConverter()); <END> mapperFactory.getConverterFactory().registerConverter(PeriodicMeterReadsGasConverter.CONVERTER_ID, new PeriodicMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(PeriodicMeterReadsConverter.CONVERTER_ID, new PeriodicMeterReadsConverter()); }</code><technical_language>registerConverter methods parameter a String used, a good reason earlier ones</technical_language>

Target:
public void configure(final MapperFactory mapperFactory) { mapperFactory.getConverterFactory().registerConverter(new AlarmRegisterConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsConverter()); mapperFactory.getConverterFactory().registerConverter(new ActualMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsGasResponseConverter()); mapperFactory.getConverterFactory().registerConverter(new AmrProfileStatusCodeConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsGasConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsConverter()); }
Source:
<code>public ConsoleDetail(final AbstractBuild<?, ?> owner, final int from, final int to) { <START> this.owner = owner; <END> this.from = from; this.to = to; start = Math.max(0, from - 10); end = to + 10; readConsole(); }</code><technical_language>this((Run<?,?>)owner, from, to) simpler</technical_language>

Target:
public ConsoleDetail(final AbstractBuild<?, ?> owner, final int from, final int to) { this((Run<?, ?>) owner, from ,to); }
Source:
<code>private BoundaryBox getLayerBoundingBox(String layerName, WMSLayer layer, String srs) { WMSLayer wmsLayer = find(layerName, layer); BoundaryBox bbox = wmsLayer.getBbox(srs); while ((bbox == null) && (wmsLayer.getParent() != null)) { wmsLayer = wmsLayer.getParent(); bbox = wmsLayer.getBbox(srs); } <START> if (bbox == null) { <END> bbox = new BoundaryBox(); bbox.setXmin(0); bbox.setYmin(0); bbox.setXmax(100); bbox.setYmax(100); bbox.setSrs(srs); } return bbox; }</code><technical_language>wait... ? need explore a further..</technical_language>

Target:
private BoundaryBox getLayerBoundingBox(String layerName, WMSLayer layer, String srs) throws DriverException { WMSLayer wmsLayer = find(layerName, layer); BoundaryBox bbox = wmsLayer.getBbox(srs); while ((bbox == null) && (wmsLayer.getParent() != null)) { wmsLayer = wmsLayer.getParent(); bbox = wmsLayer.getBbox(srs); } if (bbox == null) { throw new DriverException("Could not find a valid bounding box for the layer " + layerName); } return bbox; }
Source:
<code>public static String waitForPortFree(int port, Duration timeout, boolean failOnTimeout) { long secs = Math.max(timeout.toSeconds(), 1); <START> String netstatCommand = "sudo netstat -antp TCP"; <END> String grepCommand = "grep -E '(:|\\.)"+port+"($|\\s)' > /dev/null"; List<String> commands = ImmutableList.of( "for i in {1.."+secs+"}; do", " "+alternativesGroup( "which netstat", chain("echo \"No netstat to determine if Port "+port+" still in use; aborting\"", "exit 1")), " "+alternativesGroup( chainGroup("which awk", "AWK_EXEC=awk"), chainGroup("which gawk", "AWK_EXEC=gawk"), chainGroup("which /usr/bin/awk", "AWK_EXEC=/usr/bin/awk"), chainGroup("echo \"No awk to determine if Port "+port+" still in use; aborting\"", "exit 1")), " "+netstatCommand+" | $AWK_EXEC '{print $4}' | "+grepCommand+" && result=0 || result=$?", " [ \"$result\" != 0 ] && break", " sleep 1", "done", "if test \"$result\" -eq 0; then", " "+ (failOnTimeout ? "echo \"Port "+port+" still in use (according to netstat); aborting\" && exit 1" : "echo \"Port "+port+" still in use (according to netstat); continuing\""), "fi"); return Joiner.on("\n").join(commands); }</code><technical_language>@aledsage a this, interesting problem..</technical_language>

Target:
public static String waitForPortFree(int port, Duration timeout, boolean failOnTimeout) { long secs = Math.max(timeout.toSeconds(), 1); String netstatCommand = alternativesGroup( "sudo netstat -antp --tcp", "sudo netstat -antp TCP"); String grepCommand = "grep -E '(:|\\.)"+port+"($|\\s)' > /dev/null"; List<String> commands = ImmutableList.of( "for i in {1.."+secs+"}; do", " "+BashCommands.requireExecutable("netstat"), " "+alternativesGroup( chainGroup("which awk", "AWK_EXEC=awk"), chainGroup("which gawk", "AWK_EXEC=gawk"), chainGroup("which /usr/bin/awk", "AWK_EXEC=/usr/bin/awk"), chainGroup("echo \"No awk to determine if Port "+port+" still in use; aborting\"", "exit 1")), " "+netstatCommand+" | $AWK_EXEC '{print $4}' | "+grepCommand+" && result=0 || result=$?", " [ \"$result\" != 0 ] && break", " sleep 1", "done", "if test \"$result\" -eq 0; then", " "+ (failOnTimeout ? "echo \"Port "+port+" still in use (according to netstat); aborting\" && exit 1" : "echo \"Port "+port+" still in use (according to netstat); continuing\""), "fi"); return Joiner.on("\n").join(commands); }
Source:
<code>public void storeMessagesToDb(final List<AuditerMessage> messages) { synchronized (LOCK_DB_TABLE_AUDITER_LOG) { try { jdbc.batchUpdate("insert into auditer_log (id, msg, actor, created_at, created_by_uid) values (?,?,?," + Compatibility.getSysdate() + ",?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { final AuditerMessage auditerMessage = messages.get(i); final String message = auditerMessage.getMessage(); final PerunSession session = auditerMessage.getOriginaterPerunSession(); log.info("AUDIT: {}", message); try { ps.setInt(1, Utils.getNewId(jdbc, "auditer_log_id_seq")); } catch (InternalErrorException e) { <START> log.error("Cannot get unique id for new auditer log message ['{}'], exception: {}", message, e); <END> } ps.setString(2, message); ps.setString(3, session.getPerunPrincipal().getActor()); ps.setInt(4, session.getPerunPrincipal().getUserId()); } @Override public int getBatchSize() { return messages.size(); } }); } catch (RuntimeException e) { log.error("Cannot store auditer log message in batch for list ['{}'], exception: {}", messages, e); } catch (InternalErrorException e) { log.error("Could not get system date identifier for the DB", e); } } }</code><technical_language>Consider pass exception calling chain. ID, SQL query fail anyway</technical_language>

Target:
public void storeMessagesToDb(final List<AuditerMessage> messages) { synchronized (LOCK_DB_TABLE_AUDITER_LOG) { try { jdbc.batchUpdate("insert into auditer_log (id, msg, actor, created_at, created_by_uid) values (?,?,?," + Compatibility.getSysdate() + ",?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { final AuditerMessage auditerMessage = messages.get(i); final String message = auditerMessage.getMessage(); final PerunSession session = auditerMessage.getOriginaterPerunSession(); log.info("AUDIT: {}", message); try { ps.setInt(1, Utils.getNewId(jdbc, "auditer_log_id_seq")); } catch (InternalErrorException e) { throw new SQLException("Cannot get unique id for new auditer log message ['" + message + "']", e); } ps.setString(2, message); ps.setString(3, session.getPerunPrincipal().getActor()); ps.setInt(4, session.getPerunPrincipal().getUserId()); } @Override public int getBatchSize() { return messages.size(); } }); } catch (RuntimeException e) { log.error("Cannot store auditer log message in batch for list ['{}'], exception: {}", messages, e); } catch (InternalErrorException e) { log.error("Could not get system date identifier for the DB", e); } } }
Source:
<code>public void testGetReferencedComponentId() { String expectedStringValue; String referencedComponentId; <START> expectedStringValue = "SomeStringValue"; <END> closeProperties.referencedComponent.componentInstanceId.setValue(expectedStringValue); referencedComponentId = closeProperties.getReferencedComponentId(); assertEquals(referencedComponentId, expectedStringValue); }</code><technical_language>initialize local variable while defining it</technical_language>

Target:
public void testGetReferencedComponentId() { String expectedStringValue = "SomeStringValue";; String referencedComponentId; closeProperties.referencedComponent.componentInstanceId.setValue(expectedStringValue); referencedComponentId = closeProperties.getReferencedComponentId(); assertEquals(referencedComponentId, expectedStringValue); }
Source:
<code>public void setBrowserInput(final Viewpoint viewpoint, final RepresentationDescription representationDescription) { if (browser != null && representationDescription != null && viewpoint != null) { String userDocumentation; if <START> (representationDescription.getEndUserDocumentation() != null && !representationDescription.getEndUserDocumentation().isEmpty()) { <END> userDocumentation = representationDescription.getEndUserDocumentation(); } else { userDocumentation = viewpoint.getEndUserDocumentation(); } String content = null; if (containsHTMLDocumentation(userDocumentation)) { content = getContentWhenHtml(userDocumentation, representationDescription.eResource().getURI()); } else { content = getContentWhenNoHtml(userDocumentation); } browser.setText(content); } else if (browser != null) { browser.setText("<br><br><center><b>" + Messages.ViewpointsSelectionWizardPage_documentation_title + "</b></center>"); } }</code><technical_language>Note org.eclipse.sirius.common.tools.api.util.StringUtil.isEmpty(String) for this common test</technical_language>

Target:
public void setBrowserInput(final Viewpoint viewpoint, final RepresentationDescription representationDescription) { if (browser != null && representationDescription != null && viewpoint != null) { String userDocumentation; if (representationDescription.getEndUserDocumentation() != null && !StringUtil.isEmpty(representationDescription.getEndUserDocumentation())) { userDocumentation = representationDescription.getEndUserDocumentation(); } else { userDocumentation = viewpoint.getEndUserDocumentation(); } String content = null; if (containsHTMLDocumentation(userDocumentation)) { content = getContentWhenHtml(userDocumentation, representationDescription.eResource().getURI()); } else { content = getContentWhenNoHtml(userDocumentation); } browser.setText(content); } else if (browser != null) { browser.setText("<br><br><center><b>" + Messages.ViewpointsSelectionWizardPage_documentation_title + "</b></center>"); } }
Source:
<code>public void getDependentJarsFromManifest(JarFile jarFile, Set<String> set) throws IOException { String value = jarFile.getManifest().getMainAttributes().getValue(APEX_DEPENDENCIES); if (!StringUtils.isEmpty(value)) { Path folderPath = Paths.get(jarFile.getName()).getParent(); for (String jar : value.split(",")) { File file = folderPath.resolve(jar).toFile(); if (file.exists()) { set.add(file.getPath()); logger.debug("Jar-file was added as a dependent jar", file.getPath()); } else { <START> logger.warn("Jar-file does not exist", file.getPath()); <END> } } } }</code><technical_language>good provide details original Jar a missing dependency</technical_language>

Target:
public void getDependentJarsFromManifest(JarFile jarFile, Set<String> set) throws IOException { String value = jarFile.getManifest().getMainAttributes().getValue(APEX_DEPENDENCIES); if (!StringUtils.isEmpty(value)) { Path folderPath = Paths.get(jarFile.getName()).getParent(); for (String jar : value.split(",")) { File file = folderPath.resolve(jar).toFile(); if (file.exists()) { set.add(file.getPath()); logger.debug("The file was added as a dependent of the jar {}", file.getPath(), jarFile.getName()); } else { logger.warn("The dependent file of the jar does not exist", file.getPath(), jarFile.getName()); } } } }
Source:
<code>public IRequestablePage newPageInstance(Class<? extends IRequestablePage> pageClass, PageParameters pageParameters) { try { MockPage page; <START> page = (MockPage)pageClass.newInstance(); <END> page.setPageId(++idCounter); page.setBookmarkable(true); page.setCreatedBookmarkable(true); if (pageParameters != null) { page.getPageParameters().overwriteWith(pageParameters); } return page; } catch (Exception e) { throw new WicketRuntimeException(e); } }</code><technical_language><LINK_0> - Class#newInstance() is deprecated in Java 9+</technical_language>

Target:
public IRequestablePage newPageInstance(Class<? extends IRequestablePage> pageClass, PageParameters pageParameters) { try { MockPage page; page = (MockPage)pageClass.getDeclaredConstructor().newInstance(); page.setPageId(++idCounter); page.setBookmarkable(true); page.setCreatedBookmarkable(true); if (pageParameters != null) { page.getPageParameters().overwriteWith(pageParameters); } return page; } catch (Exception e) { throw new WicketRuntimeException(e); } }
Source:
<code>private double matchPrice(HashMap<Double, ArrayList<Integer>> orderbook) { ArrayList<Double> priceList=new ArrayList<Double>(); for(double prce:orderbook.keySet()){ priceList.add(prce); } Collections.sort(priceList, Collections.reverseOrder()); <START> ArrayList<Integer> buyCum=new ArrayList<Integer>(priceList.size()); <END> ArrayList<Integer> sellCum=new ArrayList<Integer>(priceList.size()); double key=priceList.get(0); buyCum.add(orderbook.get(key).get(0)); for(int i=1; i<priceList.size(); i++){ key=priceList.get(i); buyCum.add(orderbook.get(key).get(0)+buyCum.get(i-1)); } key=priceList.get(priceList.size()-1); sellCum.add(orderbook.get(key).get(1)); for(int i=priceList.size()-2;i>-1; i--){ key=priceList.get(i); sellCum.add(orderbook.get(key).get(1)+sellCum.get(priceList.size()-i-2)); } double matchPrice=0; int max=0; for(int i=0; i<priceList.size(); i++){ int min=Math.min(sellCum.get(i),buyCum.get(priceList.size()-1-i)); if (min>max){ max=min; matchPrice=priceList.get(i); } } return matchPrice; }</code><technical_language>bad naming. clearer</technical_language>

Target:
private double matchPrice(HashMap<Double, ArrayList<Integer>> orderbook) { ArrayList<Double> priceList=new ArrayList<Double>(); for(double prce:orderbook.keySet()){ priceList.add(prce); } Collections.sort(priceList, Collections.reverseOrder()); ArrayList<Integer> buyPriceList=new ArrayList<Integer>(priceList.size()); ArrayList<Integer> sellPriceList=new ArrayList<Integer>(priceList.size()); double price=priceList.get(0); buyPriceList.add(orderbook.get(price).get(0)); for(int i=1; i<priceList.size(); i++){ price=priceList.get(i); buyPriceList.add(orderbook.get(price).get(0)+buyPriceList.get(i-1)); } price=priceList.get(priceList.size()-1); sellPriceList.add(orderbook.get(price).get(1)); for(int i=priceList.size()-2;i>-1; i--){ price=priceList.get(i); int index=priceList.size()-i-2; sellPriceList.add(orderbook.get(price).get(1)+sellPriceList.get(index)); } double matchPrice=0; int max=0; for(int i=0; i<priceList.size(); i++){ int index=priceList.size()-1-i; int min=Math.min(sellPriceList.get(i),buyPriceList.get(index)); if (min>max){ max=min; matchPrice=priceList.get(i); } } return matchPrice; }
Source:
<code>protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = getConfig(); <START> YarnConfiguration conf = new YarnConfiguration(); <END> if (SecurityUtils.isStramWebSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); String scheme = ConfigUtils.getSchemePrefix(conf); String hostname = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName(); this.appMasterTrackingUrl = scheme + hostname + ":" + webApp.port(); LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }</code><technical_language>is necessary Configuration YarnConfiguration? this code simplified YarnConfiguration = StramClientUtils.getYarnConfiguration(getConfig());</technical_language>

Target:
protected void serviceStart() throws Exception { super.serviceStart(); if (UserGroupInformation.isSecurityEnabled()) { delegationTokenManager.startThreads(); } InetSocketAddress connectAddress = NetUtils.getConnectAddress(this.heartbeatListener.getAddress()); URI connectUri = RecoverableRpcProxy.toConnectURI(connectAddress); FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(dag.assertAppPath(), getConfig()); recoveryHandler.writeConnectUri(connectUri.toString()); try { org.mortbay.log.Log.setLog(null); } catch (Throwable throwable) { } try { Configuration config = getConfig(); if (SecurityUtils.isStramWebSecurityEnabled()) { config = new Configuration(config); config.set("hadoop.http.filter.initializers", StramWSFilterInitializer.class.getCanonicalName()); } WebApp webApp = WebApps.$for("stram", StramAppContext.class, appContext, "ws").with(config).start(new StramWebApp(this.dnmgr)); LOG.info("Started web service at port: " + webApp.port()); appMasterTrackingUrl = NetUtils.getConnectAddress(webApp.getListenerAddress()).getHostName() + ":" + webApp.port(); if (ConfigUtils.isSSLEnabled(config)) { appMasterTrackingUrl = "https://" + appMasterTrackingUrl; } LOG.info("Setting tracking URL to: " + appMasterTrackingUrl); } catch (Exception e) { LOG.error("Webapps failed to start. Ignoring for now:", e); } }
Source:
<code>private void onUserStart(int userId) { synchronized (mVpns) { Vpn userVpn = mVpns.get(userId); if (userVpn != null) { loge("Starting user already has a VPN"); return; } userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); mVpns.put(userId, userVpn); } if (mUserManager.getUserInfo(userId).isPrimary() && <START> LockdownVpnTracker.isEnabled()) { updateLockdownVpn(); <END> } }</code><technical_language>tracker is enabled change check call. LockdownVpnTracker.isEnabled() replaced mLockdownEnabled I thik</technical_language>

Target:
private void onUserStart(int userId) { synchronized (mVpns) { Vpn userVpn = mVpns.get(userId); if (userVpn != null) { loge("Starting user already has a VPN"); return; } userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); mVpns.put(userId, userVpn); if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { updateLockdownVpn(); } } }
Source:
<code>public void addBranch(final String newBranchName, final String baseBranchName, final WorkspaceProject project) { projectService.addBranch(newBranchName, baseBranchName, project); <START> Repository repository = repoService.getRepositoryFromSpace( <END> project.getSpace(), project.getRepository().getAlias()); RepositoryUpdatedEvent event = new RepositoryUpdatedEvent(repository); repositoryUpdatedEvent.fire(event); newBranchEvent.fire(new NewBranchEvent(repository, newBranchName, baseBranchName, sessionInfo.getIdentity())); }</code><technical_language>reason move events firing WorkspaceProjectServiceImpl well? I better, REST changes observable screens</technical_language>

Target:
public void addBranch(final String newBranchName, final String baseBranchName, final WorkspaceProject project) { projectService.addBranch(newBranchName, baseBranchName, project, sessionInfo.getIdentity().getIdentifier()); }
Source:
<code>public void validateRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; serverMetrics.securityServiceValidateRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("ServerSecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null) { throw new IllegalArgumentException("restRequest is null"); } <START> serverMetrics.securityServiceValidateRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); <END> callback.onCompletion(null, exception); }</code><technical_language>Remove timer</technical_language>

Target:
public void validateRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; serverMetrics.securityServiceValidateRequestRate.mark(); if (!isOpen) { exception = new RestServiceException("ServerSecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null) { throw new IllegalArgumentException("restRequest is null"); } callback.onCompletion(null, exception); }
Source:
<code>public void visitConstant(int opcode, int offset, int length, Constant cst, int value) { switch (opcode) { case ByteOps.ANEWARRAY: { machine.popArgs(frame, Type.INT); break; } case ByteOps.PUTSTATIC: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, fieldType); break; } case ByteOps.GETFIELD: case ByteOps.CHECKCAST: case ByteOps.INSTANCEOF: { machine.popArgs(frame, Type.OBJECT); break; } case ByteOps.PUTFIELD: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, Type.OBJECT, fieldType); break; } case ByteOps.INVOKEINTERFACE: { cst = ((CstInterfaceMethodRef) cst).toMethodRef(); } case ByteOps.INVOKEVIRTUAL: case ByteOps.INVOKESPECIAL: { if (cst instanceof CstInterfaceMethodRef) { <START> cst = ((CstInterfaceMethodRef) cst).toMethodRef(); <END> } Prototype prototype = ((CstMethodRef) cst).getPrototype(false); machine.popArgs(frame, prototype); break; } case ByteOps.INVOKESTATIC: { if (cst instanceof CstInterfaceMethodRef) { cst = ((CstInterfaceMethodRef) cst).toMethodRef(); } Prototype prototype = ((CstMethodRef) cst).getPrototype(true); machine.popArgs(frame, prototype); break; } case ByteOps.MULTIANEWARRAY: { Prototype prototype = Prototype.internInts(Type.VOID, value); machine.popArgs(frame, prototype); break; } default: { machine.clearArgs(); break; } } machine.auxIntArg(value); machine.auxCstArg(cst); machine.run(frame, offset, opcode); }</code><technical_language>This allowed for private methods for ACC_SUPER (the of a separate CL for) I else invalid bytecode verifier fail on. (there is <init> sense for interface)</technical_language>

Target:
public void visitConstant(int opcode, int offset, int length, Constant cst, int value) { switch (opcode) { case ByteOps.ANEWARRAY: { machine.popArgs(frame, Type.INT); break; } case ByteOps.PUTSTATIC: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, fieldType); break; } case ByteOps.GETFIELD: case ByteOps.CHECKCAST: case ByteOps.INSTANCEOF: { machine.popArgs(frame, Type.OBJECT); break; } case ByteOps.PUTFIELD: { Type fieldType = ((CstFieldRef) cst).getType(); machine.popArgs(frame, Type.OBJECT, fieldType); break; } case ByteOps.INVOKEINTERFACE: case ByteOps.INVOKEVIRTUAL: case ByteOps.INVOKESPECIAL: case ByteOps.INVOKESTATIC: { if (cst instanceof CstInterfaceMethodRef) { if (opcode != ByteOps.INVOKEINTERFACE) { if (!dexOptions.canUseDefaultInterfaceMethods()) { throw new SimException( "default or static interface method used without --min-sdk-version >= 24"); } } cst = ((CstInterfaceMethodRef) cst).toMethodRef(); } boolean staticMethod = (opcode == ByteOps.INVOKESTATIC); Prototype prototype = ((CstMethodRef) cst).getPrototype(staticMethod); machine.popArgs(frame, prototype); break; } case ByteOps.MULTIANEWARRAY: { Prototype prototype = Prototype.internInts(Type.VOID, value); machine.popArgs(frame, prototype); break; } default: { machine.clearArgs(); break; } } machine.auxIntArg(value); machine.auxCstArg(cst); machine.run(frame, offset, opcode); }
Source:
<code>public Builder registerAction( @NonNull String alias, @NonNull String actionName, @NonNull Class<? extends Action> actionClass){ List<Field> fields = new ArrayList<>(); for (Field field : actionClass.getDeclaredFields()) { <START> if (!field.getName().equals("this$0")){ END> fields.add(field); } } if (fields.size() != 1) { throw new IllegalArgumentException("action class must contain only one field."); } Gson gson = new Gson(); Action action = gson.fromJson(new JsonObject(), actionClass); if (TextUtils.isEmpty(action.getActionName())) { throw new IllegalArgumentException("getActionName() return null or empty"); } this.actionTypes.put(ThingIFAPI.actionsMapKey(alias, actionName), actionClass); return this; }</code><technical_language>I do understand want do this code. Do want check actionClass is class not</technical_language>

Target:
public Builder registerAction( @NonNull String alias, @NonNull String actionName, @NonNull Class<? extends Action> actionClass){ if (actionClass.getEnclosingClass() != null && !Modifier.isStatic(actionClass.getModifiers())) { throw new IllegalArgumentException("non static inner class is not allowed to be Action"); } if(actionClass.getDeclaredFields().length != 1) { throw new IllegalArgumentException("action class must contain only one field."); } Gson gson = new Gson(); Action action = gson.fromJson(new JsonObject(), actionClass); if (TextUtils.isEmpty(action.getActionName())) { throw new IllegalArgumentException("getActionName() return null or empty"); } this.actionTypes.put(ThingIFAPI.actionsMapKey(alias, actionName), actionClass); return this; }
Source:
<code>public void error(final String msg) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>If log error vararg arguments this throw exception I understand</technical_language>

Target:
public void error(final String msg) { logMessageWithFormat("ERROR", msg); }
Source:
<code>private static String getTimegraphSelectionName(final SWTBotView view) { final TimeGraphControl timegraph = view.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class)); <START> return UIThreadRunnable.syncExec(new StringResult() { <END> @Override public String run() { ISelection selection = timegraph.getSelectionTrace(); if (selection instanceof TimeGraphSelection) { TimeGraphSelection sel = (TimeGraphSelection) selection; ITimeGraphEntry entry = (ITimeGraphEntry) sel.getFirstElement(); return entry.getName(); } return null; } }); }</code><technical_language>lambda</technical_language>

Target:
private static String getTimegraphSelectionName(final SWTBotView view) { final TimeGraphControl timegraph = view.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class)); return UIThreadRunnable.syncExec(() -> { ISelection selection = timegraph.getSelectionTrace(); if (selection instanceof TimeGraphSelection) { TimeGraphSelection sel = (TimeGraphSelection) selection; ITimeGraphEntry entry = (ITimeGraphEntry) sel.getFirstElement(); return entry.getName(); } return null; }); }
Source:
<code>private void doCreateProject() { final String projectName = createTxt.getText().trim(); <START> String parentName = null; <END> if (showParentCandidates.getValue()) { parentName = suggestedParents.getItemText(suggestedParents.getSelectedIndex()); if (parentName.equals(NO_PARENT_SELECTED)) { parentName = ""; } } else { parentName = parentTxt.getText(); } Util.PROJECT_SVC.createNewProject(projectName, parentName, new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { History.newItem(Dispatcher.toProjectAdmin(new Project.NameKey( projectName), ProjectScreen.INFO)); } @Override public void onFailure(Throwable caught) { super.onFailure(caught); enableForm(true); } }); }</code><technical_language>Nit: this null setting useful</technical_language>

Target:
private void doCreateProject() { final String projectName = createTxt.getText().trim(); final String parentName = parentTxt.getText(); enableForm(false); Util.PROJECT_SVC.createNewProject(projectName, parentName, emptyCommit .getValue(), new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { History.newItem(Dispatcher.toProjectAdmin(new Project.NameKey( projectName), ProjectScreen.INFO)); } @Override public void onFailure(Throwable caught) { super.onFailure(caught); enableForm(true); } }); }
Source:
<code>private void generateRequestImplementation(Method method) { Name name = method.getName(); String request = getRequestName(method); String requestImpl = getRequestImplName(method); buffer.addLine("private class %1$s implements %2$s {", requestImpl, request); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateRequestParameterImplementation); buffer.addImport(Map.class); buffer.addLine( "private Map<String, String> headers;"); buffer.addLine( "public %1s headers(Map<String, String> headers) {", request); buffer.addLine( "this.headers = headers;"); buffer.addLine( "return this;"); buffer.addLine("}"); buffer.addLine( "private Map<String, String> query;"); buffer.addLine( "public %1s query(Map<String, String> query) {", request); buffer.addLine( "this.query = query;"); buffer.addLine( "return this;"); <START> buffer.addLine("}"); <END> buffer.addLine("public %1$s send() {", getResponseName(method)); if (ADD.equals(name)) { generateAddRequestImplementation(method); } else if (GET.equals(name) || LIST.equals(name)) { generateListRequestImplementation(method); } else if (REMOVE.equals(name)) { generateRemoveRequestImplementation(method); } else if (UPDATE.equals(name)) { generateUpdateRequestImplementation(method); } else { generateActionRequestImplementation(method); } buffer.addLine("}"); buffer.addLine(); buffer.addLine("}"); buffer.addLine(); }</code><technical_language>methods identical for requests, extracted a 'BaseRequest' class</technical_language>

Target:
private void generateRequestImplementation(Method method) { buffer.addImport(BASE_PACKAGE + ".BaseRequest"); Name name = method.getName(); String request = getRequestName(method); String response = getResponseName(method); String requestImpl = getRequestImplName(method); buffer.addLine("private class %1$s extends BaseRequest<%2$s, %3$s> implements %2$s {", requestImpl, request, response); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateRequestParameterImplementation); buffer.addLine("public %1$s send() {", getResponseName(method)); if (ADD.equals(name)) { generateAddRequestImplementation(method); } else if (GET.equals(name) || LIST.equals(name)) { generateListRequestImplementation(method); } else if (REMOVE.equals(name)) { generateRemoveRequestImplementation(method); } else if (UPDATE.equals(name)) { generateUpdateRequestImplementation(method); } else { generateActionRequestImplementation(method); } buffer.addLine("}"); buffer.addLine(); buffer.addLine("}"); buffer.addLine(); }
Source:
<code><START> protected ProcessHolder.Classes getClasses() { <END> return environment().getClasses(); }</code><technical_language>ProcessHolder is internal class, is meant plugins..</technical_language>

Target:
protected ClassesHolder.Classes getClasses() { return environment().getClasses(); }
Source:
<code>public ExtensionJobList getExtensionJobs( @PathParam("extension-name") String extensionName, @DefaultValue(ASCENDING_SORT_ORDER) @QueryParam("sortOrder") String sortOrder, @DefaultValue("") @QueryParam("doAs") String doAsUser) { checkIfExtensionServiceIsEnabled(); checkIfExtensionExists(extensionName); try { Map<String, String> jobAndExtensionNames = new HashMap<>(); List<ExtensionJobsBean> extensionJobs = null; if (extensionName != null) { extensionJobs = ExtensionStore.getMetaStore().getJobsForAnExtension(extensionName); } else { extensionJobs = ExtensionStore.getMetaStore().getAllExtensionJobs(); } switch (sortOrder.toLowerCase()) { case DESCENDING_SORT_ORDER: <START> Collections.sort(extensionJobs, new Comparator<ExtensionJobsBean>() { <END> public int compare(ExtensionJobsBean o1, ExtensionJobsBean o2) { return o2.getJobName().compareTo(o1.getJobName()); } }); break; default: Collections.sort(extensionJobs, new Comparator<ExtensionJobsBean>() { public int compare(ExtensionJobsBean o1, ExtensionJobsBean o2) { return o1.getJobName().compareTo(o2.getJobName()); } }); } for (ExtensionJobsBean job : extensionJobs) { jobAndExtensionNames.put(job.getJobName(), job.getExtensionName()); } return new ExtensionJobList(extensionJobs.size(), jobAndExtensionNames); } catch (Throwable e) { LOG.error("Failed to get extension job list of " + extensionName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }</code><technical_language>Instead, ExtensionJobsBean implement Comparable interface</technical_language>

Target:
public ExtensionJobList getExtensionJobs( @PathParam("extension-name") String extensionName, @DefaultValue(ASCENDING_SORT_ORDER) @QueryParam("sortOrder") String sortOrder, @DefaultValue("") @QueryParam("doAs") String doAsUser) { checkIfExtensionServiceIsEnabled(); checkIfExtensionExists(extensionName); try { return super.getExtensionJobs(extensionName, sortOrder, doAsUser); } catch (Throwable e) { LOG.error("Failed to get extension job list of " + extensionName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
<code>private static JavaMajorVersion detectCurrentVersion() { final ILogger logger = Logger.getLogger(JavaVersion.class); final Class runtimeClass; final Class versionClass; try { <START> runtimeClass = Class.forName("java.lang.Runtime"); <END> } catch (ClassNotFoundException e) { logger.warning("Unable to detect Java version, falling back to Java 8", e); return JAVA_8; } try { versionClass = Class.forName("java.lang.Runtime$Version"); } catch (ClassNotFoundException e) { logger.info("Detected runtime version: Java 8"); return JAVA_8; } try { Method versionMethod = runtimeClass.getDeclaredMethod("version"); Object versionObj = versionMethod.invoke(Runtime.getRuntime()); Method majorMethod = versionClass.getDeclaredMethod("major"); int majorVersion = (int) majorMethod.invoke(versionObj); logger.info("Detected runtime version: Java " + majorVersion); JavaVersion foundVersion = valueOf(majorVersion); if (foundVersion != null) { return foundVersion; } return new FutureJavaVersion(majorVersion); } catch (Exception e) { logger.warning("Unable to detect Java version, falling back to Java 8", e); return JAVA_8; } }</code><technical_language>need reflection here, I think. Runtime is part of Java beginning. Runtime.class do job</technical_language>

Target:
private static JavaMajorVersion detectCurrentVersion() { final ILogger logger = Logger.getLogger(JavaVersion.class); final Class runtimeClass = Runtime.class; final Class versionClass; try { versionClass = Class.forName("java.lang.Runtime$Version"); } catch (ClassNotFoundException e) { if (logger.isFineEnabled()) { logger.fine("Detected runtime version: Java 8"); } return JAVA_8; } try { Method versionMethod = runtimeClass.getDeclaredMethod("version"); Object versionObj = versionMethod.invoke(Runtime.getRuntime()); Method majorMethod = versionClass.getDeclaredMethod("major"); int majorVersion = (int) majorMethod.invoke(versionObj); if (logger.isFineEnabled()) { logger.fine("Detected runtime version: Java " + majorVersion); } JavaVersion foundVersion = valueOf(majorVersion); if (foundVersion != null) { return foundVersion; } return new FutureJavaVersion(majorVersion); } catch (Exception e) { logger.warning("Unable to detect Java version, falling back to Java 8", e); return JAVA_8; } }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_user_brick_list, container, false); setHasOptionsMenu(true); addUserBrickButton = view.findViewById(R.id.add_user_brick); addUserBrickButton.setOnClickListener(this); <START> ((AppCompatActivity) getActivity()) <END> .getSupportActionBar().setTitle(R.string.category_user_bricks); return view; }</code><technical_language>Please a null-ptr check</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_user_brick_list, container, false); setHasOptionsMenu(true); addUserBrickButton = view.findViewById(R.id.add_user_brick); addUserBrickButton.setOnClickListener(this); AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity(); if (appCompatActivity != null && appCompatActivity.getSupportActionBar() != null) { appCompatActivity.getSupportActionBar().setTitle(R.string.category_user_bricks); } return view; }
Source:
<code>protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException { Bundle originalBundle; try { originalBundle = itemService.getBundles(item, "ORIGINAL").get(0); <START> } catch (IndexOutOfBoundsException ex) { <END> originalBundle = null; } if (originalBundle != null) { for (Bitstream bitstream : originalBundle.getBitstreams()) { authorizeService.removeAllPoliciesByDSOAndType(context, bitstream, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, originalBundle, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, item, ResourcePolicy.TYPE_WORKFLOW); }</code><technical_language>check if list returned is empty instead of catching exception here</technical_language>

Target:
protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException { List<Bundle> bundles = item.getBundles(); for (Bundle originalBundle : bundles) { for (Bitstream bitstream : originalBundle.getBitstreams()) { authorizeService.removeAllPoliciesByDSOAndType(context, bitstream, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, originalBundle, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, item, ResourcePolicy.TYPE_WORKFLOW); }