List of usage examples for java.lang StringBuilder toString
@Override
@HotSpotIntrinsicCandidate
public String toString()
From source file:com.sun.faban.harness.util.CLI.java
/** * The first argument to the CLI is the action. It can be:<ul> * <li>pending</li>//w w w . j a v a2s . c om * <li>status runId</li> * <li>submit benchmark profile configfile.xml</ul> * </ul> * * @param args The command line arguments. */ public static void main(String[] args) { if (args.length == 0) { printUsage(); System.exit(1); } ArrayList<String> argList = new ArrayList<String>(); // Do the getopt thing. char opt = (char) -1; String master = null; String user = null; String password = null; for (String arg : args) { if (arg.startsWith("-M")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'M'; continue; } master = optArg; } else if (arg.startsWith("-U")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'U'; continue; } user = optArg; } else if (arg.startsWith("-P")) { String optArg = arg.substring(2); if (optArg.length() == 0) { opt = 'P'; continue; } password = optArg; } else if (opt != (char) -1) { switch (opt) { case 'M': master = arg; opt = (char) -1; break; case 'U': user = arg; opt = (char) -1; break; case 'P': password = arg; opt = (char) -1; break; } } else { argList.add(arg); opt = (char) -1; } } if (master == null) master = "http://localhost:9980/"; else if (!master.endsWith("/")) master += '/'; CLI cli = new CLI(); String action = argList.get(0); try { if ("pending".equals(action)) { cli.doGet(master + "pending"); } else if ("status".equals(action)) { if (argList.size() > 1) cli.doGet(master + "status/" + argList.get(1)); else printUsage(); } else if ("submit".equals(action)) { if (argList.size() > 3) { cli.doPostSubmit(master, user, password, argList); } else { printUsage(); System.exit(1); } } else if ("kill".equals(action)) { if (argList.size() > 1) { cli.doPostKill(master, user, password, argList); } else { printUsage(); System.exit(1); } } else if ("wait".equals(action)) { if (argList.size() > 1) { cli.pollStatus(master + "status/" + argList.get(1)); } else { printUsage(); System.exit(1); } } else if ("showlogs".equals(action)) { StringBuilder url = new StringBuilder(); if (argList.size() > 1) { url.append(master).append("logs/"); url.append(argList.get(1)); } else { printUsage(); } for (int i = 2; i < argList.size(); i++) { if ("-t".equals(argList.get(i))) url.append("/tail"); if ("-f".equals(argList.get(i))) url.append("/follow"); if ("-ft".equals(argList.get(i))) url.append("/tail/follow"); if ("-tf".equals(argList.get(i))) url.append("/tail/follow"); } cli.doGet(url.toString()); } else { printUsage(); } } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
From source file:com.cloudhopper.sxmp.PostMO.java
static public void main(String[] args) throws Exception { String URL = "https://sms.twitter.com/receive/cloudhopper"; String text = "HELP"; String srcAddr = "+16504304922"; String ticketId = System.currentTimeMillis() + ""; String operatorId = "20"; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") .append("<operation type=\"deliver\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n") .append(" <operatorId>" + operatorId + "</operatorId>\n") .append(" <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n") .append(" <destinationAddress type=\"network\">40404</destinationAddress>\n") .append(" <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(text.getBytes()) + "</text>\n") .append(" </deliverRequest>\n").append("</operation>\n").append(""); HttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); long start = System.currentTimeMillis(); // execute request try {//from w w w . j a v a2 s . c o m HttpPost post = new HttpPost(URL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); logger.debug("----------------------------------------"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } long end = System.currentTimeMillis(); logger.debug("Response took " + (end - start) + " ms"); }
From source file:com.act.biointerpretation.metadata.ProteinMetadataFactory.java
public static void main(String[] args) throws Exception { // TODO: This is referencing a temporary collection. Change it! // TODO: FIX THIS BEFORE MERGE! NoSQLAPI api = new NoSQLAPI("actv01_vijay_proteins", "actv01_vijay_proteins"); Iterator<Reaction> iterator = api.readRxnsFromInKnowledgeGraph(); //Create a single instance of the factory method to use for all json ProteinMetadataFactory factory = ProteinMetadataFactory.initiate(); //Run some tests try {//from w ww . ja va 2s . com if (factory.testHandlesubunits() == true) { System.out.println("Subunit test OK"); } } catch (Exception err) { System.err.println("Failed to test subunits"); } //Create a list to aggregate the results of the database scan List<ProteinMetadata> agg = new ArrayList<>(); //Scan the database and store ProteinMetadata objects while (iterator.hasNext()) { Reaction rxn = iterator.next(); Reaction.RxnDataSource source = rxn.getDataSource(); if (!source.equals(Reaction.RxnDataSource.BRENDA)) { continue; } Set<JSONObject> jsons = rxn.getProteinData(); for (JSONObject json : jsons) { ProteinMetadata meta = factory.create(json); agg.add(meta); } } //Write out any messages to file StringBuilder sb = new StringBuilder(); for (String aline : factory.dataList) { sb.append(aline).append("\n"); } File outfile = new File("output/ProteinMetadata/Factory_output.txt"); if (outfile.exists()) { outfile.delete(); } FileUtils.writeStringToFile(outfile, sb.toString()); sb = new StringBuilder(); for (String key : factory.dataMap.keySet()) { int value = factory.dataMap.get(key); sb.append(key + "\t" + value + "\n"); } outfile = new File("output/ProteinMetadata/Factory_output_map.txt"); if (outfile.exists()) { outfile.delete(); } FileUtils.writeStringToFile(outfile, sb.toString()); //Count up the results of modifications to get statistics int falsecount = 0; int truecount = 0; int nullcount = 0; for (ProteinMetadata datum : agg) { if (datum == null) { System.err.println("null datum"); continue; } if (datum.modifications == null) { nullcount++; } else if (datum.modifications == false) { falsecount++; } else if (datum.modifications == true) { truecount++; } } System.out.println("Total # protein metadata: " + agg.size()); System.out.println(); System.out.println("modification true count: " + truecount); System.out.println("modification false count: " + falsecount); System.out.println("modification null count: " + nullcount); System.out.println(); //Get some statistics for cloned nullcount = 0; int emptycount = 0; int colicount = 0; int humancount = 0; int bothcount = 0; for (ProteinMetadata datum : agg) { if (datum == null) { System.err.println("null datum"); continue; } if (datum.cloned == null) { nullcount++; continue; } if (datum.cloned.isEmpty()) { emptycount++; continue; } Integer human = datum.cloned.get(Host.Hsapiens); if (human != null && human > 0) { humancount++; } Integer coli = datum.cloned.get(Host.Ecoli); if (coli != null && coli > 0) { colicount++; if (human != null && human > 0) { bothcount++; } } } System.out.println("cloned null count: " + nullcount); System.out.println("cloned empty count: " + emptycount); System.out.println("cloned coli count: " + colicount); System.out.println("cloned human count: " + humancount); System.out.println("cloned both count: " + bothcount); System.out.println(); }
From source file:com.util.finalProy.java
/** * @param args the command line arguments *//*from w ww . ja v a 2s . c o m*/ public static void main(String[] args) throws JSONException { // TODO code application logic her System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println(sb.toString()); System.out.println( "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); JSONArray dataJson = new JSONArray(); dataJson = objJason.getJSONArray("data"); System.out.println("objeto normal 1 " + dataJson.toString()); // // System.out.println( "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); System.out.println("new json string" + jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); System.out.println("el objeto simple json es " + objJson2.toString()); System.out.println( "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); System.out.println( "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("id")); System.out.println( "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); Account account = gson.fromJson(objJson3.toString(), Account.class); System.out.println(account.getFirst_name()); System.out.println(account.getCreation()); }
From source file:au.org.ala.layers.intersect.IntersectConfig.java
public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100000; i++) { if (i > 0) { sb.append(','); }// w ww . ja va 2s. co m sb.append(Math.random() * (-12 + 44) - 44).append(',').append(Math.random() * (154 - 112) + 112); } try { FileUtils.writeStringToFile(new File("/data/p.txt"), sb.toString()); } catch (IOException e) { logger.error(e.getMessage(), e); } }
From source file:microbiosima.SelectiveMicrobiosima.java
/** * @param args//from w w w .j a v a 2 s .c o m * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { int populationSize = 500;//Integer.parseInt(parameters[1]); int microSize = 1000;//Integer.parseInt(parameters[2]); int numberOfSpecies = 150;//Integer.parseInt(parameters[3]); int numberOfGeneration = 10000; int Ngene = 10; int numberOfObservation = 100; int numberOfReplication = 10; double Ngenepm = 5; double pctEnv = 0; double pctPool = 0; double msCoeff = 1; double hsCoeff = 1; boolean HMS_or_TMS = true; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe" + " [default: 500 1000 150 10000 10 5]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + " msCoeff Parameter related to microbe selection strength\n" + " hsCoeff Parameter related to host selection strength\n" + " HMS_or_TMS String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 5) { System.out.println( "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); msCoeff = Double.parseDouble(pct_config[2]); hsCoeff = Double.parseDouble(pct_config[3]); if (pct_config[4].equals("HMS")) HMS_or_TMS = true; if (pct_config[4].equals("TMS")) HMS_or_TMS = false; if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } if (msCoeff < 1) { System.out.println( "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff=" + msCoeff + ")! EXIT"); System.exit(3); } if (hsCoeff < 1) { System.out.println( "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff=" + hsCoeff + ")! EXIT"); System.exit(3); } if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) { System.out.println( "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS=" + pct_config[4] + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); Ngene = Integer.parseInt(configs[4]); Ngenepm = Double.parseDouble(configs[5]); if (Ngenepm > Ngene) { System.out.println( "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT"); System.exit(3); } } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication) .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ") .append(Ngenepm).append("\n"); System.out.println(sb.toString()); double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } int[] fitnessToHost = new int[Ngene]; int[] fitnessToMicrobe = new int[Ngene]; for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix; if (HMS_or_TMS) sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt"; else sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); PrintWriter file7 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix))); PrintWriter file8 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix))); PrintWriter file9 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix))); PrintWriter file10 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix))); PrintWriter file11 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix))); PrintWriter file12 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix))); for (int i = 0; i < Ngene; i++) { fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1; fitnessToHost[i] = MathUtil.getNextInt(2) - 1; } MathUtil.setSeed(rep % numberOfReplication); SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm, msCoeff, fitnessToHost, fitnessToMicrobe); MathUtil.setSeed(); SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize, pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { //file1.print(population.gammaDiversity(false)); //file2.print(population.alphaDiversity(false)); //file1.print("\t"); //file2.print("\t"); file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); //file3.print(population.betaDiversity(true)); //file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); file7.print(population.averageHostFitness()); file7.print("\t"); file7.println(population.varianceHostFitness()); file8.println(population.cosOfMH()); file9.println(population.printOutHFitness()); file10.println(population.printOutMFitness()); file11.println(population.printBacteriaContents()); } population.getNextGen(); } for (SelectiveIndividual host : population.getIndividuals()) { file12.println(host.printBacteriaContents()); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); file7.close(); file8.close(); file9.close(); file10.close(); file11.close(); file12.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:marytts.tools.analysis.CopySynthesis.java
/** * @param args//from www . j a v a2 s.c o m */ public static void main(String[] args) throws Exception { String wavFilename = null; String labFilename = null; String pitchFilename = null; String textFilename = null; String locale = System.getProperty("locale"); if (locale == null) { throw new IllegalArgumentException("No locale given (-Dlocale=...)"); } for (String arg : args) { if (arg.endsWith(".txt")) textFilename = arg; else if (arg.endsWith(".wav")) wavFilename = arg; else if (arg.endsWith(".ptc")) pitchFilename = arg; else if (arg.endsWith(".lab")) labFilename = arg; else throw new IllegalArgumentException("Don't know how to treat argument: " + arg); } // The intonation contour double[] contour = null; double frameShiftTime = -1; if (pitchFilename == null) { // need to create pitch contour from wav file if (wavFilename == null) { throw new IllegalArgumentException("Need either a pitch file or a wav file"); } AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename)); AudioDoubleDataSource audio = new AudioDoubleDataSource(ais); PitchFileHeader params = new PitchFileHeader(); params.fs = (int) ais.getFormat().getSampleRate(); F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params); tracker.pitchAnalyze(audio); frameShiftTime = tracker.getSkipSizeInSeconds(); contour = tracker.getF0Contour(); } else { // have a pitch file -- ignore any wav file PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename); if (f0rw.contour == null) { throw new NullPointerException("Cannot read f0 contour from " + pitchFilename); } contour = f0rw.contour; frameShiftTime = f0rw.header.skipSizeInSeconds; } assert contour != null; assert frameShiftTime > 0; // The ALLOPHONES data and labels if (labFilename == null) { throw new IllegalArgumentException("No label file given"); } if (textFilename == null) { throw new IllegalArgumentException("No text file given"); } MaryTranscriptionAligner aligner = new MaryTranscriptionAligner(); aligner.SetEnsureInitialBoundary(false); String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(), aligner.getEnsureInitialBoundary(), labFilename); MaryHttpClient mary = new MaryHttpClient(); String text = FileUtils.readFileToString(new File(textFilename), "ASCII"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(bais); aligner.alignXmlTranscriptions(doc, labels); assert doc != null; // durations double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData(); assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length; // Now add durations and f0 targets to document double prevEnd = 0; NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY); for (int i = 0; i < endTimes.length; i++) { Element e = (Element) ni.nextNode(); if (e == null) throw new IllegalStateException("More durations than elements -- this should not happen!"); double durInSeconds = endTimes[i] - prevEnd; int durInMillis = (int) (1000 * durInSeconds); if (e.getTagName().equals(MaryXML.PHONE)) { e.setAttribute("d", String.valueOf(durInMillis)); e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString()); // f0 targets at beginning, mid, and end of phone StringBuilder f0String = new StringBuilder(); double startF0 = getF0(contour, frameShiftTime, prevEnd); if (startF0 != 0 && !Double.isNaN(startF0)) { f0String.append("(0,").append((int) startF0).append(")"); } double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds); if (midF0 != 0 && !Double.isNaN(midF0)) { f0String.append("(50,").append((int) midF0).append(")"); } double endF0 = getF0(contour, frameShiftTime, endTimes[i]); if (endF0 != 0 && !Double.isNaN(endF0)) { f0String.append("(100,").append((int) endF0).append(")"); } if (f0String.length() > 0) { e.setAttribute("f0", f0String.toString()); } } else { // boundary e.setAttribute("duration", String.valueOf(durInMillis)); } prevEnd = endTimes[i]; } if (ni.nextNode() != null) { throw new IllegalStateException("More elements than durations -- this should not happen!"); } // TODO: add pitch values String acoustparams = DomUtils.document2String(doc); System.out.println("ACOUSTPARAMS:"); System.out.println(acoustparams); }
From source file:Pong.java
public static void main(String... args) throws Exception { System.setProperty("os.max.pid.bits", "16"); Options options = new Options(); options.addOption("i", true, "Input chronicle path"); options.addOption("n", true, "Number of entries to write"); options.addOption("w", true, "Number of writer threads"); options.addOption("r", true, "Number of reader threads"); options.addOption("x", false, "Delete the output chronicle at startup"); CommandLine cmd = new DefaultParser().parse(options, args); final Path output = Paths.get(cmd.getOptionValue("o", "/tmp/__test/chr")); final long maxCount = Long.parseLong(cmd.getOptionValue("n", "10000000")); final int writerThreadCount = Integer.parseInt(cmd.getOptionValue("w", "4")); final int readerThreadCount = Integer.parseInt(cmd.getOptionValue("r", "4")); final boolean deleteOnStartup = cmd.hasOption("x"); if (deleteOnStartup) { FileUtil.removeRecursive(output); }/*from w w w . j a v a2 s .c om*/ final Chronicle chr = ChronicleQueueBuilder.vanilla(output.toFile()).build(); final ExecutorService executor = Executors.newFixedThreadPool(4); final List<Future<?>> futures = new ArrayList<>(); final long totalCount = writerThreadCount * maxCount; final long t0 = System.nanoTime(); for (int i = 0; i != readerThreadCount; ++i) { final int tid = i; futures.add(executor.submit((Runnable) () -> { try { IntLongMap counts = HashIntLongMaps.newMutableMap(); ExcerptTailer tailer = chr.createTailer(); final StringBuilder sb1 = new StringBuilder(); final StringBuilder sb2 = new StringBuilder(); long count = 0; while (count != totalCount) { if (!tailer.nextIndex()) continue; final int id = tailer.readInt(); final long val = tailer.readStopBit(); final long longValue = tailer.readLong(); sb1.setLength(0); sb2.setLength(0); tailer.read8bitText(sb1); tailer.read8bitText(sb2); if (counts.addValue(id, 1) - 1 != val || longValue != 0x0badcafedeadbeefL || !StringInterner.isEqual("FooBar", sb1) || !StringInterner.isEqual("AnotherFooBar", sb2)) { System.out.println("Unexpected value " + id + ", " + val + ", " + Long.toHexString(longValue) + ", " + sb1.toString() + ", " + sb2.toString()); return; } ++count; if (count % 1_000_000 == 0) { long t1 = System.nanoTime(); System.out.println(tid + " " + (t1 - t0) / 1e6 + " ms"); } } } catch (IOException e) { e.printStackTrace(); } })); } for (Future f : futures) { f.get(); } executor.shutdownNow(); final long t1 = System.nanoTime(); System.out.println("Done. Rough time=" + (t1 - t0) / 1e6 + " ms"); }
From source file:ObfuscatingStream.java
/** * Obfuscates or unobfuscates the second command-line argument, depending on * whether the first argument starts with "o" or "u" * //w ww. j a v a 2 s. co m * @param args * Command-line arguments * @throws IOException * If an error occurs obfuscating or unobfuscating */ public static void main(String[] args) throws IOException { InputStream input = new ByteArrayInputStream(args[1].getBytes()); StringBuilder toPrint = new StringBuilder(); if (args[0].startsWith("o")) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream out = obfuscate(bytes); int read = input.read(); while (read >= 0) { out.write(read); read = input.read(); } byte[] receiptBytes = bytes.toByteArray(); for (int b = 0; b < receiptBytes.length; b++) { int chr = (receiptBytes[b] + 256) % 256; toPrint.append(HEX_CHARS[chr >>> 4]); toPrint.append(HEX_CHARS[chr & 0xf]); } } else if (args[0].startsWith("u")) { input = unobfuscate(input); InputStreamReader reader = new InputStreamReader(input); int read = reader.read(); while (read >= 0) { toPrint.append((char) read); read = reader.read(); } } else throw new IllegalArgumentException("First argument must start with o or u"); System.out.println(toPrint.toString()); }
From source file:com.foxykeep.parcelablecodegenerator.Main.java
public static void main(String[] args) { File fileInputDir = new File("input"); if (!fileInputDir.exists() || !fileInputDir.isDirectory()) { return;// w ww . j av a 2 s. co m } ArrayList<FileInfo> fileInfoList = new ArrayList<FileInfo>(); findJsonFiles(fileInputDir, null, fileInfoList); StringBuilder sb = new StringBuilder(); // For each file in the input folder for (FileInfo fileInfo : fileInfoList) { String fileName = fileInfo.file.getName(); System.out.println("Generating code for " + fileName); char[] buffer = new char[2048]; sb.setLength(0); Reader in; try { in = new InputStreamReader(new FileInputStream(fileInfo.file), "UTF-8"); int read; do { read = in.read(buffer, 0, buffer.length); if (read != -1) { sb.append(buffer, 0, read); } } while (read >= 0); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return; } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } String content = sb.toString(); if (content.length() == 0) { System.out.println("file is empty."); return; } try { JSONObject root = new JSONObject(content); // Classes generation String classPackage, className, superClassPackage, superClassName; boolean isSuperClassParcelable, hasSubClasses, isAbstract; classPackage = root.getString("package"); className = root.getString("name"); superClassPackage = JsonUtils.getStringFixFalseNull(root, "superClassPackage"); superClassName = JsonUtils.getStringFixFalseNull(root, "superClassName"); isSuperClassParcelable = root.optBoolean("isSuperClassParcelable"); hasSubClasses = root.optBoolean("hasSubClasses"); if (hasSubClasses) { isAbstract = root.optBoolean("isAbstract"); } else { isAbstract = false; } JSONArray fieldJsonArray = root.optJSONArray("fields"); ArrayList<FieldData> fieldDataList; if (fieldJsonArray != null) { fieldDataList = FieldData.getFieldsData(fieldJsonArray); } else { fieldDataList = new ArrayList<FieldData>(); } // Parcelable generation ParcelableGenerator.generate(fileInfo.dirPath, classPackage, className, superClassPackage, superClassName, isSuperClassParcelable, hasSubClasses, isAbstract, fieldDataList); } catch (JSONException e) { e.printStackTrace(); return; } } }