List of usage examples for java.lang Math min
@HotSpotIntrinsicCandidate public static double min(double a, double b)
From source file:squash.tools.FakeBookingCreator.java
public static void main(String[] args) throws IOException { int numberOfDays = 21; int numberOfCourts = 5; int maxCourtSpan = 5; int numberOfSlots = 16; int maxSlotSpan = 3; int minSurnameLength = 2; int maxSurnameLength = 20; int minBookingsPerDay = 0; int maxBookingsPerDay = 8; LocalDate startDate = LocalDate.of(2016, 7, 5); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); List<Booking> bookings = new ArrayList<>(); for (LocalDate date = startDate; date.isBefore(startDate.plusDays(numberOfDays)); date = date.plusDays(1)) { int numBookings = ThreadLocalRandom.current().nextInt(minBookingsPerDay, maxBookingsPerDay + 1); List<Booking> daysBookings = new ArrayList<>(); for (int bookingIndex = 0; bookingIndex < numBookings; bookingIndex++) { String player1 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic( ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1)); String player2 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic( ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1)); Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>(); daysBookings.forEach((booking) -> { addBookingToSet(booking, bookedCourts); });//from w ww . ja va 2 s . com Booking booking; Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>(); do { // Loop until we create a booking of free courts int court = ThreadLocalRandom.current().nextInt(1, numberOfCourts + 1); int courtSpan = ThreadLocalRandom.current().nextInt(1, Math.min(maxCourtSpan + 1, numberOfCourts - court + 2)); int slot = ThreadLocalRandom.current().nextInt(1, numberOfSlots + 1); int slotSpan = ThreadLocalRandom.current().nextInt(1, Math.min(maxSlotSpan + 1, numberOfSlots - slot + 2)); booking = new Booking(court, courtSpan, slot, slotSpan, player1 + "/" + player2); booking.setDate(date.format(formatter)); courtsToBook.clear(); addBookingToSet(booking, courtsToBook); } while (Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0)); daysBookings.add(booking); } bookings.addAll(daysBookings); } // Encode bookings as JSON // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // Create a json factory to write the treenode as json. JsonFactory jsonFactory = new JsonFactory(); ObjectNode rootNode = factory.objectNode(); ArrayNode bookingsNode = rootNode.putArray("bookings"); for (int i = 0; i < bookings.size(); i++) { Booking booking = bookings.get(i); ObjectNode bookingNode = factory.objectNode(); bookingNode.put("court", booking.getCourt()); bookingNode.put("courtSpan", booking.getCourtSpan()); bookingNode.put("slot", booking.getSlot()); bookingNode.put("slotSpan", booking.getSlotSpan()); bookingNode.put("name", booking.getName()); bookingNode.put("date", booking.getDate()); bookingsNode.add(bookingNode); } // Add empty booking rules array - just so restore works rootNode.putArray("bookingRules"); rootNode.put("clearBeforeRestore", true); try (JsonGenerator generator = jsonFactory.createGenerator(new File("FakeBookings.json"), JsonEncoding.UTF8)) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_EMPTY); mapper.setSerializationInclusion(Include.NON_NULL); mapper.writeTree(generator, rootNode); } }
From source file:TreeCellEditor.java
public static void main(String[] args) { final Display display = new Display(); final Color black = display.getSystemColor(SWT.COLOR_BLACK); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); final Tree tree = new Tree(shell, SWT.BORDER); for (int i = 0; i < 16; i++) { TreeItem itemI = new TreeItem(tree, SWT.NONE); itemI.setText("Item " + i); for (int j = 0; j < 16; j++) { TreeItem itemJ = new TreeItem(itemI, SWT.NONE); itemJ.setText("Item " + j); }/*from ww w . ja v a 2 s. co m*/ } final TreeItem[] lastItem = new TreeItem[1]; final TreeEditor editor = new TreeEditor(tree); tree.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { final TreeItem item = (TreeItem) event.item; if (item != null && item == lastItem[0]) { boolean isCarbon = SWT.getPlatform().equals("carbon"); final Composite composite = new Composite(tree, SWT.NONE); if (!isCarbon) composite.setBackground(black); final Text text = new Text(composite, SWT.NONE); final int inset = isCarbon ? 0 : 1; composite.addListener(SWT.Resize, new Listener() { public void handleEvent(Event e) { Rectangle rect = composite.getClientArea(); text.setBounds(rect.x + inset, rect.y + inset, rect.width - inset * 2, rect.height - inset * 2); } }); Listener textListener = new Listener() { public void handleEvent(final Event e) { switch (e.type) { case SWT.FocusOut: item.setText(text.getText()); composite.dispose(); break; case SWT.Verify: String newText = text.getText(); String leftText = newText.substring(0, e.start); String rightText = newText.substring(e.end, newText.length()); GC gc = new GC(text); Point size = gc.textExtent(leftText + e.text + rightText); gc.dispose(); size = text.computeSize(size.x, SWT.DEFAULT); editor.horizontalAlignment = SWT.LEFT; Rectangle itemRect = item.getBounds(), rect = tree.getClientArea(); editor.minimumWidth = Math.max(size.x, itemRect.width) + inset * 2; int left = itemRect.x, right = rect.x + rect.width; editor.minimumWidth = Math.min(editor.minimumWidth, right - left); editor.minimumHeight = size.y + inset * 2; editor.layout(); break; case SWT.Traverse: switch (e.detail) { case SWT.TRAVERSE_RETURN: item.setText(text.getText()); // FALL THROUGH case SWT.TRAVERSE_ESCAPE: composite.dispose(); e.doit = false; } break; } } }; text.addListener(SWT.FocusOut, textListener); text.addListener(SWT.Traverse, textListener); text.addListener(SWT.Verify, textListener); editor.setEditor(composite, item); text.setText(item.getText()); text.selectAll(); text.setFocus(); } lastItem[0] = item; } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:com.mapr.synth.Synth.java
public static void main(String[] args) throws IOException, CmdLineException, InterruptedException, ExecutionException { final Options opts = new Options(); CmdLineParser parser = new CmdLineParser(opts); try {/* w w w. j av a2s . co m*/ parser.parseArgument(args); } catch (CmdLineException e) { System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file " + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] " + "[-threads n] " + "[-output output-directory-name] "); throw e; } Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000, "Must have at least one thread and no more than 2000"); if (opts.threads > 1) { Preconditions.checkArgument(!"-".equals(opts.output), "If more than on thread is used, you have to use -output to set the output directory"); } File outputDir = new File(opts.output); if (!"-".equals(opts.output)) { if (!outputDir.exists()) { Preconditions.checkState(outputDir.mkdirs(), String.format("Couldn't create output directory %s", opts.output)); } Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(), String.format("Couldn't create directory %s", opts.output)); } if (opts.schema == null) { throw new IllegalArgumentException("Must specify schema file using [-schema filename] option"); } final SchemaSampler sampler = new SchemaSampler(opts.schema); final AtomicLong rowCount = new AtomicLong(); final List<ReportingWorker> tasks = Lists.newArrayList(); int limit = (opts.count + opts.threads - 1) / opts.threads; int remaining = opts.count; for (int i = 0; i < opts.threads; i++) { final int count = Math.min(limit, remaining); remaining -= count; tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i)); } final double t0 = System.nanoTime() * 1e-9; ExecutorService pool = Executors.newFixedThreadPool(opts.threads); ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1); final AtomicBoolean finalRun = new AtomicBoolean(false); final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log")); Runnable blink = new Runnable() { public double oldT; private long oldN; @Override public void run() { double t = System.nanoTime() * 1e-9; long n = rowCount.get(); System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads, t - t0, n, n / (t - t0), (n - oldN) / (t - oldT)); for (ReportingWorker task : tasks) { ReportingWorker.ThreadReport r = task.report(); sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime, r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime); } oldN = n; oldT = t; } }; if (!"-".equals(opts.output)) { blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS); } List<Future<Integer>> results = pool.invokeAll(tasks); int total = 0; for (Future<Integer> result : results) { total += result.get(); } Preconditions.checkState(total == opts.count, String .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total)); pool.shutdownNow(); blinker.shutdownNow(); finalRun.set(true); sideLog.close(); blink.run(); }
From source file:jsdp.app.control.clqg.univariate.CLQG.java
public static void main(String args[]) { /******************************************************************* * Problem parameters//from w w w . j a v a 2 s . c o m */ int T = 20; // Horizon length double G = 1; // Input transition double Phi = 1; // State transition double R = 1; // Input cost double Q = 1; // State cost double Ulb = -1; // Action constraint double Uub = 20; // Action constraint double noiseStd = 5; // Standard deviation of the noise double[] noiseStdArray = new double[T]; Arrays.fill(noiseStdArray, noiseStd); double truncationQuantile = 0.975; // Random variables Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(noiseStdArray.length) .mapToObj(i -> new NormalDist(0, noiseStdArray[i])) .toArray(Distribution[]::new); double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(T) .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], 1 - truncationQuantile)).toArray(); double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(T) .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], truncationQuantile)).toArray(); double initialX = 0; // Initial state /******************************************************************* * Model definition */ // State space double stepSize = 0.5; //Stepsize must be 1 for discrete distributions double minState = -25; double maxState = 100; StateImpl.setStateBoundaries(stepSize, minState, maxState); // Actions Function<State, ArrayList<Action>> buildActionList = (Function<State, ArrayList<Action>> & Serializable) s -> { StateImpl state = (StateImpl) s; ArrayList<Action> feasibleActions = new ArrayList<Action>(); double maxAction = Math.min(Uub, (StateImpl.getMaxState() - Phi * state.getInitialState()) / G); double minAction = Math.max(Ulb, (StateImpl.getMinState() - Phi * state.getInitialState()) / G); for (double actionPointer = minAction; actionPointer <= maxAction; actionPointer += StateImpl .getStepSize()) { feasibleActions.add(new ActionImpl(state, actionPointer)); } return feasibleActions; }; Function<State, Action> idempotentAction = (Function<State, Action> & Serializable) s -> new ActionImpl(s, 0.0); ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action, finalState) -> { ActionImpl a = (ActionImpl) action; StateImpl fs = (StateImpl) finalState; double inputCost = Math.pow(a.getAction(), 2) * R; double stateCost = Math.pow(fs.getInitialState(), 2) * Q; return inputCost + stateCost; }; // Random Outcome Function RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> { double realizedNoise = ((StateImpl) finalState).getInitialState() - ((StateImpl) initialState).getInitialState() * Phi - ((ActionImpl) action).getAction() * G; return realizedNoise; }; /******************************************************************* * Solve */ // Sampling scheme SamplingScheme samplingScheme = SamplingScheme.NONE; int maxSampleSize = 50; double reductionFactorPerStage = 1; // Value Function Processing Method: backward recursion double discountFactor = 1.0; int stateSpaceLowerBound = 10000000; float loadFactor = 0.8F; BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions, supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList, idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage, stateSpaceLowerBound, loadFactor, HashType.THASHMAP); System.out.println("--------------Backward recursion--------------"); StopWatch timer = new StopWatch(); OperatingSystemMXBean osMBean; try { osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(), ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class); long nanoBefore = System.nanoTime(); long cpuBefore = osMBean.getProcessCpuTime(); timer.start(); recursion.runBackwardRecursionMonitoring(); timer.stop(); long cpuAfter = osMBean.getProcessCpuTime(); long nanoAfter = System.nanoTime(); long percent; if (nanoAfter > nanoBefore) percent = ((cpuAfter - cpuBefore) * 100L) / (nanoAfter - nanoBefore); else percent = 0; System.out.println( "Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); double ETC = recursion.getExpectedCost(initialX); StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialX); double action = recursion.getOptimalAction(initialState).getAction(); System.out.println("Expected total cost (assuming an initial state " + initialX + "): " + ETC); System.out.println("Optimal initial action: " + action); System.out.println("Time elapsed: " + timer); System.out.println(); }
From source file:org.n52.oss.testdata.sml.GeneratorClient.java
/** * @param args/*from w w w .j av a 2 s .c o m*/ */ public static void main(String[] args) { if (sending) log.info("Starting insertion of test sensors into " + sirURL); else log.warn("Starting generation of test sensors, NOT sending!"); TestSensorFactory factory = new TestSensorFactory(); // create sensors List<TestSensor> sensors = new ArrayList<TestSensor>(); for (int i = 0; i < nSensorsToGenerate; i++) { TestSensor s = factory.createRandomTestSensor(); sensors.add(s); log.info("Added new random sensor: " + s); } ArrayList<String> insertedSirIds = new ArrayList<String>(); // insert sensors to service int startOfSubList = 0; int endOfSubList = nSensorsInOneInsertRequest; while (endOfSubList <= sensors.size() + nSensorsInOneInsertRequest) { List<TestSensor> currentSensors = sensors.subList(startOfSubList, Math.min(endOfSubList, sensors.size())); if (currentSensors.isEmpty()) break; try { String[] insertedSirIDs = insertSensorsInSIR(currentSensors); if (insertedSirIDs == null) { log.error("Did not insert dummy sensors."); } else { insertedSirIds.addAll(Arrays.asList(insertedSirIDs)); } } catch (HttpException e) { log.error("Error inserting sensors.", e); } catch (IOException e) { log.error("Error inserting sensors.", e); } startOfSubList = Math.min(endOfSubList, sensors.size()); endOfSubList = endOfSubList + nSensorsInOneInsertRequest; if (sending) { try { if (log.isDebugEnabled()) log.debug("Sleeping for " + SLEEP_BETWEEN_REQUESTS + " msecs."); Thread.sleep(SLEEP_BETWEEN_REQUESTS); } catch (InterruptedException e) { log.error("Interrupted!", e); } } } log.info("Added sensors (ids in sir): " + Arrays.toString(insertedSirIds.toArray())); }
From source file:com.genentech.chemistry.openEye.apps.SDFSubRMSD.java
public static void main(String... args) throws IOException { // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file oe-supported"); opt.setRequired(true);/*w w w .j ava 2 s. c om*/ options.addOption(opt); opt = new Option("out", true, "output file oe-supported"); opt.setRequired(false); options.addOption(opt); opt = new Option("fragFile", true, "file with single 3d substructure query"); opt.setRequired(false); options.addOption(opt); opt = new Option("isMDL", false, "if given the fragFile is suposed to be an mdl query file, query features are supported."); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String fragFile = cmd.getOptionValue("fragFile"); // read fragment OESubSearch ss; oemolistream ifs = new oemolistream(fragFile); OEMolBase mol; if (!cmd.hasOption("isMDL")) { mol = new OEGraphMol(); oechem.OEReadMolecule(ifs, mol); ss = new OESubSearch(mol, OEExprOpts.AtomicNumber, OEExprOpts.BondOrder); } else { int aromodel = OEIFlavor.Generic.OEAroModelOpenEye; int qflavor = ifs.GetFlavor(ifs.GetFormat()); ifs.SetFlavor(ifs.GetFormat(), (qflavor | aromodel)); int opts = OEMDLQueryOpts.Default | OEMDLQueryOpts.SuppressExplicitH; OEQMol qmol = new OEQMol(); oechem.OEReadMDLQueryFile(ifs, qmol, opts); ss = new OESubSearch(qmol); mol = qmol; } double nSSatoms = mol.NumAtoms(); double sssCoords[] = new double[mol.GetMaxAtomIdx() * 3]; mol.GetCoords(sssCoords); mol.Clear(); ifs.close(); if (!ss.IsValid()) throw new Error("Invalid query " + args[0]); ifs = new oemolistream(inFile); oemolostream ofs = new oemolostream(outFile); int count = 0; while (oechem.OEReadMolecule(ifs, mol)) { count++; double rmsd = Double.MAX_VALUE; double molCoords[] = new double[mol.GetMaxAtomIdx() * 3]; mol.GetCoords(molCoords); for (OEMatchBase mb : ss.Match(mol, false)) { double r = 0; for (OEMatchPairAtom mp : mb.GetAtoms()) { OEAtomBase asss = mp.getPattern(); double sx = sssCoords[asss.GetIdx() * 3]; double sy = sssCoords[asss.GetIdx() * 3]; double sz = sssCoords[asss.GetIdx() * 3]; OEAtomBase amol = mp.getTarget(); double mx = molCoords[amol.GetIdx() * 3]; double my = molCoords[amol.GetIdx() * 3]; double mz = molCoords[amol.GetIdx() * 3]; r += Math.sqrt((sx - mx) * (sx - mx) + (sy - my) * (sy - my) + (sz - mz) * (sz - mz)); } r /= nSSatoms; rmsd = Math.min(rmsd, r); } if (rmsd != Double.MAX_VALUE) oechem.OESetSDData(mol, "SSSrmsd", String.format("%.3f", rmsd)); oechem.OEWriteMolecule(ofs, mol); mol.Clear(); } ifs.close(); ofs.close(); mol.delete(); ss.delete(); }
From source file:com.genentech.struchk.sdfNormalizer.java
public static void main(String[] args) { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);// w ww . j a v a 2s .c o m options.addOption(opt); opt = new Option("out", true, "output file"); opt.setRequired(true); options.addOption(opt); opt = new Option("mol", true, "molFile used for output: ORIGINAL(def)|NORMALIZED|TAUTOMERIC"); opt.setRequired(false); options.addOption(opt); opt = new Option("shortMessage", false, "Limit message to first 80 characters to conform with sdf file specs."); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { exitWithHelp(options, e.getMessage()); throw new Error(e); // avoid compiler errors } args = cmd.getArgs(); if (args.length != 0) { System.err.print("Unknown options: " + args + "\n\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sdfNormalizer", options); System.exit(1); } String molOpt = cmd.getOptionValue("mol"); OUTMolFormat outMol = OUTMolFormat.ORIGINAL; if (molOpt == null || "original".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.ORIGINAL; else if ("NORMALIZED".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.NORMALIZED; else if ("TAUTOMERIC".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.TAUTOMERIC; else { System.err.printf("Unkown option for -mol: %s\n", molOpt); System.exit(1); } String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); boolean limitMessage = cmd.hasOption("shortMessage"); try { oemolistream ifs = new oemolistream(inFile); oemolostream ofs = new oemolostream(outFile); URL cFile = OEStruchk.getResourceURL(OEStruchk.class, "Struchk.xml"); // create OEStruchk from config file OEStruchk strchk = new OEStruchk(cFile, CHECKConfig.ASSIGNStructFlag, false); OEGraphMol mol = new OEGraphMol(); StringBuilder sb = new StringBuilder(2000); while (oechem.OEReadMolecule(ifs, mol)) { if (!strchk.applyRules(mol, null)) nErrors++; switch (outMol) { case NORMALIZED: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol("parent")); break; case TAUTOMERIC: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol(null)); break; case ORIGINAL: break; } oechem.OESetSDData(mol, "CTISMILES", strchk.getTransformedIsoSmiles(null)); oechem.OESetSDData(mol, "CTSMILES", strchk.getTransformedSmiles(null)); oechem.OESetSDData(mol, "CISMILES", strchk.getTransformedIsoSmiles("parent")); oechem.OESetSDData(mol, "Strutct_Flag", strchk.getStructureFlag().getName()); List<Message> msgs = strchk.getStructureMessages(null); nMessages += msgs.size(); for (Message msg : msgs) sb.append(String.format("\t%s:%s", msg.getLevel(), msg.getText())); if (limitMessage) sb.setLength(Math.min(sb.length(), 80)); oechem.OESetSDData(mol, "NORM_MESSAGE", sb.toString()); oechem.OEWriteMolecule(ofs, mol); sb.setLength(0); nStruct++; } strchk.delete(); mol.delete(); ifs.close(); ifs.delete(); ofs.close(); ofs.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("sdfNormalizer: Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); } }
From source file:mmllabvsdextractfeature.MMllabVSDExtractFeature.java
/** * @param args the command line arguments *//*from w ww. jav a 2 s . c o m*/ public static void main(String[] args) throws IOException { // TODO code application logic here MMllabVSDExtractFeature hello = new MMllabVSDExtractFeature(); FileStructer metdata = new FileStructer(); //Utility utilityClassIni = new Utility(); FrameStructer frameStructer = new FrameStructer(); /* Flow : 1. Read metdata file 2. Untar folder: -1 Shot content 25 frame -1 folder 50 shot Process with 1 shot: - Resize All image 1 shot --> delete orginal. - Extract feature 25 frame - Pooling Max and aveg. - Delete Image, feature - zip file Feature 3. Delete File. */ // Load metadata File String dir = "/media/data1"; String metadataFileDir = "/media/data1/metdata/devel2011-new.lst"; ArrayList<FileStructer> listFileFromMetadata = metdata.readMetadata(metadataFileDir); // String test = utilityClass.readTextFile("C:\\Users\\tiendv\\Downloads\\VSD_devel2011_1.shot_1.RKF_1.Frame_1.txt"); // ArrayList <String> testFeatureSave = utilityClass.SplitUsingTokenizerWithLineArrayList(test, " "); // utilityClass.writeToFile("C:\\Users\\tiendv\\Downloads\\VSD_devel2011_1.shot_1.txt", testFeatureSave); // System.out.println(test); for (int i = 0; i < listFileFromMetadata.size(); i++) { Utility utilityClass = new Utility(); //Un zip file String folderName = listFileFromMetadata.get(i).getWholeFolderName(); String nameZipFile = dir + "/" + folderName + "/" + listFileFromMetadata.get(i).getNameZipFileName() + ".tar"; nameZipFile = nameZipFile.replaceAll("\\s", ""); String outPutFolder = dir + "/" + folderName + "/" + listFileFromMetadata.get(i).getNameZipFileName(); outPutFolder = outPutFolder.replaceAll("\\s", ""); utilityClass.unTarFolder(UNTARSHFILE, nameZipFile, outPutFolder + "_"); // Resize all image in folder has been unzip utilityClass.createFolder(CREADFOLDER, outPutFolder); utilityClass.resizeWholeFolder(outPutFolder + "_", outPutFolder, resizeWidth, resizeHeight); utilityClass.deleteWholeFolder(DELETEFOLDER, outPutFolder + "_"); // Read all file from Folder has been unzip ArrayList<FrameStructer> allFrameInZipFolder = new ArrayList<>(); allFrameInZipFolder = frameStructer.getListFileInZipFolder(outPutFolder); System.out.println(allFrameInZipFolder.size()); // sort with shot ID Collections.sort(allFrameInZipFolder, FrameStructer.frameIDNo); // Loop with 1 shot int indexFrame = 0; for (int n = 0; n < allFrameInZipFolder.size() / 25; n++) { // Process with 1 ArrayList<String> nameAllFrameOneShot = new ArrayList<>(); String shotAndFolderName = new String(); for (; indexFrame < Math.min((n + 1) * 25, allFrameInZipFolder.size()); indexFrame++) { String imageForExtract = outPutFolder + "/" + allFrameInZipFolder.get(indexFrame).toFullName() + ".jpg"; shotAndFolderName = allFrameInZipFolder.get(indexFrame).shotName(); String resultNameAfterExtract = outPutFolder + "/" + allFrameInZipFolder.get(indexFrame).toFullName() + ".txt"; nameAllFrameOneShot.add(resultNameAfterExtract); // extract and Delete image file --> ouput image'feature utilityClass.excuteFeatureExtractionAnImage(EXTRACTFEATUREANDDELETESOURCEIMAGESHFILE, "0", CUDAOVERFEATPATH, imageForExtract, resultNameAfterExtract); } // Pooling // DenseMatrix64F resultMaTrixFeatureOneShot = utilityClass.buidEJMLMatrixFeatureOneShot(nameAllFrameOneShot); // utilityClass.savePoolingFeatureOneShotWithEJMLFromMatrix(resultMaTrixFeatureOneShot,outPutFolder,shotAndFolderName); utilityClass.buidPoolingFileWithOutMatrixFeatureOneShot(nameAllFrameOneShot, outPutFolder, shotAndFolderName); // Save A file for (int frameCount = 0; frameCount < nameAllFrameOneShot.size(); frameCount++) { // Delete feature extract file utilityClass.deletefile(DELETEFILE, nameAllFrameOneShot.get(frameCount)); } // Release one shot data nameAllFrameOneShot.clear(); System.out.print("The end of one's shot" + "\n" + n); } // Delete zip file utilityClass.deletefile(DELETEFILE, nameZipFile); // Zip Whole Folder /** * Extract 1 shot * Resize 25 frame with the same shotid --> delete orgra. * Extract 25 frame --> feature file --->delete * */ } }
From source file:com.easarrive.aws.plugins.common.service.impl.SimpleProducerConsumer.java
public static void main(String[] args) throws InterruptedException { final AWSCredentials credentials = new BasicAWSCredentials("AKIAIDPJMKK4UHLE3OVA", "A+cn+TT3tUs6xbto5k1IKkWwPLBq995aOkqKxZNY"); final String endpoint = "sqs.us-west-2.amazonaws.com"; final String queueName = "image"; final int producerCount = 10; final int consumerCount = 3; final int batchSize = 3; final int messageSizeByte = 10000; final int runTimeMinutes = 100; // configure the SQS client with enough connections for all producer and // consumer threads AmazonSQS sqsClient = new AmazonSQSClient(credentials, new ClientConfiguration().withMaxConnections(producerCount + consumerCount)); sqsClient.setEndpoint(endpoint);/*from w w w . j a va 2s.c o m*/ String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl(); // the flag to stop producer, consumer, and monitor threads AtomicBoolean stop = new AtomicBoolean(false); // start the producers final AtomicInteger producedCount = new AtomicInteger(); Thread[] producers = new Thread[producerCount]; for (int i = 0; i < producerCount; i++) { producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount, stop); producers[i].start(); } // start the consumers final AtomicInteger consumedCount = new AtomicInteger(); Thread[] consumers = new Thread[consumerCount]; for (int i = 0; i < consumerCount; i++) { consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop); consumers[i].start(); } // start the monitor (thread) Thread monitor = new Monitor(producedCount, consumedCount, stop); monitor.start(); // wait for the specified amount of time then stop Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES))); stop.set(true); // join all threads for (int i = 0; i < producerCount; i++) producers[i].join(); for (int i = 0; i < consumerCount; i++) consumers[i].join(); monitor.interrupt(); monitor.join(); }
From source file:org.eclipse.swt.snippets.Snippet334.java
public static void main(String[] arg) { display = new Display(); shell = new Shell(display); shell.setText("Snippet 334"); shell.setLayout(new GridLayout(2, false)); Label label = new Label(shell, SWT.NONE); label.setText("Test:"); canvas = new Canvas(shell, SWT.MULTI | SWT.BORDER); final Caret caret = new Caret(canvas, SWT.NONE); canvas.addPaintListener(e -> {/*from ww w . j a v a 2 s.co m*/ GC gc = e.gc; gc.drawText(text, 10, 10); caret.setBounds(10, 10, 2, gc.getFontMetrics().getHeight()); Rectangle rect = canvas.getClientArea(); if (canvas.isFocusControl()) { gc.drawFocus(rect.x, rect.y, rect.width, rect.height); } }); canvas.addTraverseListener(e -> { switch (e.detail) { case SWT.TRAVERSE_TAB_NEXT: case SWT.TRAVERSE_TAB_PREVIOUS: e.doit = true; // enable traversal break; } }); // key listener enables traversal out) canvas.addKeyListener(keyPressedAdapter(e -> { })); canvas.addFocusListener(focusGainedAdapter(event -> canvas.redraw())); canvas.addFocusListener(focusLostAdapter(event -> canvas.redraw())); canvas.addMouseListener(mouseDownAdapter(e -> canvas.setFocus())); Accessible acc = canvas.getAccessible(); acc.addRelation(ACC.RELATION_LABELLED_BY, label.getAccessible()); acc.addAccessibleControlListener(new AccessibleControlAdapter() { @Override public void getRole(AccessibleControlEvent e) { e.detail = ACC.ROLE_TEXT; } @Override public void getLocation(AccessibleControlEvent e) { Rectangle rect = canvas.getBounds(); Point pt = shell.toDisplay(rect.x, rect.y); e.x = pt.x; e.y = pt.y; e.width = rect.width; e.height = rect.height; } @Override public void getValue(AccessibleControlEvent e) { e.result = text; } @Override public void getFocus(AccessibleControlEvent e) { e.childID = ACC.CHILDID_SELF; } @Override public void getChildCount(AccessibleControlEvent e) { e.detail = 0; } @Override public void getState(AccessibleControlEvent e) { e.detail = ACC.STATE_NORMAL | ACC.STATE_FOCUSABLE; if (canvas.isFocusControl()) e.detail |= ACC.STATE_FOCUSED | ACC.STATE_SELECTABLE; } }); acc.addAccessibleTextListener(new AccessibleTextExtendedAdapter() { @Override public void getSelectionRange(AccessibleTextEvent e) { // select the first 4 characters for testing e.offset = 0; e.length = 4; } @Override public void getCaretOffset(AccessibleTextEvent e) { e.offset = 0; } @Override public void getTextBounds(AccessibleTextEvent e) { // for now, assume that start = 0 and end = text.length GC gc = new GC(canvas); Point extent = gc.textExtent(text); gc.dispose(); Rectangle rect = display.map(canvas, null, 10, 10, extent.x, extent.y); e.x = rect.x; e.y = rect.y; e.width = rect.width; e.height = rect.height; } @Override public void getText(AccessibleTextEvent e) { int start = 0, end = text.length(); switch (e.type) { case ACC.TEXT_BOUNDARY_ALL: start = e.start; end = e.end; break; case ACC.TEXT_BOUNDARY_CHAR: start = e.count >= 0 ? e.start + e.count : e.start - e.count; start = Math.max(0, Math.min(end, start)); end = start; e.count = start - e.start; e.start = start; e.end = start; break; case ACC.TEXT_BOUNDARY_LINE: int offset = e.count <= 0 ? e.start : e.end; offset = Math.min(offset, text.length()); int lineCount = 0; int index = 0; while (index != -1) { lineCount++; index = text.indexOf("\n", index); if (index != -1) index++; } e.count = e.count < 0 ? Math.max(e.count, -lineCount) : Math.min(e.count, lineCount); index = 0; int lastIndex = 0; String[] lines = new String[lineCount]; for (int i = 0; i < lines.length; i++) { index = text.indexOf("\n", index); lines[i] = index != -1 ? text.substring(lastIndex, index) : text.substring(lastIndex); lastIndex = index; index++; } int len = 0; int lineAtOffset = 0; for (int i = 0; i < lines.length; i++) { len += lines[i].length(); if (len >= e.offset) { lineAtOffset = i; break; } } int result = Math.max(0, Math.min(lineCount - 1, lineAtOffset + e.count)); e.count = result - lineAtOffset; e.result = lines[result]; break; } e.result = text.substring(start, end); } @Override public void getSelectionCount(AccessibleTextEvent e) { e.count = 1; } @Override public void getSelection(AccessibleTextEvent e) { // there is only 1 selection, so index = 0 getSelectionRange(e); e.start = e.offset; e.end = e.offset + e.length; } @Override public void getRanges(AccessibleTextEvent e) { // for now, ignore bounding box e.start = 0; e.end = text.length() - 1; } @Override public void getCharacterCount(AccessibleTextEvent e) { e.count = text.length(); } @Override public void getVisibleRanges(AccessibleTextEvent e) { e.start = 0; e.end = text.length() - 1; } }); Button button = new Button(shell, SWT.PUSH); button.setText("Button"); button.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }