auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void applyRightFloor(final PatchSetApproval a) { final IdentifiedUser user = userFactory.create(a.getAccountId()); short projectMinAllowed = 0, projectMaxAllowed = 0; for (final ProjectRight r : getAllProjectRights(a.getCategoryId())) { final AccountGroup.Id grp = r.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { projectMinAllowed = (short) Math.min(projectMinAllowed, r.getMinValue()); projectMaxAllowed = (short) Math.max(projectMaxAllowed, r.getMaxValue()); } } short refMinAllowed = 0, refMaxAllowed = 0; String destRef = change.getDest().get(); for (final RefRight refRight : getRefRights(a.getCategoryId())) { if (RefControl.matches(destRef, refRight.getRefPattern())) { final AccountGroup.Id grp = refRight.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { refMinAllowed = (short) Math.min(refMinAllowed, refRight.getMinValue()); refMaxAllowed = (short) Math.max(refMaxAllowed, refRight.getMaxValue()); } } } short minAllowed = (short) Math.max(refMinAllowed, projectMinAllowed); short maxAllowed = (short) Math.min(refMaxAllowed, projectMaxAllowed); if (a.getValue() < minAllowed) { a.setValue(minAllowed); dirty(a); } else if (a.getValue() > maxAllowed) { a.setValue(maxAllowed); dirty(a); } }

Target:
public void applyRightFloor(final PatchSetApproval a) { final IdentifiedUser user = userFactory.create(a.getAccountId()); short refMinAllowed = 0, refMaxAllowed = 0; boolean foundRefRight = false; for (final RefRight refRight : getRefRights(a.getCategoryId())) { final AccountGroup.Id grp = refRight.getAccountGroupId(); foundRefRight = true; if (user.getEffectiveGroups().contains(grp)) { refMinAllowed = (short) Math.min(refMinAllowed, refRight.getMinValue()); refMaxAllowed = (short) Math.max(refMaxAllowed, refRight.getMaxValue()); } } short projectMinAllowed = 0, projectMaxAllowed = 0; for (final ProjectRight r : getAllProjectRights(a.getCategoryId())) { final AccountGroup.Id grp = r.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { projectMinAllowed = (short) Math.min(projectMinAllowed, r.getMinValue()); projectMaxAllowed = (short) Math.max(projectMaxAllowed, r.getMaxValue()); } } short minAllowed; short maxAllowed; if (foundRefRight) { minAllowed = refMinAllowed; maxAllowed = refMaxAllowed; } else { minAllowed = projectMinAllowed; maxAllowed = projectMaxAllowed; } if (a.getValue() < minAllowed) { a.setValue(minAllowed); dirty(a); } else if (a.getValue() > maxAllowed) { a.setValue(maxAllowed); dirty(a); } }
Source:
private void buildPlusOrAssignmentInvocation(BlockBuilder blockBuilder, IdentifierGenerator idGenerator, Tree element) { boolean elementIsString = isString(((ExpressionTree) element).symbolType()); if (element.is(PLUS) && elementIsString) { BinaryExpressionTree binaryExpressionTree = (BinaryExpressionTree) element; Expression lhs = idGenerator.lookupExpressionFor(binaryExpressionTree.leftOperand()); Expression rhs = idGenerator.lookupExpressionFor(binaryExpressionTree.rightOperand()); Expression.Variable var = variableWithId(idGenerator.newIdFor(binaryExpressionTree)); blockBuilder.assignTo(var, call("__concat").withArgs(lhs, rhs), location(element)); } else if (element.is(PLUS_ASSIGNMENT) && elementIsString) { Expression var = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).variable()); Expression expr = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).expression()); if (!var.isConstant()) { idGenerator.varForExpression(element, ((Expression.Variable) var).id()); blockBuilder.assignTo((Expression.Variable) var, call("__concat").withArgs(var, expr), location(element)); } } else if (element.is(ASSIGNMENT)) { Expression var = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).variable()); Expression expr = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).expression()); if (!var.isConstant()) { blockBuilder.assignTo((Expression.Variable) var, call("__id").withArgs(expr), location(element)); } } }

Target:
private void buildPlusOrAssignmentInvocation(BlockBuilder blockBuilder, IdentifierGenerator idGenerator, Tree element) { boolean elementIsString = (((ExpressionTree) element).symbolType()).is("java.lang.String"); if (element.is(PLUS) && elementIsString) { BinaryExpressionTree binaryExpressionTree = (BinaryExpressionTree) element; Expression lhs = idGenerator.lookupExpressionFor(binaryExpressionTree.leftOperand()); Expression rhs = idGenerator.lookupExpressionFor(binaryExpressionTree.rightOperand()); Expression.Variable var = variableWithId(idGenerator.newIdFor(binaryExpressionTree)); blockBuilder.assignTo(var, call("__concat").withArgs(lhs, rhs), location(element)); } else if (element.is(PLUS_ASSIGNMENT) && elementIsString) { Expression var = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).variable()); Expression expr = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).expression()); if (var instanceof Expression.Variable) { idGenerator.varForExpression(element, ((Expression.Variable) var).id()); blockBuilder.assignTo((Expression.Variable) var, call("__concat").withArgs(var, expr), location(element)); } } else if (element.is(ASSIGNMENT)) { Expression var = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).variable()); Expression expr = idGenerator.lookupExpressionFor(((AssignmentExpressionTree) element).expression()); if (var instanceof Expression.Variable) { blockBuilder.assignTo((Expression.Variable) var, call("__id").withArgs(expr), location(element)); } } }
Source:
public String getDirectoryPath(String path) throws ScriptException { if (path.startsWith("file://")) { return new JavaScriptFileManagerImpl().getFile(path).getAbsolutePath(); } String oldPath = path; path = FilenameUtils.normalizeNoEndSeparator(path); if (path == null) { String msg = "Invalid file path : " + oldPath; log.error(msg); throw new ScriptException(msg); } File file = new File(context.getRealPath("/"), path); return file.getPath(); }

Target:
public String getDirectoryPath(String path) throws ScriptException { if (path.startsWith(FILE_PATH)) { return new JavaScriptFileManagerImpl().getFile(path).getAbsolutePath(); } String oldPath = path; path = FilenameUtils.normalizeNoEndSeparator(path); if (path == null) { String msg = "Invalid file path : " + oldPath; log.error(msg); throw new ScriptException(msg); } File file = new File(context.getRealPath("/"), path); return file.getPath(); }
Source:
public void consume(String message) { logger.info("[UmpAmountTransfer] receive message: {}: {}.", this.queue(), message); try { UmpAmountTransferMessage amountTransferMessage = gson.fromJson(message, new TypeToken<UmpAmountTransferMessage>(){}.getType()); umpAmountTransferService.process(amountTransferMessage); logger.info("[UmpAmountTransfer] receive message: {}: done.", this.queue(), message); } catch (Exception e) { logger.error(MessageFormat.format("[MQ] amount transfer consumer fail, message:{0}", message), e); } }

Target:
public void consume(String message) { logger.info("[UmpAmountTransfer] receive message: {}: {}.", this.queue(), message); try { List<UmpAmountTransferMessage> messages = gson.fromJson(message, new TypeToken<List<UmpAmountTransferMessage>>(){}.getType()); umpAmountTransferService.process(messages); logger.info("[UmpAmountTransfer] receive message: {}: done.", this.queue(), message); } catch (Exception e) { logger.error(MessageFormat.format("[MQ] amount transfer consumer fail, message:{0}", message), e); } }
Source:
public void test01_03_redirectToExternalLink() { if (!(driver instanceof FirefoxDriver)) { logger.warn(testName.getMethodName() + " is not support excepting Firefox."); return; } ApServerName apServerName = webDriverOperations.getApServerName(); driver.findElement(By.id("listWithExternalPath")).click(); driver.findElement(By.id("btn1")).click(); inputFieldAccessor.overrideValue(By.id("username"), "user1", driver); inputFieldAccessor.overrideValue(By.id("password"), "user1", driver); assertThat(getRedirectValue(), is( "<LINK_1>")); screenCapture.save(driver); driver.findElement(By.id("btn1")).click(); assertTrue(driver.getCurrentUrl().contains( "/terasoluna-gfw-functionaltest-web")); String expectedMessage; if (apServerName == ApServerName.TOMCAT) { expectedMessage = "Redirect"; } else { expectedMessage = "Welcome!"; } assertThat(driver.findElement(By.xpath("/html/body/div/h2")).getText(), is(expectedMessage)); driver.get(getPackageRootUrl()); driver.findElement(By.id("listWithExternalPathWithContextPath")) .click(); driver.findElement(By.id("btn1")).click(); inputFieldAccessor.overrideValue(By.id("username"), "user1", driver); inputFieldAccessor.overrideValue(By.id("password"), "user1", driver); assertThat(getRedirectValue(), is( "<LINK_0>")); screenCapture.save(driver); driver.findElement(By.id("btn1")).click(); assertTrue(driver.getCurrentUrl().contains( "/terasoluna-gfw-functionaltest-web")); assertThat(driver.findElement(By.xpath("/html/body/div/h2")).getText(), is("Redirect (externalPathWithContextPath)")); }

Target:
public void test01_03_redirectToExternalLink() { ApServerName apServerName = webDriverOperations.getApServerName(); driver.findElement(By.id("listWithExternalPath")).click(); driver.findElement(By.id("btn1")).click(); inputFieldAccessor.overrideValue(By.id("username"), "user1", driver); inputFieldAccessor.overrideValue(By.id("password"), "user1", driver); assertThat(getRedirectValue(), is( "<LINK_1>")); screenCapture.save(driver); driver.findElement(By.id("btn1")).click(); String expectedURL; if (apServerName == ApServerName.TOMCAT) { expectedURL = applicationContextUrl + "/login"; } else { expectedURL = applicationContextUrl + "/"; } webDriverWait.until(ExpectedConditions.urlToBe(expectedURL)); driver.get(getPackageRootUrl()); driver.findElement(By.id("listWithExternalPathWithContextPath")) .click(); driver.findElement(By.id("btn1")).click(); inputFieldAccessor.overrideValue(By.id("username"), "user1", driver); inputFieldAccessor.overrideValue(By.id("password"), "user1", driver); assertThat(getRedirectValue(), is( "<LINK_0>")); screenCapture.save(driver); driver.findElement(By.id("btn1")).click(); webDriverWait.until(ExpectedConditions.urlToBe(applicationContextUrl + "/redirect/externalPathWithContextPath")); }
Source:
public void checkDiskErrorAsync() { volumeChecker.checkAllVolumesAsync( data, (healthyVolumes, failedVolumes) -> { LOG.info("checkDiskErrorAsync callback got failed volumes: {}", failedVolumes.size(), failedVolumes); lastDiskErrorCheck = Time.monotonicNow(); handleVolumeFailures(failedVolumes); }); }

Target:
public void checkDiskErrorAsync() { volumeChecker.checkAllVolumesAsync( data, (healthyVolumes, failedVolumes) -> { if (failedVolumes.size() > 0) { LOG.warn("checkDiskErrorAsync callback got failed volumes: {}", failedVolumes.size(), failedVolumes); } else { LOG.debug("checkDiskErrorAsync: no volume failures detected"); } lastDiskErrorCheck = Time.monotonicNow(); handleVolumeFailures(failedVolumes); }); }
Source:
public void parse(CommandSource source, CommandArgs args, CommandContext context) throws ArgumentParseException { Object state = args.getState(); while (args.hasNext()) { String arg = args.next(); boolean remove; if (arg.startsWith("-")) { Object start = args.getState(); if (arg.startsWith("--")) { String longFlag = arg.substring(2); remove = parseLongFlag(source, longFlag, args, context); } else { arg = arg.substring(1); remove = parseShortFlags(source, arg, args, context); } if (remove) { args.removeArgs(start, args.getState()); } } else if (this.anchorFlags) { break; } } args.setState(state); if (this.childElement != null) { this.childElement.parse(source, args, context); } }

Target:
public void parse(CommandSource source, CommandArgs args, CommandContext context) throws ArgumentParseException { Object state = args.getState(); while (args.hasNext()) { String arg = args.next(); if (arg.startsWith("-")) { Object start = args.getState(); boolean remove; if (arg.startsWith("--")) { remove = parseLongFlag(source, arg.substring(2), args, context); } else { remove = parseShortFlags(source, arg.substring(1), args, context); } if (remove) { args.removeArgs(start, args.getState()); } } else if (this.anchorFlags) { break; } } args.setState(state); if (this.childElement != null) { this.childElement.parse(source, args, context); } }
Source:
private boolean isNoRunningVmsWithLeasesExist() { List<VmStatic> runningVmsWithLeases = vmStaticDao.getAllRunningWithLeaseOnForStorageDomain(getStorageDomain().getId()); if (!runningVmsWithLeases.isEmpty()) { String vmNames = runningVmsWithLeases.stream().map(v -> v.getName()).collect(Collectors.joining(", ")); return failValidation(EngineMessage.ERROR_CANNOT_DEACTIVATE_DOMAIN_WITH_RUNNING_VMS_WITH_LEASES, String.format("$vmNames %s", vmNames)); } return true; }

Target:
private boolean isNoRunningVmsWithLeasesExist() { List<VmStatic> runningVmsWithLeases = vmStaticDao.getAllRunningWithLeaseOnStorageDomain(getStorageDomain().getId()); if (!runningVmsWithLeases.isEmpty()) { String vmNames = runningVmsWithLeases.stream().map(VmStatic::getName).collect(Collectors.joining(", ")); return failValidation(EngineMessage.ERROR_CANNOT_DEACTIVATE_DOMAIN_WITH_RUNNING_VMS_WITH_LEASES, String.format("$vmNames %s", vmNames)); } return true; }
Source:
public String getLocalURI() { String extension = null; if (mURI != null) { extension = mURI.substring(mURI.length() - 4).toLowerCase(); } try { if (extension.equals(".csv") || extension.equals(".xml")) { return getClass().getClassLoader().getResource("fake-itemset" + extension).toURI().getPath(); } else { return null; } } catch (URISyntaxException e) { return null; } }

Target:
public String getLocalURI() { try { if (uri.toLowerCase().startsWith("jr://file/")) { return getClass().getClassLoader().getResource("fake-itemset.xml").toURI().getPath(); } else if (uri.toLowerCase().startsWith("jr://file-csv/")) { return getClass().getClassLoader().getResource("fake-itemset.csv").toURI().getPath(); } else { return null; } } catch (URISyntaxException e) { return null; } }
Source:
protected boolean containsLinkedResources() { for (IPackageFragment fPackageFragment : fPackageFragments) { if (fPackageFragment.getResource().isLinked()) { return true; } } return false; }

Target:
protected boolean containsLinkedResources() { for (IPackageFragment pack : fPackageFragments) { if (pack.getResource().isLinked()) { return true; } } return false; }
Source:
public Survey getSurvey(StudyIdentifier studyIdentifier, GuidCreatedOnVersionHolder keys, boolean includeElements, boolean throwException) { Survey survey = surveyDao.getSurvey(keys, includeElements); if (throwException && survey == null || !isInStudy(studyIdentifier, survey)) { throw new EntityNotFoundException(Survey.class); } return survey; }

Target:
public Survey getSurvey(StudyIdentifier studyIdentifier, GuidCreatedOnVersionHolder keys, boolean includeElements, boolean throwException) { return getSurvey(ImmutableSet.of(), studyIdentifier, keys, includeElements, throwException); }
Source:
protected void allowAccess(long secretId, long groupId) { OffsetDateTime now = OffsetDateTime.now(); dslContext .insertInto(ACCESSGRANTS) .set(ACCESSGRANTS.SECRETID, Math.toIntExact(secretId)) .set(ACCESSGRANTS.GROUPID, Math.toIntExact(groupId)) .set(ACCESSGRANTS.CREATEDAT, now) .set(ACCESSGRANTS.UPDATEDAT, now) .execute(); }

Target:
protected void allowAccess(long secretId, long groupId) { OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); dslContext .insertInto(ACCESSGRANTS) .set(ACCESSGRANTS.SECRETID, Math.toIntExact(secretId)) .set(ACCESSGRANTS.GROUPID, Math.toIntExact(groupId)) .set(ACCESSGRANTS.CREATEDAT, now) .set(ACCESSGRANTS.UPDATEDAT, now).execute(); }
Source:
public static ParseObject create(String className) { return getSubclassingController().instantiate(className); }

Target:
public static ParseObject create(String className) { return getSubclassingController().newInstance(className); }
Source:
private void writeConditions(XMLStreamWriter export, NodeList conditionElements, URI ditavalDirectory) { try { for (int i = 0; i < conditionElements.getLength(); i++) { if (conditionElements.item(i).getNodeType() == Node.ELEMENT_NODE) { export.writeStartElement(conditionElements.item(i).getNodeName()); final NamedNodeMap atts = conditionElements.item(i).getAttributes(); if (atts.getNamedItem(ATTRIBUTE_NAME_IMAGEREF) != null || atts.getNamedItem(ATTRIBUTE_NAME_IMG) != null ) { final String imagerefAtt = atts.getNamedItem(ATTRIBUTE_NAME_IMAGEREF) != null ? atts.getNamedItem(ATTRIBUTE_NAME_IMAGEREF).getNodeValue() : atts.getNamedItem(ATTRIBUTE_NAME_IMG).getNodeValue(); if (toURI(imagerefAtt).isAbsolute()) { export.writeAttribute(DITA_OT_NS_PREFIX, DITA_OT_NS, ATTRIBUTE_NAME_IMAGEREF_URI, imagerefAtt); } else { export.writeAttribute(DITA_OT_NS_PREFIX, DITA_OT_NS, ATTRIBUTE_NAME_IMAGEREF_URI, ditavalDirectory.resolve(imagerefAtt).toString()); } } for (int j = 0; j < atts.getLength(); j++) { export.writeAttribute(atts.item(j).getNodeName(), atts.item(j).getNodeValue()); } writeConditions(export, conditionElements.item(i).getChildNodes(), ditavalDirectory); export.writeEndElement(); } else if (conditionElements.item(i).getNodeType() == Node.TEXT_NODE) { export.writeCharacters(conditionElements.item(i).getNodeValue()); } } } catch (final XMLStreamException e) { logger.error("Failed to generate merged DITAVAL file: " + e.getMessage(), e); } }

Target:
private void writeConditions(XMLStreamWriter export, NodeList conditionElements, URI ditavalDirectory) { try { for (int i = 0; i < conditionElements.getLength(); i++) { switch (conditionElements.item(i).getNodeType()) { case Node.ELEMENT_NODE: export.writeStartElement(conditionElements.item(i).getNodeName()); final NamedNodeMap atts = conditionElements.item(i).getAttributes(); if (atts.getNamedItem(ATTRIBUTE_NAME_IMAGEREF) != null || atts.getNamedItem(ATTRIBUTE_NAME_IMG) != null ) { final String imagerefAtt = atts.getNamedItem(ATTRIBUTE_NAME_IMAGEREF) != null ? atts.getNamedItem(ATTRIBUTE_NAME_IMAGEREF).getNodeValue() : atts.getNamedItem(ATTRIBUTE_NAME_IMG).getNodeValue(); if (toURI(imagerefAtt).isAbsolute()) { export.writeAttribute(DITA_OT_NS_PREFIX, DITA_OT_NS, ATTRIBUTE_NAME_IMAGEREF_URI, imagerefAtt); } else { export.writeAttribute(DITA_OT_NS_PREFIX, DITA_OT_NS, ATTRIBUTE_NAME_IMAGEREF_URI, ditavalDirectory.resolve(imagerefAtt).toString()); } } for (int j = 0; j < atts.getLength(); j++) { export.writeAttribute(atts.item(j).getNodeName(), atts.item(j).getNodeValue()); } writeConditions(export, conditionElements.item(i).getChildNodes(), ditavalDirectory); export.writeEndElement(); break; case Node.TEXT_NODE: export.writeCharacters(conditionElements.item(i).getNodeValue()); break; } } } catch (final XMLStreamException e) { logger.error("Failed to generate merged DITAVAL file: " + e.getMessage(), e); } }
Source:
public void testNullStringEquality() throws Exception { testQuery( "SELECT COUNT(*)\n" + "FROM druid.foo\n" + "WHERE NULLIF(dim2, 'a') = null", ImmutableList.of(), NullHandling.replaceWithDefault() ? ImmutableList.of(new Object[]{0L}) : ImmutableList.of(new Object[]{0L}) ); }

Target:
public void testNullStringEquality() throws Exception { testQuery( "SELECT COUNT(*)\n" + "FROM druid.foo\n" + "WHERE NULLIF(dim2, 'a') = null", ImmutableList.of(), ImmutableList.of(new Object[]{0L}) ); }
Source:
public void truncateBufferedLogs(int maxRecords) { int recordSize = getRecordCount(); if (recordSize > maxRecords) { String query = "SELECT * FROM " + TABLE_NAME + " ORDER BY id DESC" + " LIMIT " + String.valueOf(recordSize - maxRecords); Cursor cursor = db.rawQuery(query, null); Records truncateRecords; try { truncateRecords = recordsFromCursor(cursor); } finally { cursor.close(); } if (truncateRecords != null) { delete(truncateRecords); } } }

Target:
public void truncateBufferedLogs(int maxRecords) { int recordSize = getRecordCount(); if (recordSize > maxRecords) { String query = "DELETE FROM " + TABLE_NAME + " WHERE id IN ( SELECT id FROM " + TABLE_NAME + " ORDER BY id ASC LIMIT " + String.valueOf(recordSize - maxRecords) + ")"; db.execSQL(query); } }
Source:
public void setDefaultBranchIfNotSet(Entry entry, String repositoryId) { Version defaultVersion = entry.getActualDefaultVersion(); Set<Long> workflowVersionIds = (Set<Long>)entry.getWorkflowVersions().stream().map(version -> ((Version)version).getId()).collect(Collectors.toSet()); if (defaultVersion == null || !workflowVersionIds.contains(defaultVersion.getId())) { entry.setActualDefaultVersion(null); String branch = getMainBranch(entry, repositoryId); if (branch == null) { String message = String.format("%s : Error getting the main branch.", repositoryId); LOG.info(message); } else { Set<Version> workflowVersions = entry.getWorkflowVersions(); Optional<Version> firstWorkflowVersion = workflowVersions.stream() .filter(workflowVersion -> { String reference = workflowVersion.getReference(); return branch.equals(reference); }).findFirst(); firstWorkflowVersion.ifPresentOrElse(version -> entry.checkAndSetDefaultVersion(version.getName()), () -> { Version newestVersion = Collections.max(workflowVersions, Comparator.comparingInt(s -> s.getDbUpdateDate().getNanos())); entry.setActualDefaultVersion(newestVersion); }); } } }

Target:
public void setDefaultBranchIfNotSet(Entry entry, String repositoryId) { Version defaultVersion = entry.getActualDefaultVersion(); Set<Long> workflowVersionIds = (Set<Long>)entry.getWorkflowVersions().stream().map(version -> ((Version)version).getId()).collect(Collectors.toSet()); if (defaultVersion == null || !workflowVersionIds.contains(defaultVersion.getId())) { entry.setActualDefaultVersion(null); String branch = getMainBranch(entry, repositoryId); if (branch == null) { String message = String.format("%s : Error getting the main branch.", repositoryId); LOG.info(message); } else { Set<Version> workflowVersions = entry.getWorkflowVersions(); Optional<Version> firstWorkflowVersion = workflowVersions.stream() .filter(workflowVersion -> { String reference = workflowVersion.getReference(); return branch.equals(reference); }).findFirst(); firstWorkflowVersion.ifPresentOrElse(version -> entry.checkAndSetDefaultVersion(version.getName()), () -> { Version newestVersion = Collections.max(workflowVersions, Comparator.comparingLong(s -> s.getDate().getTime())); entry.setActualDefaultVersion(newestVersion); }); } } }
Source:
public LoginOptions getLoginOptions(String jwt, String url) { return getLoginOptionsInternal(jwt, url); }

Target:
public LoginOptions getLoginOptions(String jwt, String url) { if (loginOptions == null) { final BootConfig config = BootConfig.getBootConfig(context); if (TextUtils.isEmpty(jwt)) { loginOptions = new LoginOptions(url, getPasscodeHash(), config.getOauthRedirectURI(), config.getRemoteAccessConsumerKey(), config.getOauthScopes(), null); } else { loginOptions = new LoginOptions(url, getPasscodeHash(), config.getOauthRedirectURI(), config.getRemoteAccessConsumerKey(), config.getOauthScopes(), null, jwt); } } return loginOptions; }
Source:
public HttpRequestBase formatRequest() { URIBuilder uriBuilder = getRepository().getURIBuilder(fAuthIsRequired); URI uri = null; try { String path = new StringBuilder(uriBuilder.getPath()).append("/changes/") .append(getId()) .append("/revisions/").append(getRevision()) .append("/review") .toString(); uriBuilder.setPath(path); uri = new URI(URIUtil.toUnencodedString(uriBuilder.build())); } catch (URISyntaxException e) { EGerritCorePlugin.logError("URI syntax exception", e); } HttpPost httpPost = new HttpPost(uri); Gson gson = new Gson(); String json = gson.toJson(fReviewInput); StringEntity input = null; try { input = new StringEntity(json); } catch (UnsupportedEncodingException e) { EGerritCorePlugin.logError("URI error encoding ReviewInput", e); } input.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(input); return httpPost; }

Target:
public HttpRequestBase formatRequest() { URIBuilder uriBuilder = getRepository().getURIBuilder(fAuthIsRequired); URI uri = null; try { String path = new StringBuilder(uriBuilder.getPath()).append("/changes/") .append(getId()) .append("/revisions/").append(getRevision()) .append("/review") .toString(); uriBuilder.setPath(path); uri = new URI(URIUtil.toUnencodedString(uriBuilder.build())); } catch (URISyntaxException e) { EGerritCorePlugin.logError("URI syntax exception", e); } HttpPost httpPost = new HttpPost(uri); Gson gson = new Gson(); String json = gson.toJson(fReviewInput); StringEntity input = null; try { input = new StringEntity(json); } catch (UnsupportedEncodingException e) { EGerritCorePlugin.logError("URI error encoding ReviewInput", e); } input.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, GerritCommand.JSON_HEADER)); httpPost.setEntity(input); return httpPost; }
Source:
private static void updateChildrenFonts(CTabFolder folder, Font font) { for (CTabItem item : folder.getItems()) { Font itemFont = item.getFont(); if (itemFont != null && !itemFont.equals(font)) { item.setFont(font); } } }

Target:
private static void updateChildrenFonts(CTabFolder folder, Font font) { for (CTabItem item : folder.getItems()) { item.setFont(font); } }
Source:
public boolean computeEnabledState() throws Exception { if (isEditableContext()) { ISPNode n = getContextNode(ISPNode.class); return !(n.getDataObject() instanceof TargetObsComp); } return false; }

Target:
public boolean computeEnabledState() throws Exception { if (isEditableContext()) { ISPNode n = getContextNode(ISPNode.class); return (n != null) && !(n.getDataObject() instanceof TargetObsComp); } return false; }
Source:
public void batch_mutate(String kvsMethodName, Map<ByteBuffer, Map<String, List<Mutation>>> mutation_map, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { long startTime = System.currentTimeMillis(); KvsProfilingLogger.maybeLog( (KvsProfilingLogger.CallableCheckedException<Void, TException>) () -> { client.batch_mutate(kvsMethodName, mutation_map, consistency_level); return null; }, (logger, timer) -> { logger.log("CassandraClient.batch_mutate("); ThriftObjectSizeUtils.getSizeOfMutationPerTable(mutation_map).forEach((tableName, size) -> { logger.log("{} -> {}", LoggingArgs.safeInternalTableNameOrPlaceholder(tableName), LoggingArgs.sizeInBytes(size)); }); logger.log(") with consistency at time {}, on kvs.{} took ms", LoggingArgs.startTimeMillis(startTime), SafeArg.of("consistency", consistency_level.toString()), SafeArg.of("kvsMethodName", kvsMethodName), LoggingArgs.durationMillis(timer)); }); }

Target:
public void batch_mutate(String kvsMethodName, Map<ByteBuffer, Map<String, List<Mutation>>> mutation_map, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { long startTime = System.currentTimeMillis(); KvsProfilingLogger.maybeLog( (KvsProfilingLogger.CallableCheckedException<Void, TException>) () -> { client.batch_mutate(kvsMethodName, mutation_map, consistency_level); return null; }, (logger, timer) -> { logger.log("CassandraClient.batch_mutate("); ThriftObjectSizeUtils.getSizeOfMutationPerTable(mutation_map).forEach((tableName, size) -> { logger.log("{} -> {}", LoggingArgs.safeInternalTableNameOrPlaceholder(tableName), LoggingArgs.sizeInBytes(size)); }); logger.log(") with consistency at time {}, on kvs.{} took ms", SafeArg.of("consistency", consistency_level.toString()), LoggingArgs.startTimeMillis(startTime), SafeArg.of("kvsMethodName", kvsMethodName), LoggingArgs.durationMillis(timer)); }); }
Source:
public TissuePieceType getByName(String name) { return (TissuePieceType) currentSession().createCriteria(TissuePieceType.class) .add(Restrictions.eq("name", name)) .uniqueResult(); }

Target:
public TissuePieceType getByName(String name) { return getBy("name", name); }
Source:
public static OffsetDateTime now(ZoneOffset zoneOffset) { final LocalDate localDate = LocalDates.now(); final LocalTime localTime = LocalTimes.now(); final OffsetDateTime result = OffsetDateTime.newBuilder() .setDate(localDate) .setTime(localTime) .setOffset(zoneOffset) .build(); return result; }

Target:
public static OffsetDateTime now(ZoneOffset zoneOffset) { checkNotNull(zoneOffset); final Calendar now = nowAt(zoneOffset); final LocalTime localTime = toLocalTime(now); final LocalDate localDate = toLocalDate(now); final OffsetDateTime result = OffsetDateTime.newBuilder() .setDate(localDate) .setTime(localTime) .setOffset(zoneOffset) .build(); return result; }
Source:
public void testEmptyValuesAreIgnored() { Point point = Point.measurement("dontcare").tag("key","").addField("dontcare", true).build(); assertThat(point.getTags().size()).isEqualTo(0); }

Target:
public void testEmptyValuesAreIgnored() { Point point = Point.measurement("dontcare").tag("key","").addField("dontcare", true).build(); assertThat(point.getTags().size()).isEqualTo(0); point = Point.measurement("dontcare").tag("","value").addField("dontcare", true).build(); assertThat(point.getTags().size()).isEqualTo(0); point = Point.measurement("dontcare").tag(ImmutableMap.of("key","")).addField("dontcare", true).build(); assertThat(point.getTags().size()).isEqualTo(0); point = Point.measurement("dontcare").tag(ImmutableMap.of("","value")).addField("dontcare", true).build(); assertThat(point.getTags().size()).isEqualTo(0); }
Source:
public List<User> call(ApiCaller ac, Deserializer parms) throws PerunException { if(parms.contains("role")) { String roleName = parms.readString("role"); Role role; try { role = Role.valueOf(roleName); } catch (IllegalArgumentException ex) { throw new RpcException(RpcException.Type.WRONG_PARAMETER, "wrong parameter in role, not exists role with this name " + roleName); } return ac.getVosManager().getAdmins(ac.getSession(), ac.getVoById(parms.readInt("vo")), role, parms.readBoolean("onlyDirectAdmins")); } else { return ac.getVosManager().getAdmins(ac.getSession(), ac.getVoById(parms.readInt("vo")), null,parms.readBoolean("onlyDirectAdmins")); } }

Target:
public List<Vo> call(ApiCaller ac, Deserializer parms) throws PerunException { return ac.getVosManager().getVos(ac.getSession()); }
Source:
public void addProcessInstance(ProcessInstance processInstance, CorrelationKey correlationKey) { ProcessInstanceInfo processInstanceInfo = new ProcessInstanceInfo( processInstance, this.kruntime.getEnvironment() ); ProcessPersistenceContext context = ((ProcessPersistenceContextManager) this.kruntime.getEnvironment() .get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )) .getProcessPersistenceContext(); processInstanceInfo = (ProcessInstanceInfo) context.persist( processInstanceInfo ); ((org.jbpm.process.instance.ProcessInstance) processInstance).setId( processInstanceInfo.getId() ); processInstanceInfo.updateLastReadDate(); if (correlationKey == null) { correlationKey = (CorrelationKeyInfo) correlationKeyFactory.newCorrelationKey(processInstanceInfo.getId().toString()); ((org.jbpm.process.instance.ProcessInstance) processInstance).getMetaData().put("CorrelationKey", correlationKey); } CorrelationKeyInfo correlationKeyInfo = (CorrelationKeyInfo) correlationKey; correlationKeyInfo.setProcessInstanceId(processInstanceInfo.getId()); context.persist(correlationKeyInfo); internalAddProcessInstance(processInstance); EventManagerProvider.getInstance().get().create(getInstanceViewFor(processInstance)); }

Target:
public void addProcessInstance(ProcessInstance processInstance, CorrelationKey correlationKey) { ProcessInstanceInfo processInstanceInfo = new ProcessInstanceInfo( processInstance, this.kruntime.getEnvironment() ); ProcessPersistenceContext context = ((ProcessPersistenceContextManager) this.kruntime.getEnvironment() .get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )) .getProcessPersistenceContext(); processInstanceInfo = (ProcessInstanceInfo) context.persist( processInstanceInfo ); ((org.jbpm.process.instance.ProcessInstance) processInstance).setId( processInstanceInfo.getId() ); processInstanceInfo.updateLastReadDate(); if (correlationKey == null) { correlationKey = new CorrelationKeyInfo(); ((CorrelationKeyInfo) correlationKey).addProperty(new CorrelationPropertyInfo(null, processInstanceInfo.getId().toString())); ((CorrelationKeyInfo) correlationKey).setName(correlationKey.toExternalForm()); ((org.jbpm.process.instance.ProcessInstance) processInstance).getMetaData().put("CorrelationKey", correlationKey); } CorrelationKeyInfo correlationKeyInfo = (CorrelationKeyInfo) correlationKey; correlationKeyInfo.setProcessInstanceId(processInstanceInfo.getId()); context.persist(correlationKeyInfo); internalAddProcessInstance(processInstance); EventManagerProvider.getInstance().get().create(getInstanceViewFor(processInstance)); }
Source:
protected void indicating(CDODataInput in) throws IOException { int viewID = in.readInt(); InternalView view = getSession().getView(viewID); if (view == null) { throw new IllegalStateException("View not found"); } InternalLockManager lockManager = getRepository().getLockingManager(); existingLockStates = new ArrayList<CDOLockState>(); int n = in.readInt(); for (int i = 0; i < n; i++) { Object key = indicatingCDOID(in, view.getBranch()); LockState<Object, IView> lockState = lockManager.getLockState(key); if (lockState != null) { existingLockStates.add(CDOLockUtil.createLockState(lockState)); } } if (n == 0) { Collection<LockState<Object, IView>> lockStates = lockManager.getLockStates(); for (LockState<Object, IView> lockState : lockStates) { existingLockStates.add(CDOLockUtil.createLockState(lockState)); } } }

Target:
protected void indicating(CDODataInput in) throws IOException { int viewID = in.readInt(); InternalView view = getSession().getView(viewID); if (view == null) { throw new IllegalStateException("View not found"); } InternalLockManager lockManager = getRepository().getLockingManager(); existingLockStates = new ArrayList<CDOLockState>(); int n = in.readInt(); if (n == 0) { Collection<LockState<Object, IView>> lockStates = lockManager.getLockStates(); for (LockState<Object, IView> lockState : lockStates) { existingLockStates.add(CDOLockUtil.createLockState(lockState)); } } else { for (int i = 0; i < n; i++) { Object key = indicatingCDOID(in, view.getBranch()); LockState<Object, IView> lockState = lockManager.getLockState(key); if (lockState != null) { existingLockStates.add(CDOLockUtil.createLockState(lockState)); } } } }
Source:
public boolean isActive() { return !SCESIM_DISABLED && (!DROOLS_DISABLED || !DMN_DISABLED); }

Target:
public boolean isActive() { boolean scesimEnabled = !SCESIM_DISABLED; boolean droolsEnabled = !DROOLS_DISABLED; boolean dmnEnabled = !DMN_DISABLED; boolean droolsOrDmnEnabled = droolsEnabled || dmnEnabled; return scesimEnabled && droolsOrDmnEnabled; }
Source:
public void shouldSaveNewRuleInPage() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Template template = new TemplateDataGen().nextPersisted(); final HTMLPageAsset htmlPageAsset = new HTMLPageDataGen(host, template).nextPersisted(); final Rule rule = new RuleDataGen().page(htmlPageAsset).next(); this.addPermission(role, host, true); rulesAPI.saveRule(rule, user, false); final List<Rule> rules = rulesAPI.getAllRulesByParent(htmlPageAsset, systemUser, true); assertEquals(1, rules.size()); }

Target:
public void shouldSaveNewRuleInPage() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Template template = new TemplateDataGen().nextPersisted(); final HTMLPageAsset htmlPageAsset = new HTMLPageDataGen(host, template).nextPersisted(); final Rule rule = new RuleDataGen().page(htmlPageAsset).next(); this.addPermission(role, host, true); rulesAPI.saveRule(rule, user, false); final List<Rule> rules = rulesAPI.getAllRulesByParent(htmlPageAsset, systemUser, true); assertEquals(1, rules.size()); final List<String> rulesId = rules.stream().map(pageRule -> pageRule.getId()).collect(Collectors.toList()); assertTrue(rulesId.contains(rule.getId())); }
Source:
public Collection<T> findByIds(Collection<Long> ids) { if (ids == null) { return null; } return repository.retrieveAll(ids); }

Target:
public List<T> findByIds(Collection<Long> ids) { if (ids == null) { return new ArrayList<>(); } return repository.retrieveAll(ids); }
Source:
public Statement apply(final Statement statement, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { Level level = getLevel(description.getAnnotation(LogLevel.class)); Level prevLevel; if (level != null) { prevLevel = resetLogsLevel(level); } else { prevLevel = null; } try { statement.evaluate(); } finally { if (prevLevel != null) { resetLogsLevel(prevLevel); } } } }; }

Target:
public Statement apply(final Statement statement, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { Test test = description.getAnnotation(Test.class); boolean exceptionExpected = test != null && test.expected() != Test.None.class; Level level = getLevel(description.getAnnotation(LogLevel.class)); if (level == null && exceptionExpected) { level = Level.OFF; } Level prevLevel; if (level != null) { prevLevel = resetLogsLevel(level); } else { prevLevel = null; } try { statement.evaluate(); } finally { if (prevLevel != null) { resetLogsLevel(prevLevel); } } } }; }
Source:
public void setShowIgnoreFilesButtons(boolean showButtons) { this.showButtonsState = showButtons; if (showButtons == false) { setBreakOnJavaScript(true); setBreakOnCSSAndFonts(true); setBreakOnMultimedia(true); setOnlyBreakOnScope(false); } }

Target:
public void setShowIgnoreFilesButtons(boolean showButtons) { if (!showButtons) { setBreakOnJavaScript(true); setBreakOnCssAndFonts(true); setBreakOnMultimedia(true); setOnlyBreakOnScope(false); } }
Source:
public Pilot getPilot(){ if (isTranscendent) { throw new SolDescriptiveException(transcendentNotExistingPropertyExceptionMessage); } return hero.getPilot(); }

Target:
public Pilot getPilot() { return isTranscendent ? transcendentHeroShip.getPilot() : hero.getPilot(); }
Source:
public List<String> getRepositoryDirectories() { return new ArrayList<>(repositoryDirectories); }

Target:
public List<File> getRepositoryDirectories() { return new ArrayList<>(repositoryDirectories); }
Source:
private boolean isDialectExists(Connection dbConnection, String uri) throws UserStoreException { int dialectId = getDialectId(dbConnection, uri); if (dialectId != -1) { return true; } else { return false; } }

Target:
private boolean isDialectExists(Connection dbConnection, String uri) throws UserStoreException { int dialectId = getDialectId(dbConnection, uri); return dialectId != -1; }
Source:
public void testDefinitionEquals() { DefinitionImpl<String> a = new DefinitionImpl<>("a"); DefinitionImpl<String> b = new DefinitionImpl<>("a"); assertEquals(a, b); b.setDefinition("b"); assertNotEquals(a, b); b.setDefinition("a"); assertEquals(a, b); }

Target:
public void testDefinitionEquals() { DefinitionImpl<String> a = new DefinitionImpl<>("a"); DefinitionImpl<String> b = new DefinitionImpl<>("a"); assertEquals(a, b); b.setDefinition(null); assertNotEquals(a, b); b.setDefinition("b"); assertNotEquals(a, b); b.setDefinition("a"); assertEquals(a, b); }
Source:
private void testGetDocContent_authenticatedUsers(String authenticatedUsers) throws Exception { String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", TestObjectFactory.newPermissionList(ImmutableList.of( TestObjectFactory.newPermission(Permissions.AUTHENTICATED_USERS, SecurityPrincipalType.GROUP, AccessType.ALLOW, (AccessRight.READ_AS_INT | AccessRight.VIEW_CONTENT_AS_INT), 0, PermissionSource.SOURCE_DIRECT)))); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); Acl acl = response.getAcl(); assertEquals(acl.getPermitGroups().toString(), ImmutableSet.<GroupPrincipal>of(new GroupPrincipal(authenticatedUsers, options.getGlobalNamespace())), acl.getPermitGroups()); assertTrue(acl.getPermitUsers().toString(), acl.getPermitUsers().isEmpty()); assertTrue(acl.getDenyGroups().toString(), acl.getDenyGroups().isEmpty()); assertTrue(acl.getDenyUsers().toString(), acl.getDenyUsers().isEmpty()); }

Target:
private void testGetDocContent_authenticatedUsers(String authenticatedUsers) throws Exception { String id = "{AAAAAAAA-0000-0000-0000-000000000000}"; DocId docId = newDocId(new Id(id)); MockObjectStore os = getObjectStore(); mockDocument(os, id, DOCUMENT_TIMESTAMP, RELEASED, 42d, "text/plain", TestObjectFactory.newPermissionList(ImmutableList.of( TestObjectFactory.newPermission(Permissions.AUTHENTICATED_USERS, SecurityPrincipalType.GROUP, AccessType.ALLOW, Permissions.VIEW_ACCESS_RIGHTS, 0, PermissionSource.SOURCE_DIRECT)))); DocumentTraverser traverser = new DocumentTraverser(options); Request request = new MockRequest(docId); RecordingResponse response = new RecordingResponse(); traverser.getDocContent(new Id(id), request, response); Acl acl = response.getAcl(); assertEquals(ImmutableSet.of( new GroupPrincipal(authenticatedUsers, options.getGlobalNamespace())), acl.getPermitGroups()); assertTrue(acl.getPermitUsers().toString(), acl.getPermitUsers().isEmpty()); assertTrue(acl.getDenyGroups().toString(), acl.getDenyGroups().isEmpty()); assertTrue(acl.getDenyUsers().toString(), acl.getDenyUsers().isEmpty()); }
Source:
private void applyFilter() { int matches = 0; String[] needles = searchBox_.getText().toLowerCase().split("\\s+"); for (CommandPaletteEntry entry: entries_) { String hay = entry.getLabel().toLowerCase(); boolean matched = true; for (int i = 0; i < needles.length; i++) { if (!hay.contains(needles[i])) { entry.setVisible(false); matched = false; break; } } if (matched) { entry.setSearchHighlight(needles); entry.setVisible(true); matches++; } } if (needles.length == 0) { matches = entries_.size(); } updateResultsCount_.nudge(); updateSelection(); if (matches == 0 && !noResults_.isVisible()) { scroller_.setVisible(false); noResults_.setVisible(true); } else if (matches > 0 && noResults_.isVisible()) { scroller_.setVisible(true); noResults_.setVisible(false); } }

Target:
private void applyFilter() { int matches = 0; String[] needles = searchBox_.getText().toLowerCase().split("\\s+"); for (CommandPaletteEntry entry: entries_) { String hay = entry.getLabel().toLowerCase(); boolean matched = true; for (String needle: needles) { if (!hay.contains(needle)) { entry.setVisible(false); matched = false; break; } } if (matched) { entry.setSearchHighlight(needles); entry.setVisible(true); matches++; } } if (needles.length == 0) { matches = entries_.size(); } updateSelection(); if (matches == 0 && !noResults_.isVisible()) { scroller_.setVisible(false); noResults_.setVisible(true); } else if (matches > 0 && noResults_.isVisible()) { scroller_.setVisible(true); noResults_.setVisible(false); } resultsCount_.reportStatus(matches + " " + "commands found, press up and down to navigate", RStudioGinjector.INSTANCE.getUserPrefs().typingStatusDelayMs().getValue(), Severity.ALERT); }
Source:
protected boolean isFileDomainInEditState(StorageDomain storageDomain) { return (storageDomain.getStatus() == StorageDomainStatus.Maintenance || storageDomain.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached); }

Target:
private boolean isFileDomainInEditState(StorageDomain storageDomain) { return (storageDomain.getStatus() == StorageDomainStatus.Maintenance || storageDomain.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached); }
Source:
public void testPrefixDoesNotNormalizeDoubleSlashInTar() throws Exception { writeTrashFile("foo", "a file"); git.add().addFilepattern("foo").call(); git.commit().setMessage("boring commit").call(); final byte[] result = CLIGitCommand.rawExecute( "git archive --prefix=x String[] expect = { "x assertArrayEquals(expect, listTarEntries(result)); }

Target:
public void testPrefixDoesNotNormalizeDoubleSlashInTar() throws Exception { commitFoo(); final byte[] result = CLIGitCommand.rawExecute( "git archive --prefix=x String[] expect = { "x assertArrayEquals(expect, listTarEntries(result)); }
Source:
private void disableHook() { if (getWindow() != null) { return; } if (getSelectedItems() == null || getSelectedItems().size() == 0) { return; } ConfirmationModel model = new ConfirmationModel(); setConfirmWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().confirmDisableGlusterHooks()); model.setHashName("disable_hooks"); model.setMessage(ConstantsManager.getInstance().getConstants().disableGlusterHooksMessage()); if (getSelectedItems() == null) { return; } java.util.ArrayList<String> list = new java.util.ArrayList<String>(); for (GlusterHookEntity item : Linq.<GlusterHookEntity> Cast(getSelectedItems())) { list.add(item.getName()); } model.setItems(list); UICommand okCommand = new UICommand("OnDisableHook", this); okCommand.setTitle(ConstantsManager.getInstance().getConstants().ok()); okCommand.setIsDefault(true); model.getCommands().add(okCommand); UICommand cancelCommand = new UICommand("OnCancelConfirmation", this); cancelCommand.setTitle(ConstantsManager.getInstance().getConstants().cancel()); cancelCommand.setIsCancel(true); model.getCommands().add(cancelCommand); }

Target:
private void disableHook() { if (getWindow() != null) { return; } if (getSelectedItems() == null || getSelectedItems().size() == 0) { return; } ConfirmationModel model = new ConfirmationModel(); setConfirmWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().confirmDisableGlusterHooks()); model.setHashName("disable_hooks"); model.setMessage(ConstantsManager.getInstance().getConstants().disableGlusterHooksMessage()); if (getSelectedItems() == null) { return; } ArrayList<String> list = new ArrayList<String>(); for (Object item : getSelectedItems()) { GlusterHookEntity hook = (GlusterHookEntity) item; list.add(hook.getName()); } model.setItems(list); UICommand okCommand = new UICommand("OnDisableHook", this); okCommand.setTitle(ConstantsManager.getInstance().getConstants().ok()); okCommand.setIsDefault(true); model.getCommands().add(okCommand); UICommand cancelCommand = new UICommand("OnCancelConfirmation", this); cancelCommand.setTitle(ConstantsManager.getInstance().getConstants().cancel()); cancelCommand.setIsCancel(true); model.getCommands().add(cancelCommand); }
Source:
public HTNode getLatestLeaf() { List<HTNode> latest = getLatestBranch(); return NonNullUtils.checkNotNull(latest.get(latest.size() - 1)); }

Target:
public HTNode getLatestLeaf() { List<HTNode> latest = getLatestBranch(); return NonNullUtils.checkNotNull(Iterables.getLast(latest)); }
Source:
public void testOnBackpressureDropSynchronous() { for (int i = 0; i < 100; i++) { final AtomicInteger dropCount = new AtomicInteger(); int NUM = (int) (RxRingBuffer.SIZE * 1.1); AtomicInteger c = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); firehose(c).onBackpressureDrop(new Action1<Integer>() { @Override public void call(Integer i) { dropCount.incrementAndGet(); } }) .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); List<Integer> onNextEvents = ts.getOnNextEvents(); assertEquals(NUM, onNextEvents.size()); Integer lastEvent = onNextEvents.get(NUM - 1); System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Dropped: " + dropCount.get() + " Emitted: " + c.get() + " Last value: " + lastEvent); assertTrue(NUM - 1 <= lastEvent.intValue()); assertEquals(0, dropCount.get()); assertEquals(c.get(), onNextEvents.size()); } }

Target:
public void testOnBackpressureDropSynchronous() { for (int i = 0; i < 100; i++) { int NUM = (int) (RxRingBuffer.SIZE * 1.1); AtomicInteger c = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); firehose(c).onBackpressureDrop() .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); List<Integer> onNextEvents = ts.getOnNextEvents(); assertEquals(NUM, onNextEvents.size()); Integer lastEvent = onNextEvents.get(NUM - 1); System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Emitted: " + c.get() + " Last value: " + lastEvent); assertTrue(NUM - 1 <= lastEvent.intValue()); } }