Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

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

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {//from w ww  .ja  v a 2s  . c o  m
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:de.citec.sc.matoll.process.Matoll_CreateMax.java

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException,
        InstantiationException, IllegalAccessException, ClassNotFoundException, Exception {

    String directory;//from   ww w . ja va2s.c  o m
    String gold_standard_lexicon;
    String output_lexicon;
    String configFile;
    Language language;
    String output;

    Stopwords stopwords = new Stopwords();

    HashMap<String, Double> maxima;
    maxima = new HashMap<String, Double>();

    if (args.length < 3) {
        System.out.print("Usage: Matoll --mode=train/test <DIRECTORY> <CONFIG>\n");
        return;

    }

    //      Classifier classifier;

    directory = args[1];
    configFile = args[2];

    final Config config = new Config();

    config.loadFromFile(configFile);

    gold_standard_lexicon = config.getGoldStandardLexicon();

    String model_file = config.getModel();

    output_lexicon = config.getOutputLexicon();
    output = config.getOutput();

    language = config.getLanguage();

    LexiconLoader loader = new LexiconLoader();
    Lexicon gold = loader.loadFromFile(gold_standard_lexicon);

    Set<String> uris = new HashSet<>();
    //        Map<Integer,String> sentence_list = new HashMap<>();
    Map<Integer, Set<Integer>> mapping_words_sentences = new HashMap<>();

    //consider only properties
    for (LexicalEntry entry : gold.getEntries()) {
        try {
            for (Sense sense : entry.getSenseBehaviours().keySet()) {
                String tmp_uri = sense.getReference().getURI().replace("http://dbpedia.org/ontology/", "");
                if (!Character.isUpperCase(tmp_uri.charAt(0))) {
                    uris.add(sense.getReference().getURI());
                }
            }
        } catch (Exception e) {
        }
        ;
    }

    ModelPreprocessor preprocessor = new ModelPreprocessor(language);
    preprocessor.setCoreferenceResolution(false);
    Set<String> dep = new HashSet<>();
    dep.add("prep");
    dep.add("appos");
    dep.add("nn");
    dep.add("dobj");
    dep.add("pobj");
    dep.add("num");
    preprocessor.setDEP(dep);

    List<File> list_files = new ArrayList<>();

    if (config.getFiles().isEmpty()) {
        File folder = new File(directory);
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.toString().contains(".ttl"))
                list_files.add(file);
        }
    } else {
        list_files.addAll(config.getFiles());
    }
    System.out.println(list_files.size());

    int sentence_counter = 0;
    Map<String, Set<Integer>> bag_words_uri = new HashMap<>();
    Map<String, Integer> mapping_word_id = new HashMap<>();
    for (File file : list_files) {
        Model model = RDFDataMgr.loadModel(file.toString());
        for (Model sentence : getSentences(model)) {
            String reference = getReference(sentence);
            reference = reference.replace("http://dbpedia/", "http://dbpedia.org/");
            if (uris.contains(reference)) {
                sentence_counter += 1;
                Set<Integer> words_ids = getBagOfWords(sentence, stopwords, mapping_word_id);
                //TODO: add sentence preprocessing
                String obj = getObject(sentence);
                String subj = getSubject(sentence);
                preprocessor.preprocess(sentence, subj, obj, language);
                //TODO: also return marker if object or subject of property (in SPARQL this has to be optional of course)
                String parsed_sentence = getParsedSentence(sentence);
                try (FileWriter fw = new FileWriter("mapping_sentences_to_ids_goldstandard.tsv", true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        PrintWriter out = new PrintWriter(bw)) {
                    out.println(sentence_counter + "\t" + parsed_sentence);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (Integer word_id : words_ids) {
                    if (mapping_words_sentences.containsKey(word_id)) {
                        Set<Integer> tmp_set = mapping_words_sentences.get(word_id);
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);

                    } else {
                        Set<Integer> tmp_set = new HashSet<>();
                        tmp_set.add(sentence_counter);
                        mapping_words_sentences.put(word_id, tmp_set);
                    }

                }
                if (bag_words_uri.containsKey(reference)) {
                    Set<Integer> tmp = bag_words_uri.get(reference);
                    for (Integer w : words_ids) {
                        tmp.add(w);

                    }
                    bag_words_uri.put(reference, tmp);
                } else {
                    Set<Integer> tmp = new HashSet<>();
                    for (Integer w : words_ids) {
                        tmp.add(w);
                    }
                    bag_words_uri.put(reference, tmp);
                }
            }

        }
        model.close();

    }

    PrintWriter writer = new PrintWriter("bag_of_words_only_goldstandard.tsv");
    StringBuilder string_builder = new StringBuilder();
    for (String r : bag_words_uri.keySet()) {
        string_builder.append(r);
        for (Integer i : bag_words_uri.get(r)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

    writer = new PrintWriter("mapping_words_to_sentenceids_goldstandard.tsv");
    string_builder = new StringBuilder();
    for (Integer w : mapping_words_sentences.keySet()) {
        string_builder.append(w);
        for (int i : mapping_words_sentences.get(w)) {
            string_builder.append("\t");
            string_builder.append(i);
        }
        string_builder.append("\n");
    }
    writer.write(string_builder.toString());
    writer.close();

}

From source file:com.norconex.collector.http.HttpCollector.java

/**
 * Invokes the HTTP Collector from the command line.  
 * @param args Invoke it once without any arguments to get a 
 *    list of command-line options.// w w w  . jav  a2 s .  c  o m
 */
public static void main(String[] args) {
    CommandLine cmd = parseCommandLineArguments(args);
    String action = cmd.getOptionValue(ARG_ACTION);
    File configFile = new File(cmd.getOptionValue(ARG_CONFIG));
    File varFile = null;
    if (cmd.hasOption(ARG_VARIABLES)) {
        varFile = new File(cmd.getOptionValue(ARG_VARIABLES));
    }

    try {
        HttpCollector conn = new HttpCollector(configFile, varFile);
        if (ARG_ACTION_START.equalsIgnoreCase(action)) {
            conn.crawl(false);
        } else if (ARG_ACTION_RESUME.equalsIgnoreCase(action)) {
            conn.crawl(true);
        } else if (ARG_ACTION_STOP.equalsIgnoreCase(action)) {
            conn.stop();
        }
    } catch (Exception e) {
        File errorFile = new File("./error-" + System.currentTimeMillis() + ".log");
        System.err.println("\n\nAn ERROR occured:\n\n" + e.getLocalizedMessage());
        System.err.println(
                "\n\nDetails of the error has been stored at: " + errorFile.getAbsolutePath() + "\n\n");
        try {
            PrintWriter w = new PrintWriter(errorFile);
            e.printStackTrace(w);
            w.flush();
            w.close();
        } catch (FileNotFoundException e1) {
            throw new HttpCollectorException("Cannot write error file.", e1);
        }
    }
}

From source file:ca.mcgill.networkdynamics.geoinference.evaluation.CrossValidationScorer.java

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

    if (args.length != 4) {
        System.out.println("java CVS predictions-dir/ " + "cv-gold-dir/ results.txt error-sample.tsv");
        return;//from   ww w.j  a  va  2 s  . c  om
    }

    File predDir = new File(args[0]);
    File cvDir = new File(args[1]);

    TDoubleList errors = new TDoubleArrayList(10_000_000);
    TLongSet locatedUsers = new TLongHashSet(10_000_000);
    TLongSet allUsers = new TLongHashSet(10_000_000);
    TLongObjectMap<TDoubleList> userToErrors = new TLongObjectHashMap<TDoubleList>();

    TLongDoubleMap tweetIdToError = new TLongDoubleHashMap(10_000_000);
    TLongObjectMap<double[]> idToPredLoc = new TLongObjectHashMap<double[]>();

    int tweetsSeen = 0;
    int tweetsLocated = 0;

    BufferedReader cvBr = new BufferedReader(new FileReader(new File(cvDir, "folds.info.tsv")));
    for (String foldLine = null; (foldLine = cvBr.readLine()) != null;) {
        String[] cols = foldLine.split("\t");
        String foldName = cols[0];

        System.out.printf("Scoring results for fold %s%n", foldName);

        File foldPredictionsFile = new File(predDir, foldName + ".results.tsv.gz");

        File goldLocFile = new File(cvDir, foldName + ".gold-locations.tsv");

        if (foldPredictionsFile.exists()) {
            BufferedReader br = Files.openGz(foldPredictionsFile);
            for (String line = null; (line = br.readLine()) != null;) {
                String[] arr = line.split("\t");
                long id = Long.parseLong(arr[0]);
                idToPredLoc.put(id, new double[] { Double.parseDouble(arr[1]), Double.parseDouble(arr[2]) });
            }
            br.close();
        }

        System.out.printf("loaded predictions for %d tweets; " + "scoring predictions%n", idToPredLoc.size());

        BufferedReader br = new BufferedReader(new FileReader(goldLocFile));
        for (String line = null; (line = br.readLine()) != null;) {
            String[] arr = line.split("\t");
            long id = Long.parseLong(arr[0]);
            long userId = Long.parseLong(arr[1]);

            allUsers.add(userId);
            tweetsSeen++;

            double[] predLoc = idToPredLoc.get(id);
            if (predLoc == null)
                continue;

            tweetsLocated++;
            locatedUsers.add(userId);

            double[] goldLoc = new double[] { Double.parseDouble(arr[2]), Double.parseDouble(arr[3]) };

            double dist = Geometry.getDistance(predLoc, goldLoc);
            errors.add(dist);
            tweetIdToError.put(id, dist);

            TDoubleList userErrors = userToErrors.get(userId);
            if (userErrors == null) {
                userErrors = new TDoubleArrayList();
                userToErrors.put(userId, userErrors);
            }
            userErrors.add(dist);

        }
        br.close();
    }

    errors.sort();
    System.out.println("Num errors to score: " + errors.size());

    double auc = 0;
    double userCoverage = 0;
    double tweetCoverage = tweetsLocated / (double) tweetsSeen;
    double medianMaxUserError = Double.NaN;
    double medianMedianUserError = Double.NaN;

    if (errors.size() > 0) {
        auc = computeAuc(errors);
        userCoverage = locatedUsers.size() / ((double) allUsers.size());
        TDoubleList maxUserErrors = new TDoubleArrayList(locatedUsers.size());
        TDoubleList medianUserErrors = new TDoubleArrayList(locatedUsers.size());
        for (TDoubleList userErrors : userToErrors.valueCollection()) {
            userErrors.sort();
            maxUserErrors.add(userErrors.get(userErrors.size() - 1));
            medianUserErrors.add(userErrors.get(userErrors.size() / 2));
        }

        maxUserErrors.sort();
        medianMaxUserError = maxUserErrors.get(maxUserErrors.size() / 2);

        medianUserErrors.sort();
        medianMedianUserError = medianUserErrors.get(medianUserErrors.size() / 2);

        // Compute CDF
        int[] errorsPerKm = new int[MAX_KM];
        for (int i = 0; i < errors.size(); ++i) {
            int error = (int) (Math.round(errors.get(i)));
            errorsPerKm[error]++;
        }

        // The accumulated sum of errors per km
        int[] errorsBelowEachKm = new int[errorsPerKm.length];
        for (int i = 0; i < errorsBelowEachKm.length; ++i) {
            errorsBelowEachKm[i] = errorsPerKm[i];
            if (i > 0)
                errorsBelowEachKm[i] += errorsBelowEachKm[i - 1];
        }

        final double[] cdf = new double[errorsBelowEachKm.length];
        double dSize = errors.size(); // to avoid casting all the time
        for (int i = 0; i < cdf.length; ++i)
            cdf[i] = errorsBelowEachKm[i] / dSize;
    }

    PrintWriter pw = new PrintWriter(new File(args[2]));
    pw.println("AUC\t" + auc);
    pw.println("user coverage\t" + userCoverage);
    pw.println("tweet coverage\t" + tweetCoverage);
    pw.println("median-max error\t" + medianMaxUserError);
    pw.close();

    // Choose a random sampling of 10K tweets to pass on to the authors
    // here.        
    PrintWriter errorsPw = new PrintWriter(args[3]);
    TLongList idsWithErrors = new TLongArrayList(tweetIdToError.keySet());
    idsWithErrors.shuffle(new Random());
    // Choose the first 10K
    for (int i = 0, chosen = 0; i < idsWithErrors.size() && chosen < 10_000; ++i) {

        long id = idsWithErrors.get(i);
        double[] prediction = idToPredLoc.get(id);
        double error = tweetIdToError.get(id);
        errorsPw.println(id + "\t" + error + "\t" + prediction[0] + "\t" + prediction[1]);
        ++chosen;
    }
    errorsPw.close();
}

From source file:com.act.lcms.v2.fullindex.Searcher.java

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

    File indexDir = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (!indexDir.exists() || !indexDir.isDirectory()) {
        cliUtil.failWithMessage("Unable to read index directory at %s", indexDir.getAbsolutePath());
    }//from  w ww  . java  2 s  . c o  m

    if (!cl.hasOption(OPTION_MZ_RANGE) && !cl.hasOption(OPTION_TIME_RANGE)) {
        cliUtil.failWithMessage(
                "Extracting all readings is not currently supported; specify an m/z or time range");
    }

    Pair<Double, Double> mzRange = extractRange(cl.getOptionValue(OPTION_MZ_RANGE));
    Pair<Double, Double> timeRange = extractRange(cl.getOptionValue(OPTION_TIME_RANGE));

    Searcher searcher = Factory.makeSearcher(indexDir);
    List<TMzI> results = searcher.searchIndexInRange(mzRange, timeRange);

    if (cl.hasOption(OPTION_OUTPUT_FILE)) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE)))) {
            Searcher.writeOutput(writer, results);
        }
    } else {
        // Don't close the print writer if we're writing to stdout.
        Searcher.writeOutput(new PrintWriter(new OutputStreamWriter(System.out)), results);
    }

    LOGGER.info("Done");
}

From source file:com.archivas.clienttools.arcmover.cli.ManagedCLIJob.java

@SuppressWarnings({ "UseOfSystemOutOrSystemErr" })
public static void main(String args[]) {
    if (LOG.isLoggable(Level.FINE)) {
        StringBuffer sb = new StringBuffer();
        sb.append("Program Arguments").append(NEWLINE);
        for (int i = 0; i < args.length; i++) {
            sb.append("    ").append(i).append(": ").append(args[i]);
            sb.append(NEWLINE);/*  w  w  w  .ja v a  2s.c o m*/
        }
        LOG.log(Level.FINE, sb.toString());
    }

    ConfigurationHelper.validateLaunchOK();

    ManagedCLIJob arcCmd = null;
    try {
        if (args[0].equals("copy")) {
            arcCmd = new ArcCopy(args, 2);
        } else if (args[0].equals("delete")) {
            arcCmd = new ArcDelete(args, 2);
        } else if (args[0].equals("metadata")) {
            arcCmd = new ArcMetadata(args, 2);
        } else {
            throw new RuntimeException("Unsupported operation: " + args[0]);
        }

        arcCmd.parseArgs();

        if (arcCmd.shouldPrintHelp()) {
            System.out.println(arcCmd.helpScreen());
        } else {
            arcCmd.execute(new PrintWriter(System.out), new PrintWriter(System.err));
        }
    } catch (ParseException e) {
        System.out.println("Error: " + e.getMessage());
        System.out.println();
        System.out.println(arcCmd.helpScreen());
        arcCmd.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        System.out.println();
        System.err.println("Job failed.  " + e.getMessage());
        if (arcCmd != null) {
            arcCmd.setExitCode(EXIT_CODE_DM_ERROR);
        }
    } finally {
        if (arcCmd != null) {
            arcCmd.exit();
        }
    }
}

From source file:org.jfree.chart.demo.ImageMapDemo3.java

/**
 * Starting point for the demo./* w ww .j  a  v  a2s. c  o  m*/
 *
 * @param args  ignored.
 *
 * @throws ParseException if there is a problem parsing dates.
 */
public static void main(final String[] args) throws ParseException {

    //  Create a sample dataset
    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    final XYSeries dataSeries = new XYSeries("Curve data");
    final ArrayList toolTips = new ArrayList();
    dataSeries.add(sdf.parse("01-Jul-2002").getTime(), 5.22);
    toolTips.add("1D - 5.22");
    dataSeries.add(sdf.parse("02-Jul-2002").getTime(), 5.18);
    toolTips.add("2D - 5.18");
    dataSeries.add(sdf.parse("03-Jul-2002").getTime(), 5.23);
    toolTips.add("3D - 5.23");
    dataSeries.add(sdf.parse("04-Jul-2002").getTime(), 5.15);
    toolTips.add("4D - 5.15");
    dataSeries.add(sdf.parse("05-Jul-2002").getTime(), 5.22);
    toolTips.add("5D - 5.22");
    dataSeries.add(sdf.parse("06-Jul-2002").getTime(), 5.25);
    toolTips.add("6D - 5.25");
    dataSeries.add(sdf.parse("07-Jul-2002").getTime(), 5.31);
    toolTips.add("7D - 5.31");
    dataSeries.add(sdf.parse("08-Jul-2002").getTime(), 5.36);
    toolTips.add("8D - 5.36");
    final XYSeriesCollection xyDataset = new XYSeriesCollection(dataSeries);
    final CustomXYToolTipGenerator ttg = new CustomXYToolTipGenerator();
    ttg.addToolTipSeries(toolTips);

    //  Create the chart
    final StandardXYURLGenerator urlg = new StandardXYURLGenerator("xy_details.jsp");
    final ValueAxis timeAxis = new DateAxis("");
    final NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false); // override default
    final XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, null);
    final StandardXYItemRenderer sxyir = new StandardXYItemRenderer(
            StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES, ttg, urlg);
    sxyir.setShapesFilled(true);
    plot.setRenderer(sxyir);
    final JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("xychart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("xychart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"xychart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }
    return;
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

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

    CommandLine line = null;//from   w  ww .j a v  a  2s  .c om
    try {
        line = new PosixParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    String[] outFile = line.getArgs();
    if (outFile.length != 1) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(1);
    }
    if (line.hasOption("usage")) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(0);
    }

    if (line.hasOption("file")) {
        String file = line.getOptionValue("file");
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String configClass;
            while ((configClass = reader.readLine()) != null) {
                register(configClass);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    } else {
        register("com.arsdigita.runtime.RuntimeConfig");
        register("com.arsdigita.web.WebConfig");
        register("com.arsdigita.templating.TemplatingConfig");
        register("com.arsdigita.kernel.KernelConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.mail.MailConfig");
        register("com.arsdigita.versioning.VersioningConfig");
        register("com.arsdigita.search.SearchConfig");
        register("com.arsdigita.search.lucene.LuceneConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.bebop.BebopConfig");
        register("com.arsdigita.dispatcher.DispatcherConfig");
        register("com.arsdigita.workflow.simple.WorkflowConfig");
        register("com.arsdigita.cms.ContentSectionConfig");
    }

    if (line.hasOption("html")) {
        final StringWriter sout = new StringWriter();
        final PrintWriter out = new PrintWriter(sout);

        writeXML(out);

        final XSLTemplate template = new XSLTemplate(
                ParameterPrinter.class.getResource("ParameterPrinter_html.xsl"));

        final Source source = new StreamSource(new StringReader(sout.toString()));
        final Result result = new StreamResult(new File(outFile[0]));

        template.transform(source, result);
    } else {
        final PrintWriter out = new PrintWriter(new FileWriter(outFile[0]));

        writeXML(out);
    }
}

From source file:com.qwazr.utils.HtmlUtils.java

public static void main(String args[]) throws IOException {
     if (args != null && args.length == 2) {
         List<String> lines = FileUtils.readLines(new File(args[0]));
         FileWriter fw = new FileWriter(new File(args[1]));
         PrintWriter pw = new PrintWriter(fw);
         for (String line : lines)
             pw.println(StringEscapeUtils.unescapeHtml4(line));
         pw.close();//ww w .  j a  v a  2 s  .  co  m
         fw.close();
     }
     String text = "file://&shy;Users/ekeller/Moteur/infotoday_enterprisesearchsourcebook08/Open_on_Windows.exe";
     System.out.println(htmlWrap(text, 20));
     System.out.println(htmlWrapReduce(text, 20, 80));
     String url = "file://Users/ekeller/Moteur/infotoday_enterprisesearchsourcebook08/Open_on_Windows.exe?test=2";
     System.out.println(urlHostPathWrapReduce(url, 80));
 }

From source file:jena.RuleMap.java

/**
 * General command line utility to process one RDF file into another
 * by application of a set of forward chaining rules. 
 * <pre>/* w  w  w  .  j  ava 2s.c  o  m*/
 * Usage:  RuleMap [-il inlang] [-ol outlang] -d infile rulefile
 * </pre>
 */
public static void main(String[] args) {
    try {

        // Parse the command line
        String usage = "Usage:  RuleMap [-il inlang] [-ol outlang] [-d] rulefile infile (- for stdin)";
        final CommandLineParser parser = new DefaultParser();
        Options options = new Options().addOption("il", "inputLang", true, "input language")
                .addOption("ol", "outputLang", true, "output language").addOption("d", "Deductions only?");
        CommandLine cl = parser.parse(options, args);
        final List<String> filenameArgs = cl.getArgList();
        if (filenameArgs.size() != 2) {
            System.err.println(usage);
            System.exit(1);
        }

        String inLang = cl.getOptionValue("inputLang");
        String fname = filenameArgs.get(1);
        Model inModel = null;
        if (fname.equals("-")) {
            inModel = ModelFactory.createDefaultModel();
            inModel.read(System.in, null, inLang);
        } else {
            inModel = FileManager.get().loadModel(fname, inLang);
        }

        String outLang = cl.hasOption("outputLang") ? cl.getOptionValue("outputLang") : "N3";

        boolean deductionsOnly = cl.hasOption('d');

        // Fetch the rule set and create the reasoner
        BuiltinRegistry.theRegistry.register(new Deduce());
        Map<String, String> prefixes = new HashMap<>();
        List<Rule> rules = loadRules(filenameArgs.get(0), prefixes);
        Reasoner reasoner = new GenericRuleReasoner(rules);

        // Process
        InfModel infModel = ModelFactory.createInfModel(reasoner, inModel);
        infModel.prepare();
        infModel.setNsPrefixes(prefixes);

        // Output
        try (PrintWriter writer = new PrintWriter(System.out)) {
            if (deductionsOnly) {
                Model deductions = infModel.getDeductionsModel();
                deductions.setNsPrefixes(prefixes);
                deductions.setNsPrefixes(inModel);
                deductions.write(writer, outLang);
            } else {
                infModel.write(writer, outLang);
            }
        }
    } catch (Throwable t) {
        System.err.println("An error occured: \n" + t);
        t.printStackTrace();
    }
}