Search in sources :

Example 46 with Stream

use of java.util.stream.Stream in project Entitas-Java by Rubentxu.

the class CodeGeneratorUtil method loadTypesFromPlugins.

public static List<Class> loadTypesFromPlugins(Properties properties) {
    CodeGeneratorConfig config = new CodeGeneratorConfig();
    config.configure(properties);
    return config.getPlugins().stream().flatMap(s -> ClassFinder.findRecursive(s).stream()).sorted((typeA, typeB) -> typeA.getCanonicalName().compareTo(typeB.getCanonicalName())).collect(Collectors.toList());
}
Also used : CodeGeneratorConfig(ilargia.entitas.codeGeneration.config.CodeGeneratorConfig) List(java.util.List) Properties(java.util.Properties) Stream(java.util.stream.Stream) BufferedWriter(java.io.BufferedWriter) Modifier(java.lang.reflect.Modifier) Map(java.util.Map) FileWriter(java.io.FileWriter) ilargia.entitas.codeGeneration.interfaces(ilargia.entitas.codeGeneration.interfaces) IOException(java.io.IOException) CodeGeneratorConfig(ilargia.entitas.codeGeneration.config.CodeGeneratorConfig) Collectors(java.util.stream.Collectors) File(java.io.File)

Example 47 with Stream

use of java.util.stream.Stream in project Smartcity-Smarthouse by TechnionYP5777.

the class ConfigurationController method initialize.

@Override
public void initialize(URL location, ResourceBundle resources) {
    button.setOnMouseClicked(e -> {
        if (callback != null)
            Platform.runLater(callback);
        timers.values().stream().filter(l -> l != null).flatMap(l -> l.stream()).forEach(t -> t.stop());
        ((Stage) button.getScene().getWindow()).close();
        widgets.values().stream().filter(l -> l != null).flatMap(l -> l.stream()).forEach(w -> w.getTile().setForegroundBaseColor(normalTileColor));
    });
    pane.setPadding(new Insets(5));
    pane.setBackground(new Background(new BackgroundFill(Tile.BACKGROUND.darker(), CornerRadii.EMPTY, Insets.EMPTY)));
    types.setItems(FXCollections.observableArrayList(widgets.keySet()));
    types.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
        Optional.ofNullable(timers.get(newValue)).ifPresent(l -> l.stream().forEach(t -> t.start()));
        pane.getChildren().setAll(widgets.get(newValue).stream().map(BasicWidget::getTile).collect(Collectors.toList()));
        Optional.ofNullable(timers.get(oldValue)).ifPresent(l -> l.stream().forEach(t -> t.stop()));
        Optional.ofNullable(widgets.get(oldValue)).ifPresent(l -> l.stream().forEach(w -> w.getTile().setForegroundBaseColor(normalTileColor)));
    });
    types.getSelectionModel().select(3);
    ;
// sPane.setHbarPolicy(ScrollBarPolicy.ALWAYS);
// sPane.setVbarPolicy(ScrollBarPolicy.NEVER);
// sPane.setContent(pane);
}
Also used : Button(javafx.scene.control.Button) Initializable(javafx.fxml.Initializable) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) FXCollections(javafx.collections.FXCollections) HashMap(java.util.HashMap) Random(java.util.Random) BarChartItem(eu.hansolo.tilesfx.skins.BarChartItem) ArrayList(java.util.ArrayList) Insets(javafx.geometry.Insets) ResourceBundle(java.util.ResourceBundle) ComboBox(javafx.scene.control.ComboBox) BackgroundFill(javafx.scene.layout.BackgroundFill) Map(java.util.Map) Tile(eu.hansolo.tilesfx.Tile) ListWidget(il.ac.technion.cs.smarthouse.applications.dashboard.model.widget.ListWidget) Color(javafx.scene.paint.Color) TextField(javafx.scene.control.TextField) Logger(org.slf4j.Logger) GraphWidget(il.ac.technion.cs.smarthouse.applications.dashboard.model.widget.GraphWidget) Collectors(java.util.stream.Collectors) Background(javafx.scene.layout.Background) InvocationTargetException(java.lang.reflect.InvocationTargetException) FXML(javafx.fxml.FXML) Platform(javafx.application.Platform) AnimationTimer(javafx.animation.AnimationTimer) List(java.util.List) Stream(java.util.stream.Stream) FlowPane(javafx.scene.layout.FlowPane) Stage(javafx.stage.Stage) Optional(java.util.Optional) WidgetType(il.ac.technion.cs.smarthouse.applications.dashboard.model.WidgetType) BasicWidget(il.ac.technion.cs.smarthouse.applications.dashboard.model.widget.BasicWidget) LeaderBoardItem(eu.hansolo.tilesfx.skins.LeaderBoardItem) CornerRadii(javafx.scene.layout.CornerRadii) Insets(javafx.geometry.Insets) Background(javafx.scene.layout.Background) BackgroundFill(javafx.scene.layout.BackgroundFill) Stage(javafx.stage.Stage) BasicWidget(il.ac.technion.cs.smarthouse.applications.dashboard.model.widget.BasicWidget)

Example 48 with Stream

use of java.util.stream.Stream in project intellij-community by JetBrains.

the class CompilerHierarchyInfoImpl method getHierarchyChildren.

@Override
@NotNull
public Stream<PsiElement> getHierarchyChildren() {
    PsiManager psiManager = PsiManager.getInstance(myProject);
    final LanguageLightRefAdapter adapter = ObjectUtils.notNull(CompilerReferenceServiceImpl.findAdapterForFileType(mySearchFileType));
    return myCandidatePerFile.entrySet().stream().filter(e -> mySearchScope.contains(e.getKey())).flatMap(e -> {
        final VirtualFile file = e.getKey();
        final Object[] definitions = e.getValue();
        final PsiElement[] hierarchyChildren = ReadAction.compute(() -> {
            final PsiFileWithStubSupport psiFile = (PsiFileWithStubSupport) psiManager.findFile(file);
            return mySearchType.performSearchInFile(definitions, myBaseClass, psiFile, adapter);
        });
        if (hierarchyChildren.length == definitions.length) {
            return Stream.of(hierarchyChildren);
        } else {
            LOG.assertTrue(mySearchType == CompilerHierarchySearchType.DIRECT_INHERITOR, "Should not happens for functional expression search");
            return Stream.of(hierarchyChildren).filter(c -> ReadAction.compute(() -> adapter.isDirectInheritor(c, myBaseClass)));
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) CompilerDirectHierarchyInfo(com.intellij.compiler.CompilerDirectHierarchyInfo) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) FileType(com.intellij.openapi.fileTypes.FileType) PsiFileWithStubSupport(com.intellij.psi.impl.source.PsiFileWithStubSupport) ReadAction(com.intellij.openapi.application.ReadAction) PsiManager(com.intellij.psi.PsiManager) Stream(java.util.stream.Stream) Map(java.util.Map) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) PsiNamedElement(com.intellij.psi.PsiNamedElement) ObjectUtils(com.intellij.util.ObjectUtils) Logger(com.intellij.openapi.diagnostic.Logger) NotNull(org.jetbrains.annotations.NotNull) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFileWithStubSupport(com.intellij.psi.impl.source.PsiFileWithStubSupport) PsiManager(com.intellij.psi.PsiManager) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 49 with Stream

use of java.util.stream.Stream in project Alpha by alpha-asp.

the class Main method main.

public static void main(String[] args) {
    final Options options = new Options();
    Option numAnswerSetsOption = new Option("n", OPT_NUM_AS, true, "the number of Answer Sets to compute");
    numAnswerSetsOption.setArgName("number");
    numAnswerSetsOption.setRequired(false);
    numAnswerSetsOption.setArgs(1);
    numAnswerSetsOption.setType(Number.class);
    options.addOption(numAnswerSetsOption);
    Option inputOption = new Option("i", OPT_INPUT, true, "read the ASP program from this file");
    inputOption.setArgName("file");
    inputOption.setRequired(true);
    inputOption.setArgs(1);
    inputOption.setType(FileInputStream.class);
    options.addOption(inputOption);
    Option helpOption = new Option("h", OPT_HELP, false, "show this help");
    options.addOption(helpOption);
    Option grounderOption = new Option("g", OPT_GROUNDER, false, "name of the grounder implementation to use");
    grounderOption.setArgs(1);
    grounderOption.setArgName("grounder");
    options.addOption(grounderOption);
    Option solverOption = new Option("s", OPT_SOLVER, false, "name of the solver implementation to use");
    solverOption.setArgs(1);
    solverOption.setArgName("solver");
    options.addOption(solverOption);
    Option filterOption = new Option("f", OPT_FILTER, true, "predicates to show when printing answer sets");
    filterOption.setArgs(1);
    filterOption.setArgName("filter");
    filterOption.setValueSeparator(',');
    options.addOption(filterOption);
    Option sortOption = new Option("sort", OPT_SORT, false, "sort answer sets");
    options.addOption(sortOption);
    Option deterministicOption = new Option("d", OPT_DETERMINISTIC, false, "disable randomness");
    options.addOption(deterministicOption);
    Option seedOption = new Option("e", OPT_SEED, true, "set seed");
    seedOption.setArgName("number");
    seedOption.setRequired(false);
    seedOption.setArgs(1);
    seedOption.setType(Number.class);
    options.addOption(seedOption);
    Option debugFlags = new Option(OPT_DEBUG_INTERNAL_CHECKS, "run additional (time-consuming) safety checks.");
    options.addOption(debugFlags);
    Option branchingHeuristicOption = new Option("b", OPT_BRANCHING_HEURISTIC, false, "name of the branching heuristic to use");
    branchingHeuristicOption.setArgs(1);
    branchingHeuristicOption.setArgName("heuristic");
    options.addOption(branchingHeuristicOption);
    try {
        commandLine = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar alpha.jar\njava -jar alpha_bundled.jar", options);
        System.exit(1);
        return;
    }
    if (commandLine.hasOption(OPT_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        // TODO(flowlo): This is quite optimistic. How do we know that the program
        // really was invoked as "java -jar ..."?
        formatter.printHelp("java -jar alpha.jar OR java -jar alpha-bundled.jar", options);
        System.exit(0);
        return;
    }
    java.util.function.Predicate<Predicate> filter = p -> true;
    if (commandLine.hasOption(OPT_FILTER)) {
        Set<String> desiredPredicates = new HashSet<>(Arrays.asList(commandLine.getOptionValues(OPT_FILTER)));
        filter = p -> {
            return desiredPredicates.contains(p.getPredicateName());
        };
    }
    int limit = 0;
    try {
        Number n = (Number) commandLine.getParsedOptionValue(OPT_NUM_AS);
        if (n != null) {
            limit = n.intValue();
        }
    } catch (ParseException e) {
        bailOut("Failed to parse number of answer sets requested.", e);
    }
    boolean debugInternalChecks = commandLine.hasOption(OPT_DEBUG_INTERNAL_CHECKS);
    ParsedProgram program = null;
    try {
        // Parse all input files and accumulate their results in one ParsedProgram.
        String[] inputFileNames = commandLine.getOptionValues(OPT_INPUT);
        program = parseVisit(new ANTLRFileStream(inputFileNames[0]));
        for (int i = 1; i < inputFileNames.length; i++) {
            program.accumulate(parseVisit(new ANTLRFileStream(inputFileNames[i])));
        }
    } catch (RecognitionException e) {
        // In case a recognitionexception occured, parseVisit will
        // already have printed an error message, so we just exit
        // at this point without further logging.
        System.exit(1);
    } catch (FileNotFoundException e) {
        bailOut(e.getMessage());
    } catch (IOException e) {
        bailOut("Failed to parse program.", e);
    }
    // Apply program transformations/rewritings (currently none).
    IdentityProgramTransformation programTransformation = new IdentityProgramTransformation();
    ParsedProgram transformedProgram = programTransformation.transform(program);
    Grounder grounder = GrounderFactory.getInstance(commandLine.getOptionValue(OPT_GROUNDER, DEFAULT_GROUNDER), transformedProgram, filter);
    // NOTE: Using time as seed is fine as the internal heuristics
    // do not need to by cryptographically securely randomized.
    long seed = commandLine.hasOption(OPT_DETERMINISTIC) ? 0 : System.nanoTime();
    try {
        Number s = (Number) commandLine.getParsedOptionValue(OPT_SEED);
        if (s != null) {
            seed = s.longValue();
        }
    } catch (ParseException e) {
        bailOut("Failed to parse seed.", e);
    }
    LOGGER.info("Seed for pseudorandomization is {}.", seed);
    String chosenSolver = commandLine.getOptionValue(OPT_SOLVER, DEFAULT_SOLVER);
    String chosenBranchingHeuristic = commandLine.getOptionValue(OPT_BRANCHING_HEURISTIC, DEFAULT_BRANCHING_HEURISTIC);
    Heuristic parsedChosenBranchingHeuristic = null;
    try {
        parsedChosenBranchingHeuristic = Heuristic.get(chosenBranchingHeuristic);
    } catch (IllegalArgumentException e) {
        bailOut("Unknown branching heuristic: {}. Please try one of the following: {}.", chosenBranchingHeuristic, Heuristic.listAllowedValues());
    }
    Solver solver = SolverFactory.getInstance(chosenSolver, grounder, new Random(seed), parsedChosenBranchingHeuristic, debugInternalChecks);
    Stream<AnswerSet> stream = solver.stream();
    if (limit > 0) {
        stream = stream.limit(limit);
    }
    if (commandLine.hasOption(OPT_SORT)) {
        stream = stream.sorted();
    }
    stream.forEach(System.out::println);
}
Also used : org.antlr.v4.runtime(org.antlr.v4.runtime) java.util(java.util) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) Logger(org.slf4j.Logger) Solver(at.ac.tuwien.kr.alpha.solver.Solver) org.apache.commons.cli(org.apache.commons.cli) SolverFactory(at.ac.tuwien.kr.alpha.solver.SolverFactory) LoggerFactory(org.slf4j.LoggerFactory) PredictionMode(org.antlr.v4.runtime.atn.PredictionMode) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet) Grounder(at.ac.tuwien.kr.alpha.grounder.Grounder) IdentityProgramTransformation(at.ac.tuwien.kr.alpha.grounder.transformation.IdentityProgramTransformation) GrounderFactory(at.ac.tuwien.kr.alpha.grounder.GrounderFactory) ASPCore2Lexer(at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer) ASPCore2Parser(at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser) Stream(java.util.stream.Stream) java.io(java.io) Heuristic(at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory.Heuristic) Predicate(at.ac.tuwien.kr.alpha.common.Predicate) ParsedTreeVisitor(at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) Solver(at.ac.tuwien.kr.alpha.solver.Solver) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet) Predicate(at.ac.tuwien.kr.alpha.common.Predicate) IdentityProgramTransformation(at.ac.tuwien.kr.alpha.grounder.transformation.IdentityProgramTransformation) Grounder(at.ac.tuwien.kr.alpha.grounder.Grounder) Heuristic(at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory.Heuristic)

Example 50 with Stream

use of java.util.stream.Stream in project karaf by apache.

the class FilesStream method stream.

/**
     * Returns a stream of Paths for the given fileNames.
     * The given names can be delimited by ",". A name can also contain
     * {@link java.nio.file.FileSystem#getPathMatcher} syntax to refer to matching files.  
     * 
     * @param fileNames list of names 
     * @return Paths to the scripts 
     */
public static Stream<Path> stream(String fileNames) {
    if (fileNames == null) {
        return Stream.empty();
    }
    List<String> files = new ArrayList<>();
    List<String> generators = new ArrayList<>();
    StringBuilder buf = new StringBuilder(fileNames.length());
    boolean hasUnescapedReserved = false;
    boolean escaped = false;
    for (int i = 0; i < fileNames.length(); i++) {
        char c = fileNames.charAt(i);
        if (escaped) {
            buf.append(c);
            escaped = false;
        } else if (c == '\\') {
            escaped = true;
        } else if (c == ',') {
            if (hasUnescapedReserved) {
                generators.add(buf.toString());
            } else {
                files.add(buf.toString());
            }
            hasUnescapedReserved = false;
            buf.setLength(0);
        } else if ("*?{[".indexOf(c) >= 0) {
            hasUnescapedReserved = true;
            buf.append(c);
        } else {
            buf.append(c);
        }
    }
    if (buf.length() > 0) {
        if (hasUnescapedReserved) {
            generators.add(buf.toString());
        } else {
            files.add(buf.toString());
        }
    }
    Path cur = Paths.get(System.getProperty("karaf.base"));
    return Stream.concat(files.stream().map(cur::resolve), generators.stream().flatMap(s -> files(cur, s)));
}
Also used : Path(java.nio.file.Path) Logger(org.slf4j.Logger) FileVisitor(java.nio.file.FileVisitor) Files(java.nio.file.Files) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Stream(java.util.stream.Stream) FileVisitOption(java.nio.file.FileVisitOption) Paths(java.nio.file.Paths) PathMatcher(java.nio.file.PathMatcher) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) ArrayList(java.util.ArrayList)

Aggregations

Stream (java.util.stream.Stream)161 Collectors (java.util.stream.Collectors)98 List (java.util.List)89 ArrayList (java.util.ArrayList)66 Map (java.util.Map)66 Set (java.util.Set)59 IOException (java.io.IOException)58 Optional (java.util.Optional)45 Collections (java.util.Collections)43 HashMap (java.util.HashMap)43 Arrays (java.util.Arrays)33 HashSet (java.util.HashSet)33 File (java.io.File)32 Path (java.nio.file.Path)32 Function (java.util.function.Function)28 Logger (org.slf4j.Logger)26 LoggerFactory (org.slf4j.LoggerFactory)26 java.util (java.util)25 Predicate (java.util.function.Predicate)23 Objects (java.util.Objects)22