List of usage examples for java.util HashSet size
public int size()
From source file:biomine.bmvis2.pipeline.SizeSliderOperation.java
public void updateSizeSlider(VisualGraph visualGraph) { int minCount = targetSize; HashSet<VisualGroupNode> closedGroups = new HashSet<VisualGroupNode>(); HashSet<VisualGroupNode> openGroups = new HashSet<VisualGroupNode>(); for (VisualNode n : visualGraph.getNodes()) { if (n instanceof VisualGroupNode) { closedGroups.add((VisualGroupNode) n); }//from www . ja v a 2s .com VisualGroupNode p = n.getParent(); if (p != null && p.getParent() != null) { openGroups.add(p); openGroups.remove(p.getParent()); } } int curCount = visualGraph.getNodes().size(); final int order = 1; final double depthMult = 0.01; System.out.println("openGroups.size() = " + openGroups.size()); if (curCount > minCount) { // close as many open groups as possible while not going // under minCount nodes // start with nodes with most depth ArrayList<VisualGroupNode> groups = new ArrayList<VisualGroupNode>(openGroups); Collections.sort(groups, new Comparator<VisualGroupNode>() { public int compare(VisualGroupNode o1, VisualGroupNode o2) { return Double.compare((o2.getDepth() - o1.getDepth()) * depthMult // + hider.getNodeGoodness(o1) // - hider.getNodeGoodness(o2) , 0) * order; } }); for (VisualGroupNode toClose : groups) { System.out.println("closing " + toClose); int s = toClose.getChildren().size(); if (curCount - s >= minCount) { toClose.setOpen(false); curCount -= s; } } } else { ArrayList<VisualGroupNode> groups = new ArrayList<VisualGroupNode>(closedGroups); Collections.sort(groups, new Comparator<VisualGroupNode>() { public int compare(VisualGroupNode o1, VisualGroupNode o2) { return Double.compare((o2.getDepth() - o1.getDepth()) * depthMult // + hider.getNodeGoodness(o1) // - hider.getNodeGoodness(o2), , 0) * order * -1; } }); for (VisualGroupNode toOpen : groups) { System.out.println("opening " + toOpen); int s = toOpen.getChildren().size(); toOpen.setOpen(true); for (VisualNode n : toOpen.getChildren()) if (n instanceof VisualGroupNode) ((VisualGroupNode) n).setOpen(false); curCount += s; if (curCount + s >= minCount) break; } } }
From source file:com.iflytek.spider.crawl.CrawlDb.java
public int run(String[] args) throws Exception { if (args.length < 2) { System.err.println(/* w w w .j a va 2 s .c o m*/ "Usage: CrawlDb <crawldb> (-dir <segments> | <seg1> <seg2> ...) [-force] [-noAdditions]"); System.err.println("\tcrawldb\tCrawlDb to update"); System.err.println("\t-dir segments\tparent directory containing all segments to update from"); System.err.println("\tseg1 seg2 ...\tlist of segment names to update from"); System.err.println("\t-force\tforce update even if CrawlDb appears to be locked (CAUTION advised)"); System.err.println( "\t-noAdditions\tonly update already existing URLs, don't add any newly discovered URLs"); return -1; } boolean force = false; final FileSystem fs = FileSystem.get(getConf()); boolean additionsAllowed = getConf().getBoolean(CRAWLDB_ADDITIONS_ALLOWED, true); HashSet<Path> dirs = new HashSet<Path>(); for (int i = 1; i < args.length; i++) { if (args[i].equals("-force")) { force = true; } else if (args[i].equals("-noAdditions")) { additionsAllowed = false; } else if (args[i].equals("-dir")) { FileStatus[] paths = fs.listStatus(new Path(args[++i]), HadoopFSUtil.getPassDirectoriesFilter(fs)); dirs.addAll(Arrays.asList(HadoopFSUtil.getPaths(paths))); } else { dirs.add(new Path(args[i])); } } try { update(new Path(args[0]), dirs.toArray(new Path[dirs.size()]), additionsAllowed, force); return 0; } catch (Exception e) { LOG.fatal("CrawlDb update: " + StringUtils.stringifyException(e)); return -1; } }
From source file:com.antsdb.saltedfish.server.mysql.replication.MysqlSlave.java
private Parameters toParameters(TableMeta meta, Pair<Row> pair) { List<Column> colsAft = pair.getAfter().getColumns(); List<Column> colsBef = pair.getBefore().getColumns(); Object[] pureValues;/* ww w . j a v a 2s . c o m*/ PrimaryKeyMeta keyMeta = meta.getPrimaryKey(); if (keyMeta != null) { List<ColumnMeta> primaryKeys = keyMeta.getColumns(meta); // generate set for pk column id HashSet<Integer> pkNum = new HashSet<>(); for (ColumnMeta key : primaryKeys) { pkNum.add(key.getColumnId()); } pureValues = new Object[colsAft.size() + pkNum.size()]; for (int i = 0; i < colsAft.size(); i++) { pureValues[i] = toParameter(colsAft.get(i)); } // appending parameters for where clause for (int i = 0; i < colsBef.size(); i++) { // col id starts with 1 if (pkNum.contains(i + 1)) { pureValues[i + colsAft.size()] = toParameter(colsBef.get(i)); } } } else { pureValues = new Object[colsAft.size() + colsBef.size()]; for (int i = 0; i < colsAft.size(); i++) { pureValues[i] = toParameter(colsAft.get(i)); } // appending parameters for where clause for (int i = 0; i < colsBef.size(); i++) { pureValues[i + colsAft.size()] = toParameter(colsBef.get(i)); } } return new Parameters(pureValues); }
From source file:org.hippoecm.repository.jackrabbit.SessionImplHelper.java
/** * Before this method the JackRabbiit Session.checkPermission is called. * That function checks the validity of absPath and the default JCR permissions: * read, remove, add_node and set_property. So we don't have to check for those * things again here.//from w w w .ja v a2 s. c o m * @param absPath * @param actions * @throws AccessControlException * @throws RepositoryException */ public void checkPermission(String absPath, String actions) throws AccessControlException, RepositoryException { AccessControlManager acMgr = session.getAccessControlManager(); // build the set of actions to be checked HashSet<Privilege> privileges = new HashSet<Privilege>(); for (String action : actions.split(",")) { privileges.add(acMgr.privilegeFromName(action)); } privileges.removeAll(jcrPrivileges); if (privileges.size() > 0) { if (!acMgr.hasPrivileges(absPath, privileges.toArray(new Privilege[privileges.size()]))) { throw new AccessControlException("Privileges '" + actions + "' denied for " + absPath); } } }
From source file:blusunrize.immersiveengineering.common.items.ItemRailgun.java
public String[] compileRender(ItemStack stack) { HashSet<String> render = new HashSet<String>(); render.add("frame"); render.add("barrel"); render.add("grip"); render.add("capacitors"); render.add("sled"); render.add("wires"); NBTTagCompound upgrades = this.getUpgrades(stack); if (upgrades.getDouble("speed") > 0) render.add("upgrade_speed"); if (upgrades.getBoolean("scope")) render.add("upgrade_scope"); return render.toArray(new String[render.size()]); }
From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.IndividualsViaObjectPropetyOptions.java
@Override public Map<String, String> getOptions(EditConfigurationVTwo editConfig, String fieldName, WebappDaoFactory wDaoFact) {//from ww w. j a v a 2 s . c o m HashMap<String, String> optionsMap = new LinkedHashMap<String, String>(); int optionsCount = 0; // first test to see whether there's a default "leave blank" // value specified with the literal options if ((defaultOptionLabel) != null) { optionsMap.put(LEFT_BLANK, defaultOptionLabel); } Individual subject = wDaoFact.getIndividualDao().getIndividualByURI(subjectUri); //get all vclasses applicable to the individual subject HashSet<String> vclassesURIs = getApplicableVClassURIs(subject, wDaoFact); if (!rangeTypes.isEmpty()) { vclassesURIs = filterToSubclassesOfRange(vclassesURIs, rangeTypes, wDaoFact); // is there only one range class and does it have any subclasses? If not, there's no // reason to get the mostSpecificType of the individuals displayed in the select element if (vreq != null && rangeTypes.size() == 1) { hasSubclasses = rangeHasSubclasses(rangeTypes.get(0), vreq); } } if (vclassesURIs.size() == 0) { return optionsMap; } List<Individual> individuals = new ArrayList<Individual>(); HashSet<String> uriSet = new HashSet<String>(); for (String vclassURI : vclassesURIs) { List<Individual> inds = wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclassURI, -1, -1); for (Individual ind : inds) { if (!uriSet.contains(ind.getURI())) { uriSet.add(ind.getURI()); individuals.add(ind); } } } List<ObjectPropertyStatement> stmts = subject.getObjectPropertyStatements(); individuals = FieldUtils.removeIndividualsAlreadyInRange(individuals, stmts, predicateUri, objectUri); // Collections.sort(individuals,new compareIndividualsByName());a for (Individual ind : individuals) { String uri = ind.getURI(); if (uri != null) { // The picklist should only display individuals with rdfs labels. // SO changing the following line -- tlw72 // String label = ind.getName().trim(); String label = ind.getRdfsLabel(); if (label != null) { List<String> msTypes = ind.getMostSpecificTypeURIs(); if (hasSubclasses && msTypes.size() > 0) { String theType = getMsTypeLocalName(msTypes.get(0), wDaoFact); if (theType.length() > 0) { label += " (" + theType + ")"; } } optionsMap.put(uri, label); ++optionsCount; } } } return optionsMap; }
From source file:maui.main.MauiModelBuilder.java
/** * Builds the model from the training data *///w ww. j a v a 2 s . c om public void buildModel(HashSet<String> fileNames) throws Exception { // Check whether there is actually any data if (fileNames.size() == 0) { throw new Exception("Couldn't find any data in " + inputDirectoryName); } System.err.println("-- Building the model... "); FastVector atts = new FastVector(3); atts.addElement(new Attribute("filename", (FastVector) null)); atts.addElement(new Attribute("document", (FastVector) null)); atts.addElement(new Attribute("keyphrases", (FastVector) null)); Instances data = new Instances("keyphrase_training_data", atts, 0); // Build model mauiFilter = new MauiFilter(); mauiFilter.setDebug(debugMode); mauiFilter.setMaxPhraseLength(maxPhraseLength); mauiFilter.setMinPhraseLength(minPhraseLength); mauiFilter.setMinNumOccur(minNumOccur); mauiFilter.setStemmer(stemmer); mauiFilter.setDocumentLanguage(documentLanguage); mauiFilter.setVocabularyName(vocabularyName); mauiFilter.setVocabularyFormat(vocabularyFormat); mauiFilter.setStopwords(stopwords); if (wikipedia != null) { mauiFilter.setWikipedia(wikipedia); } else if (wikipediaServer.equals("localhost") && wikipediaDatabase.equals("database")) { mauiFilter.setWikipedia(wikipedia); } else { mauiFilter.setWikipedia(wikipediaServer, wikipediaDatabase, cacheWikipediaData, wikipediaDataDirectory); } if (classifier != null) { mauiFilter.setClassifier(classifier); } mauiFilter.setInputFormat(data); // set features configurations mauiFilter.setBasicFeatures(useBasicFeatures); mauiFilter.setKeyphrasenessFeature(useKeyphrasenessFeature); mauiFilter.setFrequencyFeatures(useFrequencyFeatures); mauiFilter.setPositionsFeatures(usePositionsFeatures); mauiFilter.setLengthFeature(useLengthFeature); mauiFilter.setThesaurusFeatures(useNodeDegreeFeature); mauiFilter.setBasicWikipediaFeatures(useBasicWikipediaFeatures); mauiFilter.setAllWikipediaFeatures(useAllWikipediaFeatures); mauiFilter.setThesaurusFeatures(useNodeDegreeFeature); mauiFilter.setClassifier(classifier); mauiFilter.setContextSize(contextSize); mauiFilter.setMinKeyphraseness(minKeyphraseness); mauiFilter.setMinSenseProbability(minSenseProbability); if (!vocabularyName.equals("none") && !vocabularyName.equals("wikipedia")) { loadThesaurus(stemmer, stopwords, vocabularyDirectory); mauiFilter.setVocabulary(vocabulary); } System.err.println("-- Reading the input documents... "); for (String fileName : fileNames) { double[] newInst = new double[3]; newInst[0] = (double) data.attribute(0).addStringValue(fileName); File documentTextFile = new File(inputDirectoryName + "/" + fileName + ".txt"); File documentTopicsFile = new File(inputDirectoryName + "/" + fileName + ".key"); try { String documentText; if (!documentEncoding.equals("default")) { documentText = FileUtils.readFileToString(documentTextFile, documentEncoding); } else { documentText = FileUtils.readFileToString(documentTextFile); } // Adding the text of the document to the instance newInst[1] = (double) data.attribute(1).addStringValue(documentText); } catch (Exception e) { System.err.println("Problem with reading " + documentTextFile); e.printStackTrace(); newInst[1] = Instance.missingValue(); } try { String documentTopics; if (!documentEncoding.equals("default")) { documentTopics = FileUtils.readFileToString(documentTopicsFile, documentEncoding); } else { documentTopics = FileUtils.readFileToString(documentTopicsFile); } // Adding the topics to the file newInst[2] = (double) data.attribute(2).addStringValue(documentTopics); } catch (Exception e) { System.err.println("Problem with reading " + documentTopicsFile); e.printStackTrace(); newInst[2] = Instance.missingValue(); } data.add(new Instance(1.0, newInst)); mauiFilter.input(data.instance(0)); data = data.stringFreeStructure(); } mauiFilter.batchFinished(); while ((mauiFilter.output()) != null) { } ; }
From source file:com.clust4j.algo.KMeansTests.java
@Test public void testMethods() { KMeans k = new KMeans(data_, new KMeansParameters(150).setInitializationStrategy(InitializationStrategy.RANDOM)); assertTrue(k.getMaxIter() == KMeans.DEF_MAX_ITER); assertTrue(k.getConvergenceTolerance() == KMeans.DEF_CONVERGENCE_TOLERANCE); HashSet<Integer> idcs = new HashSet<Integer>(); for (int i : k.init_centroid_indices) idcs.add(i);//from w ww. java 2 s . c o m assertTrue(idcs.size() == 150); }
From source file:com.wellsandwhistles.android.redditsp.reddit.prepared.RedditPreparedPost.java
public static void onActionMenuItemSelected(final RedditPreparedPost post, final AppCompatActivity activity, final Action action) { switch (action) { case UPVOTE:// ww w . j av a2s .c o m post.action(activity, RedditAPI.ACTION_UPVOTE); break; case DOWNVOTE: post.action(activity, RedditAPI.ACTION_DOWNVOTE); break; case UNVOTE: post.action(activity, RedditAPI.ACTION_UNVOTE); break; case SAVE: post.action(activity, RedditAPI.ACTION_SAVE); break; case UNSAVE: post.action(activity, RedditAPI.ACTION_UNSAVE); break; case HIDE: post.action(activity, RedditAPI.ACTION_HIDE); break; case UNHIDE: post.action(activity, RedditAPI.ACTION_UNHIDE); break; case EDIT: final Intent editIntent = new Intent(activity, CommentEditActivity.class); editIntent.putExtra("commentIdAndType", post.src.getIdAndType()); editIntent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(post.src.getRawSelfText())); editIntent.putExtra("isSelfPost", true); activity.startActivity(editIntent); break; case DELETE: new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm) .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.ACTION_DELETE); } }).setNegativeButton(R.string.dialog_cancel, null).show(); break; case REPORT: new AlertDialog.Builder(activity).setTitle(R.string.action_report) .setMessage(R.string.action_report_sure) .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { post.action(activity, RedditAPI.ACTION_REPORT); // TODO update the view to show the result // TODO don't forget, this also hides } }).setNegativeButton(R.string.dialog_cancel, null).show(); break; case EXTERNAL: { final Intent intent = new Intent(Intent.ACTION_VIEW); String url = (activity instanceof WebViewActivity) ? ((WebViewActivity) activity).getCurrentUrl() : post.src.getUrl(); intent.setData(Uri.parse(url)); activity.startActivity(intent); break; } case SELFTEXT_LINKS: { final HashSet<String> linksInComment = LinkHandler .computeAllLinks(StringEscapeUtils.unescapeHtml4(post.src.getRawSelfText())); if (linksInComment.isEmpty()) { General.quickToast(activity, R.string.error_toast_no_urls_in_self); } else { final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setItems(linksArr, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LinkHandler.onLinkClicked(activity, linksArr[which], false, post.src.getSrc()); dialog.dismiss(); } }); final AlertDialog alert = builder.create(); alert.setTitle(R.string.action_selftext_links); alert.setCanceledOnTouchOutside(true); alert.show(); } break; } case SAVE_IMAGE: { ((BaseActivity) activity).requestPermissionWithCallback(Manifest.permission.WRITE_EXTERNAL_STORAGE, new SaveImageCallback(activity, post.src.getUrl())); break; } case SHARE: { final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, post.src.getTitle()); mailer.putExtra(Intent.EXTRA_TEXT, post.src.getUrl()); activity.startActivity(Intent.createChooser(mailer, activity.getString(R.string.action_share))); break; } case SHARE_COMMENTS: { final boolean shareAsPermalink = PrefsUtility.pref_behaviour_share_permalink(activity, PreferenceManager.getDefaultSharedPreferences(activity)); final Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("text/plain"); mailer.putExtra(Intent.EXTRA_SUBJECT, "Comments for " + post.src.getTitle()); if (shareAsPermalink) { mailer.putExtra(Intent.EXTRA_TEXT, Constants.Reddit.getNonAPIUri(post.src.getPermalink()).toString()); } else { mailer.putExtra(Intent.EXTRA_TEXT, Constants.Reddit .getNonAPIUri(Constants.Reddit.PATH_COMMENTS + post.src.getIdAlone()).toString()); } activity.startActivity( Intent.createChooser(mailer, activity.getString(R.string.action_share_comments))); break; } case SHARE_IMAGE: { ((BaseActivity) activity).requestPermissionWithCallback(Manifest.permission.WRITE_EXTERNAL_STORAGE, new ShareImageCallback(activity, post.src.getUrl())); break; } case COPY: { ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); manager.setText(post.src.getUrl()); break; } case GOTO_SUBREDDIT: { try { final Intent intent = new Intent(activity, PostListingActivity.class); intent.setData(SubredditPostListURL.getSubreddit(post.src.getSubreddit()).generateJsonUri()); activity.startActivityForResult(intent, 1); } catch (RedditSubreddit.InvalidSubredditNameException e) { Toast.makeText(activity, R.string.invalid_subreddit_name, Toast.LENGTH_LONG).show(); } break; } case USER_PROFILE: LinkHandler.onLinkClicked(activity, new UserProfileURL(post.src.getAuthor()).toString()); break; case PROPERTIES: PostPropertiesDialog.newInstance(post.src.getSrc()).show(activity.getSupportFragmentManager(), null); break; case COMMENTS: ((PostSelectionListener) activity).onPostCommentsSelected(post); new Thread() { @Override public void run() { post.markAsRead(activity); } }.start(); break; case LINK: ((PostSelectionListener) activity).onPostSelected(post); break; case COMMENTS_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((PostSelectionListener) activity).onPostCommentsSelected(post); break; case LINK_SWITCH: if (!(activity instanceof MainActivity)) activity.finish(); ((PostSelectionListener) activity).onPostSelected(post); break; case ACTION_MENU: showActionMenu(activity, post); break; case REPLY: final Intent intent = new Intent(activity, CommentReplyActivity.class); intent.putExtra(CommentReplyActivity.PARENT_ID_AND_TYPE_KEY, post.src.getIdAndType()); intent.putExtra(CommentReplyActivity.PARENT_MARKDOWN_KEY, post.src.getUnescapedSelfText()); activity.startActivity(intent); break; case BACK: activity.onBackPressed(); break; case PIN: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> pinnedSubreddits = PrefsUtility.pref_pinned_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (!pinnedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_pinned_subreddits_add(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_pinned, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case UNPIN: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> pinnedSubreddits = PrefsUtility.pref_pinned_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (pinnedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_pinned_subreddits_remove(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_not_pinned, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case BLOCK: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> blockedSubreddits = PrefsUtility.pref_blocked_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (!blockedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_blocked_subreddits_add(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_blocked, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case UNBLOCK: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); List<String> blockedSubreddits = PrefsUtility.pref_blocked_subreddits(activity, PreferenceManager.getDefaultSharedPreferences(activity)); if (blockedSubreddits.contains(subredditCanonicalName)) { PrefsUtility.pref_blocked_subreddits_remove(activity, PreferenceManager.getDefaultSharedPreferences(activity), subredditCanonicalName); } else { Toast.makeText(activity, R.string.mainmenu_toast_not_blocked, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case SUBSCRIBE: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); RedditSubredditSubscriptionManager subMan = RedditSubredditSubscriptionManager .getSingleton(activity, RedditAccountManager.getInstance(activity).getDefaultAccount()); if (subMan.getSubscriptionState( subredditCanonicalName) == RedditSubredditSubscriptionManager.SubredditSubscriptionState.NOT_SUBSCRIBED) { subMan.subscribe(subredditCanonicalName, activity); Toast.makeText(activity, R.string.options_subscribing, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(activity, R.string.mainmenu_toast_subscribed, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; case UNSUBSCRIBE: try { String subredditCanonicalName = RedditSubreddit.getCanonicalName(post.src.getSubreddit()); RedditSubredditSubscriptionManager subMan = RedditSubredditSubscriptionManager .getSingleton(activity, RedditAccountManager.getInstance(activity).getDefaultAccount()); if (subMan.getSubscriptionState( subredditCanonicalName) == RedditSubredditSubscriptionManager.SubredditSubscriptionState.SUBSCRIBED) { subMan.unsubscribe(subredditCanonicalName, activity); Toast.makeText(activity, R.string.options_unsubscribing, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(activity, R.string.mainmenu_toast_not_subscribed, Toast.LENGTH_SHORT).show(); } } catch (RedditSubreddit.InvalidSubredditNameException e) { throw new RuntimeException(e); } break; } }
From source file:disAMS.AMRMClient.Impl.AMRMClientImpl.java
@Override public synchronized void addContainerRequest(T req) { Preconditions.checkArgument(req != null, "Resource request can not be null."); Set<String> dedupedRacks = new HashSet<String>(); if (req.getRacks() != null) { dedupedRacks.addAll(req.getRacks()); if (req.getRacks().size() != dedupedRacks.size()) { Joiner joiner = Joiner.on(','); LOG.warn("ContainerRequest has duplicate racks: " + joiner.join(req.getRacks())); }/* w w w. j a v a2 s . c o m*/ } Set<String> inferredRacks = resolveRacks(req.getNodes()); inferredRacks.removeAll(dedupedRacks); // check that specific and non-specific requests cannot be mixed within a // priority checkLocalityRelaxationConflict(req.getPriority(), ANY_LIST, req.getRelaxLocality()); // check that specific rack cannot be mixed with specific node within a // priority. If node and its rack are both specified then they must be // in the same request. // For explicitly requested racks, we set locality relaxation to true checkLocalityRelaxationConflict(req.getPriority(), dedupedRacks, true); checkLocalityRelaxationConflict(req.getPriority(), inferredRacks, req.getRelaxLocality()); // check if the node label expression specified is valid checkNodeLabelExpression(req); if (req.getNodes() != null) { HashSet<String> dedupedNodes = new HashSet<String>(req.getNodes()); if (dedupedNodes.size() != req.getNodes().size()) { Joiner joiner = Joiner.on(','); LOG.warn("ContainerRequest has duplicate nodes: " + joiner.join(req.getNodes())); } for (String node : dedupedNodes) { addResourceRequest(req.getPriority(), node, req.getCapability(), req, true, req.getNodeLabelExpression()); } } for (String rack : dedupedRacks) { addResourceRequest(req.getPriority(), rack, req.getCapability(), req, true, req.getNodeLabelExpression()); } // Ensure node requests are accompanied by requests for // corresponding rack for (String rack : inferredRacks) { addResourceRequest(req.getPriority(), rack, req.getCapability(), req, req.getRelaxLocality(), req.getNodeLabelExpression()); } // Off-switch addResourceRequest(req.getPriority(), ResourceRequest.ANY, req.getCapability(), req, req.getRelaxLocality(), req.getNodeLabelExpression()); }