Example usage for java.util Set size

List of usage examples for java.util Set size

Introduction

In this page you can find the example usage for java.util Set size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:edu.oregonstate.eecs.mcplan.abstraction.WekaUtil.java

public static Instances powerSet(final Instances D, final int n) {
    final Attribute class_attr = D.classAttribute();

    final ImmutableSet.Builder<Integer> b = new ImmutableSet.Builder<Integer>();
    final int Nattr = class_attr != null ? D.numAttributes() - 1 : D.numAttributes();
    for (final int i : Fn.range(1, Nattr)) {
        b.add(i);//from   w w w.ja va2  s.  c o  m
    }
    final Set<Set<Integer>> index = Sets.powerSet(b.build());

    final ArrayList<Attribute> attributes = new ArrayList<Attribute>();
    for (final Set<Integer> subset : index) {
        if (subset.isEmpty() || subset.size() > n) {
            continue;
        }

        final StringBuilder attr_name = new StringBuilder();
        int count = 0;
        for (final Integer i : subset) {
            if (count++ > 0) {
                attr_name.append("_x_");
            }
            attr_name.append(D.attribute(i).name());
        }

        attributes.add(new Attribute(attr_name.toString()));
    }
    if (class_attr != null) {
        assert (class_attr.isNominal());
        attributes.add(WekaUtil.createNominalAttribute(class_attr.name(), class_attr.numValues()));
    }

    final String Pname = "P" + n + "_" + D.relationName();
    final Instances P = new Instances(Pname, attributes, 0);
    if (class_attr != null) {
        P.setClassIndex(attributes.size() - 1);
    }

    for (final Instance inst : D) {
        final double[] xp = new double[attributes.size()];
        int idx = 0;
        for (final Set<Integer> subset : index) {
            if (subset.isEmpty() || subset.size() > n) {
                continue;
            }

            double p = 1.0;
            for (final Integer i : subset) {
                p *= inst.value(i);
            }
            xp[idx++] = p;
        }
        if (class_attr != null) {
            xp[idx++] = inst.classValue();
        }

        WekaUtil.addInstance(P, new DenseInstance(inst.weight(), xp));
    }

    return P;
}

From source file:com.act.lcms.db.analysis.Utils.java

/**
 * Filters a set of metlin masses by include/exclude ion names.
 * @param metlinMassesPreFilter A map of ion names to masses.
 * @param includeIons A set of ion names to include (all others will be excluded).
 * @param excludeIons A set of ion names to exclude.  Exclusion takes priority over inclusion.
 * @return A map of ion names to masses filtered by the include/exclude sets.
 *//*from   w ww.j av a  2  s  .  c  om*/
public static Map<String, Double> filterMasses(Map<String, Double> metlinMassesPreFilter,
        Set<String> includeIons, Set<String> excludeIons) {
    // Don't filter if there's nothing by which to filter.
    if ((includeIons == null || includeIons.size() == 0) && (excludeIons == null || excludeIons.size() == 0)) {
        return metlinMassesPreFilter;
    }
    // Create a fresh map and add from the old one as we go.  (Could also copy and remove, but that seems weird.)
    Map<String, Double> metlinMasses = new HashMap<>(metlinMassesPreFilter.size());
    /* Iterate over the old copy to reduce the risk of concurrent modification exceptions.
     * Note: this is not thread safe. */
    for (Map.Entry<String, Double> entry : metlinMassesPreFilter.entrySet()) {
        // Skip all exclude values immediately.
        if (excludeIons != null && excludeIons.contains(entry.getKey())) {
            continue;
        }
        // If includeIons is defined, only keep those
        if (includeIons == null || includeIons.contains(entry.getKey())) {
            metlinMasses.put(entry.getKey(), entry.getValue());
        }
    }

    return metlinMasses;
}

From source file:info.magnolia.importexport.Bootstrapper.java

/**
 * Bootstrap a specific repository.//from ww  w  .j a  v  a  2  s  . c  o  m
 */
public static boolean bootstrapRepository(String[] bootdirs, String repositoryName, BootstrapFilter filter) {
    Set<File> xmlfileset = getBootstrapFiles(bootdirs, repositoryName, filter);

    if (xmlfileset.isEmpty()) {
        log.debug("No bootstrap files found for repository [{}], skipping...", repositoryName);
        return true;
    }

    log.info("Trying to import content from {} files into repository [{}]", Integer.toString(xmlfileset.size()),
            repositoryName);

    final File[] files = xmlfileset.toArray(new File[xmlfileset.size()]);
    return bootstrapFiles(repositoryName, files);
}

From source file:com.fanfou.app.opensource.api.ApiParser.java

public static <T> ContentValues[] toContentValuesArray(final Set<? extends Storable<T>> t) {
    if ((t == null) || (t.size() == 0)) {
        return null;
    }// ww w  . j  a  v  a 2  s.com

    final ArrayList<Storable<T>> s = new ArrayList<Storable<T>>();
    s.addAll(t);
    return ApiParser.toContentValuesArray(s);

    // ArrayList<ContentValues> values=new ArrayList<ContentValues>();
    // Iterator<? extends Storable<T>> i=t.iterator();
    // while (i.hasNext()) {
    // Storable<T> st=i.next();
    // values.add(st.toContentValues());
    // }
    // return (ContentValues[]) values.toArray(new
    // ContentValues[values.size()]);

}

From source file:org.tec.webapp.jdbc.entity.support.PreparedStatementBuilder.java

/**
 * Build prepared statement for Select/* w  ww  .  j  a va2s  .  c o m*/
 *
 * @param tablename the table to select from
 * @param columns the set of column names
 * @param whereParams the map of where params
 * @param whereClause the string where clause
 * @return PreparedStatementBuilder to select
 */
public static PreparedStatementBuilder getSelectBuilder(String tablename, Set<String> columns,
        ParameterMap whereParams, String whereClause) {
    // Nothing to update
    if (0 == columns.size()) {
        throw new RuntimeException("No columns provided to select. " + tablename);
    }

    // Build the actual prepared statement
    StringBuilder buf = new StringBuilder();
    buf.append("SELECT ");

    for (Iterator<String> itCol = columns.iterator(); itCol.hasNext();) {
        buf.append(itCol.next());
        if (itCol.hasNext()) {
            buf.append(',');
        }
    }

    buf.append(" FROM ");
    buf.append(tablename);

    if (whereClause != null && whereClause.length() > 0) {
        buf.append(" WHERE ").append(whereClause);
    }

    return new PreparedStatementBuilder(buf.toString(), null, whereParams, 0);
}

From source file:net.big_oh.common.utils.CollectionsUtil.java

/**
 * /*from w w w  .j a  v a2  s  .  c  o m*/
 * @param <T>
 * @param originalSet
 *            The set of original objects from which combinations of size k
 *            will be generated.
 * @param k
 *            The size of combinations to be generated.
 * @return Returns the set of all size k sets (or combinations) that can be
 *         constructed from the originalSet
 * @throws IllegalArgumentException
 *             thrown if k is less than zero of greater than the size of the
 *             original set.
 */
@SuppressWarnings("unchecked")
public static <T> Set<Set<T>> getCombinations(Set<T> originalSet, int k) throws IllegalArgumentException {

    // sanity check
    if (k < 0) {
        throw new IllegalArgumentException("The value of the k parameter cannot be less than zero.");
    }
    if (k > originalSet.size()) {
        throw new IllegalArgumentException(
                "The value of the k parameter cannot be greater than the size of originalSet.");
    }

    // base case ... k == 0
    if (k == 0) {
        Set<Set<T>> combinations = new HashSet<Set<T>>();
        combinations.add(new HashSet<T>());
        return combinations;
    }

    // base case ... k == 1
    if (k == 1) {
        Set<Set<T>> combinations = new HashSet<Set<T>>();
        for (T t : originalSet) {
            Set<T> combination = new HashSet<T>();
            combination.add(t);
            combinations.add(combination);
        }
        return combinations;
    }

    // recursive case
    T arbitraryElement = (T) CollectionUtils.get(originalSet, 0);

    Set<T> everythingElse = new HashSet<T>(originalSet);
    everythingElse.remove(arbitraryElement);

    Set<Set<T>> combinations = new HashSet<Set<T>>();

    // pair arbitraryElelement with combinations of size k-1 from the
    // everythingElse collection
    for (Set<T> combinationForEverythingElse : getCombinations(everythingElse, k - 1)) {
        combinationForEverythingElse.add(arbitraryElement);
        combinations.add(combinationForEverythingElse);
    }

    // get combinations of size k from the everythingElse collection
    if (k <= everythingElse.size()) {
        for (Set<T> combinationForEverythingElse : getCombinations(everythingElse, k)) {
            combinations.add(combinationForEverythingElse);
        }
    }

    return combinations;
}

From source file:com.github.gdfm.shobaidogu.StatsUtils.java

/**
 * Computes the fraction of source elements that are also in target.
 * //from w ww  .  j a va  2  s.  c o m
 * @param source
 *          the source set.
 * @param target
 *          the target set.
 * @return the fraction.
 */
public static <T> double hitPercent(Set<T> source, Set<T> target) {
    checkNotNull(source);
    checkNotNull(target);
    if (source.isEmpty() || target.isEmpty())
        return 0;
    double intersectSize = Sets.intersection(source, target).size();
    return intersectSize / source.size();
}

From source file:com.jsen.javascript.java.HostedJavaObject.java

/**
 * Returns merged enumerable properties from given object members and already known super IDs.
 * //from   www .  j  a  v a  2s  . co m
 * @param objectMembers Object members that might have some enumerable properties.
 * @param superIds IDs that should be included into result array.
 * @return Array of the enumerable properties.
 */
public static Object[] getIds(ObjectMembers objectMembers, Object[] superIds) {
    Set<String> membersNames = objectMembers.getEnumerableMemberNames();

    Object[] returnIds = new Object[membersNames.size() + superIds.length];

    int i = 0;
    for (; i < superIds.length; i++) {
        returnIds[i] = superIds[i];
    }

    for (String name : membersNames) {
        returnIds[i] = name;
        i++;
    }

    return returnIds;
}

From source file:com.gargoylesoftware.htmlunit.runners.TestCaseCorrector.java

private static void removeNotYetImplemented(final List<String> lines, final int i, final String browserString) {
    final String previous = lines.get(i - 1);
    if (previous.contains("@NotYetImplemented")) {
        if (previous.indexOf('(') != -1) {
            final int p0 = previous.indexOf('(') + 1;
            final int p1 = previous.lastIndexOf(')');
            String browsers = previous.substring(p0, p1);
            if (browsers.indexOf('{') != -1) {
                browsers = browsers.substring(1, browsers.length() - 1).trim();
            }//from  w w w .  jav a 2 s .  c  om
            final Set<String> browserSet = new HashSet<>();
            for (final String browser : browsers.split(",")) {
                browserSet.add(browser.trim());
            }
            browserSet.remove(browserString);
            if (browserSet.size() == 1) {
                lines.set(i - 1, "    @NotYetImplemented(" + browserSet.iterator().next() + ")");
            } else if (browserSet.size() > 1) {
                lines.set(i - 1, "    @NotYetImplemented({ " + StringUtils.join(browserSet, ", ") + " })");
            } else {
                lines.remove(i - 1);
            }
        } else {
            final List<String> allBrowsers = new ArrayList<>(
                    Arrays.asList("CHROME", "IE11", "FF31", "FF38", "EDGE"));
            for (final Iterator<String> it = allBrowsers.iterator(); it.hasNext();) {
                if (it.next().equals(browserString)) {
                    it.remove();
                }
            }
            lines.set(i - 1, "    @NotYetImplemented({ " + StringUtils.join(allBrowsers, ", ") + " })");
        }
    }
}

From source file:com.gemstone.gemfire.internal.security.GeodeSecurityUtil.java

/**
 * It first looks the shiro subject in AccessControlContext since JMX will
 * use multiple threads to process operations from the same client, then it
 * looks into Shiro's thead context.//from   www.j  a v  a2 s  .c o m
 *
 * @return the shiro subject, null if security is not enabled
 */
public static Subject getSubject() {
    if (!isIntegratedSecurity) {
        return null;
    }

    Subject currentUser = null;

    // First try get the principal out of AccessControlContext instead of Shiro's Thread context
    // since threads can be shared between JMX clients.
    javax.security.auth.Subject jmxSubject = javax.security.auth.Subject
            .getSubject(AccessController.getContext());

    if (jmxSubject != null) {
        Set<ShiroPrincipal> principals = jmxSubject.getPrincipals(ShiroPrincipal.class);
        if (principals.size() > 0) {
            ShiroPrincipal principal = principals.iterator().next();
            currentUser = principal.getSubject();
            ThreadContext.bind(currentUser);
            return currentUser;
        }
    }

    // in other cases like admin rest call or pulse authorization
    currentUser = SecurityUtils.getSubject();

    if (currentUser == null || currentUser.getPrincipal() == null) {
        throw new GemFireSecurityException("Error: Anonymous User");
    }

    return currentUser;
}