Example usage for com.google.common.collect Iterables get

List of usage examples for com.google.common.collect Iterables get

Introduction

In this page you can find the example usage for com.google.common.collect Iterables get.

Prototype

public static <T> T get(Iterable<T> iterable, int position) 

Source Link

Document

Returns the element at the specified position in an iterable.

Usage

From source file:org.jclouds.examples.ec2.spot.MainApp.java

public static void main(String[] args) {

    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);

    // Args/*  www  .  j  a  v  a  2 s. c o  m*/
    String accesskeyid = args[0];
    String secretkey = args[1];
    String group = args[2];
    String command = args[3];

    // Init
    ComputeService compute = new ComputeServiceContextFactory().createContext("aws-ec2", accesskeyid, secretkey)
            .getComputeService();

    // wait up to 60 seconds for ssh to be accessible
    RetryablePredicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(),
            60, 1, 1, TimeUnit.SECONDS);
    try {
        if (command.equals("create")) {

            Template template = compute.templateBuilder().build();

            template.getOptions().as(AWSEC2TemplateOptions.class)
                    // set the price as 3 cents/hr
                    .spotPrice(0.03f)
                    // authorize my ssh key
                    .authorizePublicKey(Files.toString(
                            new File(System.getProperty("user.home") + "/.ssh/id_rsa.pub"), Charsets.UTF_8));

            System.out.printf(">> running one spot node type(%s) with ami(%s) in group(%s)%n",
                    template.getHardware().getProviderId(), template.getImage().getId(), group);
            // run only a single node
            NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup(group, 1, template));

            System.out.printf("<< running node(%s)%n", node.getId());
            IPSocket socket = new IPSocket(Iterables.get(node.getPublicAddresses(), 0), node.getLoginPort());
            if (socketTester.apply(socket)) {
                System.out.printf("<< socket ready [%s] node(%s)%n", socket, node.getId());
                System.out.printf("ssh to node with the following command:%n ssh %s@%s%n",
                        node.getCredentials().identity, socket.getAddress());
                System.exit(0);
            } else {
                System.out.printf("<< socket not ready [%s] node(%s)%n", socket, node.getId());
            }
        } else if (command.equals("destroy")) {
            System.out.printf(">> destroying nodes in group(%s)%n", group);
            Set<? extends NodeMetadata> destroyed = compute.destroyNodesMatching(NodePredicates.inGroup(group));
            System.out.printf("<< destroyed(%d)%n", destroyed.size());
            System.exit(0);
        } else {
            System.err.println(INVALID_SYNTAX);
            System.exit(1);
        }
    } catch (RunNodesException e) {
        System.err.println(e.getMessage());
        for (NodeMetadata node : e.getNodeErrors().keySet())
            compute.destroyNode(node.getId());
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } finally {
        compute.getContext().close();
    }

}

From source file:com.technobium.MultinomialLogisticRegression.java

public static void main(String[] args) throws Exception {
    // this test trains a 3-way classifier on the famous Iris dataset.
    // a similar exercise can be accomplished in R using this code:
    //    library(nnet)
    //    correct = rep(0,100)
    //    for (j in 1:100) {
    //      i = order(runif(150))
    //      train = iris[i[1:100],]
    //      test = iris[i[101:150],]
    //      m = multinom(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, train)
    //      correct[j] = mean(predict(m, newdata=test) == test$Species)
    //    }//  ww  w .  j av  a2  s. co  m
    //    hist(correct)
    //
    // Note that depending on the training/test split, performance can be better or worse.
    // There is about a 5% chance of getting accuracy < 90% and about 20% chance of getting accuracy
    // of 100%
    //
    // This test uses a deterministic split that is neither outstandingly good nor bad

    RandomUtils.useTestSeed();
    Splitter onComma = Splitter.on(",");

    // read the data
    List<String> raw = Resources.readLines(Resources.getResource("iris.csv"), Charsets.UTF_8);

    // holds features
    List<Vector> data = Lists.newArrayList();

    // holds target variable
    List<Integer> target = Lists.newArrayList();

    // for decoding target values
    Dictionary dict = new Dictionary();

    // for permuting data later
    List<Integer> order = Lists.newArrayList();

    for (String line : raw.subList(1, raw.size())) {
        // order gets a list of indexes
        order.add(order.size());

        // parse the predictor variables
        Vector v = new DenseVector(5);
        v.set(0, 1);
        int i = 1;
        Iterable<String> values = onComma.split(line);
        for (String value : Iterables.limit(values, 4)) {
            v.set(i++, Double.parseDouble(value));
        }
        data.add(v);

        // and the target
        target.add(dict.intern(Iterables.get(values, 4)));
    }

    // randomize the order ... original data has each species all together
    // note that this randomization is deterministic
    Random random = RandomUtils.getRandom();
    Collections.shuffle(order, random);

    // select training and test data
    List<Integer> train = order.subList(0, 100);
    List<Integer> test = order.subList(100, 150);
    logger.warn("Training set = {}", train);
    logger.warn("Test set = {}", test);

    // now train many times and collect information on accuracy each time
    int[] correct = new int[test.size() + 1];
    for (int run = 0; run < 200; run++) {
        OnlineLogisticRegression lr = new OnlineLogisticRegression(3, 5, new L2(1));
        // 30 training passes should converge to > 95% accuracy nearly always but never to 100%
        for (int pass = 0; pass < 30; pass++) {
            Collections.shuffle(train, random);
            for (int k : train) {
                lr.train(target.get(k), data.get(k));
            }
        }

        // check the accuracy on held out data
        int x = 0;
        int[] count = new int[3];
        for (Integer k : test) {
            Vector vt = lr.classifyFull(data.get(k));
            int r = vt.maxValueIndex();
            count[r]++;
            x += r == target.get(k) ? 1 : 0;
        }
        correct[x]++;

        if (run == 199) {

            Vector v = new DenseVector(5);
            v.set(0, 1);
            int i = 1;
            Iterable<String> values = onComma.split("6.0,2.7,5.1,1.6,versicolor");
            for (String value : Iterables.limit(values, 4)) {
                v.set(i++, Double.parseDouble(value));
            }

            Vector vt = lr.classifyFull(v);
            for (String value : dict.values()) {
                System.out.println("target:" + value);
            }
            int t = dict.intern(Iterables.get(values, 4));

            int r = vt.maxValueIndex();
            boolean flag = r == t;
            lr.close();

            Closer closer = Closer.create();

            try {
                FileOutputStream byteArrayOutputStream = closer
                        .register(new FileOutputStream(new File("model.txt")));
                DataOutputStream dataOutputStream = closer
                        .register(new DataOutputStream(byteArrayOutputStream));
                PolymorphicWritable.write(dataOutputStream, lr);
            } finally {
                closer.close();
            }
        }
    }

    // verify we never saw worse than 95% correct,
    for (int i = 0; i < Math.floor(0.95 * test.size()); i++) {
        System.out.println(String.format("%d trials had unacceptable accuracy of only %.0f%%: ", correct[i],
                100.0 * i / test.size()));
    }
    // nor perfect
    System.out.println(String.format("%d trials had unrealistic accuracy of 100%%", correct[test.size() - 1]));
}

From source file:org.jnario.lib.JnarioIterableExtensions.java

/**
  * Returns the element at the specified position in the arguments.
  */* www. j  a v  a2 s  . co m*/
  * @param index index of the element to return
  * @return the element at the specified position in this argument list
  * @throws IndexOutOfBoundsException if the index is out of range
  *         (<tt>index &lt; 0 || index &gt;= size()</tt>)
  */
public static <T> T get(Iterable<T> iterable, int index) {
    return Iterables.get(iterable, index);
}

From source file:org.jclouds.googlecomputeengine.domain.SlashEncodedIds.java

public static SlashEncodedIds fromSlashEncoded(String id) {
    Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, "id"));
    checkArgument(Iterables.size(parts) == 2, "id must be in format firstId/secondId");
    return new SlashEncodedIds(Iterables.get(parts, 0), Iterables.get(parts, 1));
}

From source file:org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndId.java

public static ZoneAndId fromSlashEncoded(String id) {
    Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, "id"));
    checkArgument(Iterables.size(parts) == 2, "id must be in format zoneId/id");
    return new ZoneAndId(Iterables.get(parts, 0), Iterables.get(parts, 1));
}

From source file:org.jclouds.elb.domain.regionscoped.RegionAndName.java

public static RegionAndName fromSlashEncoded(String name) {
    Iterable<String> parts = Splitter.on('/').split(checkNotNull(name, "name"));
    checkArgument(Iterables.size(parts) == 2, "name must be in format regionId/name");
    return new RegionAndName(Iterables.get(parts, 0), Iterables.get(parts, 1));
}

From source file:org.jclouds.joyent.sdc.v6_5.domain.datacenterscoped.DatacenterAndId.java

public static DatacenterAndId fromSlashEncoded(String id) {
    Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, "id"));
    checkArgument(Iterables.size(parts) == 2, "id must be in format datacenterId/id");
    return new DatacenterAndId(Iterables.get(parts, 0), Iterables.get(parts, 1));
}

From source file:org.apache.jclouds.profitbricks.rest.domain.zonescoped.DataCenterAndId.java

public static DataCenterAndId fromSlashEncoded(String id) {
    Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, "id"));
    checkArgument(Iterables.size(parts) == 2, "id must be in format dataCenterId/id");
    return new DataCenterAndId(Iterables.get(parts, 0), Iterables.get(parts, 1));
}

From source file:org.jclouds.azurecompute.arm.domain.RegionAndId.java

public static RegionAndId fromSlashEncoded(String id) {
    Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, "id"));
    checkArgument(Iterables.size(parts) == 2, "id must be in format regionId/id");
    return new AutoValue_RegionAndId(Iterables.get(parts, 0), Iterables.get(parts, 1));
}

From source file:org.apache.whirr.service.puppet.predicates.PuppetPredicates.java

public static Predicate<String> isFirstPuppetRoleIn(final Iterable<String> roles) {
    return new Predicate<String>() {

        @Override/* w  ww .j  a v a2s  . co m*/
        public boolean apply(String arg0) {
            return Iterables
                    .get(Iterables.filter(roles, Predicates.containsPattern("^" + PUPPET_ROLE_PREFIX + arg0)),
                            0)
                    .equals(PUPPET_ROLE_PREFIX + arg0);
        }

        @Override
        public String toString() {
            return "isFirstPuppetRoleIn(" + roles + ")";

        }
    };

}