Example usage for java.io BufferedReader close

List of usage examples for java.io BufferedReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:io.s4.util.AvroSchemaSupplementer.java

public static void main(String args[]) {
    if (args.length < 1) {
        System.err.println("No schema filename specified");
        System.exit(1);/*from   w  ww  .j a  va  2  s  .com*/
    }

    String filename = args[0];
    FileReader fr = null;
    BufferedReader br = null;
    InputStreamReader isr = null;
    try {
        if (filename == "-") {
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
        } else {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
        }

        String inputLine = "";
        StringBuffer jsonBuffer = new StringBuffer();
        while ((inputLine = br.readLine()) != null) {
            jsonBuffer.append(inputLine);
        }

        JSONObject jsonRecord = new JSONObject(jsonBuffer.toString());

        JSONObject keyPathElementSchema = new JSONObject();
        keyPathElementSchema.put("name", "KeyPathElement");
        keyPathElementSchema.put("type", "record");

        JSONArray fieldsArray = new JSONArray();
        JSONObject fieldRecord = new JSONObject();
        fieldRecord.put("name", "index");
        JSONArray typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyName");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);

        keyPathElementSchema.put("fields", fieldsArray);

        JSONObject keyInfoSchema = new JSONObject();
        keyInfoSchema.put("name", "KeyInfo");
        keyInfoSchema.put("type", "record");

        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "fullKeyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPathElementList");
        JSONObject typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyPathElementSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        keyInfoSchema.put("fields", fieldsArray);

        JSONObject partitionInfoSchema = new JSONObject();
        partitionInfoSchema.put("name", "PartitionInfo");
        partitionInfoSchema.put("type", "record");
        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "partitionId");
        typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundKey");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundValue");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyInfoList");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyInfoSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        partitionInfoSchema.put("fields", fieldsArray);

        fieldRecord = new JSONObject();
        fieldRecord.put("name", "S4__PartitionInfo");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", partitionInfoSchema);
        fieldRecord.put("type", typeRecord);

        fieldsArray = jsonRecord.getJSONArray("fields");
        fieldsArray.put(fieldRecord);

        System.out.println(jsonRecord.toString(3));
    } catch (Exception ioe) {
        throw new RuntimeException(ioe);
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (Exception e) {
            }
        if (isr != null)
            try {
                isr.close();
            } catch (Exception e) {
            }
        if (fr != null)
            try {
                fr.close();
            } catch (Exception e) {
            }
    }
}

From source file:com.genentech.struchk.oeStruchk.OEStruchk.java

/**
 * Command line interface to {@link OEStruchk}.
 *///from  ww  w.ja v a  2  s.c o  m
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nMessages = 0;
    int nErrors = 0;
    int nStruct = 0;
    System.err.printf("OEChem Version: %s\n", oechem.OEChemGetVersion());

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("f", true, "specify the configuration file name");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("noMsg", false, "Do not add any additional sd-tags to the sdf file");
    options.addOption(opt);

    opt = new Option("printRules", true, "Print HTML listing all the rules to filename.");
    options.addOption(opt);

    opt = new Option("errorsAsWarnings", false, "Treat errors as warnings.");
    options.addOption(opt);

    opt = new Option("stopForDebug", false, "Stop and read from stdin for user tu start debugger.");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    args = cmd.getArgs();

    if (cmd.hasOption("stopForDebug")) {
        BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in));
        System.err.print("Please press return:");

        localRdr.readLine();
    }

    URL confFile;
    if (cmd.hasOption("f")) {
        confFile = new File(cmd.getOptionValue("f")).toURI().toURL();
    } else {
        confFile = getResourceURL(OEStruchk.class, "Struchk.xml");
    }
    boolean errorsAsWarnings = cmd.hasOption("errorsAsWarnings");

    if (cmd.hasOption("printRules")) {
        String fName = cmd.getOptionValue("printRules");
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(fName)));
        OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings);
        structFlagAssigner.printRules(out);
        out.close();
        return;
    }

    if (args.length < 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("oeStruck", options);
        throw new Error("missing input file\n");
    }

    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(args[0]));
        StringBuilder mol = new StringBuilder();
        StringBuilder data = new StringBuilder();
        PrintStream out = System.out;
        if (args.length > 1)
            out = new PrintStream(args[1]);

        // create OEStruchk from config file
        OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings);

        OEStruchk structFlagChecker = new OEStruchk(confFile, CHECKConfig.CHECKStructFlag, errorsAsWarnings);

        Pattern sFlagPat = Pattern.compile("<StructFlag>\\s*([^\\n\\r]+)");
        String line;
        boolean inMolFile = true;
        boolean atEnd = false;
        while (!atEnd) {
            if ((line = in.readLine()) == null) {
                if ("".equals(mol.toString().trim()))
                    break;

                if (!inMolFile)
                    throw new Error("Invalid end of sd file!");

                line = "$$$$";
                atEnd = true;
            }

            if (line.startsWith("$$$$")) {

                OEStruchk oeStruchk;
                StructureFlag sFlag = null;
                Matcher mat = sFlagPat.matcher(data);
                if (!mat.find()) {
                    oeStruchk = structFlagAssigner;
                } else {
                    oeStruchk = structFlagChecker;
                    sFlag = StructureFlag.fromString(mat.group(1));
                }
                if (!oeStruchk.applyRules(mol.toString(), null, sFlag))
                    nErrors++;

                out.print(oeStruchk.getTransformedMolfile(null));

                out.print(data);

                if (!cmd.hasOption("noMsg")) {
                    List<Message> msgs = oeStruchk.getStructureMessages(null);
                    if (msgs.size() > 0) {
                        nMessages += msgs.size();

                        out.println("> <errors_oe2>");
                        for (Message msg : msgs)
                            out.printf("%s: %s\n", msg.getLevel(), msg.getText());
                        out.println();
                    }
                    //System.err.println(oeStruchk.getTransformedMolfile("substance"));
                    out.printf("> <outStereo>\n%s\n\n", oeStruchk.getStructureFlag().getName());
                    out.printf("> <TISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles(null));
                    out.printf("> <TSMI>\n%s\n\n", oeStruchk.getTransformedSmiles(null));
                    out.printf("> <pISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles("parent"));
                    out.printf("> <salt>\n%s\n\n", oeStruchk.getSaltCode());
                    out.printf("> <stereoCounts>\n%s.%s\n\n", oeStruchk.countChiralCentersStr(),
                            oeStruchk.countStereoDBondStr());
                }

                out.println(line);
                nStruct++;

                mol.setLength(0);
                data.setLength(0);

                inMolFile = true;
            } else if (!inMolFile || line.startsWith(">")) {
                inMolFile = false;
                data.append(line).append("\n");
            } else {
                mol.append(line).append("\n");
            }
        }

        structFlagAssigner.delete();
        structFlagChecker.delete();

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors,
                nMessages, (System.currentTimeMillis() - start) / 1000);
        if (in != null)
            in.close();
    }
    if (cmd.hasOption("stopForDebug")) {
        BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in));
        System.err.print("Please press return:");

        localRdr.readLine();
    }
}

From source file:net.sf.extjwnl.cli.ewn.java

public static void main(String[] args) throws IOException, JWNLException {
    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(0);//  w  w  w .j  av a 2  s  . c  om
    }
    //find dictionary
    Dictionary d = null;
    File config = new File(defaultConfig);
    if (!config.exists()) {
        if (System.getenv().containsKey("WNHOME")) {
            String wnHomePath = System.getenv().get("WNHOME");
            File wnHome = new File(wnHomePath);
            if (wnHome.exists()) {
                d = Dictionary.getFileBackedInstance(wnHomePath);
            } else {
                log.error("Cannot find dictionary. Make sure " + defaultConfig
                        + " is available or WNHOME variable is set.");
            }
        }
    } else {
        d = Dictionary.getInstance(new FileInputStream(config));
    }

    if (null != d) {
        //parse and execute command line
        if ((-1 < args[0].indexOf('%') && -1 < args[0].indexOf(':')) || "-script".equals(args[0])
                || (-1 < args[0].indexOf('#'))) {
            d.edit();
            //edit
            if ("-script".equals(args[0])) {
                if (args.length < 2) {
                    log.error("Filename missing for -script command");
                    System.exit(1);
                } else {
                    File script = new File(args[1]);
                    if (script.exists()) {
                        //load into args
                        ArrayList<String> newArgs = new ArrayList<String>();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(new FileInputStream(script), "UTF-8"));
                        try {
                            String str;
                            while ((str = in.readLine()) != null) {
                                String[] bits = str.split(" ");
                                StringBuilder tempArg = null;
                                for (String bit : bits) {
                                    int quoteCnt = 0;
                                    for (int j = 0; j < bit.length(); j++) {
                                        if ('"' == bit.charAt(j)) {
                                            quoteCnt++;
                                        }
                                    }
                                    if (null != tempArg) {
                                        if (0 == quoteCnt) {
                                            tempArg.append(" ").append(bit);
                                        } else {
                                            tempArg.append(" ").append(bit.replaceAll("\"\"", "\""));
                                            if (1 == (quoteCnt % 2)) {
                                                newArgs.add(
                                                        tempArg.toString().substring(1, tempArg.length() - 1));
                                                tempArg = null;
                                            }
                                        }
                                    } else {
                                        if (0 == quoteCnt) {
                                            newArgs.add(bit);
                                        } else {
                                            if (1 == (quoteCnt % 2)) {
                                                tempArg = new StringBuilder(bit.replaceAll("\"\"", "\""));
                                            } else {
                                                newArgs.add(bit.replaceAll("\"\"", "\""));
                                            }
                                        }
                                    }
                                }
                                if (null != tempArg) {
                                    newArgs.add(tempArg.toString());
                                }
                            }
                        } finally {
                            try {
                                in.close();
                            } catch (IOException e) {
                                //nop
                            }
                        }
                        args = newArgs.toArray(args);
                    }
                }
            }

            Word workWord = null;
            String key = null;
            String lemma = null;
            int lexFileNum = -1;
            int lexId = -1;
            //                String headLemma = null;
            //                int headLexId = -1;
            POS pos = null;
            String derivation = null;

            for (int i = 0; i < args.length; i++) {
                if (null == key && '-' != args[i].charAt(0)
                        && ((-1 < args[i].indexOf('%') && -1 < args[i].indexOf(':')))) {
                    key = args[i];
                    log.info("Searching " + key + "...");
                    if (null != key) {
                        workWord = d.getWordBySenseKey(key);
                    }
                    if (null == workWord) {
                        //parse sensekey
                        lemma = key.substring(0, key.indexOf('%')).replace('_', ' ');
                        String posId = key.substring(key.indexOf('%') + 1, key.indexOf(':'));
                        if ("1".equals(posId) || "2".equals(posId) || "3".equals(posId) || "4".equals(posId)
                                || "5".equals(posId)) {
                            pos = POS.getPOSForId(Integer.parseInt(posId));
                            String lexFileString = key.substring(key.indexOf(':') + 1);
                            if (-1 < lexFileString.indexOf(':')) {
                                lexFileNum = Integer
                                        .parseInt(lexFileString.substring(0, lexFileString.indexOf(':')));
                                if (lexFileString.indexOf(':') + 1 < lexFileString.length()) {
                                    String lexIdString = lexFileString
                                            .substring(lexFileString.indexOf(':') + 1);
                                    if (-1 < lexIdString.indexOf(':')) {
                                        lexId = Integer
                                                .parseInt(lexIdString.substring(0, lexIdString.indexOf(':')));
                                        //                                            if (lexIdString.indexOf(':') + 1 < lexIdString.length()) {
                                        //                                                headLemma = lexIdString.substring(lexIdString.indexOf(':') + 1);
                                        //                                                if (-1 < headLemma.indexOf(':')) {
                                        //                                                    headLemma = headLemma.substring(0, headLemma.indexOf(':'));
                                        //                                                    if (null != headLemma && !"".equals(headLemma) && lexIdString.lastIndexOf(':') + 1 < lexIdString.length()) {
                                        //                                                        headLexId = Integer.parseInt(lexIdString.substring(lexIdString.lastIndexOf(':') + 1));
                                        //                                                    }
                                        //                                                } else {
                                        //                                                    log.error("Malformed sensekey " + key);
                                        //                                                    System.exit(1);
                                        //                                                }
                                        //                                            }
                                    } else {
                                        log.error("Malformed sensekey " + key);
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Malformed sensekey " + key);
                                    System.exit(1);
                                }
                            } else {
                                log.error("Malformed sensekey " + key);
                                System.exit(1);
                            }
                        } else {
                            log.error("Malformed sensekey " + key);
                            System.exit(1);
                        }
                    }
                } else if (-1 < args[i].indexOf('#')) {
                    if (2 < args[i].length()) {
                        derivation = args[i].substring(2);
                        if (null == derivation) {
                            log.error("Missing derivation");
                            System.exit(1);
                        } else {
                            pos = POS.getPOSForKey(args[i].substring(0, 1));
                            if (null == pos) {
                                log.error("POS " + args[i] + " is not recognized for derivation " + derivation);
                                System.exit(1);
                            }
                        }
                    }
                }

                if ("-add".equals(args[i])) {
                    if (null == key) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    }
                    if (null != workWord) {
                        log.error("Duplicate sensekey " + workWord.getSenseKey());
                        System.exit(1);
                    }
                    log.info("Creating " + pos.getLabel() + " synset...");
                    Synset tempSynset = d.createSynset(pos);
                    log.info("Creating word " + lemma + "...");
                    workWord = new Word(d, tempSynset, 1, lemma);
                    workWord.setLexId(lexId);
                    tempSynset.getWords().add(workWord);
                    tempSynset.setLexFileNum(lexFileNum);
                    key = null;
                }

                if ("-remove".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        d.removeSynset(workWord.getSynset());
                        workWord = null;
                        key = null;
                    }
                }

                if ("-addword".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            Word tempWord = new Word(d, workWord.getSynset(),
                                    workWord.getSynset().getWords().size() + 1, args[i]);
                            workWord.getSynset().getWords().add(tempWord);
                            key = null;
                        } else {
                            log.error(
                                    "Missing word for addword command for sensekey " + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-removeword".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        workWord.getSynset().getWords().remove(workWord);
                        key = null;
                    }
                }

                if ("-setgloss".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.getSynset().setGloss(args[i]);
                            key = null;
                        } else {
                            log.error("Missing gloss for setgloss command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setadjclus".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.getSynset().setIsAdjectiveCluster(Boolean.parseBoolean(args[i]));
                            key = null;
                        } else {
                            log.error("Missing flag for setadjclus command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setverbframe".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            if (workWord instanceof Verb) {
                                Verb verb = (Verb) workWord;
                                if ('-' == args[i].charAt(0)) {
                                    verb.getVerbFrameFlags().clear(Integer.parseInt(args[i].substring(1)));
                                } else {
                                    verb.getVerbFrameFlags().set(Integer.parseInt(args[i]));
                                }
                            } else {
                                log.error("Word at " + workWord.getSenseKey() + " should be verb");
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing index for setverbframe command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setverbframeall".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            if (workWord.getSynset() instanceof VerbSynset) {
                                if ('-' == args[i].charAt(0)) {
                                    workWord.getSynset().getVerbFrameFlags()
                                            .clear(Integer.parseInt(args[i].substring(1)));
                                } else {
                                    workWord.getSynset().getVerbFrameFlags().set(Integer.parseInt(args[i]));
                                }
                            } else {
                                log.error("Synset at " + workWord.getSenseKey() + " should be verb");
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing index for setverbframeall command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setlexfile".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            if (-1 < args[i].indexOf('.')) {
                                workWord.getSynset()
                                        .setLexFileNum(LexFileNameLexFileIdMap.getMap().get(args[i]));
                            } else {
                                workWord.getSynset().setLexFileNum(Integer.parseInt(args[i]));
                            }
                        } else {
                            log.error("Missing file number or name for setlexfile command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-addptr".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            Word targetWord = d.getWordBySenseKey(args[i]);
                            if (null != targetWord) {
                                i++;
                                if (i < args.length) {
                                    PointerType pt = PointerType.getPointerTypeForKey(args[i]);
                                    if (null != pt) {
                                        Pointer p;
                                        if (pt.isLexical()) {
                                            p = new Pointer(pt, workWord, targetWord);
                                        } else {
                                            p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset());
                                        }
                                        if (!workWord.getSynset().getPointers().contains(p)) {
                                            workWord.getSynset().getPointers().add(p);
                                        } else {
                                            log.error("Duplicate pointer of type " + pt + " to "
                                                    + targetWord.getSenseKey()
                                                    + " in addptr command for sensekey "
                                                    + workWord.getSenseKey());
                                            System.exit(1);
                                        }
                                    } else {
                                        log.error("Invalid pointer type at " + args[i]
                                                + " in addptr command for sensekey " + workWord.getSenseKey());
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Missing pointer type at " + args[i]
                                            + " in addptr command for sensekey " + workWord.getSenseKey());
                                    System.exit(1);
                                }
                            } else {
                                log.error("Missing target at " + args[i] + " in addptr command for sensekey "
                                        + workWord.getSenseKey());
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing sensekey for addptr command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-removeptr".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            Word targetWord = d.getWordBySenseKey(args[i]);
                            if (null != targetWord) {
                                i++;
                                if (i < args.length) {
                                    PointerType pt = PointerType.getPointerTypeForKey(args[i]);
                                    if (null != pt) {
                                        Pointer p;
                                        if (pt.isLexical()) {
                                            p = new Pointer(pt, workWord, targetWord);
                                        } else {
                                            p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset());
                                        }
                                        if (workWord.getSynset().getPointers().contains(p)) {
                                            workWord.getSynset().getPointers().remove(p);
                                        } else {
                                            log.error("Missing pointer of type " + pt + " to "
                                                    + targetWord.getSenseKey()
                                                    + " in removeptr command for sensekey "
                                                    + workWord.getSenseKey());
                                            System.exit(1);
                                        }
                                    } else {
                                        log.error("Invalid pointer type at " + args[i]
                                                + " in removeptr command for sensekey "
                                                + workWord.getSenseKey());
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Missing pointer type at " + args[i]
                                            + " in removeptr command for sensekey " + workWord.getSenseKey());
                                    System.exit(1);
                                }
                            } else {
                                log.error("Missing target at " + args[i] + " in removeptr command for sensekey "
                                        + workWord.getSenseKey());
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing sensekey for removeptr command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setlexid".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.setLexId(Integer.parseInt(args[i]));
                            key = null;
                        } else {
                            log.error("Missing lexid for setlexid command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setusecount".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.setUseCount(Integer.parseInt(args[i]));
                            key = null;
                        } else {
                            log.error("Missing count for setusecount command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-addexc".equals(args[i])) {
                    i++;
                    if (i < args.length && '-' != args[i].charAt(0)) {
                        String baseform = args[i];
                        Exc e = d.getException(pos, derivation);
                        if (null != e) {
                            if (null != e.getExceptions()) {
                                if (!e.getExceptions().contains(baseform)) {
                                    e.getExceptions().add(baseform);
                                }
                            }
                        } else {
                            ArrayList<String> list = new ArrayList<String>(1);
                            list.add(baseform);
                            d.createException(pos, derivation, list);
                        }
                        derivation = null;
                    } else {
                        log.error("Missing baseform for addexc command for derivation " + derivation);
                        System.exit(1);
                    }
                }

                if ("-removeexc".equals(args[i])) {
                    Exc e = d.getException(pos, derivation);
                    if (null != e) {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            String baseform = args[i];
                            if (null != e.getExceptions()) {
                                if (e.getExceptions().contains(baseform)) {
                                    e.getExceptions().remove(baseform);
                                }
                                if (0 == e.getExceptions().size()) {
                                    d.removeException(e);
                                }
                            }
                        } else {
                            d.removeException(e);
                        }
                    } else {
                        log.error("Missing derivation " + derivation);
                        System.exit(1);
                    }
                    derivation = null;
                }
            }

            d.save();
        } else {
            //browse
            String key = args[0];
            if (1 == args.length) {
                for (POS pos : POS.getAllPOS()) {
                    IndexWord iw = d.getIndexWord(pos, key);
                    if (null == iw) {
                        System.out.println("\nNo information available for " + pos.getLabel() + " " + key);
                    } else {
                        System.out.println(
                                "\nInformation available for " + iw.getPOS().getLabel() + " " + iw.getLemma());
                        printAvailableInfo(iw);
                    }
                    if (null != d.getMorphologicalProcessor()) {
                        List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key);
                        if (null != forms) {
                            for (String form : forms) {
                                if (!key.equals(form)) {
                                    iw = d.getIndexWord(pos, form);
                                    if (null != iw) {
                                        System.out.println("\nInformation available for "
                                                + iw.getPOS().getLabel() + " " + iw.getLemma());
                                        printAvailableInfo(iw);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                boolean needHelp = false;
                boolean needGloss = false;
                boolean needLex = false;
                boolean needOffset = false;
                boolean needSenseNum = false;
                boolean needSenseKeys = false;
                int needSense = 0;
                for (String arg : args) {
                    if ("-h".equals(arg)) {
                        needHelp = true;
                    }
                    if ("-g".equals(arg)) {
                        needGloss = true;
                    }
                    if ("-a".equals(arg)) {
                        needLex = true;
                    }
                    if ("-o".equals(arg)) {
                        needOffset = true;
                    }
                    if ("-s".equals(arg)) {
                        needSenseNum = true;
                    }
                    if ("-k".equals(arg)) {
                        needSenseKeys = true;
                    }
                    if (arg.startsWith("-n") && 2 < arg.length()) {
                        needSense = Integer.parseInt(arg.substring(2));
                    }
                }

                for (String arg : args) {
                    if (arg.startsWith("-ants") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display synsets containing direct antonyms of the search string.\n" + "\n"
                                            + "Direct antonyms are a pair of words between which there is an\n"
                                            + "associative bond built up by co-occurrences.\n" + "\n"
                                            + "Antonym synsets are preceded by \"=>\".");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nAntonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ANTONYM, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //ants

                    if (arg.startsWith("-hype") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Recursively display hypernym (superordinate) tree for the search\n"
                                            + "string.\n" + "\n"
                                            + "Hypernym is the generic term used to designate a whole class of\n"
                                            + "specific instances.  Y is a hypernym of X if X is a (kind of) Y.\n"
                                            + "\n"
                                            + "Hypernym synsets are preceded by \"=>\", and are indented from\n"
                                            + "the left according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHypernyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hype

                    if (arg.startsWith("-hypo") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display immediate hyponyms (subordinates) for the search string.\n" + "\n"
                                            + "Hyponym is the generic term used to designate a member of a class.\n"
                                            + "X is a hyponym of Y if X is a (kind of) Y.\n" + "\n"
                                            + "Hyponym synsets are preceded by \"=>\".");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPONYM, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //hypo

                    if (arg.startsWith("-tree") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display hyponym (subordinate) tree for the search string.  This is\n"
                                            + "a recursive search that finds the hyponyms of each hyponym. \n"
                                            + "\n"
                                            + "Hyponym is the generic term used to designate a member of a class.\n"
                                            + "X is a hyponym of Y if X is a (kind of) Y. \n" + "\n"
                                            + "Hyponym synsets are preceded by \"=>\", and are indented from the left\n"
                                            + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPONYM, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //tree

                    if (arg.startsWith("-enta") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Recursively display entailment relations of the search string.\n" + "\n"
                                            + "The action represented by the verb X entails Y if X cannot be done\n"
                                            + "unless Y is, or has been, done.\n" + "\n"
                                            + "Entailment synsets are preceded by \"=>\", and are indented from the left\n"
                                            + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nEntailment of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ENTAILMENT, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //enta

                    if (arg.startsWith("-syns") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSynonyms of " + p.getLabel() + " " + iw.getLemma());
                            if (POS.ADJECTIVE == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Display synonyms and synsets related to synsets containing\n"
                                                    + "the search string.  If the search string is in a head synset\n"
                                                    + "the 'cluster's' satellite synsets are displayed.  If the search\n"
                                                    + "string is in a satellite synset, its head synset is displayed.\n"
                                                    + "If the search string is a pertainym the word or synset that it\n"
                                                    + "pertains to is displayed.\n" + "\n"
                                                    + "A cluster is a group of adjective synsets that are organized around\n"
                                                    + "antonymous pairs or triplets.  An adjective cluster contains two or more\n"
                                                    + "head synsets that contan antonyms.  Each head synset has one or more\n"
                                                    + "satellite synsets.\n" + "\n"
                                                    + "A head synset contains at least one word that has a direct antonym\n"
                                                    + "in another head synset of the same cluster.\n" + "\n"
                                                    + "A satellite synset represents a concept that is similar in meaning to\n"
                                                    + "the concept represented by its head synset.\n" + "\n"
                                                    + "Direct antonyms are a pair of words between which there is an\n"
                                                    + "associative bond built up by co-occurrences.\n" + "\n"
                                                    + "Direct antonyms are printed in parentheses following the adjective.\n"
                                                    + "The position of an adjective in relation to the noun may be restricted\n"
                                                    + "to the prenominal, postnominal or predicative position.  Where present\n"
                                                    + "these restrictions are noted in parentheses.\n" + "\n"
                                                    + "A pertainym is a relational adjective, usually defined by such phrases\n"
                                                    + "as \"of or pertaining to\" and that does not have an antonym.  It pertains\n"
                                                    + "to a noun or another pertainym.\n" + "\n"
                                                    + "Senses contained in head synsets are displayed above the satellites,\n"
                                                    + "which are indented and preceded by \"=>\".  Senses contained in\n"
                                                    + "satellite synsets are displayed with the head synset below.  The head\n"
                                                    + "synset is preceded by \"=>\".\n" + "\n"
                                                    + "Pertainym senses display the word or synsets that the search string\n"
                                                    + "pertains to.");
                                }
                                tracePointers(iw, PointerType.SIMILAR_TO, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                                tracePointers(iw, PointerType.PARTICIPLE_OF, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                            }

                            if (POS.ADVERB == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Display synonyms and synsets related to synsets containing\n"
                                                    + "the search string.  If the search string is a pertainym the word\n"
                                                    + "or synset that it pertains to is displayed.\n" + "\n"
                                                    + "A pertainym is a relational adverb that is derived from an adjective.\n"
                                                    + "\n"
                                                    + "Pertainym senses display the word that the search string is derived from\n"
                                                    + "and the adjective synset that contains the word.  If the adjective synset\n"
                                                    + "is a satellite synset, its head synset is also displayed.");
                                }
                                tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                            }

                            if (POS.NOUN == p || POS.VERB == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Recursively display hypernym (superordinate) tree for the search\n"
                                                    + "string.\n" + "\n"
                                                    + "Hypernym is the generic term used to designate a whole class of\n"
                                                    + "specific instances.  Y is a hypernym of X if X is a (kind of) Y.\n"
                                                    + "\n"
                                                    + "Hypernym synsets are preceded by \"=>\", and are indented from\n"
                                                    + "the left according to their level in the hierarchy.");
                                }
                                tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense,
                                        needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            }
                        }
                    } //syns

                    if (arg.startsWith("-smem") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMember Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //smem

                    if (arg.startsWith("-ssub") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSubstance Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //ssub

                    if (arg.startsWith("-sprt") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPart Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //sprt

                    if (arg.startsWith("-memb") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMember Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //memb

                    if (arg.startsWith("-subs") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSubstance Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //subs

                    if (arg.startsWith("-part") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPart Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //part

                    if (arg.startsWith("-mero") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //mero

                    if (arg.startsWith("-holo") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //holo

                    if (arg.startsWith("-caus") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Recursively display CAUSE TO relations of the search string.\n"
                                    + "\n"
                                    + "The action represented by the verb X causes the action represented by\n"
                                    + "the verb Y.\n" + "\n"
                                    + "CAUSE TO synsets are preceded by \"=>\", and are indented from the left\n"
                                    + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\n'Cause to' of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CAUSE, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //caus

                    if (arg.startsWith("-pert") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPertainyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //pert

                    if (arg.startsWith("-attr") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        if (needHelp) {
                            if (POS.NOUN == p) {
                                System.out
                                        .println("Display adjectives for which search string is an attribute.");
                            }
                            if (POS.ADJECTIVE == p) {
                                System.out.println("Display nouns that are attributes of search string.");
                            }
                        }
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nAttributes of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ATTRIBUTE, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //attr

                    if (arg.startsWith("-deri") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display derived forms - nouns and verbs that are related morphologically.\n"
                                            + "Each related synset is preceeded by its part of speech. Each word in the\n"
                                            + "synset is followed by its sense number.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDerived forms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.NOMINALIZATION, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //deri

                    if (arg.startsWith("-domn") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display domain to which this synset belongs.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CATEGORY, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.USAGE, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.REGION, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //domn

                    if (arg.startsWith("-domt") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all synsets belonging to the domain.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CATEGORY_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.USAGE_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.REGION_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //domt

                    if (arg.startsWith("-faml") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display familiarity and polysemy information for the search string.\n"
                                            + "The polysemy count is the number of senses in WordNet.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            String[] freqs = { "extremely rare", "very rare", "rare", "uncommon", "common",
                                    "familiar", "very familiar", "extremely familiar" };
                            String[] pos = { "a noun", "a verb", "an adjective", "an adverb" };
                            int cnt = iw.getSenses().size();
                            int familiar = 0;
                            if (cnt == 0) {
                                familiar = 0;
                            }
                            if (cnt == 1) {
                                familiar = 1;
                            }
                            if (cnt == 2) {
                                familiar = 2;
                            }
                            if (cnt >= 3 && cnt <= 4) {
                                familiar = 3;
                            }
                            if (cnt >= 5 && cnt <= 8) {
                                familiar = 4;
                            }
                            if (cnt >= 9 && cnt <= 16) {
                                familiar = 5;
                            }
                            if (cnt >= 17 && cnt <= 32) {
                                familiar = 6;
                            }
                            if (cnt > 32) {
                                familiar = 7;
                            }
                            System.out.println("\n" + iw.getLemma() + " used as " + pos[p.getId() - 1] + " is "
                                    + freqs[familiar] + " (polysemy count = " + cnt + ")");
                        }
                    } //faml

                    if (arg.startsWith("-fram") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display applicable verb sentence frames for the search string.\n" + "\n"
                                            + "A frame is a sentence template illustrating the usage of a verb.\n"
                                            + "\n"
                                            + "Verb sentence frames are preceded with the string \"*>\" if a sentence\n"
                                            + "frame is acceptable for all of the words in the synset, and with \"=>\"\n"
                                            + "if a sentence frame is acceptable for the search string only.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nVerb frames of " + p.getLabel() + " " + iw.getLemma());
                            for (int i = 0; i < iw.getSenses().size(); i++) {
                                Synset synset = iw.getSenses().get(i);
                                for (String vf : synset.getVerbFrames()) {
                                    System.out.println("\t*> " + vf);
                                }
                                for (Word word : synset.getWords()) {
                                    if (iw.getLemma().equalsIgnoreCase(word.getLemma())) {
                                        if (word instanceof Verb) {
                                            Verb verb = (Verb) word;
                                            for (String vf : verb.getVerbFrames()) {
                                                System.out.println("\t=> " + vf);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } //fram

                    if (arg.startsWith("-hmer") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display meronyms for search string tree.  This is a recursive search\n"
                                            + "the prints all the meronyms of the search string and all of its\n"
                                            + "hypernyms. \n" + "\n"
                                            + "A meronym is the name of a constituent part, the substance of, or a\n"
                                            + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hmer

                    if (arg.startsWith("-hhol") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "\"Display holonyms for search string tree.  This is a recursive search\n"
                                            + "that prints all the holonyms of the search string and all of the\n"
                                            + "holonym's holonyms.\n" + "\n"
                                            + "A holonym is the name of the whole of which the meronym names a part.\n"
                                            + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hhol

                    if (arg.startsWith("-mero") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //mero

                    if (arg.startsWith("-grep") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out
                                    .println("Print all strings in the database containing the search string\n"
                                            + "as an individual word, or as the first or last string in a word or\n"
                                            + "collocation.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        System.out.println("\nGrep of " + p.getLabel() + " " + key);
                        Iterator<IndexWord> ii = d.getIndexWordIterator(p, key);
                        while (ii.hasNext()) {
                            System.out.println(ii.next().getLemma());
                        }
                    } //grep

                    if ("-over".equals(arg)) {
                        for (POS pos : POS.getAllPOS()) {
                            if (null != d.getMorphologicalProcessor()) {
                                IndexWord iw = d.getIndexWord(pos, key);
                                //for plurals like species, glasses
                                if (null != iw && key.equals(iw.getLemma())) {
                                    printOverview(pos, iw, needGloss, needLex, needOffset, needSenseNum,
                                            needSenseKeys);
                                }

                                List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key);
                                if (null != forms) {
                                    for (String form : forms) {
                                        if (!form.equals(key)) {
                                            iw = d.getIndexWord(pos, form);
                                            if (null != iw) {
                                                printOverview(pos, iw, needGloss, needLex, needOffset,
                                                        needSenseNum, needSenseKeys);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } //over
                }
            }
        }
    }
}

From source file:com.yahoo.labs.yamall.local.Yamall.java

public static void main(String[] args) {
    String[] remainingArgs = null;
    String inputFile = null;//from   ww w . ja  va  2s. co  m
    String predsFile = null;
    String saveModelFile = null;
    String initialModelFile = null;
    String lossName = null;
    String parserName = null;
    String linkName = null;
    String invertHashName = null;
    double learningRate = 1;
    String minPredictionString = null;
    String maxPredictionString = null;
    String fmNumberFactorsString = null;
    int bitsHash;
    int numberPasses;
    int holdoutPeriod = 10;

    boolean testOnly = false;
    boolean exponentialProgress;
    double progressInterval;

    options.addOption("h", "help", false, "displays this help");
    options.addOption("t", false, "ignore label information and just test");
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("binary")
            .desc("reports loss as binary classification with -1,1 labels").build());
    options.addOption(
            Option.builder().hasArg(false).required(false).longOpt("solo").desc("uses SOLO optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pcsolo")
            .desc("uses Per Coordinate SOLO optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pistol")
            .desc("uses PiSTOL optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("kt")
            .desc("(EXPERIMENTAL) uses KT optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pckt")
            .desc("(EXPERIMENTAL) uses Per Coordinate KT optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("pccocob")
            .desc("(EXPERIMENTAL) uses Per Coordinate COCOB optimizer").build());
    options.addOption(Option.builder().hasArg(false).required(false).longOpt("cocob")
            .desc("(EXPERIMENTAL) uses COCOB optimizer").build());
    options.addOption(
            Option.builder().hasArg(false).required(false).longOpt("fm").desc("Factorization Machine").build());
    options.addOption(Option.builder("f").hasArg(true).required(false).desc("final regressor to save")
            .type(String.class).longOpt("final_regressor").build());
    options.addOption(Option.builder("p").hasArg(true).required(false).desc("file to output predictions to")
            .longOpt("predictions").type(String.class).build());
    options.addOption(
            Option.builder("i").hasArg(true).required(false).desc("initial regressor(s) to load into memory")
                    .longOpt("initial_regressor").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc(
            "specify the loss function to be used. Currently available ones are: absolute, squared (default), hinge, logistic")
            .longOpt("loss_function").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc(
            "specify the link function used in the output of the predictions. Currently available ones are: identity (default), logistic")
            .longOpt("link").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("output human-readable final regressor with feature names").longOpt("invert_hash")
            .type(String.class).build());
    options.addOption(
            Option.builder("l").hasArg(true).required(false).desc("set (initial) learning Rate, default = 1.0")
                    .longOpt("learning_rate").type(String.class).build());
    options.addOption(Option.builder("b").hasArg(true).required(false)
            .desc("number of bits in the feature table, default = 18").longOpt("bit_precision")
            .type(String.class).build());
    options.addOption(Option.builder("P").hasArg(true).required(false)
            .desc("progress update frequency, integer: additive; float: multiplicative, default = 2.0")
            .longOpt("progress").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("smallest prediction to output, before the link function, default = -50")
            .longOpt("min_prediction").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("smallest prediction to output, before the link function, default = 50")
            .longOpt("max_prediction").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("ignore namespaces beginning with the characters in <arg>").longOpt("ignore")
            .type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc("number of training passes")
            .longOpt("passes").type(String.class).build());
    options.addOption(
            Option.builder().hasArg(true).required(false).desc("holdout period for test only, default = 10")
                    .longOpt("holdout_period").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("number of factors for Factorization Machines default = 8").longOpt("fmNumberFactors")
            .type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false)
            .desc("specify the parser to use. Currently available ones are: vw (default), libsvm, tsv")
            .longOpt("parser").type(String.class).build());
    options.addOption(Option.builder().hasArg(true).required(false).desc("schema file for the TSV input")
            .longOpt("schema").type(String.class).build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("Unrecognized option");
        help();
    }
    if (cmd.hasOption("h"))
        help();
    if (cmd.hasOption("t"))
        testOnly = true;
    if (cmd.hasOption("binary")) {
        binary = true;
        System.out.println("Reporting binary loss");
    }
    initialModelFile = cmd.getOptionValue("i");
    predsFile = cmd.getOptionValue("p");
    lossName = cmd.getOptionValue("loss_function", "squared");
    linkName = cmd.getOptionValue("link", "identity");
    saveModelFile = cmd.getOptionValue("f");
    learningRate = Double.parseDouble(cmd.getOptionValue("l", "1.0"));
    bitsHash = Integer.parseInt(cmd.getOptionValue("b", "18"));
    invertHashName = cmd.getOptionValue("invert_hash");
    minPredictionString = cmd.getOptionValue("min_prediction", "-50");
    maxPredictionString = cmd.getOptionValue("max_prediction", "50");
    fmNumberFactorsString = cmd.getOptionValue("fmNumberFactors", "8");
    parserName = cmd.getOptionValue("parser", "vw");

    numberPasses = Integer.parseInt(cmd.getOptionValue("passes", "1"));
    System.out.println("Number of passes = " + numberPasses);
    if (numberPasses > 1) {
        holdoutPeriod = Integer.parseInt(cmd.getOptionValue("holdout_period", "10"));
        System.out.println("Holdout period = " + holdoutPeriod);
    }

    remainingArgs = cmd.getArgs();
    if (remainingArgs.length == 1)
        inputFile = remainingArgs[0];

    InstanceParser instanceParser = null;
    if (parserName.equals("vw"))
        instanceParser = new VWParser(bitsHash, cmd.getOptionValue("ignore"), (invertHashName != null));
    else if (parserName.equals("libsvm"))
        instanceParser = new LIBSVMParser(bitsHash, (invertHashName != null));
    else if (parserName.equals("tsv")) {
        String schema = cmd.getOptionValue("schema");
        if (schema == null) {
            System.out.println("TSV parser requires a schema file.");
            System.exit(0);
        } else {
            String spec = null;
            try {
                spec = new String(Files.readAllBytes(Paths.get(schema)));
            } catch (IOException e) {
                System.out.println("Error reading the TSV schema file.");
                e.printStackTrace();
                System.exit(0);
            }
            instanceParser = new TSVParser(bitsHash, cmd.getOptionValue("ignore"), (invertHashName != null),
                    spec);
        }
    } else {
        System.out.println("Unknown parser.");
        System.exit(0);
    }
    System.out.println("Num weight bits = " + bitsHash);

    // setup progress
    String progress = cmd.getOptionValue("P", "2.0");
    if (progress.indexOf('.') >= 0) {
        exponentialProgress = true;
        progressInterval = (double) Double.parseDouble(progress);
    } else {
        exponentialProgress = false;
        progressInterval = (double) Integer.parseInt(progress);
    }

    // min and max predictions
    minPrediction = (double) Double.parseDouble(minPredictionString);
    maxPrediction = (double) Double.parseDouble(maxPredictionString);

    // number of factors for Factorization Machines
    fmNumberFactors = (int) Integer.parseInt(fmNumberFactorsString);

    // configure the learner
    Loss lossFnc = null;
    LinkFunction link = null;
    if (initialModelFile == null) {
        if (cmd.hasOption("kt")) {
            learner = new KT(bitsHash);
        } else if (cmd.hasOption("pckt")) {
            learner = new PerCoordinateKT(bitsHash);
        } else if (cmd.hasOption("pcsolo")) {
            learner = new PerCoordinateSOLO(bitsHash);
        } else if (cmd.hasOption("solo")) {
            learner = new SOLO(bitsHash);
        } else if (cmd.hasOption("pccocob")) {
            learner = new PerCoordinateCOCOB(bitsHash);
        } else if (cmd.hasOption("cocob")) {
            learner = new COCOB(bitsHash);
        } else if (cmd.hasOption("pistol")) {
            learner = new PerCoordinatePiSTOL(bitsHash);
        } else if (cmd.hasOption("fm")) {
            learner = new SGD_FM(bitsHash, fmNumberFactors);
        } else
            learner = new SGD_VW(bitsHash);
    } else {
        learner = IOLearner.loadLearner(initialModelFile);
    }

    // setup link function
    if (linkName.equals("identity")) {
        link = new IdentityLinkFunction();
    } else if (linkName.equals("logistic")) {
        link = new LogisticLinkFunction();
    } else {
        System.out.println("Unknown link function.");
        System.exit(0);
    }

    // setup loss function
    if (lossName.equals("squared")) {
        lossFnc = new SquareLoss();
    } else if (lossName.equals("hinge")) {
        lossFnc = new HingeLoss();
    } else if (lossName.equals("logistic")) {
        lossFnc = new LogisticLoss();
    } else if (lossName.equals("absolute")) {
        lossFnc = new AbsLoss();
    } else {
        System.out.println("Unknown loss function.");
        System.exit(0);
    }

    learner.setLoss(lossFnc);
    learner.setLearningRate(learningRate);

    // maximum range predictions
    System.out.println("Max prediction = " + maxPrediction + ", Min Prediction = " + minPrediction);
    // print information about the learner
    System.out.println(learner.toString());
    // print information about the link function
    System.out.println(link.toString());
    // print information about the parser
    System.out.println(instanceParser.toString());
    // print information about ignored namespaces
    System.out.println("Ignored namespaces = " + cmd.getOptionValue("ignore", ""));

    long start = System.nanoTime();
    FileInputStream fstream;
    try {
        BufferedReader br = null;
        if (inputFile != null) {
            fstream = new FileInputStream(inputFile);
            System.out.println("Reading datafile = " + inputFile);
            br = new BufferedReader(new InputStreamReader(fstream));
        } else {
            System.out.println("Reading from console");
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        File fout = null;
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        if (predsFile != null) {
            fout = new File(predsFile);
            fos = new FileOutputStream(fout);
            bw = new BufferedWriter(new OutputStreamWriter(fos));
        }

        try {
            System.out.println("average       example  current  current  current");
            System.out.println("loss          counter    label  predict  features");
            int iter = 0;
            double cumLoss = 0;
            double weightedSampleSum = 0;
            double sPlus = 0;
            double sMinus = 0;
            Instance sample = null;
            boolean justPrinted = false;
            int pass = 0;
            ObjectOutputStream ooutTr = null;
            ObjectOutputStream ooutHO = null;
            ObjectInputStream oinTr = null;
            double pred = 0;
            int limit = 1;
            double hError = Double.MAX_VALUE;
            double lastHError = Double.MAX_VALUE;
            int numTestSample = 0;
            int numTrainingSample = 0;
            int idx = 0;

            if (numberPasses > 1) {
                ooutTr = new ObjectOutputStream(new FileOutputStream("cache_training.bin"));
                ooutHO = new ObjectOutputStream(new FileOutputStream("cache_holdout.bin"));
                oinTr = new ObjectInputStream(new FileInputStream("cache_training.bin"));
            }

            do {
                while (true) {
                    double score;

                    if (pass > 0 && numberPasses > 1) {
                        Instance tmp = (Instance) oinTr.readObject();
                        if (tmp != null)
                            sample = tmp;
                        else
                            break;
                    } else {
                        String strLine = br.readLine();
                        if (strLine != null)
                            sample = instanceParser.parse(strLine);
                        else
                            break;
                    }

                    justPrinted = false;
                    idx++;

                    if (numberPasses > 1 && pass == 0 && idx % holdoutPeriod == 0) {
                        // store the current sample for the holdout set
                        ooutHO.writeObject(sample);
                        ooutHO.reset();
                        numTestSample++;
                    } else {
                        if (numberPasses > 1 && pass == 0) {
                            ooutTr.writeObject(sample);
                            ooutTr.reset();
                            numTrainingSample++;
                        }

                        iter++;
                        if (testOnly) {
                            // predict the sample
                            score = learner.predict(sample);
                        } else {
                            // predict the sample and update the classifier using the sample
                            score = learner.update(sample);
                        }
                        score = Math.min(Math.max(score, minPrediction), maxPrediction);
                        pred = link.apply(score);
                        if (!binary)
                            cumLoss += learner.getLoss().lossValue(score, sample.getLabel())
                                    * sample.getWeight();
                        else if (Math.signum(score) != sample.getLabel())
                            cumLoss += sample.getWeight();

                        weightedSampleSum += sample.getWeight();
                        if (sample.getLabel() > 0)
                            sPlus = sPlus + sample.getWeight();
                        else
                            sMinus = sMinus + sample.getWeight();

                        // output predictions to file
                        if (predsFile != null) {
                            bw.write(String.format("%.6f %s", pred, sample.getTag()));
                            bw.newLine();
                        }

                        // print statistics to screen
                        if (iter == limit) {
                            justPrinted = true;
                            System.out.printf("%.6f %12d  % .4f  % .4f  %d\n", cumLoss / weightedSampleSum,
                                    iter, sample.getLabel(), pred, sample.getVector().size());
                            if (exponentialProgress)
                                limit *= progressInterval;
                            else
                                limit += progressInterval;
                        }
                    }
                }
                if (numberPasses > 1) {
                    if (pass == 0) { // finished first pass of many
                        // write a null at the end of the files
                        ooutTr.writeObject(null);
                        ooutHO.writeObject(null);
                        ooutTr.flush();
                        ooutHO.flush();
                        ooutTr.close();
                        ooutHO.close();

                        System.out.println("finished first epoch");
                        System.out.println(numTrainingSample + " training samples");
                        System.out.println(numTestSample + " holdout samples saved");
                    }
                    lastHError = hError;
                    hError = evalHoldoutError();
                }
                if (numberPasses > 1) {
                    System.out.printf("Weighted loss on holdout on epoch %d = %.6f\n", pass + 1, hError);

                    oinTr.close();
                    oinTr = new ObjectInputStream(new FileInputStream("cache_training.bin"));

                    if (hError > lastHError) {
                        System.out.println("Early stopping");
                        break;
                    }
                }
                pass++;
            } while (pass < numberPasses);

            if (justPrinted == false) {
                System.out.printf("%.6f %12d  % .4f  % .4f  %d\n", cumLoss / weightedSampleSum, iter,
                        sample.getLabel(), pred, sample.getVector().size());
            }
            System.out.println("finished run");

            System.out.println(String.format("average loss best constant predictor: %.6f",
                    lossFnc.lossConstantBinaryLabels(sPlus, sMinus)));

            if (saveModelFile != null)
                IOLearner.saveLearner(learner, saveModelFile);
            if (invertHashName != null)
                IOLearner.saveInvertHash(learner.getWeights(), instanceParser.getInvertHashMap(),
                        invertHashName);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // close the input stream
        try {
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // close the output stream
        if (predsFile != null) {
            try {
                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        long millis = System.nanoTime() - start;
        System.out.printf("Elapsed time: %d min, %d sec\n", TimeUnit.NANOSECONDS.toMinutes(millis),
                TimeUnit.NANOSECONDS.toSeconds(millis) - 60 * TimeUnit.NANOSECONDS.toMinutes(millis));
    } catch (

    FileNotFoundException e) {
        System.out.println("Error opening the input file");
        e.printStackTrace();
    }

}

From source file:com.pari.nm.utils.backup.BackupRestore.java

/**
 * @param args//from  w w w.ja  v a  2 s.  co  m
 */
public static void main(String[] args) {
    com.maverick.ssh.LicenseManager.addLicense("----BEGIN 3SP LICENSE----\r\n" + "Product : J2SSH Maverick\r\n"
            + "Licensee: Pari Networks Inc.\r\n" + "Comments: Sreenivas Devalla\r\n"
            + "Type    : Foundation License\r\n" + "Created : 20-Jun-2007\r\n" + "\r\n"
            + "3787201A027FCA5BA600F3CF9CCEF4C85068187D70F94ABC\r\n"
            + "E7D7280AAFB06CE499DC968A4CB25795475D5B79FDDD6CB4\r\n"
            + "7971A60E947E84A4DADFAB2F89E2F52470182ED2EF429A2F\r\n"
            + "2EC6D8B49CAF167605A7F56C4EB736ECA7150819FCF04DC6\r\n"
            + "01B1404EA9BC83BEAA4AB2F4FC7AB344BEC08CF9DDDAAA34\r\n"
            + "EC80C1C14FA8BB1A8B47E86D393FAECD3C0E7C450E0D1FE3\r\n" + "----END 3SP LICENSE----\r\n");
    String mode = null;
    BufferedReader br = null;

    if (args.length < 9) {
        System.err.println("BackUpDatabase: Invalid Syntax.");
        System.err.println(
                "Usage - java BackUpDatabase <ftpserver> <ftpuser> <ftppassword> <ftpdir> <ftpfile> <localdir>  <backup | recovery> ");
        System.exit(-1);
    }

    try {

        mode = args[8];
        System.out.println("Request received with mode :" + mode + "\n");
        // BackupRestore tbk = BackupRestore.getInstance();
        BackupRestore tbk = new BackupRestore();
        if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("recovery")) {
            File restoreDir = new File(args[7], args[6].substring(0, args[6].length() - 4));
            System.out.println("Restore Directory :" + restoreDir + "\n");
            if (!restoreDir.exists()) {
                try {
                    FTPServerType serverType = FTPServerType.valueOf(FTPServerType.class, args[0]);
                    System.out.println("Fetching the backup File :" + args[6] + "\n");
                    System.out.println("Please wait, it may take sometime....." + "\n");

                    if (tbk.fetchAndExtractBackupFile(serverType, args[1], Integer.parseInt(args[2]), args[3],
                            args[4], args[5], args[6], args[7]) == null) {
                        System.err.println("Error : Failed to fetch the backup File.\n");
                        System.exit(-1);
                    }
                    System.out.println("Successfully fetched the backup File :" + args[6] + "\n");
                } catch (Exception e) {
                    System.out.println(
                            "Error : Exception while fetching the backup file.Failed to restore the backup File.\n");
                    e.printStackTrace();
                    System.exit(-1);
                }
            }
            try {
                Thread.sleep(10000);
            } catch (Exception ee) {
                ee.printStackTrace();
            }

            System.out.println("Starting recovery ...\n");

            if (!File.separator.equals("\\")) {
                System.out.println("Stopping the Pari Server process.\n");
                Process p = Runtime.getRuntime().exec("killall -9 pari_server");
                MyReader min = new MyReader(p.getInputStream());
                MyReader merr = new MyReader(p.getErrorStream());

                try {
                    min.join(20000);
                } catch (Exception ee) {
                }

                try {
                    merr.join(20000);
                } catch (Exception ex) {
                }
            }

            if (!File.separator.equals("\\")) {
                System.out.println("Stopping the Pari Server process.\n");
                // Process p = Runtime.getRuntime().exec("killall -9 pari_server");
                Process p = Runtime.getRuntime().exec("/etc/init.d/dash stop");
                MyReader min = new MyReader(p.getInputStream());
                MyReader merr = new MyReader(p.getErrorStream());

                try {
                    min.join(20000);
                } catch (Exception ee) {
                }

                try {
                    merr.join(20000);
                } catch (Exception ex) {
                }
            }
            System.out.println("Start recovering the backup file.\n");
            if (tbk.doRecovery(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])) {
                System.out.println("Done recovering...\n");
                validateCSPCInstanace();
            } else {
                System.out.println("Failed to recover the backup File...\n");
            }

            try {
                Process p = null;
                String cmd = "";

                if (File.separator == "\\") {
                    cmd = "cmd /k start_server.cmd > pari.out 2>&1";
                } else {
                    cmd = "/etc/init.d/dash start";
                }

                System.err.println(cmd);
                Runtime.getRuntime().exec(cmd);
                Boolean flag = false;
                int count = 0;
                String[] nccmStatusCheckCmd = { "/bin/sh", "-c",
                        "netstat -an  | grep 42605 | grep LISTEN | wc -l" };

                do {
                    count++;
                    Thread.sleep(60000);
                    // The command output will be 1 if NCCM server started and Listening on port 42605 otherwise it
                    // will return 0
                    p = Runtime.getRuntime().exec(nccmStatusCheckCmd);
                    int ex = -1;
                    try {
                        ex = p.waitFor();
                    } catch (InterruptedException e) {
                        System.out.println("Normal execution, exception: " + e);
                    }
                    System.out.println("Normal execution, exit value: " + ex);
                    br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String thisLine = null;
                    while ((thisLine = br.readLine()) != null) {
                        System.out.println("Command Execution Result:" + thisLine);
                        if (thisLine.equals("1")) {
                            flag = true;
                            break;
                        }
                    }
                    System.out.println("Count - " + count);
                    BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                    while ((thisLine = error.readLine()) != null) {
                        System.out.println(thisLine);
                    }

                } while ((!flag) && count < 30);

                if (flag) {
                    // System.out.println("NCCM Server came to listening state: after " + count + " mins");
                    // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/shutdown.sh");
                    Thread.sleep(60000);
                    System.out.println("NCCM Server came to listening state: after " + count + " mins");
                    // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/startup.sh");
                } else {
                    System.out.println("NCCM Server didn't come to listening state: last " + count + " mins");
                    System.out.println("Please verify NCCM Server and start tomcat server manually.");
                }
                System.exit(1);
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        } else if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("ftplist")) {
            PariFTP pftp = new PariFTP("10.100.1.20", "guest", "guest", "/");
            String[] list = pftp.getRemoteListing();

            System.out.println("List of Files\n");

            for (int i = 0; (list != null) && (i < list.length); i++) {
                System.out.println(list[i] + "\n");
            }
        } else {
            System.out.println("Mode \t" + mode + "\t not supported\n");
        }

        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:Main.java

public static void close(BufferedReader reader) {
    try {/*  w  w w  . j a va  2 s. c  o m*/
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Close a InputStream passed in./*from w  w w . j  av a2  s.c o  m*/
 *
 * @param stream - InputStream to be closed.
 */
public static void closeBufferedReader(BufferedReader stream, String tag) {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            Log.e(tag, "Exception occured when closing BufferedReader." + e);
        }
    }
}

From source file:JarRead.java

private static void process(InputStream input) throws IOException {
    InputStreamReader isr = new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;/*from   w  w  w  . j  a va2 s .  com*/
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();
}

From source file:Main.java

private static void readFile(String fileName) throws Exception {
    File file = new File(fileName);
    FileReader reader = new FileReader(file);
    BufferedReader in = new BufferedReader(reader);
    String string;//  ww w .jav a  2 s. c o m
    while ((string = in.readLine()) != null) {
        System.out.println(string);
    }
    in.close();
}

From source file:Main.java

public static String getEncoding(String f) {
    String encoding = "UTF-8";
    File file = new File(f);
    try {//from  www .  j a  va 2s.c o m
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String xml = reader.readLine();
        reader.close();
        xml = xml.toLowerCase();
        int pos = xml.indexOf("encoding");
        if (pos < 0) {
            return encoding;
        }
        xml = xml.substring(pos + "encoding".length());
        pos = xml.indexOf("\"");
        xml = xml.substring(pos + 1);
        pos = xml.indexOf("\"");
        xml = xml.substring(0, pos).trim();
        return xml.toUpperCase();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return encoding;
}