Example usage for java.io File isDirectory

List of usage examples for java.io File isDirectory

Introduction

In this page you can find the example usage for java.io File isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Tests whether the file denoted by this abstract pathname is a directory.

Usage

From source file:net.metanotion.sqlc.SQLC.java

public static void main(final String[] args) throws Exception {
    final String outputFolder = args[0];
    final String sqlFileName = args[1];

    Iterable<String> srcPathes = java.util.Collections.emptyList();
    if (args.length > 3) {
        srcPathes = java.util.Arrays.asList(args[3].split(File.pathSeparator));
    }//from   www. j  a v  a2  s.  c o m

    final ClassInfo ir = new ClassInfo();
    final File f = new File(sqlFileName);
    if (f.isDirectory()) {
        treewalk(ir, f, srcPathes);
    } else {
        processFile(ir, sqlFileName, srcPathes);
    }
    for (final SQLClass q : ir.classes) {
        SQLC.compile(outputFolder, q, ir.sm, srcPathes);
    }
    if (ir.implicits.size() > 0) {
        SQLC.generateStructs(outputFolder, ir.sm, ir.implicits, ir.implicitDocs, ir.implicitVisibility,
                srcPathes);
        SQLC.generateExceptions(outputFolder, ir.exceptions, ir.inheritanceMap, ir.implicits, ir.implicitDocs,
                ir.implicitVisibility);
    }
}

From source file:data_gen.Data_gen.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    long startTime = System.nanoTime();
    if (args.length < 2) {
        System.out.println("Usage:");
        System.out.println(//from   w  ww .j  av  a 2 s  .c  om
                "java -jar \"jarfile\" [Directory of text source folder] [Dierctory of configration file]"
                        + "\n");
        System.exit(0);
    }

    String Dir = args[0]; // get text source dir from user
    String config_dir = args[1];
    File folder = new File(Dir);
    if (folder.isDirectory() == false) {
        System.out.println("Text souce folder is not a Directory." + "\n");
        System.exit(0);
    }
    if (!config_dir.endsWith(".properties") && !config_dir.endsWith(".PROPERTIES")) {
        System.out.println("\n"
                + "There was error parsing dataset parameters from configuration file, make sure you have the 4 parameters specified and the right type of file"
                + "\n");
        System.exit(0);
    }

    listOfFiles = folder.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".txt");
        }
    });

    if (listOfFiles.length == 0) {
        System.out.println("Text source folder is empty ! Have at least one .txt file there" + "\n");
        System.exit(0);
    }

    System.out.println("\n");
    Parse_Document_values(config_dir);// parse config file to get class attribute values
    document_size = Docments_Total_size / documents_count; // to get each document size 
    max = (long) ((double) document_size * 1.8);
    min = (long) ((double) document_size * 0.2);

    schema_fields = Parse_Document_fields(config_dir);

    try {
        LineIterator it = FileUtils.lineIterator(listOfFiles[0]);

        while (it.hasNext()) {
            tx.add(it.nextLine());
        }
    } catch (NullPointerException | FileNotFoundException e) {
        System.out.println("The text source file could not be found." + "\n");
        System.exit(0);
    }

    new File(output_dir).mkdir();
    //////////////////////////////////////////////////////////////// build json or .dat
    ////////////////////////////////////////////////////////////////////     
    if (Default_DataSet_name.endsWith(".json")) {
        Build_json_file(config_dir, startTime);
    }

    if (Default_DataSet_name.endsWith(".dat")) {
        Build_dat_file(config_dir, startTime);
    }

    generate_xml();
    generate_field_map();

}

From source file:au.org.ala.layers.grid.GridClassBuilder.java

public static void main(String[] args) {

    logger.info("args[0]=diva grid input file (do not include .grd or .gri)\n\n");

    if (args.length > 0) {

        //remove existing
        try {/*from  w  w  w. j  a  v a 2  s.c o  m*/
            File f;

            if ((f = new File(args[0] + ".classes.json")).exists()) {
                f.delete();
            }

            if ((f = new File(args[0])).exists() && f.isDirectory()) {
                File[] fs = f.listFiles();
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].isFile()) {
                        fs[i].delete();
                    }
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        //build new
        try {
            buildFromGrid(args[0]);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

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

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*w ww.ja v a 2s  .  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\n", 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_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);
        StandardIonAnalysis analysis = new StandardIonAnalysis();
        HashMap<Integer, Plate> plateCache = new HashMap<>();

        String plateBarcode = cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE);
        String inputChemicals = cl.getOptionValue(OPTION_STANDARD_CHEMICAL);
        String medium = cl.getOptionValue(OPTION_MEDIUM);

        // If standard chemical is specified, do standard LCMS ion selection analysis
        if (inputChemicals != null && !inputChemicals.equals("")) {
            String[] chemicals;
            if (!inputChemicals.contains(",")) {
                chemicals = new String[1];
                chemicals[0] = inputChemicals;
            } else {
                chemicals = inputChemicals.split(",");
            }

            String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + CSV_FORMAT;
            String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);
            String[] headerStrings = { "Molecule", "Plate Bar Code", "LCMS Detection Results" };
            CSVPrinter printer = new CSVPrinter(new FileWriter(outAnalysis),
                    CSVFormat.DEFAULT.withHeader(headerStrings));

            for (String inputChemical : chemicals) {
                List<StandardWell> standardWells;

                Plate queryPlate = Plate.getPlateByBarcode(db,
                        cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                if (plateBarcode != null && medium != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlateAndMedium(db,
                            inputChemical, queryPlate.getId(), medium);
                } else if (plateBarcode != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db, inputChemical,
                            queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, inputChemical);
                }

                if (standardWells.size() == 0) {
                    throw new RuntimeException("Found no LCMS wells for " + inputChemical);
                }

                // Sort in descending order of media where MeOH and Water related media are promoted to the top and
                // anything derived from yeast media are demoted.
                Collections.sort(standardWells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        if (StandardWell.doesMediaContainYeastExtract(o1.getMedia())
                                && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) {
                            return 1;
                        } else {
                            return 0;
                        }
                    }
                });

                Map<StandardWell, StandardIonResult> wellToIonRanking = StandardIonAnalysis
                        .getBestMetlinIonsForChemical(inputChemical, lcmsDir, db, standardWells,
                                plottingDirectory);

                if (wellToIonRanking.size() != standardWells.size()
                        && !cl.hasOption(OPTION_OVERRIDE_NO_SCAN_FILE_FOUND)) {
                    throw new Exception("Could not find a scan file associated with one of the standard wells");
                }

                for (StandardWell well : wellToIonRanking.keySet()) {
                    LinkedHashMap<String, XZ> snrResults = wellToIonRanking.get(well).getAnalysisResults();

                    String snrRankingResults = "";
                    int numResultsToShow = 0;

                    Plate plateForWellToAnalyze = Plate.getPlateById(db, well.getPlateId());

                    for (Map.Entry<String, XZ> ionToSnrAndTime : snrResults.entrySet()) {
                        if (numResultsToShow > 3) {
                            break;
                        }

                        String ion = ionToSnrAndTime.getKey();
                        XZ snrAndTime = ionToSnrAndTime.getValue();

                        snrRankingResults += String.format(ion + " (%.2f SNR at %.2fs); ",
                                snrAndTime.getIntensity(), snrAndTime.getTime());
                        numResultsToShow++;
                    }

                    String[] resultSet = { inputChemical,
                            plateForWellToAnalyze.getBarcode() + " " + well.getCoordinatesString() + " "
                                    + well.getMedia() + " " + well.getConcentration(),
                            snrRankingResults };

                    printer.printRecord(resultSet);
                }
            }

            try {
                printer.flush();
                printer.close();
            } catch (IOException e) {
                System.err.println("Error while flushing/closing csv writer.");
                e.printStackTrace();
            }
        } else {
            // Get the set of chemicals that includes the construct and all it's intermediates
            Pair<ConstructEntry, List<ChemicalAssociatedWithPathway>> constructAndPathwayChems = analysis
                    .getChemicalsForConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));
            System.out.format("Construct: %s\n", constructAndPathwayChems.getLeft().getCompositionId());

            for (ChemicalAssociatedWithPathway pathwayChem : constructAndPathwayChems.getRight()) {
                System.out.format("  Pathway chem %s\n", pathwayChem.getChemical());

                // Get all the standard wells for the pathway chemicals. These wells contain only the
                // the chemical added with controlled solutions (ie no organism or other chemicals in the
                // solution)

                List<StandardWell> standardWells;

                if (plateBarcode != null) {
                    Plate queryPlate = Plate.getPlateByBarcode(db,
                            cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db,
                            pathwayChem.getChemical(), queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, pathwayChem.getChemical());
                }

                for (StandardWell wellToAnalyze : standardWells) {
                    List<StandardWell> negativeControls = analysis.getViableNegativeControlsForStandardWell(db,
                            wellToAnalyze);
                    Map<StandardWell, List<ScanFile>> allViableScanFiles = analysis
                            .getViableScanFilesForStandardWells(db, wellToAnalyze, negativeControls);

                    List<String> primaryStandardScanFileNames = new ArrayList<>();
                    for (ScanFile scanFile : allViableScanFiles.get(wellToAnalyze)) {
                        primaryStandardScanFileNames.add(scanFile.getFilename());
                    }
                    Plate plate = plateCache.get(wellToAnalyze.getPlateId());
                    if (plate == null) {
                        plate = Plate.getPlateById(db, wellToAnalyze.getPlateId());
                        plateCache.put(plate.getId(), plate);
                    }

                    System.out.format("    Standard well: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                            wellToAnalyze.getCoordinatesString(), wellToAnalyze.getChemical(),
                            wellToAnalyze.getMedia() == null ? ""
                                    : String.format(" in %s", wellToAnalyze.getMedia()),
                            wellToAnalyze.getConcentration() == null ? ""
                                    : String.format(" @ %s", wellToAnalyze.getConcentration()));
                    System.out.format("      Scan files: %s\n",
                            StringUtils.join(primaryStandardScanFileNames, ", "));

                    for (StandardWell negCtrlWell : negativeControls) {
                        plate = plateCache.get(negCtrlWell.getPlateId());
                        if (plate == null) {
                            plate = Plate.getPlateById(db, negCtrlWell.getPlateId());
                            plateCache.put(plate.getId(), plate);
                        }
                        List<String> negativeControlScanFileNames = new ArrayList<>();
                        for (ScanFile scanFile : allViableScanFiles.get(negCtrlWell)) {
                            negativeControlScanFileNames.add(scanFile.getFilename());
                        }

                        System.out.format("      Viable negative: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                                negCtrlWell.getCoordinatesString(), negCtrlWell.getChemical(),
                                negCtrlWell.getMedia() == null ? ""
                                        : String.format(" in %s", negCtrlWell.getMedia()),
                                negCtrlWell.getConcentration() == null ? ""
                                        : String.format(" @ %s", negCtrlWell.getConcentration()));
                        System.out.format("        Scan files: %s\n",
                                StringUtils.join(negativeControlScanFileNames, ", "));
                        // TODO: do something useful with the standard wells and their scan files, and then stop all the printing.
                    }
                }
            }
        }
    }
}

From source file:GenAppStoreSales.java

/**
 * Starting point for the demonstration application.
 * @throws IOException /*from w w w. j a  va  2  s  . c  o  m*/
 * 
 */
public static void main(String[] args) throws IOException {
    System.out.print("\nRefreshing Apple Store Reports...");

    // Init Calendars
    rollCalendar = Calendar.getInstance();
    updateRollCalendar();
    currentYear = rollCalendar.get(Calendar.YEAR);
    currentMonth = rollCalendar.get(Calendar.MONTH) + 1;
    currentDay = rollCalendar.get(Calendar.DATE);
    Calendar launchCalendar = Calendar.getInstance();
    int launchYear = 2013, launchMonth = 2, launchDay = 28; //Month from 0..11
    launchCalendar.set(launchYear, launchMonth, launchDay);
    /* Report Folders
     */
    currentPath = new File("").getAbsolutePath();
    String sourceName = "/sources";
    File sourceDir = new File(currentPath, sourceName);
    if (!sourceDir.isDirectory()) {
        if (!(new File(currentPath + sourceName)).mkdirs()) {
            System.out.println("[Error] Couldn't create 'source' folder.");
        }
    }
    sourcePath = sourceDir.getAbsolutePath();

    String chartName = "/charts";
    File chartDir = new File(currentPath, chartName);
    if (!chartDir.isDirectory()) {
        if (!(new File(currentPath + chartName)).mkdirs()) {
            System.out.println("[Error] Couldn't create 'chart' folder.");
        }
    }
    chartPath = chartDir.getAbsolutePath();

    String dateCode, reportName;

    // DAILY REPORT
    System.out.println("\n-> Daily reports");
    for (int d = 0; d < 14; d++) {
        rollCalendar.add(Calendar.DATE, -1);
        if (rollCalendar.compareTo(launchCalendar) <= 0)
            break;
        updateRollCalendar();
        dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
        reportName = "S_D_" + appID + "_" + dateCode + ".txt";
        autoingestionDownload(reportName, "Daily", dateCode);
    }
    printDatePeriod("DAILY", "report");

    // WEEKLY REPORT
    System.out.println("\n-> Weekly reports");
    rollCalendar = Calendar.getInstance();
    rollCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    pursuedDay = currentDay;
    pursuedMonth = currentMonth;
    pursuedYear = currentYear;
    for (int w = 0; w < 13; w++) {
        rollCalendar.add(Calendar.DATE, -7);
        if (rollCalendar.compareTo(launchCalendar) <= 0)
            break;
        updateRollCalendar();
        dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
        reportName = "S_W_" + appID + "_" + dateCode + ".txt";
        autoingestionDownload(reportName, "Weekly", dateCode);
    }
    printDatePeriod("WEEKLY", "report");

    // MONTHLY REPORTS
    System.out.println("\n-> Monthly reports");
    rollCalendar = Calendar.getInstance();
    pursuedDay = currentDay;
    pursuedMonth = currentMonth - 1;
    pursuedYear = currentYear;
    for (int m = 0; m < 12; m++) {
        rollCalendar.add(Calendar.MONTH, -1);
        rollCalendar.set(Calendar.DATE, rollCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        if (rollCalendar.compareTo(launchCalendar) <= 0)
            break;
        updateRollCalendar();
        dateCode = String.format("%d%02d", pursuedYear, pursuedMonth);
        reportName = "S_M_" + appID + "_" + dateCode + ".txt";
        autoingestionDownload(reportName, "Monthly", dateCode);
    }
    printDatePeriod("MONTHLY", "report");

    // YEARLY REPORTS
    System.out.println("\n-> Yearly reports");
    rollCalendar = Calendar.getInstance();
    rollCalendar.add(Calendar.DATE, -1);
    pursuedDay = currentDay - 1;
    pursuedMonth = currentMonth;
    pursuedYear = currentYear;
    for (int y = 0; y < 100; y++) {
        rollCalendar.add(Calendar.YEAR, -1);
        if (rollCalendar.compareTo(launchCalendar) <= 0)
            break;
        updateRollCalendar();
        dateCode = String.format("%d", pursuedYear);
        reportName = "S_Y_" + appID + "_" + dateCode + ".txt";
        autoingestionDownload(reportName, "Yearly", dateCode);
    }
    printDatePeriod("YEARLY", "report");

    /**
     * Reading Sales.txt & Generating Charts
     */
    // WEEK CHARTS
    String plotName, pursuedPeriodDate;
    System.out.print("\nRestoring charts...\n");
    System.out.println("-> Week charts");
    rollCalendar = Calendar.getInstance();
    rollCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    rollCalendar.add(Calendar.DATE, -7);
    updateRollCalendar();
    while (rollCalendar.compareTo(launchCalendar) > 0) {
        pursuedPeriodDate = String.format("%d.%d.%d", pursuedDay, pursuedMonth, pursuedYear);
        dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
        plotName = "S_W_" + appID + "_" + dateCode;
        File plotFile = new File(chartPath + "/" + plotName + ".png");
        if (!plotFile.isFile()) {
            readSales("week", true, true);
            if (countryLabels.size() > 0) {
                genPlot("WEEK", plotName, pursuedPeriodDate, countryLabels, countryUnits);
            }
            if (countryInAppLabels.size() > 0) {
                genPlot("WEEK IN-APP", plotName + "_InApp", pursuedPeriodDate, countryInAppLabels,
                        countryInAppUnits);
            }
        } else
            readSales("week", false, true);// Week already plotted
    }
    printDatePeriod("WEEK", "charts");

    // Incomplete current Week (let the current day be computed)
    rollCalendar = Calendar.getInstance();
    updateRollCalendar();
    readSales("week", false, true);
    // MONTH CHARTS
    System.out.println("\n-> Month charts");
    rollCalendar = Calendar.getInstance();
    rollCalendar.add(Calendar.MONTH, -1);
    rollCalendar.set(Calendar.DATE, rollCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    updateRollCalendar();
    while (rollCalendar.compareTo(launchCalendar) > 0) {
        pursuedPeriodDate = String.format("%d.%d.%d", pursuedDay, pursuedMonth, pursuedYear);
        dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
        plotName = "S_M_" + appID + "_" + dateCode;
        File plotFile = new File(chartPath + "/" + plotName + ".png");
        if (!plotFile.isFile()) {
            readSales("month", true, false);
            if (countryLabels.size() > 0) {
                genPlot("MONTH", plotName, pursuedPeriodDate, countryLabels, countryUnits);
            }
            if (countryInAppLabels.size() > 0) {
                genPlot("MONTH", plotName + "_InApp", pursuedPeriodDate, countryInAppLabels, countryInAppUnits);
            }
        } else {
            readSales("month", false, false);
        }

    }
    printDatePeriod("MONTH", "charts");

    // YEAR CHARTS
    System.out.println("\n-> Year charts");
    rollCalendar = (Calendar) launchCalendar.clone();
    rollCalendar.set(Calendar.DATE, -1);
    rollCalendar.add(Calendar.YEAR, -1);
    updateRollCalendar();
    while (rollCalendar.compareTo(launchCalendar) > 0) {
        pursuedPeriodDate = String.format("%d.%d.%d", pursuedDay, pursuedMonth, pursuedYear);
        dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
        plotName = "S_Y_" + appID + "_" + dateCode;
        File plotFile = new File(chartPath + "/" + plotName + ".png");
        if (!plotFile.isFile()) {
            readSales("year", true, false);
            if (countryLabels.size() > 0) {
                genPlot("YEAR", plotName, pursuedPeriodDate, countryLabels, countryUnits);
            }
            if (countryInAppLabels.size() > 0) {
                genPlot("YEAR", plotName + "_InApp", pursuedPeriodDate, countryInAppLabels, countryInAppUnits);
            }
        } else
            readSales("year", false, false);
    }
    printDatePeriod("YEAR", "charts");

    // CUSTOM CHART PERIOD
    System.out.println("\n-> Custom charts");
    customCalendar = (Calendar) launchCalendar.clone(); // begin day
    rollCalendar = Calendar.getInstance(); // end day
    rollCalendar.add(Calendar.DATE, -1);
    updateRollCalendar();
    pursuedPeriodDate = String.format("%d.%d.%d", pursuedDay, pursuedMonth, pursuedYear);
    dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
    plotName = "S_C_" + appID + "__whole";// + dateCode;
    File plotFile = new File(chartPath + "/" + plotName + ".png");
    if (!plotFile.isFile()) {
        readSales("custom", true, false);
        if (countryLabels.size() > 0) {
            genPlot("CUSTOM", plotName, pursuedPeriodDate, countryLabels, countryUnits);
        }
        if (countryInAppLabels.size() > 0) {
            genPlot("CUSTOM IN-APP", plotName + "_InApp", pursuedPeriodDate, countryInAppLabels,
                    countryInAppUnits);
        }
    }
    printDatePeriod("CUSTOM Period", "charts");

    // Day Sales units
    rollCalendar = Calendar.getInstance();
    rollCalendar.add(Calendar.DATE, -1);
    updateRollCalendar();
    readSales("day", false, false);

    System.out.println("\nTotal units: " + totalUnits + "/" + totalUpdateUnits + "-Up (+" + dayUnits + ")");
    System.out.println("Total IN-APP units: " + totalInAppUnits + " (+" + dayINAPPUnits + ")\n");
    System.exit(0);
}

From source file:de.prozesskraft.pkraft.Merge.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*w  w  w  .  ja v  a2s.  c o  m*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] instance you want to merge another instance into.")
            //            .isRequired()
            .create("instance");

    Option oguest = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] this instance will be merged into -instance.")
            //            .isRequired()
            .create("guest");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.")
            //            .isRequired()
            .create("basedir");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oguest);
    options.addOption(obasedir);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("merge", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("instance"))) {
        System.err.println("option -instance is mandatory");
        exiter();
    }
    if (!(commandline.hasOption("guest"))) {
        System.err.println("at least one option -guest is mandatory");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);

    String[] pathToGuest = commandline.getOptionValues("guest");

    String baseDir = null;
    if (commandline.hasOption("basedir")) {
        java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath());
            exiter();
        } else if (!fileBaseDir.isDirectory()) {
            System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath());
            exiter();
        }
        baseDir = commandline.getOptionValue("basedir");
    }

    // ueberpruefen ob die process.pmb files vorhanden sind
    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }
    for (String pathGuest : pathToGuest) {
        java.io.File fileGuest = new java.io.File(pathGuest);

        // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
        if (!fileGuest.exists()) {
            System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath());
            exiter();
        }
    }

    // base - instance einlesen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    p1.setOutfilebinary(pathToInstance);
    Process p2 = p1.readBinary();

    // alle guests einlesen
    ArrayList<Process> alleGuests = new ArrayList<Process>();
    for (String actPathGuest : pathToGuest) {
        Process p30 = new Process();
        p30.setInfilebinary(actPathGuest);
        Process pGuest = p30.readBinary();

        // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind
        if (!p2.getName().equals(pGuest.getName())) {
            System.err.println("error: instances are not from the same type (-instance=" + p2.getName()
                    + " != -guest=" + pGuest.getName());
            exiter();
        }

        // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind
        if (!p2.getVersion().equals(pGuest.getVersion())) {
            System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!="
                    + pGuest.getVersion());
            exiter();
        }

        alleGuests.add(pGuest);
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p3 = new Process();
    p3.setInfilebinary(pathToInstance);
    Process process = p3.readBinary();

    // den main-prozess ueber die static function klonen
    // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess);
                // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir()
                        + "/process.pmb";
                System.err.println("info: calling: " + call2);

                try {
                    java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
                } catch (IOException e) {
                    System.err.println("error: " + e.getMessage());
                }
            }
        }
    }

    // alle dependent steps der zielinstanz einsammeln
    // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden
    Map<Step, String> dependentSteps = new HashMap<Step, String>();

    // alle guest prozesse merge durchfuehren
    for (Process actGuestProcess : alleGuests) {
        System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary());

        // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren
        for (Step actStep : actGuestProcess.getStep()) {
            if (actStep.isAFannedMultistep()) {
                System.err.println("info: merging from guest instance step " + actStep.getName());
                Step clonedStepForIntegrationInClonedProcess = actStep.clone();
                if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) {
                    System.err.println("info: merging step successfully.");
                    // die downstream steps vom merge-punkt merken
                    for (Step actStepToResetBecauseOfDependency : clonedProcess
                            .getStepDependent(actStep.getName())) {
                        dependentSteps.put(actStepToResetBecauseOfDependency, "dummy");
                    }

                    // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden
                    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                    if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null
                            && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) {
                        String call5 = ini.get("apps", "pradar-attend") + " -instance "
                                + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb";
                        System.err.println("info: calling: " + call5);
                        try {
                            java.lang.Process sysproc = Runtime.getRuntime().exec(call5);
                        } catch (IOException e) {
                            System.err.println("error: " + e.getMessage());
                        }
                    }
                } else {
                    System.err.println("error: merging step failed.");
                }
            } else {
                System.err.println("debug: because it's not a multistep, ignoring from guest instance step "
                        + actStep.getName());
            }
        }
    }

    // alle steps downstream der merge-positionen resetten
    for (Step actStep : dependentSteps.keySet()) {
        actStep.resetBecauseOfDependency();
    }

    // speichern der ergebnis instanz
    clonedProcess.writeBinary();

    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
    String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir()
            + "/process.pmb";
    System.err.println("info: calling: " + call2);

    try {
        java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
    } catch (IOException e) {
        System.err.println("error: " + e.getMessage());
    }

}

From source file:co.cask.cdap.etl.tool.UpgradeTool.java

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

    Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message."))
            .addOption(new Option("u", "uri", true,
                    "CDAP instance URI to interact with in the format "
                            + "[http[s]://]<hostname>:<port>. Defaults to localhost:10000."))
            .addOption(new Option("a", "accesstoken", true,
                    "File containing the access token to use when interacting "
                            + "with a secure CDAP instance."))
            .addOption(new Option("t", "timeout", true,
                    "Timeout in milliseconds to use when interacting with the "
                            + "CDAP RESTful APIs. Defaults to " + DEFAULT_READ_TIMEOUT_MILLIS + "."))
            .addOption(new Option("n", "namespace", true,
                    "Namespace to perform the upgrade in. If none is given, "
                            + "pipelines in all namespaces will be upgraded."))
            .addOption(new Option("p", "pipeline", true,
                    "Name of the pipeline to upgrade. If specified, a namespace " + "must also be given."))
            .addOption(new Option("f", "configfile", true, "File containing old application details to update. "
                    + "The file contents are expected to be in the same format as the request body for creating an "
                    + "ETL application from one of the etl artifacts. "
                    + "It is expected to be a JSON Object containing 'artifact' and 'config' fields."
                    + "The value for 'artifact' must be a JSON Object that specifies the artifact scope, name, and version. "
                    + "The value for 'config' must be a JSON Object specifies the source, transforms, and sinks of the pipeline, "
                    + "as expected by older versions of the etl artifacts."))
            .addOption(new Option("o", "outputfile", true,
                    "File to write the converted application details provided in "
                            + "the configfile option. If none is given, results will be written to the input file + '.converted'. "
                            + "The contents of this file can be sent directly to CDAP to update or create an application."))
            .addOption(new Option("e", "errorDir", true,
                    "Optional directory to write any upgraded pipeline configs that "
                            + "failed to upgrade. The problematic configs can then be manually edited and upgraded separately. "
                            + "Upgrade errors may happen for pipelines that use plugins that are not backwards compatible. "
                            + "This directory must be writable by the user that is running this tool."));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    String[] commandArgs = commandLine.getArgs();

    // if help is an option, or if there isn't a single 'upgrade' command, print usage and exit.
    if (commandLine.hasOption("h") || commandArgs.length != 1 || !"upgrade".equalsIgnoreCase(commandArgs[0])) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(UpgradeTool.class.getName() + " upgrade",
                "Upgrades Hydrator pipelines created for 3.2.x versions"
                        + "of the cdap-etl-batch and cdap-etl-realtime artifacts into pipelines compatible with 3.3.x versions of "
                        + "cdap-etl-batch and cdap-etl-realtime. Connects to an instance of CDAP to find any 3.2.x pipelines, then "
                        + "upgrades those pipelines.",
                options, "");
        System.exit(0);//  ww w.  j  a  va  2s .c om
    }

    ClientConfig clientConfig = getClientConfig(commandLine);

    if (commandLine.hasOption("f")) {
        String inputFilePath = commandLine.getOptionValue("f");
        String outputFilePath = commandLine.hasOption("o") ? commandLine.getOptionValue("o")
                : inputFilePath + ".new";
        convertFile(inputFilePath, outputFilePath, new ArtifactClient(clientConfig));
        System.exit(0);
    }

    File errorDir = commandLine.hasOption("e") ? new File(commandLine.getOptionValue("e")) : null;
    if (errorDir != null) {
        if (!errorDir.exists()) {
            if (!errorDir.mkdirs()) {
                LOG.error("Unable to create error directory {}.", errorDir.getAbsolutePath());
                System.exit(1);
            }
        } else if (!errorDir.isDirectory()) {
            LOG.error("{} is not a directory.", errorDir.getAbsolutePath());
            System.exit(1);
        } else if (!errorDir.canWrite()) {
            LOG.error("Unable to write to error directory {}.", errorDir.getAbsolutePath());
            System.exit(1);
        }
    }
    UpgradeTool upgradeTool = new UpgradeTool(clientConfig, errorDir);

    String namespace = commandLine.getOptionValue("n");
    String pipelineName = commandLine.getOptionValue("p");

    if (pipelineName != null) {
        if (namespace == null) {
            throw new IllegalArgumentException("Must specify a namespace when specifying a pipeline.");
        }
        Id.Application appId = Id.Application.from(namespace, pipelineName);
        if (upgradeTool.upgrade(appId)) {
            LOG.info("Successfully upgraded {}.", appId);
        } else {
            LOG.info("{} did not need to be upgraded.", appId);
        }
        System.exit(0);
    }

    if (namespace != null) {
        printUpgraded(upgradeTool.upgrade(Id.Namespace.from(namespace)));
        System.exit(0);
    }

    printUpgraded(upgradeTool.upgrade());
}

From source file:imp.lstm.main.Driver.java

public static void main(String[] args)
        throws FileNotFoundException, IOException, ConfigurationException, InvalidParametersException {
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
            PropertiesConfiguration.class).configure(
                    new Parameters().properties().setFileName(args[0]).setThrowExceptionOnMissing(true)
                            .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                            .setIncludesAllowed(false));
    Configuration config = builder.getConfiguration();

    String inputSongPath = config.getString("input_song");
    String outputFolderPath = config.getString("output_folder");
    String autoEncoderParamsPath = config.getString("auto_encoder_params");
    String nameGeneratorParamsPath = config.getString("name_generator_params");
    String queueFolderPath = config.getString("queue_folder");
    String referenceQueuePath = config.getString("reference_queue", "nil");
    String inputCorpusFolder = config.getString("input_corpus_folder");
    boolean shouldWriteQueue = config.getBoolean("should_write_generated_queue");
    boolean frankensteinTest = config.getBoolean("queue_tests_frankenstein");
    boolean interpolateTest = config.getBoolean("queue_tests_interpolation");
    boolean iterateOverCorpus = config.getBoolean("iterate_over_corpus", false);
    boolean shouldGenerateSongTitle = config.getBoolean("generate_song_title");
    boolean shouldGenerateSong = config.getBoolean("generate_leadsheet");

    LogTimer.initStartTime(); //start our logging timer to keep track of our execution time
    LogTimer.log("Creating name generator...");

    //here is just silly code for generating name based on an LSTM lol $wag
    LSTM lstm = new LSTM();
    FullyConnectedLayer fullLayer = new FullyConnectedLayer(Operations.None);
    Loadable titleNetLoader = new Loadable() {
        @Override/*from w  w  w .  ja va2s  .c  o m*/
        public boolean load(INDArray array, String path) {
            String car = pathCar(path);
            String cdr = pathCdr(path);
            switch (car) {
            case "full":
                return fullLayer.load(array, cdr);
            case "lstm":
                return lstm.load(array, cdr);
            default:
                return false;
            }
        }
    };

    LogTimer.log("Packing name generator from files...");
    (new NetworkConnectomeLoader()).load(nameGeneratorParamsPath, titleNetLoader);

    String characterString = " !\"'[],-.01245679:?ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwxyz";

    //Initialization
    LogTimer.log("Creating autoencoder...");
    int inputSize = 34;
    int outputSize = EncodingParameters.noteEncoder.getNoteLength();
    int featureVectorSize = 100;
    ProductCompressingAutoencoder autoencoder = new ProductCompressingAutoencoder(24, 48, 84 + 1, false); //create our network

    int numInterpolationDivisions = 5;

    //"pack" the network from weights and biases file directory
    LogTimer.log("Packing autoencoder from files");
    (new NetworkConnectomeLoader()).load(autoEncoderParamsPath, autoencoder);

    File[] songFiles;
    if (iterateOverCorpus) {
        songFiles = new File(inputCorpusFolder).listFiles();
    } else {
        songFiles = new File[] { new File(inputSongPath) };
    }
    for (File inputFile : songFiles) {
        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
        String songTitle;
        if (shouldGenerateSong) {
            Random rand = new Random();
            AVector charOut = Vector.createLength(characterString.length());
            GroupedSoftMaxSampler sampler = new GroupedSoftMaxSampler(
                    new Group[] { new Group(0, characterString.length(), true) });
            songTitle = "";
            for (int i = 0; i < 50; i++) {
                charOut = fullLayer.forward(lstm.step(charOut));
                charOut = sampler.filter(charOut);
                int charIndex = 0;
                for (; charIndex < charOut.length(); charIndex++) {
                    if (charOut.get(charIndex) == 1.0) {
                        break;
                    }
                }
                songTitle += characterString.substring(charIndex, charIndex + 1);
            }
            songTitle = songTitle.trim();

            LogTimer.log("Generated song name: " + songTitle);
        } else {
            songTitle = "The Song We Never Name";
        }
        LogTimer.log("Reading file...");
        LeadSheetDataSequence inputSequence = LeadSheetIO.readLeadSheet(inputFile); //read our leadsheet to get a data vessel as retrieved in rbm-provisor
        LeadSheetDataSequence outputSequence = inputSequence.copy();

        outputSequence.clearMelody();
        if (interpolateTest) {
            LeadSheetDataSequence additionalOutput = outputSequence.copy();
            for (int i = 0; i < numInterpolationDivisions; i++) {
                outputSequence.concat(additionalOutput.copy());
            }
        }
        LeadSheetDataSequence decoderInputSequence = outputSequence.copy();

        LogTimer.startLog("Encoding data...");
        //TradingTimer.initStart(); //start our trading timer to keep track our our generation versus realtime play
        while (inputSequence.hasNext()) { //iterate through time steps in input data
            //TradingTimer.waitForNextTimedInput();
            autoencoder.encodeStep(inputSequence.retrieve()); //feed the resultant input vector into the network
            if (advanceDecoding) { //if we are using advance decoding (we start decoding as soon as we can)
                if (autoencoder.canDecode()) { //if queue has enough data to decode from
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are
                }
            }
        }
        LogTimer.endLog();

        if (shouldWriteQueue) {
            String queueFilePath = queueFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", ".q");
            FragmentedNeuralQueue currQueue = autoencoder.getQueue();
            currQueue.writeToFile(queueFilePath);
            LogTimer.log("Wrote queue " + inputFile.getName().replace(".ls", ".q") + " to file...");
        }
        if (shouldGenerateSong) {
            if (interpolateTest) {

                FragmentedNeuralQueue refQueue = new FragmentedNeuralQueue();
                refQueue.initFromFile(referenceQueuePath);

                FragmentedNeuralQueue currQueue = autoencoder.getQueue();
                //currQueue.writeToFile(queueFilePath);

                autoencoder.setQueue(currQueue.copy());
                while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                }

                for (int i = 1; i <= numInterpolationDivisions; i++) {
                    System.out.println("Starting interpolation " + ((1.0 / numInterpolationDivisions) * (i)));
                    (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
                    FragmentedNeuralQueue currCopy = currQueue.copy();
                    currCopy.basicInterpolate(refQueue, (1.0 / numInterpolationDivisions) * (i));
                    autoencoder.setQueue(currCopy);
                    int timeStep = 0;
                    while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                        System.out.println("interpolation " + i + " step " + ++timeStep);
                        outputSequence.pushStep(null, null,
                                autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                        //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                    }
                }

            }
            if (frankensteinTest) {
                LogTimer.startLog("Loading queues");
                File queueFolder = new File(queueFolderPath);
                int numComponents = config.getInt("frankenstein_num_components", 5);
                int numCombinations = config.getInt("frankenstein_num_combinations", 6);
                double interpolationMagnitude = config.getDouble("frankenstein_magnitude", 2.0);
                if (queueFolder.isDirectory()) {
                    File[] queueFiles = queueFolder.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.contains(".q");
                        }
                    });

                    List<File> fileList = new ArrayList<>();
                    for (File file : queueFiles) {
                        fileList.add(file);
                    }
                    Collections.shuffle(fileList);
                    int numSelectedFiles = (numComponents > queueFiles.length) ? queueFiles.length
                            : numComponents;

                    for (int i = 0; i < queueFiles.length - numSelectedFiles; i++) {
                        fileList.remove(fileList.size() - 1);
                    }
                    List<FragmentedNeuralQueue> queuePopulation = new ArrayList<>(fileList.size());
                    songTitle += " - a mix of ";
                    for (File file : fileList) {
                        FragmentedNeuralQueue newQueue = new FragmentedNeuralQueue();
                        newQueue.initFromFile(file.getPath());
                        queuePopulation.add(newQueue);
                        songTitle += file.getName().replaceAll(".ls", "") + ", ";
                    }
                    LogTimer.endLog();

                    LeadSheetDataSequence additionalOutput = outputSequence.copy();
                    for (int i = 1; i < numCombinations; i++) {
                        outputSequence.concat(additionalOutput.copy());
                    }
                    decoderInputSequence = outputSequence.copy();

                    FragmentedNeuralQueue origQueue = autoencoder.getQueue();

                    for (int i = 0; i < numCombinations; i++) {

                        LogTimer.startLog("Performing queue interpolation...");
                        AVector combinationStrengths = Vector.createLength(queuePopulation.size());
                        Random vectorRand = new Random(i);
                        for (int j = 0; j < combinationStrengths.length(); j++) {
                            combinationStrengths.set(j, vectorRand.nextDouble());
                        }
                        combinationStrengths.divide(combinationStrengths.elementSum());
                        FragmentedNeuralQueue currQueue = origQueue.copy();
                        for (int k = 0; k < combinationStrengths.length(); k++) {
                            currQueue.basicInterpolate(queuePopulation.get(k),
                                    combinationStrengths.get(k) * interpolationMagnitude);
                        }
                        LogTimer.endLog();
                        autoencoder.setQueue(currQueue);
                        LogTimer.startLog("Refreshing autoencoder state...");
                        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder,
                                "initialstate");
                        LogTimer.endLog();
                        LogTimer.startLog("Decoding segment...");
                        while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                            outputSequence.pushStep(null, null,
                                    autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                            //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                        }
                        LogTimer.endLog();
                    }

                }
            }

            while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
            }
            LogTimer.log("Writing file...");

            String outputFilename = outputFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", "_Output"); //we'll write our generated file with the same name plus "_Output"
            LeadSheetIO.writeLeadSheet(outputSequence, outputFilename, songTitle);
            System.out.println(outputFilename);
        } else {
            autoencoder.setQueue(new FragmentedNeuralQueue());
        }
    }
    LogTimer.log("Process finished"); //Done!

}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

/** Main method. Very simple, does not perform sanity checks on input.
 * /*from   w w  w.  j  a v a  2 s.  com*/
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    CommandLineParser parser = new BasicParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("assistant", getOptions());
            return;
        }

        // Instantiate assistant
        Assistant assistant = new Assistant();

        // Add default plugins
        assistant.addScanPlugin(ChecksumPlugin.class);
        assistant.addScanPlugin(HtmlDependencyPlugin.class);
        assistant.addScanPlugin(NodeDependencyPlugin.class);
        assistant.addScanPlugin(MavenDependencyPlugin.class);
        assistant.addScanPlugin(GemfileDependencyPlugin.class);

        if (line.hasOption(NO_DEPENDENCIES_OPTION)) {
            assistant.setExportDependencies(false);
        } else {
            assistant.setExportDependencies(true);
        }
        assistant.setIncludeImages(!line.hasOption(NO_IMAGES_OPTION));
        assistant.setIncludeArtifacts(!line.hasOption(NO_ARTIFACTS_OPTION));

        // Determine operation type
        boolean doScan = line.hasOption("scan");
        boolean doMerge = line.hasOption("merge");
        boolean doImport = line.hasOption("import");
        int count = 0;
        if (doScan)
            count++;
        if (doMerge)
            count++;
        if (doImport)
            count++;
        if (count > 1) {
            System.err.println("Only one of 'scan', 'merge', or import may be selected");
            return;
        }

        if (doScan) {
            // Get the output directory
            if (!line.hasOption("D")) {
                System.err.println("An output directory must be specified");
                return;
            }
            File outputDir = new File(line.getOptionValue("D"));
            if (!outputDir.exists())
                outputDir.mkdir();
            if (!outputDir.isDirectory()) {
                System.err.println("Output option is not a directory: " + outputDir);
                return;
            }

            doScan(assistant, line.getOptionValue("scan"), outputDir, line.hasOption(VERBOSE_OUTPUT_OPTION));
            return;
        }

        if (doMerge) {
            // Get the output directory
            if (!line.hasOption("D")) {
                System.err.println("An output directory must be specified");
                return;
            }
            File outputDir = new File(line.getOptionValue("D"));
            if (!outputDir.exists())
                outputDir.mkdir();
            if (!outputDir.isDirectory()) {
                System.err.println("Output option is not a directory: " + outputDir);
                return;
            }

            doMerge(assistant, line.getOptionValues("merge"), outputDir);
            return;
        }

        if (doImport) {
            // Get the output directory
            if (!line.hasOption("D")) {
                System.err.println("An output directory must be specified");
                return;
            }
            File outputDir = new File(line.getOptionValue("D"));
            if (!outputDir.exists())
                outputDir.mkdir();
            if (!outputDir.isDirectory()) {
                System.err.println("Output option is not a directory: " + outputDir);
                return;
            }

            doImport(assistant, line.getOptionValue("import"), outputDir);
            return;
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("assistant", getOptions());
    return;
}

From source file:act.installer.reachablesexplorer.Loader.java

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

    File reachablesDir = new File(cl.getOptionValue(OPTION_REACHABLES_SOURCE_DATA, DEFAULT_REACHABLES_PATH));
    if (!(reachablesDir.exists() && reachablesDir.isDirectory())) {
        cliUtil.failWithMessage("Reachables directory at %s does not exist or is not a directory",
                reachablesDir.getAbsolutePath());
    }// www.j  a  va  2s  . com

    Loader loader = new Loader(cl.getOptionValue(OPTION_DB_HOST, DEFAULT_HOST),
            Integer.parseInt(cl.getOptionValue(OPTION_DB_PORT, DEFAULT_PORT.toString())),
            cl.getOptionValue(OPTION_INSTALLER_SOURCE_DB, DEFAULT_CHEMICALS_DATABASE),
            cl.getOptionValue(OPTION_TARGET_DB, DEFAULT_TARGET_DATABASE),
            cl.getOptionValue(OPTION_TARGET_REACHABLES_COLLECTION),
            cl.getOptionValue(OPTION_TARGET_SEQUENCES_COLLECTION),
            cl.getOptionValue(OPTION_RENDERING_CACHE, DEFAULT_ASSETS_LOCATION));
    loader.updateFromReachableDir(reachablesDir);

    if (cl.hasOption(OPTION_PROJECTIONS_SOURCE_DATA)) {
        File projectionFile = new File(
                cl.getOptionValue(OPTION_PROJECTIONS_SOURCE_DATA, DEFAULT_PROJECTIONS_PATH));
        if (!projectionFile.exists() || projectionFile.isDirectory()) {
            cliUtil.failWithMessage("Projection file at %s does not exist or is a directory",
                    projectionFile.getAbsolutePath());
        }
        loader.updateFromProjectionFile(projectionFile);
    }

    if (cl.hasOption(OPTION_PROJECTED_INCHIS_SOURCE_DATA)) {
        File projectedInchisFile = new File(cl.getOptionValue(OPTION_PROJECTED_INCHIS_SOURCE_DATA));
        if (!projectedInchisFile.exists() || projectedInchisFile.isDirectory()) {
            cliUtil.failWithMessage("InChI file at %s does not exist or is a directory",
                    projectedInchisFile.getAbsolutePath());
        }
        loader.updateFromProjectedInchiFile(projectedInchisFile);
    }
}