List of usage examples for java.lang String substring
public String substring(int beginIndex, int endIndex)
From source file:com.sxjun.core.generate.Generate.java
public static void main(String[] args) throws Exception { // ========== ?? ==================== // ??????/*from w ww . jav a 2 s . c om*/ // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className} // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4? String packageName = "com.sxjun"; String moduleName = "retrieval"; // ???sys String subModuleName = ""; // ????? String className = "IndexManager"; // ??user String classAuthor = "sxjun"; // ThinkGem String functionName = "?"; // ?? // ??? Boolean isEnable = true; // ========== ?? ==================== if (!isEnable) { logger.error("????isEnable = true"); return; } if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className) || StringUtils.isBlank(functionName)) { logger.error("??????????????"); return; } // ? String separator = File.separator; String classPath = new DefaultResourceLoader().getResource("").getFile().getPath(); String templatePath = classPath.replace( separator + "WebRoot" + separator + "WEB-INF" + separator + "classes", separator + "src" + separator + "com" + separator + "sxjun" + separator + "retrieval"); String javaPath = classPath.replace(separator + "WebRoot" + separator + "WEB-INF" + separator + "classes", separator + "src" + separator + (StringUtils.lowerCase(packageName)).replace(".", separator)); String viewPath = classPath.replace(separator + "classes", separator + "retrieval"); // ??? Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(templatePath.substring(0, templatePath.lastIndexOf(separator)) + separator + "generate" + separator + "template")); // ??? Map<String, String> model = Maps.newHashMap(); model.put("packageName", StringUtils.lowerCase(packageName)); model.put("moduleName", StringUtils.lowerCase(moduleName)); model.put("subModuleName", StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : ""); model.put("className", StringUtils.uncapitalize(className)); model.put("ClassName", StringUtils.capitalize(className)); model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools"); model.put("classVersion", DateUtils.getDate()); model.put("functionName", functionName); model.put("urlPrefix", (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) + "/" : "") + model.get("className")); model.put("viewPrefix", StringUtils.substringAfterLast(model.get("packageName"), ".") + "/" + model.get("urlPrefix")); // ? Entity Template template = cfg.getTemplate("pojo.ftl"); String content = FreeMarkers.renderTemplate(template, model); String filePath = javaPath + separator + model.get("moduleName") + separator + "pojo" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + ".java"; writeFile(content, filePath); logger.info(filePath); // ? Dao /*template = cfg.getTemplate("dao.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath+separator+model.get("moduleName")+separator+"dao"+separator +StringUtils.lowerCase(subModuleName)+separator+model.get("ClassName")+"Dao.java"; writeFile(content, filePath); logger.info(filePath); // ? Service template = cfg.getTemplate("service.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath+separator+model.get("moduleName")+separator+"service"+separator +StringUtils.lowerCase(subModuleName)+separator+model.get("ClassName")+"Service.java"; writeFile(content, filePath); logger.info(filePath);*/ // ? Controller template = cfg.getTemplate("controller.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = javaPath + separator + model.get("moduleName") + separator + "controller" + separator + StringUtils.lowerCase(subModuleName) + separator + model.get("ClassName") + "Controller.java"; writeFile(content, filePath); logger.info(filePath); // ? ViewForm template = cfg.getTemplate("viewForm.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + model.get("className") + separator + model.get("className") + "Form.jsp"; writeFile(content, filePath); logger.info(filePath); // ? ViewList template = cfg.getTemplate("viewList.ftl"); content = FreeMarkers.renderTemplate(template, model); filePath = viewPath + separator + model.get("className") + separator + model.get("className") + "List.jsp"; writeFile(content, filePath); logger.info(filePath); logger.info("????"); }
From source file:HLA.java
public static void main(String[] args) throws IOException { if (!isVersionOrHigher()) { System.err.println("JRE of 1.8+ is required to run Kourami. Exiting."); System.exit(1);/*from w w w .j a v a2s .c o m*/ } CommandLineParser parser = new DefaultParser(); Options options = HLA.createOption(); Options helponlyOpts = HLA.createHelpOption(); String[] bams = null; CommandLine line = null; boolean exitRun = false; try { CommandLine helpcheck = new DefaultParser().parse(helponlyOpts, args, true); if (helpcheck.getOptions().length > 0) HLA.help(options); else { line = parser.parse(options, args); if (line.hasOption("h"))//help")) HLA.help(options); else { if (line.hasOption("a")) HLA.TYPEADDITIONAL = true; HLA.OUTPREFIX = line.getOptionValue("o");//outfilePrefix"); String tmploc = line.getOptionValue("d");//msaDirectory"); HLA.MSAFILELOC = tmploc; if (tmploc.endsWith(File.separator)) HLA.MSAFILELOC = tmploc.substring(0, tmploc.length() - 1); if (!new File(HLA.MSAFILELOC).exists() || !new File(HLA.MSAFILELOC).isDirectory()) { System.err.println("Given msaDirectory: " + HLA.MSAFILELOC + "\t does NOT exist or is NOT a directory."); exitRun = true; } else if (!new File(HLA.MSAFILELOC + File.separator + "hla_nom_g.txt").exists()) { System.err.println("hla_nom_g.txt NOT FOUND in " + HLA.MSAFILELOC); System.err .println("Please download hla_nom_g.txt from the same IMGT Release as msa files."); exitRun = true; } } bams = line.getArgs(); if (bams.length < 1 || (bams.length == 1 && bams[bams.length - 1].equals("DEBUG1228"))) throw new ParseException("At least 1 bam file is required. See Usage:"); else { if (bams.length > 1 && bams[bams.length - 1].equals("DEBUG1228")) { String[] tmpbams = new String[bams.length - 1]; for (int i = 0; i < bams.length - 1; i++) tmpbams[i] = bams[i]; bams = tmpbams; HLA.DEBUG = true; } for (String b : bams) if (!new File(b).exists()) { System.err .println("Input bam : " + b + " DOES NOT exist. Please check the bam exists."); exitRun = true; } } } if (exitRun) throw new ParseException("Exitting . . ."); } catch (ParseException e) { System.err.println(e.getMessage()); //System.err.println("Failed to parse command line args. Check usage."); HLA.help(options); } String[] list = { "A", "B", "C", "DQA1", "DQB1", "DRB1" }; String[] extList = { "A", "B", "C", "DQA1", "DQB1", "DRB1", "DOA", "DMA", "DMB", "DPA1", "DPB1", "DRA", "DRB3", "DRB5", "F", "G", "H", "J", "L" }; //,"DPA1", "DPB1", "DRA", "DRB4", "F", "G" , "H", "J" ,"K", "L", "V"}; //,"DPA1", "DPB1", "DRA", "DRB3", "DRB4", "F", "G" , "H", "J" ,"K", "L", "V"}; if (HLA.TYPEADDITIONAL) list = extList; File[] bamfiles = new File[bams.length]; for (int i = 0; i < bams.length; i++) bamfiles[i] = new File(bams[i]); //check if <HLA.OUTPREFIX>.result is writable //if not exit. BufferedWriter resultWriter = null; try { resultWriter = new BufferedWriter(new FileWriter(HLA.OUTPREFIX + ".result")); } catch (IOException ioe) { ioe.printStackTrace(); System.err.println("\n\n>>> CANNOT open output file: " + HLA.OUTPREFIX + ".result <<<\n\n"); HLA.help(options); } HLA.log = new LogHandler(); for (int i = 0; i < args.length; i++) HLA.log.append(" " + args[i]); HLA.log.appendln(); try { System.err.println("----------------REF GRAPH CONSTRUCTION--------------"); HLA.log.appendln("----------------REF GRAPH CONSTRUCTION--------------"); HLA hla = new HLA(list, HLA.MSAFILELOC + File.separator + "hla_nom_g.txt"); //1. bubble counting before loading reads. //System.err.println("----------------BUBBLE COUNTING: REF GRAPH--------------"); //HLA.log.appendln("----------------BUBBLE COUNTING: REF GRAPH--------------"); //hla.countStems(); System.err.println("---------------- READ LOADING --------------"); HLA.log.appendln("---------------- READ LOADING --------------"); hla.loadReads(bamfiles); System.err.println("---------------- GRAPH CLEANING --------------"); HLA.log.appendln("---------------- GRAPH CLEANING --------------"); hla.flattenInsertionNodes(list); hla.removeUnused(list); hla.removeStems(list); /*updating error prob*/ hla.updateErrorProb(); hla.log.flush(); StringBuffer resultBuffer = new StringBuffer(); HLA.DEBUG3 = HLA.DEBUG; hla.countBubblesAndMerge(list, resultBuffer); hla.writeResults(resultBuffer, resultWriter); } catch (Exception e) { e.printStackTrace(); HLA.log.outToFile(); System.exit(-1); } /*printingWeights*/ //hla.printWeights(); HLA.log.outToFile(); HLA.log.appendln("NEW_NODE_ADDED:\t" + HLA.NEW_NODE_ADDED); HLA.log.appendln("HOPPPING:\t" + HLA.HOPPING); HLA.log.appendln("INSERTION_NODE_ADDED:\t" + HLA.INSERTION_NODE_ADDED); HLA.log.appendln("INSERTION_WITH_NO_NEW_NODE:\t" + HLA.INSERTION_WITH_NO_NEW_NODE); HLA.log.appendln("INSERTION_COUNTS:\t" + HLA.INSERTION); }
From source file:com.github.ansell.shp.SHPDump.java
public static void main(String... args) throws Exception { final OptionParser parser = new OptionParser(); final OptionSpec<Void> help = parser.accepts("help").forHelp(); final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required() .describedAs("The input SHP file"); final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class).required() .describedAs("The output directory to use for debugging files"); final OptionSpec<String> outputPrefix = parser.accepts("prefix").withRequiredArg().ofType(String.class) .defaultsTo("shp-debug").describedAs("The output prefix to use for debugging files"); final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg() .ofType(File.class).describedAs("The output mapping template file if it needs to be generated."); final OptionSpec<Integer> resolution = parser.accepts("resolution").withRequiredArg().ofType(Integer.class) .defaultsTo(2048).describedAs("The output image file resolution"); final OptionSpec<String> format = parser.accepts("format").withRequiredArg().ofType(String.class) .defaultsTo("png").describedAs("The output image format"); final OptionSpec<String> removeIfEmpty = parser.accepts("remove-if-empty").withRequiredArg() .ofType(String.class).describedAs( "The name of an attribute to remove if its value is empty before outputting the resulting shapefile. Use multiple times to specify multiple fields to check"); OptionSet options = null;/*from w w w.j av a2s . com*/ try { options = parser.parse(args); } catch (final OptionException e) { System.out.println(e.getMessage()); parser.printHelpOn(System.out); throw e; } if (options.has(help)) { parser.printHelpOn(System.out); return; } final Path inputPath = input.value(options).toPath(); if (!Files.exists(inputPath)) { throw new FileNotFoundException("Could not find input SHP file: " + inputPath.toString()); } final Path outputPath = output.value(options).toPath(); if (!Files.exists(outputPath)) { throw new FileNotFoundException("Output directory does not exist: " + outputPath.toString()); } final Path outputMappingPath = options.has(outputMappingTemplate) ? outputMappingTemplate.value(options).toPath() : null; if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) { throw new FileNotFoundException( "Output mapping template file already exists: " + outputMappingPath.toString()); } final Set<String> filterFields = ConcurrentHashMap.newKeySet(); if (options.has(removeIfEmpty)) { for (String nextFilterField : removeIfEmpty.values(options)) { System.out.println("Will filter field if empty value found: " + nextFilterField); filterFields.add(nextFilterField); } } if (!filterFields.isEmpty()) { System.out.println("Full set of filter fields: " + filterFields); } final String prefix = outputPrefix.value(options); FileDataStore store = FileDataStoreFinder.getDataStore(inputPath.toFile()); if (store == null) { throw new RuntimeException("Could not read the given input as an ESRI Shapefile: " + inputPath.toAbsolutePath().toString()); } for (String typeName : new LinkedHashSet<>(Arrays.asList(store.getTypeNames()))) { System.out.println(""); System.out.println("Type: " + typeName); SimpleFeatureSource featureSource = store.getFeatureSource(typeName); SimpleFeatureType schema = featureSource.getSchema(); Name outputSchemaName = new NameImpl(schema.getName().getNamespaceURI(), schema.getName().getLocalPart().replace(" ", "").replace("%20", "")); System.out.println("Replacing name on schema: " + schema.getName() + " with " + outputSchemaName); SimpleFeatureType outputSchema = SHPUtils.changeSchemaName(schema, outputSchemaName); List<String> attributeList = new ArrayList<>(); for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) { System.out.println("Attribute: " + attribute.getName().toString()); attributeList.add(attribute.getName().toString()); } CsvSchema csvSchema = CSVUtil.buildSchema(attributeList); SimpleFeatureCollection collection = featureSource.getFeatures(); int featureCount = 0; Path nextCSVFile = outputPath.resolve(prefix + ".csv"); Path nextSummaryCSVFile = outputPath .resolve(prefix + "-" + outputSchema.getTypeName() + "-Summary.csv"); List<SimpleFeature> outputFeatureList = new CopyOnWriteArrayList<>(); try (SimpleFeatureIterator iterator = collection.features(); Writer bufferedWriter = Files.newBufferedWriter(nextCSVFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); SequenceWriter csv = CSVUtil.newCSVWriter(bufferedWriter, csvSchema);) { List<String> nextLine = new ArrayList<>(); while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); featureCount++; if (featureCount <= 2) { System.out.println(""); System.out.println(feature.getIdentifier()); } else if (featureCount % 100 == 0) { System.out.print("."); } boolean filterThisFeature = false; for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) { String featureString = Optional.ofNullable(feature.getAttribute(attribute.getName())) .orElse("").toString(); nextLine.add(featureString); if (filterFields.contains(attribute.getName().toString()) && featureString.trim().isEmpty()) { filterThisFeature = true; } if (featureString.length() > 100) { featureString = featureString.substring(0, 100) + "..."; } if (featureCount <= 2) { System.out.print(attribute.getName() + "="); System.out.println(featureString); } } if (!filterThisFeature) { outputFeatureList.add(SHPUtils.changeSchemaName(feature, outputSchema)); csv.write(nextLine); } nextLine.clear(); } } try (Reader csvReader = Files.newBufferedReader(nextCSVFile, StandardCharsets.UTF_8); Writer summaryOutput = Files.newBufferedWriter(nextSummaryCSVFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); final Writer mappingWriter = options.has(outputMappingTemplate) ? Files.newBufferedWriter(outputMappingPath) : NullWriter.NULL_WRITER) { CSVSummariser.runSummarise(csvReader, summaryOutput, mappingWriter, CSVSummariser.DEFAULT_SAMPLE_COUNT, false); } if (featureCount > 100) { System.out.println(""); } System.out.println(""); System.out.println("Feature count: " + featureCount); SimpleFeatureCollection outputCollection = new ListFeatureCollection(outputSchema, outputFeatureList); Path outputShapefilePath = outputPath.resolve(prefix + "-" + outputSchema.getTypeName() + "-dump"); if (!Files.exists(outputShapefilePath)) { Files.createDirectory(outputShapefilePath); } SHPUtils.writeShapefile(outputCollection, outputShapefilePath); // Create ZIP file from the contents to keep the subfiles together Path outputShapefileZipPath = outputPath .resolve(prefix + "-" + outputSchema.getTypeName() + "-dump.zip"); try (final OutputStream out = Files.newOutputStream(outputShapefileZipPath, StandardOpenOption.CREATE_NEW); final ZipOutputStream zip = new ZipOutputStream(out, StandardCharsets.UTF_8);) { Files.list(outputShapefilePath).forEachOrdered(Unchecked.consumer(e -> { zip.putNextEntry(new ZipEntry(e.getFileName().toString())); Files.copy(e, zip); zip.closeEntry(); })); } try (final OutputStream outputStream = Files.newOutputStream( outputPath.resolve(prefix + "." + format.value(options)), StandardOpenOption.CREATE_NEW);) { MapContent map = new MapContent(); map.setTitle(prefix + "-" + outputSchema.getTypeName()); Style style = SLD.createSimpleStyle(featureSource.getSchema()); Layer layer = new FeatureLayer(new CollectionFeatureSource(outputCollection), style); map.addLayer(layer); SHPUtils.renderImage(map, outputStream, resolution.value(options), format.value(options)); } } }
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 = ""; }//w w w .java 2 s .c om 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:kilim.tools.Weaver.java
/** * <pre>//from w ww. j a v a 2s.com * Usage: java kilim.tools.Weaver -d <output directory> {source classe, jar, directory ...} * </pre> * * If directory names or jar files are given, all classes in that container are processed. It is * perfectly fine to specify the same directory for source and output like this: * <pre> * java kilim.tools.Weaver -d ./classes ./classes * </pre> * Ensure that all classes to be woven are in the classpath. The output directory does not have to be * in the classpath during weaving. * * @see #weave(List) for run-time weaving. */ public static void main(String[] args) throws IOException { // System.out.println(System.getProperty("java.class.path")); Detector detector = Detector.DEFAULT; String currentName = null; for (String name : parseArgs(args)) { try { if (name.endsWith(".class")) { if (exclude(name)) continue; currentName = name; weaveFile(name, new BufferedInputStream(new FileInputStream(name)), detector); } else if (name.endsWith(".jar")) { for (FileLister.Entry fe : new FileLister(name)) { currentName = fe.getFileName(); if (currentName.endsWith(".class")) { currentName = currentName.substring(0, currentName.length() - 6).replace('/', '.'); if (exclude(currentName)) continue; weaveFile(currentName, fe.getInputStream(), detector); } } } else if (new File(name).isDirectory()) { for (FileLister.Entry fe : new FileLister(name)) { currentName = fe.getFileName(); if (currentName.endsWith(".class")) { if (exclude(currentName)) continue; weaveFile(currentName, fe.getInputStream(), detector); } } } else { weaveClass(name, detector); } } catch (KilimException ke) { log.error("Error weaving " + currentName + ". " + ke.getMessage()); // ke.printStackTrace(); System.exit(1); } catch (IOException ioe) { log.error("Unable to find/process '" + currentName + "'"); System.exit(1); } catch (Throwable t) { log.error("Error weaving " + currentName); t.printStackTrace(); System.exit(1); } } System.exit(err); }
From source file:ffx.xray.TimerTest.java
public static void main(String args[]) { // Parameters collection from original Timer script String pdbname = System.getProperty("pdbFile", "1N7S.pdb"); String mtzname = System.getProperty("mtzFile", null); String cifname = System.getProperty("cifFile", null); final boolean ciOnly = false; final String info = "SNARE complex"; final double r = 19.412671496011; final double rfree = 21.555930987573; final double sigmaA = 0.9336853524690557; final double sigmaW = 0.13192537249786418; boolean ci = System.getProperty("ffx.ci", "false").equalsIgnoreCase("true"); if (!ci && ciOnly) { crystalStats = null;//from w w w.ja va 2 s .c om return; } int index = pdbname.lastIndexOf("."); String name = pdbname.substring(0, index); // load the structure MolecularAssembly molecularAssembly; File structure, mtzFile, cifFile; structure = new File(pdbname); PotentialsFileOpener opener = new PotentialsFileOpener(structure); opener.run(); molecularAssembly = opener.getAssembly(); mtzFile = new File(mtzname); cifFile = new File(cifname); // load any properties associated with it CompositeConfiguration properties = Keyword.loadProperties(structure); // read in Fo/sigFo/FreeR MTZFilter mtzFilter = new MTZFilter(); CIFFilter cifFilter = new CIFFilter(); Crystal crystal = Crystal.checkProperties(properties); Resolution resolution = Resolution.checkProperties(properties); if (crystal == null || resolution == null) { if (mtzname != null) { reflectionList = mtzFilter.getReflectionList(mtzFile); } else { reflectionList = cifFilter.getReflectionList(cifFile); } } else { reflectionList = new ReflectionList(crystal, resolution); } refinementData = new DiffractionRefinementData(properties, reflectionList); if (mtzname != null) { // assertTrue(info + " mtz file should be read in without errors", // mtzFilter.readFile(mtzFile, reflectionList, refinementData, // properties)); } else { // assertTrue(info + " cif file should be read in without errors", // cifFilter.readFile(cifFile, reflectionList, refinementData, // properties)); } ForceFieldFilter forceFieldFilter = new ForceFieldFilter(properties); ForceField forceField = forceFieldFilter.parse(); // associate molecular assembly with the structure, set up forcefield molecularAssembly.setForceField(forceField); PDBFilter pdbFile = new PDBFilter(structure, molecularAssembly, forceField, properties); pdbFile.readFile(); pdbFile.applyAtomProperties(); molecularAssembly.finalize(true, forceField); ForceFieldEnergy energy = new ForceFieldEnergy(molecularAssembly, pdbFile.getCoordRestraints()); List<Atom> atomList = molecularAssembly.getAtomList(); Atom atomArray[] = atomList.toArray(new Atom[atomList.size()]); // set up FFT and run it parallelTeam = new ParallelTeam(); CrystalReciprocalSpace crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam, parallelTeam, false); crs.computeDensity(refinementData.fc); refinementData.setCrystalReciprocalSpace_fc(crs); crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam, parallelTeam, true); crs.computeDensity(refinementData.fs); refinementData.setCrystalReciprocalSpace_fs(crs); ScaleBulkMinimize scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, crs, parallelTeam); scaleBulkMinimize.minimize(6, 1.0e-4); SigmaAMinimize sigmaAMinimize = new SigmaAMinimize(reflectionList, refinementData, parallelTeam); sigmaAMinimize.minimize(7, 2.0e-2); SplineMinimize splineMinimize = new SplineMinimize(reflectionList, refinementData, refinementData.spline, SplineEnergy.Type.FOFC); splineMinimize.minimize(7, 1e-5); crystalStats = new CrystalStats(reflectionList, refinementData); scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, refinementData.crs_fs, parallelTeam); ScaleBulkEnergy scaleBulkEnergy = scaleBulkMinimize.getScaleBulkEnergy(); int n = scaleBulkMinimize.getNumberOfVariables(); double x[] = new double[n]; double g[] = new double[n]; scaleBulkMinimize.getCoordinates(x); scaleBulkEnergy.energyAndGradient(x, g); double delta = 1.0e-4; double tolerance = 1.0e-4; logger.info(String.format("SCATTER TEST")); for (int i = 0; i < 30; i++) { long time = -System.nanoTime(); scaleBulkEnergy.energyAndGradient(x, g); time += System.nanoTime(); logger.info(String.format(" Time %12.8f", time * 1.0e-9)); } }
From source file:ReflectClass.java
public static void main(String args[]) { Constructor cn[];/*from w ww . j a v a 2 s . co m*/ Class cc[]; Method mm[]; Field ff[]; Class c = null; Class supClass; String x, y, s1, s2, s3; Hashtable classRef = new Hashtable(); if (args.length == 0) { System.out.println("Please specify a class name on the command line."); System.exit(1); } try { c = Class.forName(args[0]); } catch (ClassNotFoundException ee) { System.out.println("Couldn't find class '" + args[0] + "'"); System.exit(1); } /* * Step 0: If our name contains dots we're in a package so put * that out first. */ x = c.getName(); if (x.lastIndexOf(".") != -1) { y = x.substring(0, x.lastIndexOf(".")); System.out.println("package " + y + ";\n\r"); } /* * Let's use the Reflection API to sift through what is * inside this class. * * Step 1: Collect referenced classes * This step is used so that I can regenerate the import statements. * It isn't strictly required of course, Java works just fine with * fully qualified object class names, but it looks better when you * use 'String' rather than 'java.lang.String' as the return type. */ ff = c.getDeclaredFields(); for (int i = 0; i < ff.length; i++) { x = tName(ff[i].getType().getName(), classRef); } cn = c.getDeclaredConstructors(); for (int i = 0; i < cn.length; i++) { Class cx[] = cn[i].getParameterTypes(); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { x = tName(cx[j].getName(), classRef); } } } mm = c.getDeclaredMethods(); for (int i = 0; i < mm.length; i++) { x = tName(mm[i].getReturnType().getName(), classRef); Class cx[] = mm[i].getParameterTypes(); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { x = tName(cx[j].getName(), classRef); } } } // Don't import ourselves ... classRef.remove(c.getName()); /* * Step 2: Start class description generation, start by printing * out the import statements. * * This is the line that goes 'public SomeClass extends Foo {' */ for (Enumeration e = classRef.keys(); e.hasMoreElements();) { System.out.println("import " + e.nextElement() + ";"); } System.out.println(); /* * Step 3: Print the class or interface introducer. We use * a convienience method in Modifer to print the whole string. */ int mod = c.getModifiers(); System.out.print(Modifier.toString(mod)); if (Modifier.isInterface(mod)) { System.out.print(" interface "); } else { System.out.print(" class "); } System.out.print(tName(c.getName(), null)); supClass = c.getSuperclass(); if (supClass != null) { System.out.print(" extends " + tName(supClass.getName(), classRef)); } System.out.println(" {"); /* * Step 4: Print out the fields (internal class members) that are declared * by this class. * * Fields are of the form [Modifiers] [Type] [Name] ; */ System.out.println("\n\r/*\n\r * Field Definitions.\r\n */"); for (int i = 0; i < ff.length; i++) { Class ctmp = ff[i].getType(); int md = ff[i].getModifiers(); System.out.println(" " + Modifier.toString(md) + " " + tName(ff[i].getType().getName(), null) + " " + ff[i].getName() + ";"); } /* * Step 5: Print out the constructor declarations. * * We note the name of the class which is the 'name' for all * constructors. Also there is no type, so the definition is * simplye [Modifiers] ClassName ( [ Parameters ] ) { } * */ System.out.println("\n\r/*\n\r * Declared Constructors. \n\r */"); x = tName(c.getName(), null); for (int i = 0; i < cn.length; i++) { int md = cn[i].getModifiers(); System.out.print(" " + Modifier.toString(md) + " " + x); Class cx[] = cn[i].getParameterTypes(); System.out.print("( "); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), null)); if (j < (cx.length - 1)) System.out.print(", "); } } System.out.print(") "); System.out.println("{ ... }"); } /* * Step 6: Print out the method declarations. * * Now methods have a name, a return type, and an optional * set of parameters so they are : * [modifiers] [type] [name] ( [optional parameters] ) { } */ System.out.println("\n\r/*\n\r * Declared Methods.\n\r */"); for (int i = 0; i < mm.length; i++) { int md = mm[i].getModifiers(); System.out.print(" " + Modifier.toString(md) + " " + tName(mm[i].getReturnType().getName(), null) + " " + mm[i].getName()); Class cx[] = mm[i].getParameterTypes(); System.out.print("( "); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), classRef)); if (j < (cx.length - 1)) System.out.print(", "); } } System.out.print(") "); System.out.println("{ ... }"); } /* * Step 7: Print out the closing brace and we're done! */ System.out.println("}"); }
From source file:net.sf.firemox.Magic.java
/** * @param args// w w w . j a v a 2 s. co m * the command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { Log.init(); Log.debug("MP v" + IdConst.VERSION + ", jre:" + System.getProperty("java.runtime.version") + ", jvm:" + System.getProperty("java.vm.version") + ",os:" + System.getProperty("os.name") + ", res:" + Toolkit.getDefaultToolkit().getScreenSize().width + "x" + Toolkit.getDefaultToolkit().getScreenSize().height + ", root:" + MToolKit.getRootDir()); System.setProperty("swing.aatext", "true"); System.setProperty(SubstanceLookAndFeel.WATERMARK_IMAGE_PROPERTY, MToolKit.getIconPath(Play.ZONE_NAME + "/hardwoodfloor.png")); final File substancelafFile = MToolKit.getFile(FILE_SUBSTANCE_PROPERTIES); if (substancelafFile == null) { Log.warn("Unable to locate '" + FILE_SUBSTANCE_PROPERTIES + "' file, you are using the command line with wrong configuration. See http://www.firemox.org/dev/project.html documentation"); } else { System.getProperties().load(new FileInputStream(substancelafFile)); } MToolKit.defaultFont = new Font("Arial", 0, 11); try { if (args.length > 0) { final String[] args2 = new String[args.length - 1]; System.arraycopy(args, 1, args2, 0, args.length - 1); if ("-rebuild".equals(args[0])) { XmlConfiguration.main(args2); } else if ("-oracle2xml".equals(args[0])) { Oracle2Xml.main(args2); } else if ("-batch".equals(args[0])) { if ("-server".equals(args[1])) { batchMode = BATCH_SERVER; } else if ("-client".equals(args[1])) { batchMode = BATCH_CLIENT; } } else { Log.error("Unknown options '" + Arrays.toString(args) + "'\nUsage : java -jar starter.jar <options>, where options are :\n" + "\t-rebuild -game <tbs name> [-x] [-d] [-v] [-h] [-f] [-n]\n" + "\t-oracle2xml -f <oracle file> -d <output directory> [-v] [-h]"); } System.exit(0); return; } if (batchMode == -1 && !"Mac OS X".equals(System.getProperty("os.name"))) { splash = new SplashScreen(MToolKit.getIconPath("splash.jpg"), null, 2000); } // language settings LanguageManager.initLanguageManager(Configuration.getString("language", "auto")); } catch (Throwable t) { Log.error("START-ERROR : \n\t" + t.getMessage()); System.exit(1); return; } Log.debug("MP Language : " + LanguageManager.getLanguage().getName()); speparateAvatar = Toolkit.getDefaultToolkit().getScreenSize().height > 768; // verify the java version, minimal is 1.5 if (new JavaVersion().compareTo(new JavaVersion(IdConst.MINIMAL_JRE)) == -1) { Log.error(LanguageManager.getString("wrongjava") + IdConst.MINIMAL_JRE); } // load look and feel settings lookAndFeelName = Configuration.getString("preferred", MUIManager.LF_SUBSTANCE_CLASSNAME); // try { // FileInputStream in= new FileInputStream("MAGIC.TTF"); // MToolKit.defaultFont= Font.createFont(Font.TRUETYPE_FONT, in); // in.close(); // MToolKit.defaultFont= MToolKit.defaultFont.deriveFont(Font.BOLD, 11); // } // catch (FileNotFoundException e) { // System.out.println("editorfont.ttf not found, using default."); // } // catch (Exception ex) { // ex.printStackTrace(); // } // Read available L&F final LinkedList<Pair<String, String>> lfList = new LinkedList<Pair<String, String>>(); try { BufferedReader buffReader = new BufferedReader( new InputStreamReader(MToolKit.getResourceAsStream(IdConst.FILE_THEME_SETTINGS))); String line; while ((line = buffReader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { final int index = line.indexOf(';'); if (index != -1) { lfList.add(new Pair<String, String>(line.substring(0, index), line.substring(index + 1))); } } } IOUtils.closeQuietly(buffReader); } catch (Throwable e) { // no place for resolve this problem Log.debug("Error reading L&F properties : " + e.getMessage()); } for (Pair<String, String> pair : lfList) { UIManager.installLookAndFeel(pair.key, pair.value); } // install L&F if (SkinLF.isSkinLF(lookAndFeelName)) { // is a SkinLF Look & Feel /* * Make sure we have a nice window decoration. */ SkinLF.installSkinLF(lookAndFeelName); } else { // is Metal Look & Feel if (!MToolKit.isAvailableLookAndFeel(lookAndFeelName)) { // preferred look&feel is not available JOptionPane.showMessageDialog(magicForm, LanguageManager.getString("preferredlfpb", lookAndFeelName), LanguageManager.getString("error"), JOptionPane.INFORMATION_MESSAGE); setDefaultUI(); } // Install the preferred LookAndFeel newLAF = MToolKit.geLookAndFeel(lookAndFeelName); frameDecorated = newLAF.getSupportsWindowDecorations(); /* * Make sure we have a nice window decoration. */ JFrame.setDefaultLookAndFeelDecorated(frameDecorated); JDialog.setDefaultLookAndFeelDecorated(frameDecorated); UIManager.setLookAndFeel(MToolKit.geLookAndFeel(lookAndFeelName)); } // Start main thread try { new Magic(); SwingUtilities.invokeLater(SkinLF.REFRESH_RUNNER); } catch (Throwable e) { Log.fatal("In main thread, occurred exception : ", e); ConnectionManager.closeConnexions(); return; } }
From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java
public static void main(String[] args) { String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a"; //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603"; //test();//from w ww. j a v a 2 s. c o m //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf"); // File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf"); File file = new File( "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf"); MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file); try { mbf.readFile(); } catch (IOException e) { //System.out.println(e.getMessage()); System.err.println( "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!"); System.exit(-1); } MetFusionBatchSettings settings = mbf.getBatchSettings(); List<String> absent = settings.getSubstrucAbsent(); List<String> present = settings.getSubstrucPresent(); for (String s : present) { System.out.println("present -> " + s); } for (String s : absent) { System.out.println("absent -> " + s); } String formula = settings.getMfFormula(); System.out.println("formula -> " + formula); boolean useFormulaAsQuery = true; boolean useSDF = false; String sdfFile = ""; if (useSDF) { sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf"; if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file? System.err.println("SDF file needs to be specified! Exiting."); System.exit(-1); } } SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery, useSDF, sdfFile); ss.run(); List<ResultSubstructure> remaining = ss.getResultsRemaining(); List<Result> resultsForSDF = new ArrayList<Result>(); StringBuilder sb = new StringBuilder(); String sep = ","; for (ResultSubstructure rs : remaining) { sb.append(rs.getId()).append(sep); Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore()); r.setMol(rs.getMol()); r.setSmiles(rs.getSmiles()); r.setInchi(rs.getInchi()); r.setInchikey(rs.getInchikey()); resultsForSDF.add(r); } String ids = sb.toString(); String fileSep = System.getProperty("file.separator"); if (!ids.isEmpty()) { ids = ids.substring(0, ids.length() - 1); System.out.println("ids -> " + ids); settings.setMfDatabaseIDs(ids); String filename = file.getName(); String prefix = filename.substring(0, filename.lastIndexOf(".")); filename = filename.replace(prefix, prefix + "_ids"); String dir = file.getParent(); System.out.println("dir -> " + dir); if (!dir.endsWith(fileSep)) dir += fileSep; File output = new File(file.getParent(), filename); mbf.writeFile(output, settings); SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf"); boolean writeOK = so.writeOriginalResults(resultsForSDF, false); if (!writeOK) System.err.println("Error writing SDF [" + so.getFilename()); } }
From source file:edu.stanford.muse.xword.Crossword.java
public static void main(String args[]) { List<String> ownNameTerms = new ArrayList<String>(); // e.g. n = "sudheendra hangal" returns pair <"sudheendrahangal", [10,6]> String n = "sudheendra - hangal"; Pair<String, List<Integer>> p = convertToWord(n); String word = p.getFirst(); ownNameTerms.add(word); // add the full name // extract individual words from the word lens, e.g. pair <"sudheendrahangal", [10,6]> -> ["sudheendra", "hangal"] int prev = 0; for (Integer I : p.getSecond()) { ownNameTerms.add(word.substring(prev, prev + I)); // add the tokens prev = prev + I;//from www .j a va 2s . c o m } for (String s : ownNameTerms) System.out.println(s); }