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:com.act.lcms.db.analysis.IonDetectionAnalysis.java

public static void main(String[] args) throws Exception {

    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());// w  w  w  .  ja  va2  s  .c  o  m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_LCMS_FILE_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);

    // Get include and excluse ions from command line
    Set<String> includeIons;
    if (cl.hasOption(OPTION_INCLUDE_IONS)) {
        includeIons = new HashSet<>(Arrays.asList(cl.getOptionValues(OPTION_INCLUDE_IONS)));
        LOGGER.info("Including ions in search: %s", StringUtils.join(includeIons, ", "));
    } else {
        includeIons = new HashSet<>();
        includeIons.add(DEFAULT_ION);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        File inputPredictionCorpus = new File(cl.getOptionValue(OPTION_INPUT_PREDICTION_CORPUS));

        Map<Double, Set<Pair<String, String>>> massChargeToChemicalAndIon = constructMassChargeToChemicalIonsFromInputFile(
                inputPredictionCorpus, includeIons, cl.hasOption(OPTION_LIST_OF_INCHIS_INPUT_FILE));

        Pair<Set<Pair<String, Double>>, Map<String, Double>> values = constructFakeNameToMassChargeAndSetOfMassChargePairs(
                massChargeToChemicalAndIon.keySet());
        Set<Pair<String, Double>> searchMZs = values.getLeft();
        Map<String, Double> chemIDToMassCharge = values.getRight();

        LOGGER.info("The number of mass charges are: %d", searchMZs.size());

        Map<ScanData.KIND, List<LCMSWell>> wellTypeToLCMSWells = readInputExperimentalSetup(db,
                new File(cl.getOptionValue(OPTION_INPUT_POSITIVE_AND_NEGATIVE_CONTROL_WELLS_FILE)));

        // Get experimental setup ie. positive and negative wells from config file
        List<LCMSWell> positiveWells = wellTypeToLCMSWells.get(ScanData.KIND.POS_SAMPLE);
        List<LCMSWell> negativeWells = wellTypeToLCMSWells.get(ScanData.KIND.NEG_CONTROL);

        LOGGER.info("Number of positive wells is: %d", positiveWells.size());
        LOGGER.info("Number of negative wells is: %d", negativeWells.size());

        HashMap<Integer, Plate> plateCache = new HashMap<>();
        String outputPrefix = cl.getOptionValue(OPTION_OUTPUT_PREFIX);

        IonDetectionAnalysis<LCMSWell> ionDetectionAnalysis = new IonDetectionAnalysis<LCMSWell>(lcmsDir,
                positiveWells, negativeWells, plottingDirectory, plateCache, searchMZs, db);

        ionDetectionAnalysis.runLCMSMiningAnalysisAndPlotResults(chemIDToMassCharge, massChargeToChemicalAndIon,
                outputPrefix, cl.hasOption(OPTION_NON_REPLICATE_ANALYSIS));
    }
}

From source file:de.unisb.cs.st.javaslicer.slicing.Slicer.java

public static void main(String[] args) throws InterruptedException {
    Options options = createOptions();//www  .j ava2 s.c  om
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine;

    try {
        cmdLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println("Error parsing the command line arguments: " + e.getMessage());
        return;
    }

    if (cmdLine.hasOption('h')) {
        printHelp(options, System.out);
        System.exit(0);
    }

    String[] additionalArgs = cmdLine.getArgs();
    if (additionalArgs.length != 2) {
        printHelp(options, System.err);
        System.exit(-1);
    }
    // ?? 1. ? 2.?
    File traceFile = new File(additionalArgs[0]);
    String slicingCriterionString = additionalArgs[1];

    Long threadId = null;
    if (cmdLine.hasOption('t')) { // the interesting thread id for slicing 
        try {
            threadId = Long.parseLong(cmdLine.getOptionValue('t'));
        } catch (NumberFormatException e) {
            System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t'));
            System.exit(-1);
        }
    }

    TraceResult trace;
    try {
        trace = TraceResult.readFrom(traceFile);
    } catch (IOException e) {
        System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e);
        System.exit(-1);
        return;
    }

    List<SlicingCriterion> sc = null; // a list contains the instruction's info corresponds to the slicing criterion
    //slicingCriterionString get from additionalArgs[1]
    try {
        sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses());
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing slicing criterion: " + e.getMessage());
        System.exit(-1);
        return;
    }

    List<ThreadId> threads = trace.getThreads(); // the threads that generate the traces
    if (threads.size() == 0) {
        System.err.println("The trace file contains no tracing information.");
        System.exit(-1);
    }

    // threadID is used to mark the interesting thread
    ThreadId tracing = null;
    for (ThreadId t : threads) {
        if (threadId == null) {
            if ("main".equals(t.getThreadName())
                    && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId()))
                tracing = t;
        } else if (t.getJavaThreadId() == threadId.longValue()) {
            tracing = t;
        }
    }

    if (tracing == null) {
        System.err.println(threadId == null ? "Couldn't find the main thread."
                : "The thread you specified was not found.");
        System.exit(-1);
        return;
    }

    long startTime = System.nanoTime();
    Slicer slicer = new Slicer(trace);
    if (cmdLine.hasOption("progress")) // the parameter process indicates that we need to monitor the process of slicing
        slicer.addProgressMonitor(new ConsoleProgressMonitor());
    boolean multithreaded;
    if (cmdLine.hasOption("multithreaded")) {
        String multithreadedStr = cmdLine.getOptionValue("multithreaded");
        multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr));
    } else {
        multithreaded = Runtime.getRuntime().availableProcessors() > 1;
    }

    boolean warnUntracedMethods = cmdLine.hasOption("warn-untraced"); // give some warns when encounters untraced functions

    //sliceInstructionCollector implements the interface slice visitor, which travel the dependence graph
    SliceInstructionsCollector collector = new SliceInstructionsCollector(); // the collector is used to collect the instructions in the dependence graph according to the slice criterion. 
    slicer.addSliceVisitor(collector);
    // zhushi by yhb

    if (warnUntracedMethods)
        slicer.addUntracedCallVisitor(new PrintUniqueUntracedMethods()); // the user need the untraced function info, so add untraced call visitor

    slicer.process(tracing, sc, multithreaded); //----------------------the key process of slicing!!!
    Set<InstructionInstance> slice = collector.getDynamicSlice(); // return the slice result from the collector
    long endTime = System.nanoTime();

    Instruction[] sliceArray = slice.toArray(new Instruction[slice.size()]); // convert the set to array
    Arrays.sort(sliceArray); // in order to ensure the sequence of dynamic execution

    // show the slicing result
    System.out.println("The dynamic slice for criterion " + sc + ":");
    for (Instruction insn : sliceArray) {
        System.out.format((Locale) null, "%s.%s:%d %s%n", insn.getMethod().getReadClass().getName(),
                insn.getMethod().getName(), insn.getLineNumber(), insn.toString());
    }
    System.out.format((Locale) null, "%nSlice consists of %d bytecode instructions.%n", sliceArray.length);
    System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime));
}

From source file:org.ptm.translater.App.java

public static void main(String... args) {
    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    ctx.load("file:src/main/resources/spring/datasource.xml");
    ctx.refresh();//from   w  w w  . j av a 2  s .  c  om

    GenericXmlApplicationContext ctx2 = new GenericXmlApplicationContext();
    ctx2.load("file:src/main/resources/spring/datasource2.xml");
    ctx2.refresh();

    ArchiveDao archiveDao = ctx.getBean("archiveDao", ArchiveDao.class);
    List<Archive> archives = archiveDao.findAll();

    UserDao userDao = ctx2.getBean("userDao", UserDao.class);
    TagDao tagDao = ctx2.getBean("tagDao", TagDao.class);
    PhotoDao photoDao = ctx2.getBean("photoDao", PhotoDao.class);

    List<Tag> tagz = tagDao.findAll();
    Map<String, Long> hashTags = new HashMap<String, Long>();
    for (Tag tag : tagz)
        hashTags.put(tag.getName(), tag.getId());

    MongoCache cache = new MongoCache();
    Calendar calendar = Calendar.getInstance();

    Map<String, String> associates = new HashMap<String, String>();

    for (Archive archive : archives) {
        AppUser appUser = new AppUser();
        appUser.setName(archive.getName());
        appUser.setEmail(archive.getUid() + "@mail.th");
        appUser.setPassword("123456");

        Role role = new Role();
        role.setRoleId("ROLE_USER");
        appUser.setRole(role);

        userDao.save(appUser);
        System.out.println("\tCreate user " + appUser);

        for (Photo photo : archive.getPhotos()) {
            // ?  ??? 
            if (cache.contains(photo.getUid()))
                continue;

            System.out.println("\tNew photo");
            org.ptm.translater.ch2.domain.Photo photo2 = new org.ptm.translater.ch2.domain.Photo();
            photo2.setAppUser(appUser);
            photo2.setName(photo.getTitle());
            photo2.setLicense((byte) 7);
            photo2.setDescription(photo.getDescription());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                calendar.setTime(sdf.parse(photo.getTaken()));

                if (calendar.get(Calendar.YEAR) != 0 && calendar.get(Calendar.YEAR) > 1998)
                    continue;
                photo2.setYear(calendar.get(Calendar.YEAR));
                photo2.setMonth(calendar.get(Calendar.MONTH) + 1);
                photo2.setDay(calendar.get(Calendar.DAY_OF_MONTH));
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (photo.getLongitude() != null && photo.getLongitude().length() > 0) {
                //                    String key = photo.getLongitude()+"#"+photo.getLatitude();
                photo2.setLatitude(photo.getLatitude());
                photo2.setLongitude(photo.getLongitude());
                //                    if (associates.containsKey(key)) {
                //                        photo2.setAddress(associates.get(key));
                //                    } else {
                //                        Geocoder geocoder = new Geocoder();
                //                        GeocoderRequestBuilder geocoderRequest = new GeocoderRequestBuilder();
                //                        GeocoderRequest request =
                //                            geocoderRequest.setLocation(new LatLng(photo.getLongitude(), photo.getLatitude())).getGeocoderRequest();
                //
                //                        GeocodeResponse response = geocoder.geocode(request);
                //                        if (response.getResults().size() > 0) {
                //                            photo2.setAddress(response.getResults().get(0).getFormattedAddress());
                //                        }
                //                        try { Thread.sleep(2000); } catch (InterruptedException ex) { ex.printStackTrace(); }
                //                    }
            }

            System.out.println("\tFind tags");
            Set<Tag> tags = new HashSet<Tag>();
            for (org.ptm.translater.ch1.domain.Tag tag : photo.getTags()) {
                Tag item = new Tag();
                item.setName(tag.getName());
                if (hashTags.containsKey(tag.getName())) {
                    item.setId(hashTags.get(tag.getName()));
                } else {
                    tagDao.save(item);
                    hashTags.put(item.getName(), item.getId());
                }
                System.out.println("\t\tinit tag " + tag.getName());
                tags.add(item);
            }
            photo2.setTags(tags);
            System.out.println("\tFind " + tags.size() + " tags");
            photoDao.save(photo2);
            System.out.println("\tSave photo");

            Imaginator img = new Imaginator();
            img.setFolder(photo2.getId().toString());
            img.setPath();

            for (PhotoSize ps : photo.getSizes()) {
                if (ps.getLabel().equals("Original")) {
                    img.setImage(ps.getSource());
                    break;
                }
            }
            img.generate();
            System.out.println("\tGenerate image of photo");
            img = null;
            cache.create(photo.getUid());
            cache.create(photo2);

            System.out.println("Generate: " + photo2);
        }
    }
}

From source file:gr.iti.mklab.bubing.parser.ITIHTMLParser.java

public static void main(String arg[]) throws IllegalArgumentException, IOException, URISyntaxException,
        JSAPException, NoSuchAlgorithmException {

    final SimpleJSAP jsap = new SimpleJSAP(ITIHTMLParser.class.getName(),
            "Produce the digest of a page: the page is downloaded or passed as argument by specifying a file",
            new Parameter[] {
                    new UnflaggedOption("url", JSAP.STRING_PARSER, JSAP.REQUIRED, "The url of the page."),
                    new Switch("crossAuthorityDuplicates", 'c', "cross-authority-duplicates"),
                    new FlaggedOption("charBufferSize", JSAP.INTSIZE_PARSER, Integer.toString(CHAR_BUFFER_SIZE),
                            JSAP.NOT_REQUIRED, 'b', "buffer",
                            "The size of the parser character buffer (0 for dynamic sizing)."),
                    new FlaggedOption("file", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'f',
                            "file", "The page to be processed."),
                    new FlaggedOption("digester", JSAP.STRING_PARSER, "MD5", JSAP.NOT_REQUIRED, 'd', "digester",
                            "The digester to be used.") });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        System.exit(1);// www .  j  ava  2  s .  c  o m

    final String url = jsapResult.getString("url");
    final String digester = jsapResult.getString("digester");
    final boolean crossAuthorityDuplicates = jsapResult.userSpecified("crossAuthorityDuplicates");
    final int charBufferSize = jsapResult.getInt("charBufferSize");

    final ITIHTMLParser<Void> htmlParser = new ITIHTMLParser<Void>(BinaryParser.forName(digester),
            (TextProcessor<Void>) null, crossAuthorityDuplicates, charBufferSize);
    final SetLinkReceiver linkReceiver = new SetLinkReceiver();
    final byte[] digest;

    if (!jsapResult.userSpecified("file")) {
        final URI uri = new URI(url);
        final HttpGet request = new HttpGet(uri);
        request.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
        digest = htmlParser.parse(uri, HttpClients.createDefault().execute(request), linkReceiver);
    } else {
        final String file = jsapResult.getString("file");
        String content = IOUtils.toString(new InputStreamReader(new FileInputStream(file)));
        digest = htmlParser.parse(BURL.parse(url), new StringHttpMessages.HttpResponse(content), linkReceiver);
    }

    System.out.println("DigestHexString: " + Hex.encodeHexString(digest));
    System.out.println("Links: " + linkReceiver.urls);

    Set<String> urlStrings = new ObjectOpenHashSet<String>();
    for (URI link : linkReceiver.urls)
        urlStrings.add(link.toString());
    if (urlStrings.size() != linkReceiver.urls.size())
        System.out.println(
                "There are " + linkReceiver.urls.size() + " URIs but " + urlStrings.size() + " strings");

}

From source file:edu.umass.cs.reconfiguration.ReconfigurableNode.java

/**
 * {@code args} contains a list of app arguments followed by a list of
 * active or reconfigurator node IDs at the end. The string "start all" is
 * accepted as a proxy for the list of all nodes if the socket addresses of
 * all nodes are on the local machine./*w ww  .  j a  v  a  2s  . c om*/
 * 
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Config.register(args);
    PaxosConfig.sanityCheck();
    ReconfigurationConfig.setConsoleHandler();
    if (Config.getGlobalBoolean(PC.EMULATE_DELAYS))
        AbstractPacketDemultiplexer.emulateDelays();

    if (args.length == 0)
        throw new RuntimeException(
                "At least one node ID must be specified as a command-line argument for starting "
                        + ReconfigurableNode.class);
    ReconfigurableNodeConfig<String> nodeConfig = new DefaultNodeConfig<String>(PaxosConfig.getActives(),
            ReconfigurationConfig.getReconfigurators());
    PaxosConfig.sanityCheck(nodeConfig);
    Set<String> servers = getAllNodes(args);

    if (clear) {
        for (String id : servers)
            try {
                SQLReconfiguratorDB.dropState(id,
                        new ConsistentReconfigurableNodeConfig<String>(new DefaultNodeConfig<String>(
                                PaxosConfig.getActives(), ReconfigurationConfig.getReconfigurators())));
            } catch (Exception e) {
                /* ignore all exceptions as they correspond to non-local
                 * nodes */
                e.printStackTrace();
            }
        return;
    }

    String sysPropAppArgsAsString = System.getProperty(ReconfigurationConfig.CommandArgs.appArgs.toString());
    // append cmdline args to system property based args
    String cmdlineAppArgs = getAppArgs(args);
    String[] appArgs = ((sysPropAppArgsAsString != null ? sysPropAppArgsAsString : "") + " " + cmdlineAppArgs)
            .split("\\s");
    int numServers = servers.size();
    if (numServers == 0)
        throw new RuntimeException("No valid server names supplied");
    System.out.print("Initializing gigapaxos server" + (numServers > 1 ? "s" : "") + " [ ");
    for (String node : servers) {
        System.out
                .print(node + ":" + nodeConfig.getNodeAddress(node) + ":" + nodeConfig.getNodePort(node) + " ");
        new DefaultReconfigurableNode(node,
                // must use a different nodeConfig for each
                new DefaultNodeConfig<String>(PaxosConfig.getActives(),
                        ReconfigurationConfig.getReconfigurators()),
                appArgs, false);
    }
    System.out.println("]; server" + (numServers > 1 ? "s" : "") + servers + " ready");
}

From source file:de.clusteval.serverclient.BackendClient.java

/**
 * @param args//from  www  .  j  av  a2 s .  c  o  m
 *            Command line parameters for the backend client (see
 *            {@link #params}).
 * @throws IOException
 */
@SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
    try {
        CommandLine params = parseParams(args, false);

        if (params.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("clustevalClient", clientCLIOptions);
            System.exit(0);
        }

        if (params.hasOption("version")) {
            System.out.println(VERSION);
            System.exit(0);
        }

        initLogging(params);

        Logger log = LoggerFactory.getLogger(BackendClient.class);

        System.out.println("Starting clusteval client");
        System.out.println(VERSION);
        System.out.println("=========================");

        // if command line arguments (except connection parameters) are
        // passed, we do not start a console
        Set<String> paramKeys = new HashSet<String>();
        @SuppressWarnings("unchecked")
        Iterator<Option> it = params.iterator();
        while (it.hasNext()) {
            paramKeys.add(it.next().getOpt());
        }

        paramKeys.remove("ip");
        paramKeys.remove("port");
        paramKeys.remove("clientId");
        if (paramKeys.size() > 0) {
            try {
                new BackendClient(args);
            } catch (Exception e) {
            }
        } else {
            String clientId;
            if (params.hasOption("clientId"))
                clientId = params.getOptionValue("clientId");
            else
                // parse args because of possible connection parameters
                clientId = new BackendClient(args).clientId;

            reader = new ConsoleReader();

            List<Completer> completers = new LinkedList<Completer>();
            completers.add(new BackendClientCompleter(clientId, args));

            String ip = params.hasOption("ip") ? params.getOptionValue("ip") : "localhost";
            String port = params.hasOption("port") ? params.getOptionValue("port") : "1099";

            setDefaultPromptAndCompleter(ip, port, completers);

            String line;

            while ((line = reader.readLine()) != null) {

                if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) {
                    break;
                }

                boolean connectException = false;
                do {
                    try {
                        new BackendClient(
                                ArraysExt.merge(args, ("-clientId " + clientId + " -" + line).split(" ")));
                        connectException = false;
                    } catch (ConnectException e) {
                        e.printStackTrace();
                        connectException = true;
                    } catch (Exception e) {
                        log.warn(e.getMessage());
                    }
                    Thread.sleep(1000);
                } while (connectException);
                // }
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("clustevalClient",
                "Invoking this client without any parameters will open a shell with tab-completion.",
                clientCLIOptions, "", true);
    } catch (Throwable t) {
        // t.printStackTrace();
    }
}

From source file:com.act.biointerpretation.ProductExtractor.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(ProductExtractor.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    String orgPrefix = cl.getOptionValue(OPTION_ORGANISM_PREFIX);
    LOGGER.info("Using organism prefix %s", orgPrefix);

    MongoDB db = new MongoDB(DEFAULT_DB_HOST, DEFAULT_DB_PORT, cl.getOptionValue(OPTION_DB_NAME));

    Map<Long, String> validOrganisms = new TreeMap<>();
    DBIterator orgIter = db.getDbIteratorOverOrgs();
    Organism o = null;/*from  w  w w.j a va 2s.co m*/
    while ((o = db.getNextOrganism(orgIter)) != null) {
        if (!o.getName().isEmpty() && o.getName().startsWith(orgPrefix)) {
            validOrganisms.put(o.getUUID(), o.getName());
        }
    }

    LOGGER.info("Found %d valid organisms", validOrganisms.size());

    Set<Long> productIds = new TreeSet<>(); // Use something with implicit ordering we can traverse in order.
    DBIterator reactionIterator = db.getIteratorOverReactions();
    Reaction r;
    while ((r = db.getNextReaction(reactionIterator)) != null) {
        Set<JSONObject> proteins = r.getProteinData();
        boolean valid = false;
        for (JSONObject j : proteins) {
            if (j.has("organism") && validOrganisms.containsKey(j.getLong("organism"))) {
                valid = true;
                break;
            } else if (j.has("organisms")) {
                JSONArray organisms = j.getJSONArray("organisms");
                for (int i = 0; i < organisms.length(); i++) {
                    if (validOrganisms.containsKey(organisms.getLong(i))) {
                        valid = true;
                        break;
                    }
                }
            }
        }

        if (valid) {
            for (Long id : r.getProducts()) {
                productIds.add(id);
            }
            for (Long id : r.getProductCofactors()) {
                productIds.add(id);
            }
        }
    }

    LOGGER.info("Found %d valid product ids for '%s'", productIds.size(), orgPrefix);
    PrintWriter writer = cl.hasOption(OPTION_OUTPUT_FILE)
            ? new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))
            : new PrintWriter(System.out);

    for (Long id : productIds) {
        Chemical c = db.getChemicalFromChemicalUUID(id);
        String inchi = c.getInChI();
        if (inchi.startsWith("InChI=") && !inchi.startsWith("InChI=/FAKE")) {
            writer.println(inchi);
        }
    }

    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        writer.close();
    }
    LOGGER.info("Done.");
}

From source file:com.music.tools.ScaleTester.java

public static void main(String[] args) {
    System.out.println(//from  ww  w  .j  a v a 2s  .  c o  m
            "Usage: java ScaleTester <fundamental frequency> <chromatic scale size> <scale size> <use ET>");
    final AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true);
    try {
        fundamentalFreq = getArgument(args, 0, FUNDAMENTAL_FREQUENCY, Double.class);
        int pitchesInChromaticScale = getArgument(args, 1, CHROMATIC_SCALE_SILZE, Integer.class);

        List<Double> harmonicFrequencies = new ArrayList<>();
        List<String> ratios = new ArrayList<>();
        Set<Double> frequencies = new HashSet<Double>();
        frequencies.add(fundamentalFreq);
        int octaveMultiplier = 2;
        for (int i = 2; i < 100; i++) {
            // Exclude the 7th harmonic TODO exclude the 11th as well?
            // http://www.phy.mtu.edu/~suits/badnote.html
            if (i % 7 == 0) {
                continue;
            }
            double actualFreq = fundamentalFreq * i;
            double closestTonicRatio = actualFreq / (fundamentalFreq * octaveMultiplier);
            if (closestTonicRatio < 1 || closestTonicRatio > 2) {
                octaveMultiplier *= 2;
            }
            double closestTonic = actualFreq - actualFreq % (fundamentalFreq * octaveMultiplier);
            double normalizedFreq = fundamentalFreq * (actualFreq / closestTonic);

            harmonicFrequencies.add(actualFreq);
            frequencies.add(normalizedFreq);
            if (frequencies.size() == pitchesInChromaticScale) {
                break;
            }
        }

        System.out.println("Harmonic (overtone) frequencies: " + harmonicFrequencies);
        System.out.println("Transposed harmonic frequencies: " + frequencies);

        List<Double> chromaticScale = new ArrayList<>(frequencies);
        Collections.sort(chromaticScale);

        // find the "perfect" interval (e.g. perfect fifth)
        int perfectIntervalIndex = 0;
        int idx = 0;
        for (Iterator<Double> it = chromaticScale.iterator(); it.hasNext();) {
            Double noteFreq = it.next();
            long[] fraction = findCommonFraction(noteFreq / fundamentalFreq);
            fractionCache.put(noteFreq, fraction);
            if (fraction[0] == 3 && fraction[1] == 2) {
                perfectIntervalIndex = idx;
                System.out.println("Perfect interval (3/2) idx: " + perfectIntervalIndex);
            }
            idx++;
            ratios.add(Arrays.toString(fraction));
        }
        System.out.println("Ratios to fundemental frequency: " + ratios);

        if (getBooleanArgument(args, 4, USE_ET)) {
            chromaticScale = temper(chromaticScale);
        }

        System.out.println();
        System.out.println("Chromatic scale: " + chromaticScale);

        Set<Double> scaleSet = new HashSet<Double>();
        scaleSet.add(chromaticScale.get(0));
        idx = 0;
        List<Double> orderedInCircle = new ArrayList<>();
        // now go around the circle of perfect intervals and put the notes
        // in order
        while (orderedInCircle.size() < chromaticScale.size()) {
            orderedInCircle.add(chromaticScale.get(idx));
            idx += perfectIntervalIndex;
            idx = idx % chromaticScale.size();
        }
        System.out.println("Pitches Ordered in circle of perfect intervals: " + orderedInCircle);

        List<Double> scale = new ArrayList<Double>(scaleSet);
        int currentIdxInCircle = orderedInCircle.size() - 1; // start with
                                                             // the last
                                                             // note in the
                                                             // circle
        int scaleSize = getArgument(args, 3, SCALE_SIZE, Integer.class);
        while (scale.size() < scaleSize) {
            double pitch = orderedInCircle.get(currentIdxInCircle % orderedInCircle.size());
            if (!scale.contains(pitch)) {
                scale.add(pitch);
            }
            currentIdxInCircle++;
        }
        Collections.sort(scale);

        System.out.println("Scale: " + scale);

        SourceDataLine line = AudioSystem.getSourceDataLine(af);
        line.open(af);
        line.start();

        Double[] scaleFrequencies = scale.toArray(new Double[scale.size()]);

        // first play the whole scale
        WaveMelodyGenerator.playScale(line, scaleFrequencies);
        // then generate a random melody in the scale
        WaveMelodyGenerator.playMelody(line, scaleFrequencies);

        line.drain();
        line.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.glaf.core.util.StringTools.java

public static void main(String[] args) {
    String text = "123,234,345,567,789";
    List<String> rows = StringTools.split(text, ",");
    System.out.println(rows.get(2));
    System.out.println(rows);//from   www  .  j  ava  2  s .c  o m
    for (int i = 0, len = rows.size(); i < len; i++) {
        System.out.println(rows.get(i));
    }

    Set<String> x = new HashSet<String>();
    for (int i = 0; i < 9999; i++) {
        String str = StringTools.random();
        x.add(str);
        System.out.println(str);
    }
    System.out.println("size=" + x.size());

    Random random = new Random();

    for (int i = 1; i < 100; i++) {
        int k = Math.abs(random.nextInt(9999));
        int a = String.valueOf(k).length();
        int b = String.valueOf(9999).length();
        System.out.println("a=" + a);
        System.out.println("b=" + b);
        String xx = "";
        if (a != b) {
            for (int j = 0; j < (b - a); j++) {
                xx = "0" + xx;
            }
        }
        xx = xx + k;
        System.out.println(xx);
    }

    System.out.println(toUnderLineName("ISOCertifiedStaff"));
    System.out.println(toUnderLineName("CertifiedStaff"));
    System.out.println(toUnderLineName("UserID"));
    System.out.println(toCamelCase("iso_certified_staff"));
    System.out.println(toCamelCase("certified_staff"));
    System.out.println(toCamelCase("user_id"));
}

From source file:edu.cuhk.hccl.evaluation.EvaluationApp.java

public static void main(String[] args) throws IOException, TasteException {
    File realFile = new File(args[0]);
    File estimateFile = new File(args[1]);

    // Build real-rating map
    Map<String, long[]> realMap = buildRatingMap(realFile);

    // Build estimate-rating map
    Map<String, long[]> estimateMap = buildRatingMap(estimateFile);

    // Compare realMap with estimateMap
    Map<Integer, List<Double>> realList = new HashMap<Integer, List<Double>>();
    Map<Integer, List<Double>> estimateList = new HashMap<Integer, List<Double>>();

    // Use set to store non-duplicate pairs only
    Set<String> noRatingList = new HashSet<String>();

    for (String pair : realMap.keySet()) {
        long[] realRatings = realMap.get(pair);
        long[] estimateRatings = estimateMap.get(pair);

        if (realRatings == null || estimateRatings == null)
            continue;

        for (int i = 0; i < realRatings.length; i++) {
            long real = realRatings[i];
            long estimate = estimateRatings[i];

            // continue if the aspect rating can not be estimated due to incomplete reviews
            if (estimate <= 0) {
                noRatingList.add(pair.replace("@", "\t"));
                continue;
            }//from   w w  w . ja va  2 s.c o  m

            if (real > 0 && estimate > 0) {
                if (!realList.containsKey(i))
                    realList.put(i, new ArrayList<Double>());

                realList.get(i).add((double) real);

                if (!estimateList.containsKey(i))
                    estimateList.put(i, new ArrayList<Double>());

                estimateList.get(i).add((double) estimate);
            }
        }
    }

    System.out.println("[INFO] RMSE, MAE for estimate ratings: ");
    System.out.println("------------------------------");
    System.out.println("Index \t RMSE \t MAE");
    for (int i = 1; i < 6; i++) {
        double rmse = Metric.computeRMSE(realList.get(i), estimateList.get(i));
        double mae = Metric.computeMAE(realList.get(i), estimateList.get(i));

        System.out.printf("%d \t %.3f \t %.3f \n", i, rmse, mae);
    }

    System.out.println("------------------------------");

    if (noRatingList.size() > 0) {
        String noRatingFileName = "evaluation-no-ratings.txt";
        FileUtils.writeLines(new File(noRatingFileName), noRatingList, false);

        System.out.println("[INFO] User-item pairs with no ratings are saved in file: " + noRatingFileName);
    } else {
        System.out.println("[INFO] All user-item pairs have ratings.");
    }
}