List of usage examples for java.lang String equals
public boolean equals(Object anObject)
From source file:PCC.java
/** * @param args the command line arguments * @throws java.io.IOException/*from w w w .j a va 2s . co m*/ */ public static void main(String[] args) throws IOException { // TODO code application logic here PearsonsCorrelation corel = new PearsonsCorrelation(); PCC method = new PCC(); ArrayList<String> name = new ArrayList<>(); Multimap<String, String> genes = ArrayListMultimap.create(); BufferedWriter bw = new BufferedWriter(new FileWriter(args[1])); BufferedReader br = new BufferedReader(new FileReader(args[0])); String str; while ((str = br.readLine()) != null) { String[] a = str.split("\t"); name.add(a[0]); for (int i = 1; i < a.length; i++) { genes.put(a[0], a[i]); } } for (String key : genes.keySet()) { double[] first = new double[genes.get(key).size()]; int element1 = 0; for (String value : genes.get(key)) { double d = Double.parseDouble(value); first[element1] = d; element1++; } for (String key1 : genes.keySet()) { if (!key.equals(key1)) { double[] second = new double[genes.get(key1).size()]; int element2 = 0; for (String value : genes.get(key1)) { double d = Double.parseDouble(value); second[element2] = d; element2++; } double corrlation = corel.correlation(first, second); if (corrlation > 0.5) { bw.write(key + "\t" + key1 + "\t" + corrlation + "\t" + method.pvalue(corrlation, second.length) + "\n"); } } } } br.close(); bw.close(); }
From source file:io.alicorn.device.client.DeviceClient.java
public static void main(String[] args) { logger.info("Starting Alicorn Client System"); // Prepare Display Color. transform3xWrite(DisplayTools.commandForColor(0, 204, 255)); // Setup text information. // transform3xWrite(DisplayTools.commandForText("Sup Fam")); class StringWrapper { public String string = ""; }// ww w. jav a2 s .co m final StringWrapper string = new StringWrapper(); // Text Handler. Thread thread = new Thread(new Runnable() { @Override public void run() { String latestString = ""; String outputStringLine1Complete = ""; long outputStringLine1Cursor = 1; int outputStringLine1Mask = 0; String outputStringLine2 = ""; while (true) { if (!latestString.equals(string.string)) { latestString = string.string; String[] latestStrings = latestString.split("::"); outputStringLine1Complete = latestStrings[0]; outputStringLine1Mask = outputStringLine1Complete.length(); outputStringLine1Cursor = 0; // Trim second line to a length of sixteen. outputStringLine2 = latestStrings.length > 1 ? latestStrings[1] : ""; if (outputStringLine2.length() > 16) { outputStringLine2 = outputStringLine2.substring(0, 16); } } StringBuilder outputStringLine1 = new StringBuilder(); if (outputStringLine1Complete.length() > 0) { long cursor = outputStringLine1Cursor; for (int i = 0; i < 16; i++) { outputStringLine1.append( outputStringLine1Complete.charAt((int) (cursor % outputStringLine1Mask))); cursor += 1; } outputStringLine1Cursor += 1; } else { outputStringLine1.append(" "); } try { transform3xWrite( DisplayTools.commandForText(outputStringLine1.toString() + outputStringLine2)); Thread.sleep(400); } catch (Exception e) { e.printStackTrace(); } } } }); thread.start(); // Event Handler while (true) { try { String url = "http://169.254.90.174:9789/api/iot/narwhalText"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); string.string = apacheHttpEntityToString(response.getEntity()); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } }
From source file:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {/*from www . ja v a 2 s . c o m*/ String driver = null, url = null, user = "", password = ""; // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { if (args[n].equals("-d")) driver = args[++n]; else if (args[n].equals("-u")) user = args[++n]; else if (args[n].equals("-p")) password = args[++n]; else if (url == null) url = args[n]; else throw new IllegalArgumentException("Unknown argument."); } // The only required argument is the database URL. if (url == null) throw new IllegalArgumentException("No database specified"); // If the user specified the classname for the DB driver, load // that class dynamically. This gives the driver the opportunity // to register itself with the DriverManager. if (driver != null) Class.forName(driver); // Now open a connection the specified database, using the // user-specified username and password, if any. The driver // manager will try all of the DB drivers it knows about to try to // parse the URL and connect to the DB server. conn = DriverManager.getConnection(url, user, password); // Now create the statement object we'll use to talk to the DB Statement s = conn.createStatement(); // Get a stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop forever, reading the user's queries and executing them while (true) { System.out.print("sql> "); // prompt the user System.out.flush(); // make the prompt appear now. String sql = in.readLine(); // get a line of input from user // Quit when the user types "quit". if ((sql == null) || sql.equals("quit")) break; // Ignore blank lines if (sql.length() == 0) continue; // Now, execute the user's line of SQL and display results. try { // We don't know if this is a query or some kind of // update, so we use execute() instead of executeQuery() // or executeUpdate() If the return value is true, it was // a query, else an update. boolean status = s.execute(sql); // Some complex SQL queries can return more than one set // of results, so loop until there are no more results do { if (status) { // it was a query and returns a ResultSet ResultSet rs = s.getResultSet(); // Get results printResultsTable(rs, System.out); // Display them } else { // If the SQL command that was executed was some // kind of update rather than a query, then it // doesn't return a ResultSet. Instead, we just // print the number of rows that were affected. int numUpdates = s.getUpdateCount(); System.out.println("Ok. " + numUpdates + " rows affected."); } // Now go see if there are even more results, and // continue the results display loop if there are. status = s.getMoreResults(); } while (status || s.getUpdateCount() != -1); } // If a SQLException is thrown, display an error message. // Note that SQLExceptions can have a general message and a // DB-specific message returned by getSQLState() catch (SQLException e) { System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState()); } // Each time through this loop, check to see if there were any // warnings. Note that there can be a whole chain of warnings. finally { // print out any warnings that occurred SQLWarning w; for (w = conn.getWarnings(); w != null; w = w.getNextWarning()) System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState()); } } } // Handle exceptions that occur during argument parsing, database // connection setup, etc. For SQLExceptions, print the details. catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQL State: " + ((SQLException) e).getSQLState()); System.err.println( "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>"); } // Be sure to always close the database connection when we exit, // whether we exit because the user types 'quit' or because of an // exception thrown while setting things up. Closing this connection // also implicitly closes any open statements and result sets // associated with it. finally { try { conn.close(); } catch (Exception e) { } } }
From source file:com.dopsun.msg4j.tools.CodeGen.java
/** * @param args// w ww . j a v a2 s . co m * @throws IOException * @throws MalformedURLException * @throws ParseException */ public static void main(String[] args) throws MalformedURLException, IOException, ParseException { Options options = new Options(); options.addOption("o", "out", true, "Output file"); options.addOption("s", "src", true, "Source file"); options.addOption("l", "lang", true, "Language"); CommandLineParser cmdParser = new DefaultParser(); CommandLine cmd = cmdParser.parse(options, args); String lang = cmd.getOptionValue("lang", "Java"); String srcFile = cmd.getOptionValue("src"); String outFile = cmd.getOptionValue("out"); YamlModelSource modelSource = YamlModelSource.load(new File(srcFile).toURI().toURL()); YamlModelParser parser = YamlModelParser.create(); ModelInfo modelInfo = parser.parse(modelSource); String codeText = null; if (lang.equals("Java")) { codeText = Generator.JAVA.generate(modelInfo); } else { throw new UnsupportedOperationException("Unrecognized lang: " + lang); } if (outFile != null) { File file = new File(outFile); if (file.exists()) { file.delete(); } file.createNewFile(); Files.append(codeText, new File(outFile), Charsets.UTF_8); } else { System.out.println(codeText); } }
From source file:com.github.xbn.examples.regexutil.non_xbn.BetweenLineMarkersButSkipFirstXmpl.java
public static final void main(String[] as_1RqdTxtFilePath) { Iterator<String> lineItr = null; try {/* w w w.j a va 2 s . com*/ lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null } catch (IOException iox) { throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox); } catch (RuntimeException rx) { throw new RuntimeException("One required parameter: The path to the text file.", rx); } String LINE_SEP = System.getProperty("line.separator", "\n"); ArrayList<String> alsItems = new ArrayList<String>(); boolean bStartMark = false; boolean bLine1Skipped = false; StringBuilder sdCurrentItem = new StringBuilder(); while (lineItr.hasNext()) { String sLine = lineItr.next().trim(); if (!bStartMark) { if (sLine.startsWith(".START_SEQUENCE")) { bStartMark = true; continue; } throw new IllegalStateException("Start mark not found."); } if (!bLine1Skipped) { bLine1Skipped = true; continue; } else if (!sLine.equals(".END_SEQUENCE")) { sdCurrentItem.append(sLine).append(LINE_SEP); } else { alsItems.add(sdCurrentItem.toString()); sdCurrentItem.setLength(0); bStartMark = false; bLine1Skipped = false; continue; } } for (String s : alsItems) { System.out.println("----------"); System.out.print(s); } }
From source file:com.linkedin.pinot.tools.PinotSegmentRebalancer.java
public static void main(String[] args) throws Exception { final boolean dryRun = true; if (args.length != 4) { usage();/*from w w w . j av a2s .c o m*/ } final String subCmd = args[0]; final String zkAddress = args[1]; final String clusterName = args[2]; final String tableOrTenant = args[3]; PinotSegmentRebalancer rebalancer = new PinotSegmentRebalancer(zkAddress, clusterName, dryRun); if (subCmd.equals(rebalanceTenantCmd)) { rebalancer.rebalanceTenantTables(tableOrTenant); } else if (subCmd.equals(rebalanceTableCmd)) { rebalancer.rebalanceTable(tableOrTenant); } else { usage(); } if (dryRun) { System.out.println("That was a dryrun"); } }
From source file:edu.psu.citeseerx.disambiguation.CsxDisambiguation.java
public static void main(String[] args) { Date start = new Date(); System.out.println("START:" + start); try {/*from w ww .j a va 2 s . co m*/ CommandLineParser cmdparser = new GnuParser(); Options options = setupOptions(); CommandLine line = cmdparser.parse(options, args); ListableBeanFactory factory = ContextReader.loadContext(); if (!validOptions(line, options)) { usage(options); System.exit(0); } String cmd = line.getOptionValue("cmd"); String infile = line.getOptionValue("infile"); String indir = line.getOptionValue("indir"); String outdir = line.getOptionValue("outdir"); if (cmd.equals("init_dirs")) { // 1) init directories initDirectories("data/csauthors/blocks"); initDirectories("data/csauthors/output"); } else if (cmd.equals("init_blocks")) { // 2) create blocks createBlocks(factory); } else if (cmd.equals("dbscan")) { // 3) disambiguate (required 1. & 2.) //disambiguateDirectory(factory, args[0], args[1]); //disambiguateFile(factory, args[0]); if (infile != null) { disambiguateFile(factory, infile); } else if (indir != null && outdir != null) { disambiguateDirectory(factory, indir, outdir); } else { usage(options); System.exit(0); } } /*else if (cmd.equals("match_author")) { String input_file = ""; disambiguateOneAuthor(input_file); }*/ } catch (Exception ex) { ex.printStackTrace(); Date now = new Date(); System.out.println("CRASH:" + now); } Date end = new Date(); System.out.println("END:" + end); System.out.println("TIME:" + (end.getTime() - start.getTime())); }
From source file:edu.oregonstate.eecs.mcplan.domains.tamarisk.TamariskParameters.java
public static void main(final String[] argv) { // for( int i = 0; i < 1000; ++i ) { // final int Nreaches = 4; // final int Nhabitats = 4; // final RandomGenerator rng = new MersenneTwister( 42 ); // final ListenableDirectedWeightedGraph<Integer, DefaultEdge> g // = new TamariskParameters( rng, Nreaches, Nhabitats ).createRandomGraph( 42 + i, true ); // }/*from w w w . j a v a 2s . c o m*/ final int Nreaches = 10; final int Nhabitats = 4; final RandomGenerator rng = new MersenneTwister(42); final TamariskParameters params = new TamariskParameters(rng, Nreaches, Nhabitats); // final ListenableDirectedWeightedGraph<Integer, DefaultEdge> g = params.createRandomGraph( 42, true ); final ListenableDirectedWeightedGraph<Integer, DefaultEdge> g = params.createBalancedGraph(3); final double[][] K = params.calculateDispersionKernel(g); for (int i = 0; i < K.length; ++i) { System.out.println(Arrays.toString(K[i])); } final JGraphModelAdapter adapter = new JGraphModelAdapter(g); final JGraph jgraph = new JGraph(adapter); // final JGraphLayoutAlgorithm layout = new SugiyamaLayoutAlgorithm(); final JFrame frame = new JFrame(); frame.setSize(480, 360); frame.getContentPane().add(new JGraph(new JGraphModelAdapter(g))); frame.setVisible(true); final TamariskState state = new TamariskState(rng, params, g); final TamariskSimulator sim = new TamariskSimulator(state); System.out.println(state); System.out.println(); final int T = 30; final ArrayDeque<String> hist = new ArrayDeque<String>(); for (int t = 0; t < T; ++t) { sim.takeAction(new JointAction<TamariskAction>(new NothingAction())); System.out.println(state); System.out.println(); hist.push(state.toString()); } for (int t = 0; t < T; ++t) { final String forward = hist.pop(); final String backward = sim.state().toString(); assert (forward.equals(backward)); sim.untakeLastAction(); } }
From source file:com.joliciel.frenchTreebank.FrenchTreebank.java
/** * @param args/*www. java2 s .com*/ */ public static void main(String[] args) throws Exception { String command = args[0]; String outFilePath = ""; String outDirPath = ""; String treebankPath = ""; String ftbFileName = ""; String rawTextDir = ""; String queryPath = ""; String sentenceNumber = null; boolean firstArg = true; for (String arg : args) { if (firstArg) { firstArg = false; continue; } int equalsPos = arg.indexOf('='); String argName = arg.substring(0, equalsPos); String argValue = arg.substring(equalsPos + 1); if (argName.equals("outfile")) outFilePath = argValue; else if (argName.equals("outdir")) outDirPath = argValue; else if (argName.equals("ftbFileName")) ftbFileName = argValue; else if (argName.equals("treebank")) treebankPath = argValue; else if (argName.equals("sentence")) sentenceNumber = argValue; else if (argName.equals("query")) queryPath = argValue; else if (argName.equals("rawTextDir")) rawTextDir = argValue; else throw new RuntimeException("Unknown argument: " + argName); } TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance(); TreebankServiceLocator locator = TreebankServiceLocator.getInstance(talismaneServiceLocator); if (treebankPath.length() == 0) locator.setDataSourcePropertiesFile("jdbc-live.properties"); if (command.equals("search")) { final SearchService searchService = locator.getSearchService(); final XmlPatternSearch search = searchService.newXmlPatternSearch(); search.setXmlPatternFile(queryPath); List<SearchResult> searchResults = search.perform(); FileWriter fileWriter = new FileWriter(outFilePath); for (SearchResult searchResult : searchResults) { String lineToWrite = ""; Sentence sentence = searchResult.getSentence(); Phrase phrase = searchResult.getPhrase(); lineToWrite += sentence.getFile().getFileName() + "|"; lineToWrite += sentence.getSentenceNumber() + "|"; List<PhraseUnit> phraseUnits = searchResult.getPhraseUnits(); LOG.debug("Phrase: " + phrase.getId()); for (PhraseUnit phraseUnit : phraseUnits) lineToWrite += phraseUnit.getLemma().getText() + "|"; lineToWrite += phrase.getText(); fileWriter.write(lineToWrite + "\n"); } fileWriter.flush(); fileWriter.close(); } else if (command.equals("load")) { final TreebankService treebankService = locator.getTreebankService(); final TreebankSAXParser parser = new TreebankSAXParser(); parser.setTreebankService(treebankService); parser.parseDocument(treebankPath); } else if (command.equals("loadAll")) { final TreebankService treebankService = locator.getTreebankService(); File dir = new File(treebankPath); String firstFile = null; if (args.length > 2) firstFile = args[2]; String[] files = dir.list(); if (files == null) { throw new RuntimeException("Not a directory or no children: " + treebankPath); } else { boolean startProcessing = true; if (firstFile != null) startProcessing = false; for (int i = 0; i < files.length; i++) { if (!startProcessing && files[i].equals(firstFile)) startProcessing = true; if (startProcessing) { String filePath = args[1] + "/" + files[i]; LOG.debug(filePath); final TreebankSAXParser parser = new TreebankSAXParser(); parser.setTreebankService(treebankService); parser.parseDocument(filePath); } } } } else if (command.equals("loadRawText")) { final TreebankService treebankService = locator.getTreebankService(); final TreebankRawTextAssigner assigner = new TreebankRawTextAssigner(); assigner.setTreebankService(treebankService); assigner.setRawTextDirectory(rawTextDir); assigner.loadRawText(); } else if (command.equals("tokenize")) { Writer csvFileWriter = null; if (outFilePath != null && outFilePath.length() > 0) { if (outFilePath.lastIndexOf("/") > 0) { String outputDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/")); File outputDir = new File(outputDirPath); outputDir.mkdirs(); } File csvFile = new File(outFilePath); csvFile.delete(); csvFile.createNewFile(); csvFileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(csvFile, false), "UTF8")); } try { final TreebankService treebankService = locator.getTreebankService(); TreebankExportService treebankExportService = locator.getTreebankExportServiceLocator() .getTreebankExportService(); TreebankUploadService treebankUploadService = locator.getTreebankUploadServiceLocator() .getTreebankUploadService(); TreebankReader treebankReader = null; if (treebankPath.length() > 0) { File treebankFile = new File(treebankPath); if (sentenceNumber != null) treebankReader = treebankUploadService.getXmlReader(treebankFile, sentenceNumber); else treebankReader = treebankUploadService.getXmlReader(treebankFile); } else { treebankReader = treebankService.getDatabaseReader(TreebankSubSet.ALL, 0); } TokeniserAnnotatedCorpusReader reader = treebankExportService .getTokeniserAnnotatedCorpusReader(treebankReader, csvFileWriter); while (reader.hasNextTokenSequence()) { TokenSequence tokenSequence = reader.nextTokenSequence(); List<Integer> tokenSplits = tokenSequence.getTokenSplits(); String sentence = tokenSequence.getText(); LOG.debug(sentence); int currentPos = 0; StringBuilder sb = new StringBuilder(); for (int split : tokenSplits) { if (split == 0) continue; String token = sentence.substring(currentPos, split); sb.append('|'); sb.append(token); currentPos = split; } LOG.debug(sb.toString()); } } finally { csvFileWriter.flush(); csvFileWriter.close(); } } else if (command.equals("export")) { if (outDirPath.length() == 0) throw new RuntimeException("Parameter required: outdir"); File outDir = new File(outDirPath); outDir.mkdirs(); final TreebankService treebankService = locator.getTreebankService(); FrenchTreebankXmlWriter xmlWriter = new FrenchTreebankXmlWriter(); xmlWriter.setTreebankService(treebankService); if (ftbFileName.length() == 0) { xmlWriter.write(outDir); } else { TreebankFile ftbFile = treebankService.loadTreebankFile(ftbFileName); String fileName = ftbFileName.substring(ftbFileName.lastIndexOf('/') + 1); File xmlFile = new File(outDir, fileName); xmlFile.delete(); xmlFile.createNewFile(); Writer xmlFileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(xmlFile, false), "UTF8")); xmlWriter.write(xmlFileWriter, ftbFile); xmlFileWriter.flush(); xmlFileWriter.close(); } } else { throw new RuntimeException("Unknown command: " + command); } LOG.debug("========== END ============"); }
From source file:com.vmware.fdmsecprotomgmt.PasswdEncrypter.java
/** * Entry point into this Class/*from w w w . ja va2 s . co m*/ */ public static void main(String[] args) { boolean validVals = false; String secretKey = ""; String esxi_pwd = ""; System.out.println("This Utility program would help you to ENCRYPT password with a given secretKey"); Scanner in = new Scanner(System.in); System.out.print("Enter ESXi host password:"); esxi_pwd = in.nextLine().trim(); if (esxi_pwd.equals("")) { System.err.println("Invalid password entry, please try again ..."); } else { System.out.println( "Enter SecretKey to be used for encrypting ESXi Password. MUST NOT exceed 16 characters," + "and should be different from ESXi password; for better security"); secretKey = in.nextLine().trim(); if (secretKey.equals("")) { System.err.println("Invalid SecretKey entry, please try again ..."); } else if (secretKey.length() > STD_KEYSIZE) { System.err.println("SecretKey can NOT exceed 16 characters. Please try again"); } else if (secretKey.length() < STD_KEYSIZE) { int remainingChars = STD_KEYSIZE - secretKey.length(); while (remainingChars > 0) { secretKey = secretKey + PADDING_ARRAY[remainingChars]; --remainingChars; } } if (secretKey.length() == STD_KEYSIZE) { validVals = true; } } // Go for encrypting the password with provided SecretKey if (validVals) { String encryptedStr = encrypt(secretKey, esxi_pwd); if ((!encryptedStr.equals(""))) { // Validate that on decrypt, you would receive the same password String decryptedStr = decrypt(secretKey, encryptedStr); if (!decryptedStr.equals("")) { if (decryptedStr.equals(esxi_pwd)) { System.out.println("Successfully encrypted the password"); System.out.println("----------------------------------------------------------------"); System.out.println("ESXi Password: " + esxi_pwd); System.out.println("Your Secret key: " + secretKey); System.out.println("Encrypted String for the password: " + encryptedStr); System.out.println("[TESTED] Decrypted string: " + decryptedStr); System.out.println("----------------------------------------------------------------"); System.out.println("**** NOTE ****"); System.out.println( "Please remember the secretkey, which is later needed when running TLS-Configuration script"); } else { System.err.println("Failed to match the password with decrypted string"); } } else { System.err.println("Failed to decrypt the encrypted string"); } } else { System.err.println("Failed to encrypt the provided password"); } } // close the scanner in.close(); }