auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static final Read makeRead(SAMRecord record) { <END> Read read = new Read(); read.setName(record.getReadName()); read.setFlags(record.getFlags()); read.setReferenceSequenceName(record.getReferenceName()); read.setPosition(record.getAlignmentStart()); read.setMappingQuality(record.getMappingQuality()); read.setCigar(record.getCigarString()); read.setMateReferenceSequenceName(record.getMateReferenceName()); read.setMatePosition(record.getMateAlignmentStart()); read.setTemplateLength(record.getInferredInsertSize()); read.setOriginalBases(record.getReadString()); read.setBaseQuality(record.getBaseQualityString()); if (record.getAttributes() != null) { HashMap<String, List<String>> tags = new HashMap<String, List<String>>(); for(SAMTagAndValue tagPair : record.getAttributes()) { if (tags.containsKey(tagPair.tag)) { tags.get(tagPair.tag).add(tagPair.value.toString()); } else { tags.put(tagPair.tag, Lists.newArrayList((tagPair.value.toString()))); } } read.setTags(tags); } return read; }</code><technical_language>dont add final static methods</technical_language>

Target:
public static Read makeRead(SAMRecord record) { Read read = new Read(); read.setName(record.getReadName()); read.setFlags(record.getFlags()); read.setReferenceSequenceName(record.getReferenceName()); read.setPosition(record.getAlignmentStart()); read.setMappingQuality(record.getMappingQuality()); read.setCigar(record.getCigarString()); read.setMateReferenceSequenceName(record.getMateReferenceName()); read.setMatePosition(record.getMateAlignmentStart()); read.setTemplateLength(record.getInferredInsertSize()); read.setOriginalBases(record.getReadString()); read.setBaseQuality(record.getBaseQualityString()); if (record.getAttributes() != null) { HashMap<String, List<String>> tags = new HashMap<String, List<String>>(); for (SAMTagAndValue tagPair : record.getAttributes()) { if (tags.containsKey(tagPair.tag)) { tags.get(tagPair.tag).add(tagPair.value.toString()); } else { tags.put(tagPair.tag, Lists.newArrayList((tagPair.value.toString()))); } } read.setTags(tags); } return read; }
Source:
<code>public TapeResult call() throws Exception { final EjectTapeSpectraS3Request request = new EjectTapeSpectraS3Request(id) <START> .withEjectLabel(ejectLabel).withEjectLocation(ejectLocation); <END> final EjectTapeSpectraS3Response response = this.getClient().ejectTapeSpectraS3(request); return new TapeResult(response.getTapeResult()); }</code><technical_language>ejectLabel ejectLocation optional, of with-constructors if-statement</technical_language>

Target:
public TapeResult call() throws Exception { final EjectTapeSpectraS3Request request = new EjectTapeSpectraS3Request(id); if (!Guard.isStringNullOrEmpty(ejectLabel)) { request.withEjectLabel(ejectLabel); } if (!Guard.isStringNullOrEmpty(ejectLocation)) { request.withEjectLocation(ejectLocation); } final EjectTapeSpectraS3Response response = this.getClient().ejectTapeSpectraS3(request); return new TapeResult(response.getTapeResult()); }
Source:
<code>protected ActionResult execute() { account.studentProfile = logic.getStudentProfile(account.googleId); String isEditingPhoto = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_PHOTOEDIT); if (isEditingPhoto == null) { isEditingPhoto = "false"; } if (account.studentProfile == null) { log.severe("Student Profile returned as null for " + account.toString()); return createRedirectResult(Const.ActionURIs.STUDENT_HOME_PAGE); } StudentProfilePageData data = new StudentProfilePageData(account, sessionToken, isEditingPhoto); <START> statusToAdmin = "studentProfile Page Load <br> Profile: test"; <END> return createShowPageResult(Const.ViewURIs.STUDENT_PROFILE_PAGE, data); }</code><technical_language>hardcode test. In #8717, test is mentioned google id in screenshot is test. need display googleId</technical_language>

Target:
protected ActionResult execute() { account.studentProfile = logic.getStudentProfile(account.googleId); String isEditingPhoto = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_PHOTOEDIT); if (isEditingPhoto == null) { isEditingPhoto = "false"; } if (account.studentProfile == null) { log.severe("Student Profile returned as null for " + account.toString()); return createRedirectResult(Const.ActionURIs.STUDENT_HOME_PAGE); } StudentProfilePageData data = new StudentProfilePageData(account, sessionToken, isEditingPhoto); statusToAdmin = "studentProfile Page Load <br> Profile: " + account.googleId; return createShowPageResult(Const.ViewURIs.STUDENT_PROFILE_PAGE, data); }
Source:
<code>protected String findOp(ExprNodeDesc exprNodeDesc) { String udfName = getGenericUDFNameFromExprDesc(exprNodeDesc); if (udfName == null) return null; String[] arr = udfName.split("\\."); <START> udfName = arr[arr.length - 1]; <END> String op = sargableParser.udfOp(udfName); if (op == null) return udfName; else return sargableParser.synonymOp(op); }</code><technical_language>More efficient get instance of . substring index + 1 end</technical_language>

Target:
protected String findOp(ExprNodeDesc exprNodeDesc) { String udfName = getGenericUDFNameFromExprDesc(exprNodeDesc); if (udfName == null) { return null; } int index = udfName.lastIndexOf("."); udfName = udfName.substring(index + 1); String op = sargableParser.udfOp(udfName); if (op == null) { return udfName; } else { return sargableParser.synonymOp(op); } }
Source:
<code><START> public static int[] getColors(Context context) { <END> int[] res = new int[colors.length]; for (int i = 0; i < colors.length; i++) { res[i] = ContextCompat.getColor(context, colors[i]); } return res; }</code><technical_language>This array calculated time</technical_language>

Target:
public static int[] getColors(Context context) { if (colors != null) { return colors; } colors = new int[colorsIds.length]; for (int i = 0; i < colorsIds.length; i++) { colors[i] = ContextCompat.getColor(context, colorsIds[i]); } return colors; }
Source:
<code>public Set<IRepositoryFileStore> getFileStoreForConfiguration(final AbstractProcess process, final Configuration configuration) { final Set<IRepositoryFileStore> result = new HashSet<IRepositoryFileStore>(); final List<FormMapping> allFormMappings = getAllItemsOfType(process, ProcessPackage.Literals.FORM_MAPPING); for (final WebPageFileStore fStore : transform(filter(allFormMappings, withInternalType()), formMappingToFileStore())) { if (fStore != null) { result.add(fStore); try { result.addAll(getRelatedFileStore(fStore)); } catch (final BarResourceCreationException | IOException e) { BonitaStudioLog.error("Failed to retrieve related Form resoruces", e); <START> } <END> } } return result; }</code><technical_language>log is a mapping</technical_language>

Target:
public Set<IRepositoryFileStore> getFileStoreForConfiguration(final AbstractProcess process, final Configuration configuration) { final Set<IRepositoryFileStore> result = new HashSet<IRepositoryFileStore>(); final List<FormMapping> allFormMappings = getAllItemsOfType(process, ProcessPackage.Literals.FORM_MAPPING); for (final WebPageFileStore fStore : transform(filter(allFormMappings, withInternalType()), formMappingToFileStore())) { if (fStore != null) { result.add(fStore); try { result.addAll(getRelatedFileStore(fStore)); } catch (final BarResourceCreationException | IOException e) { BonitaStudioLog.error("Failed to retrieve related form resources", e); } } } return result; }
Source:
<code>private void generateHTMLResponse(ServletResponse response) { String path = "backup_in_progress.html"; InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(path); response.setContentType("text/html"); StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); String content = writer.toString(); content = replaceStringLiterals(content); <START> response.getWriter().print(content); <END> } catch (FileNotFoundException e) { LOGGER.error(String.format("File not found: %s", path)); } catch (IOException e) { LOGGER.error(String.format("General IOException: %s", e.getMessage())); } }</code><technical_language>Prefer FileUtils.readToEnd(InputStream)? I want close inputstream FileUtils well</technical_language>

Target:
private void generateHTMLResponse(ServletResponse response) { String path = "backup_in_progress.html"; InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(path); response.setContentType("text/html"); try { String content = FileUtil.readToEnd(resourceAsStream); content = replaceStringLiterals(content); response.getWriter().print(content); resourceAsStream.close(); } catch (IOException e) { LOGGER.error(String.format("General IOException: %s", e.getMessage())); } }
Source:
<code>public static byte[] serializeAuthorizerUserMap(ObjectMapper objectMapper, Map<String, BasicAuthorizerUser> userMap) { try { return objectMapper.writeValueAsBytes(userMap); } catch (IOException ioe) { <START> throw new ISE("WTF? Couldn't serialize userMap!"); <END> } }</code><technical_language>Please add ioe exception</technical_language>

Target:
public static byte[] serializeAuthorizerUserMap(ObjectMapper objectMapper, Map<String, BasicAuthorizerUser> userMap) { try { return objectMapper.writeValueAsBytes(userMap); } catch (IOException ioe) { throw new ISE(ioe, "WTF? Couldn't serialize userMap!"); } }
Source:
<code>private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader <START> contextFinder = <END> Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); return new CombinedClassLoader(testClassLoader, surefireClassLoader, new TychoContextFinder(contextFinder.getParent())); }</code><technical_language>named currentContextClassloader</technical_language>

Target:
private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); return new CombinedClassLoader(testClassLoader, surefireClassLoader, new TychoContextFinder(contextClassLoader.getParent())); }
Source:
<code>public void includeEpisodeInSeriesAndBrand(Episode episode) { if (Boolean.TRUE.equals(episode.getGenericDescription()) && episode.getEpisodeNumber() == null && episode.getSeriesNumber() == null) { <START> return; <END> } if (IGNORED_BRANDS.contains(episode.getContainer().getUri())) { log.info("Not maintaing child refs for brand " + episode.getContainer().getUri()); return; } ChildRef childRef = episode.childRef(); if (episode.getSeriesRef() == null) { includeChildRefInContainer(episode, childRef, containers, CHILDREN_KEY); return; } String brandUri = episode.getContainer().getUri(); String seriesUri = episode.getSeriesRef().getUri(); Maybe<Container> maybeBrand = getContainer(brandUri, containers); Maybe<Container> maybeSeries = getContainer(seriesUri, programmeGroups); if (maybeBrand.isNothing() || maybeSeries.isNothing()) { throw new IllegalStateException(String.format("Container or series not found for episode %s", episode.getCanonicalUri())); } episode.setContainer(maybeBrand.requireValue()); episode.setSeries((Series)maybeSeries.requireValue()); addChildRef(childRef, containers, maybeBrand.requireValue()); addChildRef(childRef, programmeGroups, maybeSeries.requireValue()); }</code><technical_language>add a debug log this happens? useful monitoring post-production release</technical_language>

Target:
public void includeEpisodeInSeriesAndBrand(Episode episode) { if (Boolean.TRUE.equals(episode.getGenericDescription()) && episode.getEpisodeNumber() == null && episode.getSeriesNumber() == null) { log.debug("Not including episode " + episode.getCanonicalUri() + "in series and brand."); return; } if (IGNORED_BRANDS.contains(episode.getContainer().getUri())) { log.debug("Not maintaining child refs for brand " + episode.getContainer().getUri()); return; } ChildRef childRef = episode.childRef(); if (episode.getSeriesRef() == null) { includeChildRefInContainer(episode, childRef, containers, CHILDREN_KEY); return; } String brandUri = episode.getContainer().getUri(); String seriesUri = episode.getSeriesRef().getUri(); Maybe<Container> maybeBrand = getContainer(brandUri, containers); Maybe<Container> maybeSeries = getContainer(seriesUri, programmeGroups); if (maybeBrand.isNothing() || maybeSeries.isNothing()) { throw new IllegalStateException(String.format("Container or series not found for episode %s", episode.getCanonicalUri())); } episode.setContainer(maybeBrand.requireValue()); episode.setSeries((Series)maybeSeries.requireValue()); addChildRef(childRef, containers, maybeBrand.requireValue()); addChildRef(childRef, programmeGroups, maybeSeries.requireValue()); }
Source:
<code>public void validPidsAssignedToObjectsEvent() throws Exception { String detail = "Assigned PIDs to 3 objects"; <START> Element eventEl = addEvent(premisDoc, ACCESSION_TYPE, detail, EVENT_DATE); <END> addInitiatorAgent(eventEl, METS_NORMAL_AGENT); transformer.compute(); Model model = deserializeLogFile(logFile); List<Resource> eventRescs = listEventResources(objPid, model); assertEquals(1, eventRescs.size()); Resource eventResc = eventRescs.get(0); assertEventType(Premis.InformationPackageCreation, eventResc); assertEventDetail(detail, eventResc); assertEventDateTime(EVENT_DATE_UTC, eventResc); assertAgent(depositService.getFullname(), eventResc); }</code><technical_language>need undo changes in</technical_language>

Target:
public void validPidsAssignedToObjectsEvent() throws Exception { String detail = "Assigned PIDs to 3 objects"; Element eventEl = addEvent(premisDoc, NORMALIZATION_TYPE, detail, EVENT_DATE); addInitiatorAgent(eventEl, METS_NORMAL_AGENT); transformer.compute(); Model model = deserializeLogFile(logFile); List<Resource> eventRescs = listEventResources(objPid, model); assertEquals(1, eventRescs.size()); Resource eventResc = eventRescs.get(0); assertEventType(Premis.InformationPackageCreation, eventResc); assertEventDetail(detail, eventResc); assertEventDateTime(EVENT_DATE_UTC, eventResc); assertAgent(depositService.getFullname(), eventResc); }
Source:
<code>public boolean execute() throws Exception { String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg")); QName varName = new QName("archive", "active-archive"); SrampArchive archive = (SrampArchive) getContext().getVariable(varName); if (archive == null) { print(Messages.i18n.format("NO_ARCHIVE_OPEN")); return false; <START> } else if (archivePathArg.endsWith(File.separator)) { <END> print(Messages.i18n.format("Archive.Path.Arg.should.not.contain.slash.end")); return false; } else { SrampArchiveEntry entry = archive.getEntry(archivePathArg); if (entry != null) { BaseArtifactType metaData = entry.getMetaData(); print(Messages.i18n.format("ENTRY", archivePathArg)); print("-----"); PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor(); ArtifactVisitorHelper.visitArtifact(visitor, metaData); } else { print(Messages.i18n.format("ListEntryArchive.Entry.Not.Exist", archivePathArg)); } } return true; }</code><technical_language>Re-use some sort of "validateArchivePath" method (share other archive commands)</technical_language>

Target:
public boolean execute() throws Exception { super.initialize(); String archivePathArg = requiredArgument(0, Messages.i18n.format("InvalidArgMsg")); if (!validate(archivePathArg)) { return false; } else { SrampArchiveEntry entry = archive.getEntry(archivePathArg); if (entry != null) { BaseArtifactType metaData = entry.getMetaData(); print(Messages.i18n.format("ENTRY", archivePathArg)); print("-----"); PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor(); ArtifactVisitorHelper.visitArtifact(visitor, metaData); } else { print(Messages.i18n.format("ListEntryArchive.Entry.Not.Exist", archivePathArg)); } } return true; }
Source:
<code>static Map<Integer, String> errorCodeNumberToName() { Map<Integer, String> result = new LinkedHashMap<>(); for (Field field : RpcException.class.getDeclaredFields()) { <START> if (Modifier.isStatic(field.getModifiers()) && field.getType() == int.class) { <END> try { result.put((Integer) field.get(null), field.getName()); } catch (Exception e) { assert false : e.getMessage(); Platform.get().log("Error reading error code %s", field, e); } } } return result; }</code><technical_language>checking Modifier.isPublic too</technical_language>

Target:
static Map<Integer, String> errorCodeNumberToName() { Map<Integer, String> result = new LinkedHashMap<>(); for (Field field : RpcException.class.getDeclaredFields()) { if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && field.getType() == int.class ) { try { result.put((Integer) field.get(null), field.getName()); } catch (Exception e) { assert false : e.getMessage(); Platform.get().log("Error reading error code %s", field, e); } } } return result; }
Source:
<code>protected boolean checkDisksNotInBackupStorage() { <START> Disk disk = getVm().getDiskMap() .values() .stream() .filter(vmDisk -> vmDisk.getDiskStorageType() == DiskStorageType.IMAGE && storageDomainStaticDao.get(((DiskImage) vmDisk).getStorageIds().get(0)).isBackup()) .findFirst() .orElse(null); if (disk != null) { return false; } return true; <END> }</code><technical_language>I this a bit simplified: return getVm().getDiskMap() .values() .stream() .map(disk -> (DiskImage)disk) .anyMatch(vmDisk -> vmDisk.getDiskStorageType() == DiskStorageType.IMAGE && storageDomainStaticDao.get(vmDisk.getStorageIds().get(0)).isBackup());</technical_language>

Target:
protected boolean checkDisksNotInBackupStorage() { return getVm().getDiskMap() .values() .stream() .map(disk -> (DiskImage) disk) .anyMatch(vmDisk -> vmDisk.getDiskStorageType() == DiskStorageType.IMAGE && storageDomainStaticDao.get(vmDisk.getStorageIds().get(0)).isBackup()); }
Source:
<code>public boolean canMatchTrace(ITmfTrace trace) { if (!(trace instanceof CtfTmfTrace)) { return false; } CtfTmfTrace ktrace = (CtfTmfTrace) trace; <START> Set<String> events = ImmutableSet.of( TcpEventStrings.INET_SOCK_LOCAL_IN, TcpEventStrings.INET_SOCK_LOCAL_OUT ); <END> Set<String> traceEvents = TmfEventTypeCollectionHelper.getEventNames(ktrace.getEventTypes()); traceEvents.retainAll(events); return !traceEvents.isEmpty(); }</code><technical_language>This immutableSet defined statically, instead of recreating a new Set time this method is called</technical_language>

Target:
public boolean canMatchTrace(ITmfTrace trace) { if (!(trace instanceof CtfTmfTrace)) { return false; } CtfTmfTrace ktrace = (CtfTmfTrace) trace; Set<String> traceEvents = TmfEventTypeCollectionHelper.getEventNames(ktrace.getContainedEventTypes()); traceEvents.retainAll(REQUIRED_EVENTS); return !traceEvents.isEmpty(); }
Source:
<code>private void processPenaltyCodes(Settings s) { PenaltyCodesManager pm = new PenaltyCodesManager(s); <START> updateMap.put("ScoreBoard.PenaltyCode", null); <END> try { PenaltyCodesDefinition penalties = pm.loadFromJSON(); for(PenaltyCode p : penalties.getPenalties()) { updateMap.put("ScoreBoard.PenaltyCode."+p.getCode(), p.CuesForWS(p)); } updateMap.put("ScoreBoard.PenaltyCode.?","Unknown"); updateMap.put("ScoreBoard.PenaltyCode.FO", "Foul-Out"); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>I clear a subtree this give entries in go, updateMap processes in order maps unordered</technical_language>

Target:
private void processPenaltyCodes(Settings s) { PenaltyCodesManager pm = new PenaltyCodesManager(s); updates.add(new WSUpdate("ScoreBoard.PenaltyCode", null)); try { PenaltyCodesDefinition penalties = pm.loadFromJSON(); for(PenaltyCode p : penalties.getPenalties()) { updates.add(new WSUpdate("ScoreBoard.PenaltyCode."+p.getCode(), p.CuesForWS(p))); } updates.add(new WSUpdate("ScoreBoard.PenaltyCode.?","Unknown")); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void testCookieForStateFullClientForAnonUser() throws HttpException, IOException { GlobalConfigurationResource settings = SettingsMessageUtil.getCurrentSettings(); settings.setSecurityAnonymousAccessEnabled( true ); SettingsMessageUtil.save( settings ); TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod( url ); Assert.assertEquals( httpClient.executeMethod( getMethod ), 200 ); getMethod.releaseConnection(); Cookie sessionCookie = this.getSessionCookie( httpClient.getState().getCookies() ); Assert.assertNotNull( sessionCookie, "Session Cookie not set" ); httpClient.getState().clear(); httpClient.getState().addCookie( sessionCookie ); getMethod = new GetMethod( url ); <START> Assert.assertEquals( httpClient.executeMethod( getMethod ), 200 ); <END> getMethod.releaseConnection(); }</code><technical_language>this assert, is call (username password unused). do cookie is recreated? is tested here? Needs more doc IMO</technical_language>

Target:
public void testCookieForStateFullClientForAnonUser() throws HttpException, IOException { GlobalConfigurationResource settings = SettingsMessageUtil.getCurrentSettings(); settings.setSecurityAnonymousAccessEnabled( true ); SettingsMessageUtil.save( settings ); TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod( url ); Assert.assertEquals( executeAndRelease( httpClient, getMethod ), 200 ); Cookie sessionCookie = this.getSessionCookie( httpClient.getState().getCookies() ); Assert.assertNotNull( sessionCookie, "Session Cookie not set" ); httpClient.getState().clear(); httpClient.getState().addCookie( sessionCookie ); getMethod = new GetMethod( url ); Assert.assertEquals( executeAndRelease( httpClient, getMethod ), 200 ); }
Source:
<code>public Property getProperty(String propertyName) { Property property; for (int i = 0, icount = propertyArray.length; i < icount; i++) { property = propertyArray[i]; final Name name = property.getName(); <START> if (name!=null && name.getLocalPart().equalsIgnoreCase(propertyName)) return property; <END> } return null; }</code><technical_language>this is pretty loose matching for xpath - case sensitive</technical_language>

Target:
public Property getProperty(String propertyName) { int propertyIndex = index.get(propertyName); return propertyIndex != -1 ? propertyArray[propertyIndex] : null; }
Source:
<code>public int compare(T divisionOne, T divisionTwo) { String divisionNameOne = getName(divisionOne); String divisionNameTwo = getName(divisionTwo); int romanNumberOne = getNumber(divisionNameOne); int romanNumberTwo = getNumber(divisionNameTwo); if (romanNumberOne == 0 && romanNumberTwo == 0) { return Collator.getInstance(WebappConst.LOCALE_PL).compare(divisionNameOne, divisionNameTwo); } else { <START> return (romanNumberOne - romanNumberTwo); <END> } }</code><technical_language>com.google.common.primitives.Ints#compare(romanNumberOne, romanNumberTwo)</technical_language>

Target:
public int compare(T divisionOne, T divisionTwo) { String divisionNameOne = getName(divisionOne); String divisionNameTwo = getName(divisionTwo); int romanNumberOne = getNumber(divisionNameOne); int romanNumberTwo = getNumber(divisionNameTwo); if (romanNumberOne == 0 && romanNumberTwo == 0) { return Collator.getInstance(WebappConst.LOCALE_PL).compare(divisionNameOne, divisionNameTwo); } else { return Ints.compare(romanNumberOne, romanNumberTwo); } }
Source:
<code>public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { clearClientTrackedAtReconnectComplete(); if (message instanceof EhcacheOperationMessage) { EhcacheOperationMessage operationMessage = (EhcacheOperationMessage) message; EhcacheMessageType messageType = operationMessage.getMessageType(); if (isLifecycleMessage(messageType)) { return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); <START> } else if (isPassiveReplicationMessage(messageType)) { <END> return responseFactory.success(); } } throw new AssertionError("Unsupported message : " + message.getClass()); } catch (ClusterException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(new InvalidOperationException(e)); } }</code><technical_language>I guess EhcacheActiveEntity PassiveReplicationMessage execution strategy prohibits that, right</technical_language>

Target:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { clearClientTrackedAtReconnectComplete(); if (message instanceof EhcacheOperationMessage) { EhcacheOperationMessage operationMessage = (EhcacheOperationMessage) message; EhcacheMessageType messageType = operationMessage.getMessageType(); if (isLifecycleMessage(messageType)) { return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); } } throw new AssertionError("Unsupported message : " + message.getClass()); } catch (ClusterException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(new InvalidOperationException(e)); } }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } <START> if (o == null || getClass() != o.getClass()) { <END> return false; } PredicateInfo that = (PredicateInfo) o; return Objects.equals(_stringVal, that._stringVal) && Objects.equals(_column, that._column) && Objects .equals(_predicate, that._predicate) && Objects.equals(_predicateEvaluator, that._predicateEvaluator); }</code><technical_language>suggestion if (o instanceof PredicateEvaluator) {</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PredicateInfo)) { return false; } PredicateInfo that = (PredicateInfo) o; return Objects.equals(_stringVal, that._stringVal) && Objects.equals(_column, that._column) && Objects .equals(_predicate, that._predicate); }
Source:
<code>public void run() { running = true; while (running) { FrameWrapper frame; try { frame = workQueue.take(); } catch (InterruptedException e) { continue; } long duration = System.currentTimeMillis() - frame.getTimestamp(); if (duration > getHighWatermark()) { <START> LOGGER.warning("frame spend " + duration + "ms in the transport buffer, your consumer might be backed up"); <END> } try { registry.execute(frame.getFrameBytes()); } catch (TException e) { LOGGER.severe("closing transport due to unrecoverable error processing frame: " + e.getMessage()); close(e); return; } } }</code><technical_language>s/spend/spent</technical_language>

Target:
public void run() { running = true; while (running) { FrameWrapper frame; try { frame = workQueue.take(); } catch (InterruptedException e) { continue; } long duration = System.currentTimeMillis() - frame.getTimestamp(); if (duration > getHighWatermark()) { LOGGER.warning("frame spent " + duration + "ms in the transport buffer, your consumer might be backed up"); } try { registry.execute(frame.getFrameBytes()); } catch (TException e) { LOGGER.severe("closing transport due to unrecoverable error processing frame: " + e.getMessage()); close(e); return; } } }
Source:
<code>private void markChangeMergedByPush(ReviewDb db, final ReplaceRequest result) throws OrmException, IOException { Change.Id id = result.change.getId(); db.changes().beginTransaction(id); Change change; try { change = db.changes().atomicUpdate(id, new AtomicUpdate<Change>() { @Override public Change update(Change change) { if (change.getStatus().isOpen()) { change.setCurrentPatchSet(result.info); change.setStatus(Change.Status.MERGED); ChangeUtil.updated(change); } return change; } }); String mergedIntoRef = result.mergedIntoRef; StringBuilder msgBuf = new StringBuilder(); msgBuf.append("Change has been successfully pushed"); if (!mergedIntoRef.equals(change.getDest().get())) { msgBuf.append(" into "); if (mergedIntoRef.startsWith(Constants.R_HEADS)) { msgBuf.append("branch "); msgBuf.append(Repository.shortenRefName(mergedIntoRef)); } else { msgBuf.append(mergedIntoRef); } } msgBuf.append("."); ChangeMessage msg = new ChangeMessage( new ChangeMessage.Key(id, ChangeUtil.messageUUID(db)), currentUser.getAccountId(), change.getLastUpdatedOn(), result.info.getKey()); msg.setMessage(msgBuf.toString()); <START> db.changeMessages().insert(Collections.singleton(msg)); <END> } finally { db.rollback(); } indexer.index(db, change); }</code><technical_language>missing db.commit();</technical_language>

Target:
private void markChangeMergedByPush(ReviewDb db, final ReplaceRequest result) throws OrmException, IOException { Change.Id id = result.change.getId(); db.changes().beginTransaction(id); Change change; try { change = db.changes().atomicUpdate(id, new AtomicUpdate<Change>() { @Override public Change update(Change change) { if (change.getStatus().isOpen()) { change.setCurrentPatchSet(result.info); change.setStatus(Change.Status.MERGED); ChangeUtil.updated(change); } return change; } }); String mergedIntoRef = result.mergedIntoRef; StringBuilder msgBuf = new StringBuilder(); msgBuf.append("Change has been successfully pushed"); if (!mergedIntoRef.equals(change.getDest().get())) { msgBuf.append(" into "); if (mergedIntoRef.startsWith(Constants.R_HEADS)) { msgBuf.append("branch "); msgBuf.append(Repository.shortenRefName(mergedIntoRef)); } else { msgBuf.append(mergedIntoRef); } } msgBuf.append("."); ChangeMessage msg = new ChangeMessage( new ChangeMessage.Key(id, ChangeUtil.messageUUID(db)), currentUser.getAccountId(), change.getLastUpdatedOn(), result.info.getKey()); msg.setMessage(msgBuf.toString()); db.changeMessages().insert(Collections.singleton(msg)); db.commit(); } finally { db.rollback(); } indexer.index(db, change); }
Source:
<code>public void testExecutorsParallel() throws Exception { CompactConfig config = new CompactConfig(null, INPUT_DIR, OUTPUT_DIR, "test", 100); List<URIStatus> inputFiles = new ArrayList<>(); <START> for (int i = 0; i < 50; i++) { <END> inputFiles.add(newFile(Integer.toString(i))); } when(mMockFileSystem.listStatus(new AlluxioURI(INPUT_DIR))).thenReturn(inputFiles); Set<Pair<WorkerInfo, ArrayList<CompactTask>>> result = new CompactDefinition().selectExecutors( config, SelectExecutorsTest.JOB_WORKERS, new SelectExecutorsContext(1, new JobServerContext(mMockFileSystem, mMockFileSystemContext, mMockUfsManager))); assertEquals(40, result.size()); int allCompactTasks = 0; for (Pair<WorkerInfo, ArrayList<CompactTask>> tasks : result) { allCompactTasks += tasks.getSecond().size(); } assertEquals(50, allCompactTasks); }</code><technical_language>NIT: this a local variable numFiles, here, end of test verify</technical_language>

Target:
public void testExecutorsParallel() throws Exception { int tasksPerWorker = 10; int numCompactedFiles = 100; int totalFiles = 5000; CompactConfig config = new CompactConfig(null, INPUT_DIR, OUTPUT_DIR, "test", numCompactedFiles); List<URIStatus> inputFiles = new ArrayList<>(); for (int i = 0; i < totalFiles; i++) { inputFiles.add(newFile(Integer.toString(i))); } when(mMockFileSystem.listStatus(new AlluxioURI(INPUT_DIR))).thenReturn(inputFiles); Set<Pair<WorkerInfo, ArrayList<CompactTask>>> result = new CompactDefinition().selectExecutors( config, SelectExecutorsTest.JOB_WORKERS, new SelectExecutorsContext(1, new JobServerContext(mMockFileSystem, mMockFileSystemContext, mMockUfsManager))); assertEquals(JOB_WORKERS.size() * tasksPerWorker, result.size()); int allCompactTasks = 0; for (Pair<WorkerInfo, ArrayList<CompactTask>> tasks : result) { allCompactTasks += tasks.getSecond().size(); } assertEquals(numCompactedFiles, allCompactTasks); }
Source:
<code>public void notifySurfaceDetached() { super.notifySurfaceDetached(); <START> if (mImageReaderToReleaseList.size() > 0) { <END> for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { imageReader.close(); } mImageReaderToReleaseList.clear(); } }</code><technical_language>assume notifySurfaceDetached happens, surface is totally detached. I name is confusing, surface attached more 1 time. means 1 notifySurfaceDetached call. correct check detach event is setOnSurfaceDetachListener</technical_language>

Target:
public void notifySurfaceDetached() { super.notifySurfaceDetached(); if (mImageReaderToReleaseList.size() > 0) { for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } }
Source:
<code>public HumanReadableDuration leaderAddressCacheTtl() { <START> return HumanReadableDuration.seconds(15); <END> }</code><technical_language>Do need this configurable</technical_language>

Target:
public Duration leaderAddressCacheTtl() { return Duration.ofSeconds(15); }
Source:
<code>private boolean isVisibleTo(Change change, IdentifiedUser user) { <START> final ProjectState pe = projectCache.get(change.getProject()); <END> final ProjectControl pc = pe.controlFor(user); final RefControl rc = pc.controlForRef(change.getDest().get()); return rc.isVisible(); }</code><technical_language>This return null if project suddenly disappear. I guard testing for null skipping rest of method: if (pe == null) { return false; }</technical_language>

Target:
private boolean isVisibleTo(Change change, IdentifiedUser user) { final ProjectState pe = projectCache.get(change.getProject()); if (pe == null) { return false; } final ProjectControl pc = pe.controlFor(user); return pc.controlFor(change).isVisible(); }
Source:
<code>public boolean supports(Class c) { <START> return c.equals(RelationshipType.class); <END> }</code><technical_language>RelationshipType.class.isAssignableFrom(c) subclasses get validated</technical_language>

Target:
public boolean supports(Class c) { return RelationshipType.class.isAssignableFrom(c); }
Source:
<code><START> private void updateExportDialogAutoScaleSettings(boolean value) { IDialogSettings settings = getExportDialogSettings(); settings.put(AbstractExportRepresentationsAsImagesDialog.AUTO_SCALE_SETTING_PROPERTY, value); } <END></code><technical_language>Is needed autoScale is displayed in dialog</technical_language>

Target:
private void updateExportDialogAutoScaleSettings(boolean value) { IDialogSettings settings = getExportDialogSettings(); settings.put(AbstractExportRepresentationsAsImagesDialog.AUTO_SCALE_SETTING_PROPERTY, value); if (value) { settings.put(AbstractExportRepresentationsAsImagesDialog.SCALE_LEVEL_SETTING_PROPERTY, 100); } else { settings.put(AbstractExportRepresentationsAsImagesDialog.SCALE_LEVEL_SETTING_PROPERTY, 0); } }
Source:
<code>protected void verifyQuery(AbstractStatisticalQuery<Host, VDS> query, VDS entity) throws Exception { assertEquals(Host.class, query.getParentType()); assertSame(entity, query.resolve(GUIDS[0])); List<Statistic> statistics = query.getStatistics(entity); verifyStatistics(statistics, new String[] {"memory.total", "memory.used", "memory.free", "memory.shared", "memory.buffers", "memory.cached", "swap.total", "swap.free", "swap.used", "swap.cached", "ksm.cpu.current", "cpu.current.user", "cpu.current.system", <START> "cpu.current.idle", "cpu.load.avg.5m", "time.boot"}, <END> new BigDecimal[] {asDec(5120*Mb), asDec(1024*Mb), asDec(4096*Mb), asDec(38*Mb), asDec(0), asDec(0), asDec(30*Mb), asDec(25*Mb), asDec(5*Mb), asDec(0), asDec(40), asDec(45), asDec(50), asDec(55), new BigDecimal(0.0060, new MathContext(2)), asDec(0)}); Statistic adopted = query.adopt(new Statistic()); assertTrue(adopted.isSetHost()); assertEquals(GUIDS[0].toString(), adopted.getHost().getId()); }</code><technical_language>Remember change "boot.time" well</technical_language>

Target:
protected void verifyQuery(AbstractStatisticalQuery<Host, VDS> query, VDS entity) throws Exception { assertEquals(Host.class, query.getParentType()); assertSame(entity, query.resolve(GUIDS[0])); List<Statistic> statistics = query.getStatistics(entity); verifyStatistics(statistics, new String[] {"memory.total", "memory.used", "memory.free", "memory.shared", "memory.buffers", "memory.cached", "swap.total", "swap.free", "swap.used", "swap.cached", "ksm.cpu.current", "cpu.current.user", "cpu.current.system", "cpu.current.idle", "cpu.load.avg.5m", "boot.time"}, new BigDecimal[] {asDec(5120*Mb), asDec(1024*Mb), asDec(4096*Mb), asDec(38*Mb), asDec(0), asDec(0), asDec(30*Mb), asDec(25*Mb), asDec(5*Mb), asDec(0), asDec(40), asDec(45), asDec(50), asDec(55), new BigDecimal(0.0060, new MathContext(2)), asDec(0)}); Statistic adopted = query.adopt(new Statistic()); assertTrue(adopted.isSetHost()); assertEquals(GUIDS[0].toString(), adopted.getHost().getId()); }
Source:
<code>private void insertInput() throws IOException, JAXBException { try (FileWriter fw = new FileWriter(Paths.get(target, "input.js").toFile()); BufferedWriter jsfile = new BufferedWriter(fw);) { jsfile.write("var input = "); JSONExporter.writeObjectAsJSON(model, jsfile); jsfile.write(";"); } catch (IOException e) { throw e; } catch (JAXBException e) { throw e; <START> } <END> }</code><technical_language>catches necessary</technical_language>

Target:
private void insertInput() throws IOException, JAXBException { try (FileWriter fw = new FileWriter(Paths.get(target, GENERATED_FILE).toFile()); BufferedWriter jsfile = new BufferedWriter(fw);) { jsfile.write(GENERATED_FILE_HEAD); JSONExporter.writeObjectAsJSON(model, jsfile); jsfile.write(GENERATED_FILE_TAIL); } }
Source:
<code>public void testInputScreenOnOff() throws Exception{ JadbDevice any = jadb.getAnyDevice(); KeyEvent.Builder keyEventBuilder = new KeyEvent.Builder(any); keyEventBuilder.addKey(KeyEvent.KEYCODE_POWER).build().execute(); <START> } <END></code><technical_language>easier if interface java KeyManager keys = new KeyManager(any); keys.press(Keys.KEYCODE_POWER);</technical_language>

Target:
public void testInputScreenOnOff() throws Exception{ JadbDevice any = jadb.getAnyDevice(); InputManager inputManager = new InputManager(any); inputManager.sendEvent(KeyEvent.press(KeyCode.KEYCODE_POWER)); }
Source:
<code><START> public <T> List<T> eval(BranchContext context, ValidationRule rule, Map<String, Object> filterParams) throws Exception { <END> final String script = Files .lines(validationResourcesDirectory.resolve(rule.getImplementation())) .collect(Collectors.joining(System.getProperty("line.separator"))); final Builder<String, Object> paramsBuilder = ImmutableMap.<String, Object>builder().put("resourcesDir", validationResourcesDirectory); if (filterParams != null && !filterParams.isEmpty()) { paramsBuilder.putAll(filterParams); } return ScriptEngine.run("groovy", context.service(ClassLoader.class), script, ImmutableMap.<String, Object>of( "ctx", context, "params", paramsBuilder.build() ) ); }</code><technical_language>wildcard ? well</technical_language>

Target:
public List<?> eval(BranchContext context, ValidationRule rule, Map<String, Object> filterParams) throws Exception { final String script = Files .lines(validationResourcesDirectory.resolve(rule.getImplementation())) .collect(Collectors.joining(System.getProperty("line.separator"))); final Builder<String, Object> paramsBuilder = ImmutableMap.<String, Object>builder().put("resourcesDir", validationResourcesDirectory); if (filterParams != null && !filterParams.isEmpty()) { paramsBuilder.putAll(filterParams); } return ScriptEngine.run("groovy", context.service(ClassLoader.class), script, ImmutableMap.<String, Object>of( "ctx", context, "params", paramsBuilder.build() ) ); }
Source:
<code>public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); log.debug("value complex: " + obs.getValueComplex()); log.debug("file path: " + file.getAbsolutePath()); ComplexData complexData = null; if (ComplexObsHandler.TEXT_VIEW.equals(view) || ComplexObsHandler.RAW_VIEW.equals(view)) { String[] names = obs.getValueComplex().split("\\|"); String originalFilename = names[0]; originalFilename = originalFilename.replaceAll(",", "").replaceAll(" ", "").replaceAll("file$", ""); try { complexData = ComplexObsHandler.RAW_VIEW.equals(view) ? new ComplexData(originalFilename, OpenmrsUtil .getFileAsBytes(file)) : new ComplexData(originalFilename, OpenmrsUtil.getFileAsString(file)); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } } else if (ComplexObsHandler.URI_VIEW.equals(view)) { complexData = new ComplexData(file.getName(), file.getPath()); } else { return null; } Assert.notNull(complexData, "Complex data must not be null"); String mimeType = getMimeTypeFromFile(file); <START> mimeType = mimeType != null ? mimeType : "application/octet-stream"; <END> complexData.setMimeType(mimeType); obs.setComplexData(complexData); return obs; }</code><technical_language>Of "application/octet-stream" "text/plain", is more for this class</technical_language>

Target:
public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); log.debug("value complex: " + obs.getValueComplex()); log.debug("file path: " + file.getAbsolutePath()); ComplexData complexData = null; if (ComplexObsHandler.TEXT_VIEW.equals(view) || ComplexObsHandler.RAW_VIEW.equals(view)) { String[] names = obs.getValueComplex().split("\\|"); String originalFilename = names[0]; originalFilename = originalFilename.replaceAll(",", "").replaceAll(" ", "").replaceAll("file$", ""); try { complexData = ComplexObsHandler.RAW_VIEW.equals(view) ? new ComplexData(originalFilename, OpenmrsUtil .getFileAsBytes(file)) : new ComplexData(originalFilename, OpenmrsUtil.getFileAsString(file)); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } } else if (ComplexObsHandler.URI_VIEW.equals(view)) { complexData = new ComplexData(file.getName(), file.getPath()); } else { return null; } Assert.notNull(complexData, "Complex data must not be null"); String mimeType = OpenmrsUtil.getFileMimeType(file); mimeType = !(mimeType.equals("application/octet-stream")) ? mimeType : "text/plain"; complexData.setMimeType(mimeType); obs.setComplexData(complexData); return obs; }
Source:
<code>public Picasso build() { Context context = this.context; if (downloader == null) { <START> downloader = Utils.createDefaultLoader(context); <END> } if (memoryCache == null) { memoryCache = new LruCache(context); } if (service == null) { service = Executors.newFixedThreadPool(3, new Utils.PicassoThreadFactory()); } Stats stats = new Stats(memoryCache); return new Picasso(context, downloader, service, memoryCache, listener, stats); }</code><technical_language>createDefaultDownloader</technical_language>

Target:
public Picasso build() { Context context = this.context; if (downloader == null) { downloader = Utils.createDefaultDownloader(context); } if (memoryCache == null) { memoryCache = new LruCache(context); } if (service == null) { service = Executors.newFixedThreadPool(3, new Utils.PicassoThreadFactory()); } Stats stats = new Stats(memoryCache); return new Picasso(context, downloader, service, memoryCache, listener, stats); }
Source:
<code>public void setPageTitle(@NonNull PageTitle pageTitle) { this.pageTitle = pageTitle; originalDescription = pageTitle.getDescription(); setHintText(); <START> if (invokeSource != SUGGESTED_EDITS_ADD_CAPTION && invokeSource != SUGGESTED_EDITS_TRANSLATE_CAPTION) { <END> setDescription(originalDescription); } setReviewHeaderText(false); }</code><technical_language>If a user added Suggested edits flow, this break current logic of showing "added" caption</technical_language>

Target:
public void setPageTitle(@NonNull PageTitle pageTitle) { this.pageTitle = pageTitle; originalDescription = pageTitle.getDescription(); setHintText(); setDescription(originalDescription); setReviewHeaderText(false); }
Source:
<code>public static IndexingParameters parseText(IndexingParameters parameters, Charset encoding) { <START> Objects.requireNonNull(encoding, "'Encoding' cannot be null"); <END> configure(parameters, PARSING_MODE_KEY, "text"); configure(parameters, "encoding", encoding.name()); return parameters; }</code><technical_language>suggestion Objects.requireNonNull(encoding, "'encoding' null.");</technical_language>

Target:
public static IndexingParameters parseText(IndexingParameters parameters, Charset encoding) { Objects.requireNonNull(encoding, "'encoding' cannot be null."); configure(parameters, PARSING_MODE_KEY, "text"); configure(parameters, "encoding", encoding.name()); return parameters; }
Source:
<code>public void showNotifications() { this.waitForNotificationsLoaded(); executeScript("$('#WallNotifications li ul.subnav').addClass('show');$('#WallNotifications').mouseover();"); <START> builder.moveToElement(notifications).build().perform(); <END> waitForElementVisibleByElement(notificationsSubnav); PageObjectLogging.log("#WallNotifications li ul.subnav", "show notifications", true, driver); waitForElementPresenceByBy(By.cssSelector("#WallNotifications .subnav li.notifications-for-wiki:nth-child(2)")); waitForElementNotPresent("#WallNotifications .subnav li.notifications-for-wiki:nth-child(2) li.notifications-empty"); }</code><technical_language>is necessary add class move mouse? line 51 52</technical_language>

Target:
public void showNotifications() { waitForNotificationsLoaded(); openNotifications(); waitForNotificationsMessagesToLoad(); PageObjectLogging.log("#WallNotifications li ul.subnav", "show notifications", true, driver); }
Source:
<code>private void createServices() { <START> runWithCompose("up -d " + String.join(" ", this.services)); <END> }</code><technical_language>In case of services empty list, run command "up -d ". _I know_ for Docker Compose this is functionally identical starts services. However, explicit in code, do if/else check this, concatenate services list "up -d" if necessary? fine string duplicated in code. notice a hypocrite explicitness of code, original -d is clear . If mind changing -d --detach while editing code, another improvement</technical_language>

Target:
private void createServices() { if(services.isEmpty()) { runWithCompose("up -d"); } else { runWithCompose("up -d " + String.join(" ", services)); } }
Source:
<code>public boolean handleKey(char c, int i) { <START> return this.inputField.textboxKeyTyped(c,i); <END> }</code><technical_language>Formatting</technical_language>

Target:
public boolean handleKey(char c, int i) { if (GuiScreen.isKeyComboCtrlC(i) && (getSelectedText().isEmpty())) GuiScreen.setClipboardString(this.getText()); return textboxKeyTyped(c, i); }
Source:
<code>protected Object setSkipRemoteGetsAndInvokeNextForDataCommand(InvocationContext ctx, DataWriteCommand command, CompletionStage<Void> delay) { <START> if (!CompletionStages.isCompletedSuccessfully(delay)) { <END> return asyncValue(delay).thenApply(ctx, command, (rCtx, rCommand, rValue) -> invokeNextAndExceptionally(ctx, command, handleManyWriteReturn)); } return invokeNextAndExceptionally(ctx, command, handleDataWriteReturn); }</code><technical_language>BiasedEntryWrappingInterceptor is checking if delay == null. Is missing here</technical_language>

Target:
protected Object setSkipRemoteGetsAndInvokeNextForDataCommand(InvocationContext ctx, DataWriteCommand command, CompletionStage<Void> delay) { return makeStage(asyncInvokeNext(ctx, command, delay)).andExceptionally(ctx, command, handleDataWriteReturn); }