List of usage examples for java.util ArrayList stream
default Stream<E> stream()
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
private void getByListBlocking(List<String> ids, AsyncResultHandler<List<T>> resultHandler) { if (ids == null) { resultHandler.handle(Future.failedFuture(new IllegalArgumentException("List of ids can't be null."))); return;/*from ww w. j a va2 s.c o m*/ } else if (ids.isEmpty()) { resultHandler.handle(Future.succeededFuture(Collections.emptyList())); return; } AtomicLong c = new AtomicLong(0); ArrayList<T> l = new ArrayList<>(ids.size()); IntStream.range(0, ids.size()).forEach(i -> l.add(null)); ids.stream().forEach(e -> { getBlocking(e, r -> { l.set(ids.indexOf(e), r.result()); if (c.incrementAndGet() == ids.size()) { resultHandler.handle(Future.succeededFuture( l.stream().filter(s -> s != null).collect(Collectors.toCollection(ArrayList::new)))); } }); }); }
From source file:pathwaynet.PathwayCalculator.java
private <E> TestResultForList testForGivenListPermutationBased(Graph<E, String> graph, Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) { // calculate and cache all distances DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph); HashMap<E, Map<E, Number>> distancesMap = new HashMap<>(); graph.getVertices().stream().forEach((component) -> { Map<E, Number> distancesFromThis = distances.getDistanceMap(component); distancesMap.put(component, distancesFromThis); });//from ww w.ja va 2 s. c o m // generate in-group list and all-available list HashSet<E> componentsInGroupAvailable = new HashSet<>(); componentsInGroupAvailable.addAll(graph.getVertices()); componentsInGroupAvailable.retainAll(componentsConsidered); componentsInGroupAvailable.retainAll(componentsInGroup); HashSet<E> componentsAvailable = new HashSet<>(); componentsAvailable.addAll(graph.getVertices()); componentsAvailable.retainAll(componentsConsidered); // store within-group distances for the given list if (componentsInGroupAvailable.size() < 2 || componentsInGroupAvailable.size() > componentsAvailable.size() - 2) { System.err.println( "ERROE! Please check your component list: too few or too many components in the list."); return new TestResultForList(Double.NaN, Double.NaN, Double.NaN); } ArrayList<Double> distInGroup = new ArrayList<>(); componentsInGroupAvailable.forEach((component1) -> { componentsInGroupAvailable.forEach((component2) -> { Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource); if (!component1.equals(component2) && minDist != null) { distInGroup.add(minDist.doubleValue()); } }); }); double[] distInGroupVector = new double[distInGroup.size()]; for (int i = 0; i < distInGroup.size(); i++) distInGroupVector[i] = distInGroup.get(i); double meanInGroup = new Mean().evaluate(distInGroupVector); // permutations ArrayList<Double> meansInPermutGroups = new ArrayList<>(); ArrayList<HashSet<E>> permutatedGroups = generatePermutatedGroups(componentsAvailable, componentsInGroupAvailable.size()); permutatedGroups.forEach((componentsInPermutatedGroup) -> { ArrayList<Double> distInPermutGroup = new ArrayList<>(); componentsInPermutatedGroup.forEach((component1) -> { componentsInPermutatedGroup.forEach((component2) -> { Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource); if (!component1.equals(component2) && minDist != null) { distInPermutGroup.add(minDist.doubleValue()); } }); }); double[] distInPermutGroupVector = new double[distInPermutGroup.size()]; for (int i = 0; i < distInPermutGroup.size(); i++) distInPermutGroupVector[i] = distInPermutGroup.get(i); meansInPermutGroups.add(new Mean().evaluate(distInPermutGroupVector)); }); double[] meansInPermutGroupsVector = new double[meansInPermutGroups.size()]; for (int i = 0; i < meansInPermutGroups.size(); i++) meansInPermutGroupsVector[i] = meansInPermutGroups.get(i); double medianPermut = new Median().evaluate(meansInPermutGroupsVector); double p = ((double) meansInPermutGroups.stream().filter(notGreaterThan(meanInGroup)).count()) / meansInPermutGroups.size(); return new TestResultForList(p, meanInGroup, medianPermut); }
From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java
private void checkAndRemoveDuplicates(MaterialInstance materialInstance, List<Modification> newChanges, ArrayList<Modification> list) { if (!new SystemEnvironment().get(SystemEnvironment.CHECK_AND_REMOVE_DUPLICATE_MODIFICATIONS)) { return;//from w w w. j ava2s . com } DetachedCriteria criteria = DetachedCriteria.forClass(Modification.class); criteria.setProjection(Projections.projectionList().add(Projections.property("revision"))); criteria.add(Restrictions.eq("materialInstance.id", materialInstance.getId())); ArrayList<String> revisions = new ArrayList<>(); for (Modification modification : newChanges) { revisions.add(modification.getRevision()); } criteria.add(Restrictions.in("revision", revisions)); List<String> matchingRevisionsFromDb = (List<String>) getHibernateTemplate().findByCriteria(criteria); if (!matchingRevisionsFromDb.isEmpty()) { for (final String revision : matchingRevisionsFromDb) { Modification modification = list.stream().filter(item -> item.getRevision().equals(revision)) .findFirst().orElse(null); list.remove(modification); } } if (!newChanges.isEmpty() && list.isEmpty()) { LOGGER.debug("All modifications already exist in db [{}]", revisions); } if (!matchingRevisionsFromDb.isEmpty()) { LOGGER.info("Saving revisions for material [{}] after removing the following duplicates {}", materialInstance.toOldMaterial(null, null, null).getLongDescription(), matchingRevisionsFromDb); } }
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
private void ensureUniqueAndIndexingBlocking(String id, JsonObject data, Boolean isNew, AsyncResultHandler<String> resultHandler) { Async.waterfall().<String>task(t -> { RBatch batch = redissonOther.createBatch(); ArrayList<String> pList = new ArrayList(); try {/*from w w w . j a v a 2s . c o m*/ prepareEnsureUnique(id, data, batch, pList, null); } catch (RepositoryException ex) { t.handle(Future.failedFuture(ex)); return; } if (pList.isEmpty()) { t.handle(Future.succeededFuture()); return; } batch.executeAsync().addListener(future -> { if (future.isSuccess() && future.get() != null) { List<String> result = (List<String>) future.get(); Stream<String> filter = pList.stream().filter( p -> result.get(pList.indexOf(p)) != null && !result.get(pList.indexOf(p)).equals(id));//uniques are ensured by using putIfAbsent and all results should be null or itself to indicate no violation. Object[] filterArray = filter.toArray(); if (filterArray.length != 0) { t.handle(Future.succeededFuture( new JsonObject().put("uniqueViolation", Json.encode(filterArray)).encode())); //now undo these things. ArrayList<String> undoList = pList.stream() .filter(p -> result.get(pList.indexOf(p)) == null || result.get(pList.indexOf(p)).equals(id)) .collect(Collectors.toCollection(ArrayList::new)); Async.<Void>waterfall().<Void>task(task -> { RBatch b = redissonOther.createBatch(); try { prepareUndoUnique(id, data, b, undoList, null); } catch (RepositoryException ex) { task.handle(Future.failedFuture(ex)); } b.executeAsync().addListener(fu -> { task.handle(fu.isSuccess() ? Future.succeededFuture((Void) fu.get()) : Future.failedFuture(fu.cause())); }); }).run(run -> { logger.debug("Parallel undo indexing [id: " + id + "] " + (run.succeeded() ? "successed." : "failed.")); }); } else { t.handle(Future.succeededFuture()); } } else { t.handle(Future.failedFuture(!future.isSuccess() ? future.cause().fillInStackTrace() : new RepositoryException("No unique check result returned"))); } }); }).<String>task((violations, t) -> { if (violations != null) { t.handle(Future.failedFuture(violations)); return; } else { t.handle(Future.succeededFuture()); } //parallel indexing Async.<Void>waterfall().<T>task(task -> { if (!isNew) { fetch(id, Boolean.TRUE, task); } else { task.handle(Future.succeededFuture(null)); } }).<Void>task((r, task) -> { reIndex(id, r, data, isNew, ri -> { task.handle( ri.succeeded() ? Future.succeededFuture(ri.result()) : Future.failedFuture(ri.cause())); }); }).run(run -> { logger.debug("Parallel Indexing [id: " + id + "] " + (run.succeeded() ? "successed." : "failed."), run.cause()); }); }).run(resultHandler); }
From source file:org.jsweet.transpiler.JSweetTranspiler.java
private void generateTsBundle(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] files, List<JCCompilationUnit> compilationUnits) throws IOException { if (context.useModules) { return;/*from w ww. jav a 2 s . c om*/ } StaticInitilializerAnalyzer analizer = new StaticInitilializerAnalyzer(context); analizer.process(compilationUnits); ArrayList<Node<JCCompilationUnit>> sourcesInCycle = new ArrayList<>(); java.util.List<JCCompilationUnit> orderedCompilationUnits = analizer.globalStaticInitializersDependencies .topologicalSort(n -> { sourcesInCycle.add(n); }); if (!sourcesInCycle.isEmpty()) { transpilationHandler.report(JSweetProblem.CYCLE_IN_STATIC_INITIALIZER_DEPENDENCIES, null, JSweetProblem.CYCLE_IN_STATIC_INITIALIZER_DEPENDENCIES.getMessage(sourcesInCycle.stream() .map(n -> n.element.sourcefile.getName()).collect(Collectors.toList()))); DirectedGraph.dumpCycles(sourcesInCycle, u -> u.sourcefile.getName()); return; } new OverloadScanner<C>(transpilationHandler, context).process(orderedCompilationUnits); logger.debug("ordered compilation units: " + orderedCompilationUnits.stream().map(cu -> { return cu.sourcefile.getName(); }).collect(Collectors.toList())); logger.debug("count: " + compilationUnits.size() + " (initial), " + orderedCompilationUnits.size() + " (ordered)"); int[] permutation = new int[orderedCompilationUnits.size()]; StringBuilder permutationString = new StringBuilder(); for (int i = 0; i < orderedCompilationUnits.size(); i++) { permutation[i] = compilationUnits.indexOf(orderedCompilationUnits.get(i)); permutationString.append("" + i + "=" + permutation[i] + ";"); } logger.debug("permutation: " + permutationString.toString()); createBundle(transpilationHandler, files, permutation, orderedCompilationUnits, false); if (isGenerateDefinitions()) { createBundle(transpilationHandler, files, permutation, orderedCompilationUnits, true); } }
From source file:sh.isaac.convert.rxnorm.standard.RxNormMojo.java
/** * Process CUI rows./*from w ww. j a v a 2 s . c om*/ * * @param conceptData the concept data * @throws IOException Signals that an I/O exception has occurred. * @throws SQLException the SQL exception * @throws PropertyVetoException the property veto exception */ private void processCUIRows(ArrayList<RXNCONSO> conceptData) throws IOException, SQLException, PropertyVetoException { final String rxCui = conceptData.get(0).rxcui; final HashSet<String> uniqueTTYs = new HashSet<>(); final HashSet<String> uniqueSABs = new HashSet<>(); // ensure all the same CUI, gather the TTYs involved conceptData.stream().map((row) -> { uniqueTTYs.add(row.tty); return row; }).map((row) -> { uniqueSABs.add(row.sab); return row; }).filter((row) -> (!row.rxcui.equals(rxCui))).forEachOrdered((_item) -> { throw new RuntimeException("Oops"); }); ComponentReference cuiConcept; if ((uniqueSABs.size() == 1) && uniqueSABs.iterator().next().equals(this.sctSab)) { // This is a SCT only concept - we don't want to create it. But we might need to put some relationships or associations here. final String sctId = conceptData.get(0).code; if (sctId == null) { throw new RuntimeException("Unexpected"); } cuiConcept = ComponentReference.fromConcept(this.sctIdToUUID.get(sctId)); // Add the RxCUI UUID this.importUtil.addUUID(cuiConcept.getPrimordialUuid(), createCUIConceptUUID(rxCui)); // TODO need to look at what else I should be grabbing - the RXCUI for example should be attached. What else? } else { // just creating the reference here, with the UUID - because we don't know if it should be active or inactive yet. // create the real concept later. cuiConcept = ComponentReference.fromConcept(createCUIConceptUUID(rxCui)); long conceptTime = Integer.MAX_VALUE; // Activate the concept if any description is active Status conceptState = Status.INACTIVE; this.importUtil.addStringAnnotation(cuiConcept, rxCui, this.ptUMLSAttributes.getProperty("RXCUI").getUUID(), Status.ACTIVE); final ArrayList<ValuePropertyPairWithSAB> cuiDescriptions = new ArrayList<>(); final HashSet<String> sabs = new HashSet<>(); for (final RXNCONSO atom : conceptData) { if (atom.sab.equals(this.sctSab)) { continue; } // Add attributes from SAT table this.descSat.clearParameters(); this.descSat.setString(1, rxCui); this.descSat.setString(2, atom.rxaui); final ArrayList<RXNSAT> satData; boolean disableDescription; Long descriptionTime; try (ResultSet rs = this.descSat.executeQuery()) { satData = new ArrayList<>(); disableDescription = false; descriptionTime = null; while (rs.next()) { final RXNSAT current = new RXNSAT(rs); satData.add(current); if ("RXN_OBSOLETED".equals(current.atn)) { disableDescription = true; } if ("RXN_ACTIVATED".equals(current.atn)) { try { final long time = this.dateParse.parse(current.atv).getTime(); descriptionTime = time; if (time < conceptTime) { conceptTime = time; } } catch (final ParseException e) { throw new RuntimeException("Can't parse date?"); } } } } final ValuePropertyPairWithSAB desc = new ValuePropertyPairWithSAB(atom.str, this.ptDescriptions.getProperty(atom.tty), atom.sab, satData); if (disableDescription) { desc.setDisabled(true); } else { // if any description is active, concept is still active conceptState = Status.ACTIVE; } if (descriptionTime != null) { desc.setTime(descriptionTime); } desc.setUUID(ConverterUUID.createNamespaceUUIDFromStrings(cuiConcept.getPrimordialUuid().toString(), atom.rxaui)); // used for sorting description to figure out what to use for FULLY_QUALIFIED_NAME cuiDescriptions.add(desc); desc.addStringAttribute(this.ptUMLSAttributes.getProperty("RXAUI").getUUID(), atom.rxaui); desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SAB").getUUID(), this.ptSABs.getProperty(atom.sab).getUUID()); if (StringUtils.isNotBlank(atom.code) && !atom.code.equals("NOCODE")) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("CODE").getUUID(), atom.code); } if (StringUtils.isNotBlank(atom.saui)) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SAUI").getUUID(), atom.saui); } if (StringUtils.isNotBlank(atom.scui)) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SCUI").getUUID(), atom.scui); } if (StringUtils.isNotBlank(atom.suppress)) { desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SUPPRESS").getUUID(), this.suppress.get(atom.suppress)); } if (StringUtils.isNotBlank(atom.cvf)) { if (atom.cvf.equals("4096")) { desc.addRefsetMembership(this.cpcRefsetConcept.getPrimordialUuid()); } else { throw new RuntimeException("Unexpected value in RXNCONSO cvf column '" + atom.cvf + "'"); } } if (!atom.lat.equals("ENG")) { ConsoleUtil.printErrorln("Non-english lang settings not handled yet!"); } // TODO - at this point, sometime in the future, we make make attributes out of the relationships that occur between the AUIs // and store them on the descriptions, since OTF doesn't allow relationships between descriptions // TODO am I supposed to be using sabs? sabs.add(atom.sab); } // sanity check on descriptions - make sure we only have one that is of type synonym with the preferred flag final ArrayList<String> items = new ArrayList<>(); cuiDescriptions.stream() .filter((vpp) -> ((vpp.getProperty().getPropertySubType() >= BPT_Descriptions.SYNONYM) && (vpp.getProperty().getPropertySubType() <= (BPT_Descriptions.SYNONYM + 20)))) .forEachOrdered((vpp) -> { items.add(vpp.getProperty().getSourcePropertyNameFQN() + " " + vpp.getProperty().getPropertySubType()); }); // Numbers come from the rankings down below in makeDescriptionType(...) final HashSet<String> ranksLookedAt = new HashSet<>(); ranksLookedAt.add("204"); ranksLookedAt.add("206"); ranksLookedAt.add("210"); ranksLookedAt.add("208"); ranksLookedAt.add("212"); boolean oneNotInList = false; if (items.size() > 1) { for (final String s : items) { if (!ranksLookedAt.contains(s.substring(s.length() - 3, s.length()))) { oneNotInList = true; break; } } } if (oneNotInList) { ConsoleUtil.printErrorln( "Need to rank multiple synonym types that are each marked preferred, determine if ranking is appropriate!"); items.forEach((s) -> { ConsoleUtil.printErrorln(s); }); } final List<SemanticChronology> addedDescriptions = this.importUtil.addDescriptions(cuiConcept, cuiDescriptions); if (addedDescriptions.size() != cuiDescriptions.size()) { throw new RuntimeException("oops"); } final HashSet<String> uniqueUMLSCUI = new HashSet<>(); for (int i = 0; i < cuiDescriptions.size(); i++) { final SemanticChronology desc = addedDescriptions.get(i); final ValuePropertyPairWithSAB descPP = cuiDescriptions.get(i); final BiFunction<String, String, Boolean> functions = (atn, atv) -> { // Pull these up to the concept. if ("UMLSCUI".equals(atn)) { uniqueUMLSCUI.add(atv); return true; } return false; }; // TODO should I be passing in item code here? processSAT(ComponentReference.fromChronology(desc), descPP.getSatData(), null, descPP.getSab(), functions); } // pulling up the UMLS CUIs. // uniqueUMLSCUI is populated during processSAT uniqueUMLSCUI.forEach((umlsCui) -> { final UUID itemUUID = ConverterUUID.createNamespaceUUIDFromString("UMLSCUI" + umlsCui); this.importUtil.addStringAnnotation(cuiConcept, itemUUID, umlsCui, this.ptTermAttributes.getProperty("UMLSCUI").getUUID(), Status.ACTIVE); }); ValuePropertyPairWithAttributes.processAttributes(this.importUtil, cuiDescriptions, addedDescriptions); // there are no attributes in rxnorm without an AUI. // try // { this.importUtil.addRefsetMembership(cuiConcept, this.allCUIRefsetConcept.getPrimordialUuid(), Status.ACTIVE, null); // } // catch (RuntimeException e) // { // if (e.toString().contains("duplicate UUID")) // { // //ok - this can happen due to multiple merges onto an existing SCT concept // } // else // { // throw e; // } // } // add semantic types this.semanticTypeStatement.clearParameters(); this.semanticTypeStatement.setString(1, rxCui); final ResultSet rs = this.semanticTypeStatement.executeQuery(); processSemanticTypes(cuiConcept, rs); if (conceptTime < 0) { throw new RuntimeException("oops"); } this.importUtil.createConcept(cuiConcept.getPrimordialUuid(), conceptTime, conceptState, null); } final HashSet<UUID> parents = new HashSet<>(); this.cuiRelStatementForward.clearParameters(); this.cuiRelStatementForward.setString(1, rxCui); parents.addAll(addRelationships(cuiConcept, REL.read(null, this.cuiRelStatementForward.executeQuery(), true, this.allowedCUIsForSABs, this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string))))); this.cuiRelStatementBackward.clearParameters(); this.cuiRelStatementBackward.setString(1, rxCui); parents.addAll(addRelationships(cuiConcept, REL.read(null, this.cuiRelStatementBackward.executeQuery(), false, this.allowedCUIsForSABs, this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string))))); // Have to add multiple parents at once, no place to keep all the other details. Load those as associations for now. if (parents.size() > 0) { ComponentReference.fromChronology(this.importUtil.addParent(cuiConcept, null, parents.toArray(new UUID[parents.size()]), null, null)); } }
From source file:Creator.WidgetPanel.java
public void loadWidgetCode() { boolean ide = true; String pathWidgetCode = "textFiles/widgets/"; ArrayList<String> results = new ArrayList<>(); String dirCode = new File("").getAbsolutePath() + "/src/Creator/" + pathWidgetCode; try {//from ww w. ja v a 2s. c o m getWidgetFiles(dirCode, results); results.stream().forEach((s) -> { readCodeFile(s); }); updateWidgetCode(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); ide = false; } if (!ide) { CodeSource src = WidgetPanel.class.getProtectionDomain().getCodeSource(); try { List<String> list = new ArrayList<>(); if (src != null) { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze = null; while ((ze = zip.getNextEntry()) != null) { String entryName = ze.getName(); if (entryName.startsWith("Creator/textFiles/widgets") && entryName.endsWith(".txt")) { list.add("/" + entryName); //System.out.println("Added name: " + entryName); } } list.stream().forEach((s) -> { readJarFile(s); }); updateWidgetCode(); } else { System.out.println("Src null"); } } catch (IOException e) { System.out.println(e.getMessage()); } } readWidgetVars(); }
From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java
/** * This function gathers all dates where an event takes place within a specific month and year. The function is invoked by GETting the URI /api/admin/event/month and specifying the month and year via the request parameters. * @param month The selected month./*from w w w .j a v a2 s.com*/ * @param year The selected year. * @return An HTTP response with a status code. If the function succeeds, a list of dates, during the month, that contain an event, is returned, otherwise an error code is returned. */ @RequestMapping(value = "month", produces = "application/json", method = RequestMethod.GET) public ResponseEntity<List<LocalDate>> getEventDatesOfMonth(@RequestParam String month, @RequestParam String year, @CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Gathering events of month " + month + " and year " + year); ArrayList<LocalDate> dates = new ArrayList<>(); int monthInt, yearInt; try { monthInt = Integer.parseInt(month); yearInt = Integer.parseInt(year); } catch (NumberFormatException e) { logger.warn("[" + currentUser + "] Unable to parse month or year."); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } LocalDateTime start = LocalDate.of(yearInt, monthInt, 1).atStartOfDay(); LocalDateTime end = start.plusMonths(1); logger.debug("Getting all single day events..."); dates.addAll(eventRepository.findAllByEndDateTimeBetweenAndMultiDate(start, end, false).parallelStream() .map(Event::getStartDate).collect(Collectors.toList())); logger.debug("All single day events retrieved, got " + dates.size() + " dates so far"); logger.debug("Getting all multi day events..."); //Collecting all multi date events, that either start or end within the selected month (which means that events that are spanning over several months are not collected) Stream.concat(eventRepository.findAllByStartDateTimeBetweenAndMultiDate(start, end, true).stream(), //All multi date events starting within the month eventRepository.findAllByEndDateTimeBetweenAndMultiDate(start, end, true).stream()) //All multi date events ending within the month .distinct() //Removing all duplicated events .parallel().forEach(event -> { //Creating a local date for each occupied date of the event for (LocalDate date = event.getStartDate(); //Starting with the start date !date.equals(event.getEndDateTime().toLocalDate()); //Until reaching the end date date = date.plusDays(1)) //Adding a day within each iterations { dates.add(date); } dates.add(event.getEndDateTime().toLocalDate()); //Finally adding the last date }); logger.debug("All multi day events gathered, got " + dates.size() + " dates so far"); if (dates.isEmpty()) { logger.warn("[" + currentUser + "] Returning empty dates list of " + month + "/" + year); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } else { logger.debug("[" + currentUser + "] Returning dates list " + month + "/" + year); return new ResponseEntity<>(dates.stream().distinct().collect(Collectors.toList()), HttpStatus.OK); //Returning an optimized set of events } }
From source file:org.apache.sysml.parser.BuiltinFunctionExpression.java
public static BuiltinFunctionExpression getBuiltinFunctionExpression(ParserRuleContext ctx, String functionName, ArrayList<ParameterExpression> paramExprsPassed, String filename) { if (functionName == null || paramExprsPassed == null) return null; // check if the function name is built-in function // (assign built-in function op if function is built-in Expression.BuiltinFunctionOp bifop = null; if (functionName.equals("avg")) bifop = Expression.BuiltinFunctionOp.MEAN; else if (functionName.equals("cos")) bifop = Expression.BuiltinFunctionOp.COS; else if (functionName.equals("sin")) bifop = Expression.BuiltinFunctionOp.SIN; else if (functionName.equals("tan")) bifop = Expression.BuiltinFunctionOp.TAN; else if (functionName.equals("acos")) bifop = Expression.BuiltinFunctionOp.ACOS; else if (functionName.equals("asin")) bifop = Expression.BuiltinFunctionOp.ASIN; else if (functionName.equals("atan")) bifop = Expression.BuiltinFunctionOp.ATAN; else if (functionName.equals("cosh")) bifop = Expression.BuiltinFunctionOp.COSH; else if (functionName.equals("sinh")) bifop = Expression.BuiltinFunctionOp.SINH; else if (functionName.equals("tanh")) bifop = Expression.BuiltinFunctionOp.TANH; else if (functionName.equals("diag")) bifop = Expression.BuiltinFunctionOp.DIAG; else if (functionName.equals("exp")) bifop = Expression.BuiltinFunctionOp.EXP; else if (functionName.equals("abs")) bifop = Expression.BuiltinFunctionOp.ABS; else if (functionName.equals("min")) bifop = Expression.BuiltinFunctionOp.MIN; else if (functionName.equals("max")) bifop = Expression.BuiltinFunctionOp.MAX; //NOTE: pmin and pmax are just kept for compatibility to R // min and max is capable of handling all unary and binary // operations (in contrast to R) else if (functionName.equals("pmin")) bifop = Expression.BuiltinFunctionOp.MIN; else if (functionName.equals("pmax")) bifop = Expression.BuiltinFunctionOp.MAX; else if (functionName.equals("ppred")) bifop = Expression.BuiltinFunctionOp.PPRED; else if (functionName.equals("list") //unnamed list && paramExprsPassed.stream().allMatch(p -> p.getName() == null)) bifop = Expression.BuiltinFunctionOp.LIST; else if (functionName.equals("log")) bifop = Expression.BuiltinFunctionOp.LOG; else if (functionName.equals("length")) bifop = Expression.BuiltinFunctionOp.LENGTH; else if (functionName.equals("ncol")) bifop = Expression.BuiltinFunctionOp.NCOL; else if (functionName.equals("nrow")) bifop = Expression.BuiltinFunctionOp.NROW; else if (functionName.equals("sign")) bifop = Expression.BuiltinFunctionOp.SIGN; else if (functionName.equals("sqrt")) bifop = Expression.BuiltinFunctionOp.SQRT; else if (functionName.equals("sum")) bifop = Expression.BuiltinFunctionOp.SUM; else if (functionName.equals("mean")) bifop = Expression.BuiltinFunctionOp.MEAN; else if (functionName.equals("sd")) bifop = Expression.BuiltinFunctionOp.SD; else if (functionName.equals("var")) bifop = Expression.BuiltinFunctionOp.VAR; else if (functionName.equals("trace")) bifop = Expression.BuiltinFunctionOp.TRACE; else if (functionName.equals("t")) bifop = Expression.BuiltinFunctionOp.TRANS; else if (functionName.equals("rev")) bifop = Expression.BuiltinFunctionOp.REV; else if (functionName.equals("cbind") || functionName.equals("append")) bifop = Expression.BuiltinFunctionOp.CBIND; else if (functionName.equals("rbind")) bifop = Expression.BuiltinFunctionOp.RBIND; else if (functionName.equals("range")) bifop = Expression.BuiltinFunctionOp.RANGE; else if (functionName.equals("prod")) bifop = Expression.BuiltinFunctionOp.PROD; else if (functionName.equals("rowSums")) bifop = Expression.BuiltinFunctionOp.ROWSUM; else if (functionName.equals("colSums")) bifop = Expression.BuiltinFunctionOp.COLSUM; else if (functionName.equals("rowMins")) bifop = Expression.BuiltinFunctionOp.ROWMIN; else if (functionName.equals("colMins")) bifop = Expression.BuiltinFunctionOp.COLMIN; else if (functionName.equals("rowMaxs")) bifop = Expression.BuiltinFunctionOp.ROWMAX; else if (functionName.equals("rowIndexMax")) bifop = Expression.BuiltinFunctionOp.ROWINDEXMAX; else if (functionName.equals("rowIndexMin")) bifop = Expression.BuiltinFunctionOp.ROWINDEXMIN; else if (functionName.equals("colMaxs")) bifop = Expression.BuiltinFunctionOp.COLMAX; else if (functionName.equals("rowMeans")) bifop = Expression.BuiltinFunctionOp.ROWMEAN; else if (functionName.equals("colMeans")) bifop = Expression.BuiltinFunctionOp.COLMEAN; else if (functionName.equals("rowSds")) bifop = Expression.BuiltinFunctionOp.ROWSD; else if (functionName.equals("colSds")) bifop = Expression.BuiltinFunctionOp.COLSD; else if (functionName.equals("rowVars")) bifop = Expression.BuiltinFunctionOp.ROWVAR; else if (functionName.equals("colVars")) bifop = Expression.BuiltinFunctionOp.COLVAR; else if (functionName.equals("rowProds")) bifop = Expression.BuiltinFunctionOp.ROWPROD; else if (functionName.equals("colProds")) bifop = Expression.BuiltinFunctionOp.COLPROD; else if (functionName.equals("cummax")) bifop = Expression.BuiltinFunctionOp.CUMMAX; else if (functionName.equals("cummin")) bifop = Expression.BuiltinFunctionOp.CUMMIN; else if (functionName.equals("cumprod")) bifop = Expression.BuiltinFunctionOp.CUMPROD; else if (functionName.equals("cumsum")) bifop = Expression.BuiltinFunctionOp.CUMSUM; //'castAsScalar' for backwards compatibility else if (functionName.equals("as.scalar") || functionName.equals("castAsScalar")) bifop = Expression.BuiltinFunctionOp.CAST_AS_SCALAR; else if (functionName.equals("as.matrix")) bifop = Expression.BuiltinFunctionOp.CAST_AS_MATRIX; else if (functionName.equals("as.frame")) bifop = Expression.BuiltinFunctionOp.CAST_AS_FRAME; else if (functionName.equals("as.double")) bifop = Expression.BuiltinFunctionOp.CAST_AS_DOUBLE; else if (functionName.equals("as.integer")) bifop = Expression.BuiltinFunctionOp.CAST_AS_INT; else if (functionName.equals("as.logical")) //alternative: as.boolean bifop = Expression.BuiltinFunctionOp.CAST_AS_BOOLEAN; else if (functionName.equals("quantile")) bifop = Expression.BuiltinFunctionOp.QUANTILE; else if (functionName.equals("interQuantile")) bifop = Expression.BuiltinFunctionOp.INTERQUANTILE; else if (functionName.equals("interQuartileMean")) bifop = Expression.BuiltinFunctionOp.IQM; //'ctable' for backwards compatibility else if (functionName.equals("table") || functionName.equals("ctable")) bifop = Expression.BuiltinFunctionOp.TABLE; else if (functionName.equals("round")) bifop = Expression.BuiltinFunctionOp.ROUND; //'centralMoment' for backwards compatibility else if (functionName.equals("moment") || functionName.equals("centralMoment")) bifop = Expression.BuiltinFunctionOp.MOMENT; else if (functionName.equals("cov")) bifop = Expression.BuiltinFunctionOp.COV; else if (functionName.equals("seq")) bifop = Expression.BuiltinFunctionOp.SEQ; else if (functionName.equals("qr")) bifop = Expression.BuiltinFunctionOp.QR; else if (functionName.equals("lu")) bifop = Expression.BuiltinFunctionOp.LU; else if (functionName.equals("eigen")) bifop = Expression.BuiltinFunctionOp.EIGEN; else if (functionName.equals("lstm")) bifop = Expression.BuiltinFunctionOp.LSTM; else if (functionName.equals("lstm_backward")) bifop = Expression.BuiltinFunctionOp.LSTM_BACKWARD; else if (functionName.equals("batch_norm2d")) bifop = Expression.BuiltinFunctionOp.BATCH_NORM2D; else if (functionName.equals("batch_norm2d_backward")) bifop = Expression.BuiltinFunctionOp.BATCH_NORM2D_BACKWARD; else if (functionName.equals("conv2d")) bifop = Expression.BuiltinFunctionOp.CONV2D; else if (functionName.equals("bias_add")) bifop = Expression.BuiltinFunctionOp.BIASADD; else if (functionName.equals("bias_multiply")) bifop = Expression.BuiltinFunctionOp.BIASMULT; else if (functionName.equals("conv2d_backward_filter")) bifop = Expression.BuiltinFunctionOp.CONV2D_BACKWARD_FILTER; else if (functionName.equals("conv2d_backward_data")) bifop = Expression.BuiltinFunctionOp.CONV2D_BACKWARD_DATA; else if (functionName.equals("max_pool")) bifop = Expression.BuiltinFunctionOp.MAX_POOL; else if (functionName.equals("max_pool_backward")) bifop = Expression.BuiltinFunctionOp.MAX_POOL_BACKWARD; else if (functionName.equals("avg_pool")) bifop = Expression.BuiltinFunctionOp.AVG_POOL; else if (functionName.equals("avg_pool_backward")) bifop = Expression.BuiltinFunctionOp.AVG_POOL_BACKWARD; else if (functionName.equals("solve")) bifop = Expression.BuiltinFunctionOp.SOLVE; else if (functionName.equals("ceil") || functionName.equals("ceiling")) bifop = Expression.BuiltinFunctionOp.CEIL; else if (functionName.equals("floor")) bifop = Expression.BuiltinFunctionOp.FLOOR; else if (functionName.equals("median")) bifop = Expression.BuiltinFunctionOp.MEDIAN; else if (functionName.equals("inv")) bifop = Expression.BuiltinFunctionOp.INVERSE; else if (functionName.equals("cholesky")) bifop = Expression.BuiltinFunctionOp.CHOLESKY; else if (functionName.equals("svd")) bifop = Expression.BuiltinFunctionOp.SVD; else if (functionName.equals("sample")) bifop = Expression.BuiltinFunctionOp.SAMPLE; else if (functionName.equals("outer")) bifop = Expression.BuiltinFunctionOp.OUTER; else if (functionName.equals("xor")) bifop = Expression.BuiltinFunctionOp.XOR; else if (functionName.equals("bitwAnd")) bifop = Expression.BuiltinFunctionOp.BITWAND; else if (functionName.equals("bitwOr")) bifop = Expression.BuiltinFunctionOp.BITWOR; else if (functionName.equals("bitwXor")) bifop = Expression.BuiltinFunctionOp.BITWXOR; else if (functionName.equals("bitwShiftL")) bifop = Expression.BuiltinFunctionOp.BITWSHIFTL; else if (functionName.equals("bitwShiftR")) bifop = Expression.BuiltinFunctionOp.BITWSHIFTR; else if (functionName.equals("ifelse")) bifop = Expression.BuiltinFunctionOp.IFELSE; else if (functionName.equals("eval")) bifop = Expression.BuiltinFunctionOp.EVAL; else if (functionName.equals("exists")) bifop = Expression.BuiltinFunctionOp.EXISTS; else// w w w . java 2s . c om return null; BuiltinFunctionExpression retVal = new BuiltinFunctionExpression(ctx, bifop, paramExprsPassed, filename); return retVal; }
From source file:it.polimi.diceH2020.launcher.controller.LaunchAnalysis.java
@RequestMapping(value = "/simulationSetupSingleInputData", method = RequestMethod.GET) public String showSimulationsManagerFormSingleData(SessionStatus sessionStatus, Model model, @ModelAttribute("instanceData") String instanceDataPath, @ModelAttribute("pathList") ArrayList<String> pathList, @ModelAttribute("scenario") String scenarioString, RedirectAttributes redirectAttrs) { Scenarios scenario = Scenarios.valueOf(scenarioString); model.addAttribute("scenario", scenario); redirectAttrs.addAttribute("scenario", scenario); if (pathList.size() == 0) { deleteUploadedFiles(pathList);//w w w . j a v a 2 s.c o m redirectAttrs.addAttribute("message", "You haven't submitted any file!"); return "redirect:/launchRetry"; } if (instanceDataPath == null) { redirectAttrs.addAttribute("message", "Select a Json file!"); deleteUploadedFiles(pathList); return "redirect:/launchRetry"; } InstanceDataMultiProvider instanceData = validator .objectFromPath(Paths.get(instanceDataPath), InstanceDataMultiProvider.class).get(); String check = scenarioValidation(instanceData, scenario); if (!check.equals("ok")) { redirectAttrs.addAttribute("message", check); deleteUploadedFiles(pathList); return "redirect:/launchRetry"; } List<InstanceDataMultiProvider> inputList = new ArrayList<>(); inputList.add(instanceData); if (inputList.size() > 1) { List<String> providersList = inputList.stream().map(InstanceDataMultiProvider::getProvider) .collect(Collectors.toList()); if (!minNumTxt(providersList, pathList)) { deleteUploadedFiles(pathList); model.addAttribute("message", "Not enough TXT files selected.\nFor each provider in your JSON there must be 2 TXT files containing in their name the provider name."); return "redirect:/launchRetry"; } } List<SimulationsManager> simManagerList = initializeSimManagers(inputList); List<String> txtFoldersList = new ArrayList<>(); for (SimulationsManager sm : simManagerList) { sm.setInputFileName(Paths.get(instanceDataPath).getFileName().toString()); String txtFolder = new String(); try { txtFolder = fileUtility.createInputSubFolder(); txtFoldersList.add(txtFolder); } catch (Exception e) { deleteUploadedFiles(pathList); deleteUploadedFiles(txtFoldersList); redirectAttrs.addAttribute("message", "Too many folders for TXTs with the same name have been created!"); return "redirect:/launchRetry"; } InstanceDataMultiProvider input = sm.getInputData(); for (Entry<String, Map<String, Map<String, JobProfile>>> jobIDs : input.getMapJobProfiles() .getMapJobProfile().entrySet()) { for (Entry<String, Map<String, JobProfile>> provider : jobIDs.getValue().entrySet()) { for (Entry<String, JobProfile> typeVMs : provider.getValue().entrySet()) { String secondPartOfTXTName = getSecondPartOfReplayersName(jobIDs.getKey(), provider.getKey(), typeVMs.getKey()); List<String> txtToBeSaved = pathList.stream().filter(s -> s.contains(secondPartOfTXTName)) .filter(s -> s.contains(input.getId())).collect(Collectors.toList()); if (txtToBeSaved.isEmpty()) { deleteUploadedFiles(pathList); deleteUploadedFiles(txtFoldersList); model.addAttribute("message", "Missing TXT file for Instance:" + input.getId() + ", Job: " + jobIDs.getKey() + ", Provider:" + provider.getKey() + ", TypeVM:" + typeVMs.getKey()); return "redirect:/launchRetry"; } for (String srcPath : txtToBeSaved) { File src = new File(srcPath); String fileContent = new String(); try { fileUtility.copyFile(srcPath, txtFolder + src.getName()); } catch (IOException e) { deleteUploadedFiles(pathList); deleteUploadedFiles(txtFoldersList); model.addAttribute("message", "Problem with TXT paths. [TXT file for Instance:" + input.getId() + ", Job: " + jobIDs.getKey() + ", Provider:" + provider.getKey() + ", TypeVM:" + typeVMs.getKey() + "]"); return "redirect:/launchRetry"; } if (fileContent.length() == 0) { deleteUploadedFiles(pathList); deleteUploadedFiles(txtFoldersList); model.addAttribute("message", "Missing TXT file for Instance:" + input.getId() + ", Job: " + jobIDs.getKey() + ", Provider:" + provider.getKey() + ", TypeVM:" + typeVMs.getKey()); return "redirect:/launchRetry"; } sm.addInputFolder(txtFolder); sm.setNumCompletedSimulations(0); sm.buildExperiments(); } } } } } deleteUploadedFiles(pathList); for (SimulationsManager sm : simManagerList) { ds.simulation(sm); } model.addAttribute("simManagersList", simManagerList); return "redirect:/"; }