Search in sources :

Example 61 with Stream

use of java.util.stream.Stream in project fx2048 by brunoborges.

the class GameManager method moveTiles.

/**
     * Moves the tiles according to given direction
     * At any move, takes care of merge tiles, add a new one and perform the
     * required animations
     * It updates the score and checks if the user won the game or if the game is over 
     * 
     * @param direction is the selected direction to move the tiles
     */
private void moveTiles(Direction direction) {
    synchronized (gameGrid) {
        if (movingTiles) {
            return;
        }
    }
    board.setPoints(0);
    mergedToBeRemoved.clear();
    ParallelTransition parallelTransition = new ParallelTransition();
    gridOperator.sortGrid(direction);
    final int tilesWereMoved = gridOperator.traverseGrid((x, y) -> {
        Location thisloc = new Location(x, y);
        // farthest available location
        Location farthestLocation = findFarthestLocation(thisloc, direction);
        Optional<Tile> opTile = optionalTile(thisloc);
        AtomicInteger result = new AtomicInteger();
        // calculates to a possible merge
        Location nextLocation = farthestLocation.offset(direction);
        optionalTile(nextLocation).filter(t -> t.isMergeable(opTile) && !t.isMerged()).ifPresent(t -> {
            Tile tile = opTile.get();
            t.merge(tile);
            t.toFront();
            gameGrid.put(nextLocation, t);
            gameGrid.replace(thisloc, null);
            parallelTransition.getChildren().add(animateExistingTile(tile, t.getLocation()));
            parallelTransition.getChildren().add(animateMergedTile(t));
            mergedToBeRemoved.add(tile);
            board.addPoints(t.getValue());
            if (t.getValue() == FINAL_VALUE_TO_WIN) {
                board.setGameWin(true);
            }
            result.set(1);
        });
        if (result.get() == 0 && opTile.isPresent() && !farthestLocation.equals(thisloc)) {
            Tile tile = opTile.get();
            parallelTransition.getChildren().add(animateExistingTile(tile, farthestLocation));
            gameGrid.put(farthestLocation, tile);
            gameGrid.replace(thisloc, null);
            tile.setLocation(farthestLocation);
            result.set(1);
        }
        return result.get();
    });
    board.animateScore();
    if (parallelTransition.getChildren().size() > 0) {
        parallelTransition.setOnFinished(e -> {
            board.getGridGroup().getChildren().removeAll(mergedToBeRemoved);
            gameGrid.values().stream().filter(Objects::nonNull).forEach(Tile::clearMerge);
            Location randomAvailableLocation = findRandomAvailableLocation();
            if (randomAvailableLocation == null && mergeMovementsAvailable() == 0) {
                board.setGameOver(true);
            } else if (randomAvailableLocation != null && tilesWereMoved > 0) {
                synchronized (gameGrid) {
                    movingTiles = false;
                }
                addAndAnimateRandomTile(randomAvailableLocation);
            }
        });
        synchronized (gameGrid) {
            movingTiles = true;
        }
        parallelTransition.play();
    }
}
Also used : Arrays(java.util.Arrays) HashMap(java.util.HashMap) Random(java.util.Random) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) HostServices(javafx.application.HostServices) KeyValue(javafx.animation.KeyValue) HBox(javafx.scene.layout.HBox) KeyFrame(javafx.animation.KeyFrame) Iterator(java.util.Iterator) Set(java.util.Set) Timeline(javafx.animation.Timeline) Group(javafx.scene.Group) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ParallelTransition(javafx.animation.ParallelTransition) List(java.util.List) ScaleTransition(javafx.animation.ScaleTransition) BooleanProperty(javafx.beans.property.BooleanProperty) Duration(javafx.util.Duration) Stream(java.util.stream.Stream) Interpolator(javafx.animation.Interpolator) SequentialTransition(javafx.animation.SequentialTransition) Optional(java.util.Optional) Collections(java.util.Collections) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ParallelTransition(javafx.animation.ParallelTransition)

Example 62 with Stream

use of java.util.stream.Stream in project Gargoyle by callakrsos.

the class FileSearcher method listClases.

public static List<ProjectInfo> listClases(String classDirName) throws Exception {
    File file = new File(classDirName);
    // 기본적인 파일의 존재유무 및 디렉토리인지 체크.
    if (!file.exists())
        throw new FileNotFoundException(file + " Not found!");
    //
    if (!file.isDirectory())
        throw new IllegalArgumentException("only directory.");
    /*
		 * 디렉토리안에 클래스패스 정보가 존재하는지 확인하고 존재한다면 classpath에 기술된 정보 기준으로 클래스 파일을
		 * 로드한다. 프로그램내에서 workspace를 선택한 경우일수있고, 프로젝트를 선택한 두가지의 경우가 있기때문에 두가지의
		 * 케이스를 고려한 로직이 들어간다.
		 */
    /*
		 * 일단 워크스페이스를 선택한경우라고 가정하고 워크스페이스내에 폴더들을 순차적으로 돌아보면서 classpath의 존재유무를 찾고
		 * 존재하는케이스는 따로 모아놓는다. 파일레벨은 워크스페이스(0레벨)-프로젝트(1레벨)로 가정하여 1레벨까지만 이동한다.
		 */
    List<File> listFiles = findClassPaths(file);
    /*
		 * classpath파일을 찾은경우 그 파일path를 기준으로 클래스들을 로딩한다.
		 */
    List<ProjectInfo> allClasses = new ArrayList<>();
    if (listFiles != null && !listFiles.isEmpty())
        LOGGER.debug(" im will working...");
    long startTime = System.currentTimeMillis();
    int searchedDirCount = 0;
    StringBuffer srchedDirNames = new StringBuffer();
    for (File f : listFiles) {
        try {
            ClassPath parsingClassPath = parsingClassPath(f.getAbsolutePath());
            // 프로젝트파일.
            File projectFile = f.getParentFile();
            // output 속성값의 존재유무만 확인하여 컴파일되는 경로를 찾는다.
            List<ProjectInfo> collect = parsingClassPath.toStream().filter(entry -> {
                boolean notEmpty = ValueUtil.isNotEmpty(entry.getOutput());
                LOGGER.debug(String.format("srch entry path : %s is Traget %b ", entry.getPath(), notEmpty));
                return notEmpty;
            }).map(pram -> pram.getOutput()).distinct().parallel().flatMap(new Function<String, Stream<ProjectInfo>>() {

                @Override
                public Stream<ProjectInfo> apply(String entry) {
                    LOGGER.debug(String.format("entry : %s", entry));
                    File compiledFilePath = new File(projectFile, entry);
                    int length = compiledFilePath.getAbsolutePath().length() + 1;
                    List<String> findClases = findClases(projectFile.getAbsolutePath(), compiledFilePath, length);
                    LOGGER.debug(compiledFilePath.toString());
                    LOGGER.debug(findClases.toString());
                    LOGGER.debug(String.valueOf(findClases.size()));
                    ProjectInfo classInfo = new ProjectInfo();
                    classInfo.setProjectName(projectFile.getName());
                    classInfo.setProjectDir(compiledFilePath.getAbsolutePath());
                    classInfo.setClasses(findClases);
                    return Stream.of(classInfo);
                }
            }).collect(Collectors.toList());
            allClasses.addAll(collect);
            searchedDirCount++;
            srchedDirNames.append(f.getAbsolutePath()).append(SystemUtils.LINE_SEPARATOR);
        } catch (SAXParseException e) {
            LOGGER.error(String.format("정상적인 XML 형태가 아님. 파일명 :  %s", f.getAbsolutePath()));
            LOGGER.error(String.format("%d 행 :: %d 열", e.getLineNumber(), e.getColumnNumber()));
        }
    }
    long endTime = System.currentTimeMillis();
    long costMillisend = endTime - startTime;
    LOGGER.debug(String.format("Total Cost time : %s (ms) searched Directory Count : %d ", costMillisend, searchedDirCount));
    LOGGER.debug(String.format("Searched Dirs info \n%s", srchedDirNames.toString()));
    return allClasses;
}
Also used : URL(java.net.URL) ZipUtil(com.kyj.fx.voeditor.visual.util.ZipUtil) LoggerFactory(org.slf4j.LoggerFactory) Function(java.util.function.Function) Supplier(java.util.function.Supplier) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) Document(org.w3c.dom.Document) Node(org.w3c.dom.Node) NamedNodeMap(org.w3c.dom.NamedNodeMap) Method(java.lang.reflect.Method) SystemUtils(org.apache.commons.lang.SystemUtils) ClassPathEntry(com.kyj.fx.voeditor.visual.main.model.vo.ClassPathEntry) InputSource(org.xml.sax.InputSource) Logger(org.slf4j.Logger) NodeList(org.w3c.dom.NodeList) MalformedURLException(java.net.MalformedURLException) Predicate(java.util.function.Predicate) ClassPath(com.kyj.fx.voeditor.visual.main.model.vo.ClassPath) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) FileInputStream(java.io.FileInputStream) Reader(java.io.Reader) ConfigResourceLoader(com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) StringUtils(org.h2.util.StringUtils) List(java.util.List) SAXParseException(org.xml.sax.SAXParseException) Stream(java.util.stream.Stream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileTypeMap(javax.activation.FileTypeMap) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ClassPath(com.kyj.fx.voeditor.visual.main.model.vo.ClassPath) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) Function(java.util.function.Function) SAXParseException(org.xml.sax.SAXParseException) File(java.io.File)

Example 63 with Stream

use of java.util.stream.Stream in project gatk by broadinstitute.

the class CoverageModelEMWorkspace method getCopyRatioSegmentsSpark.

/**
     * Fetch copy ratio segments from compute blocks (Spark implementation)
     *
     * @return a list of {@link CopyRatioHMMResults}
     */
private List<List<HiddenStateSegmentRecord<STATE, Target>>> getCopyRatioSegmentsSpark() {
    /* local final member variables for lambda capture */
    final List<Target> processedTargetList = new ArrayList<>();
    processedTargetList.addAll(this.processedTargetList);
    final List<SexGenotypeData> processedSampleSexGenotypeData = new ArrayList<>();
    processedSampleSexGenotypeData.addAll(this.processedSampleSexGenotypeData);
    final List<String> processedSampleNameList = new ArrayList<>();
    processedSampleNameList.addAll(this.processedSampleNameList);
    final INDArray sampleReadDepths = Transforms.exp(sampleMeanLogReadDepths, true);
    final CopyRatioExpectationsCalculator<CoverageModelCopyRatioEmissionData, STATE> copyRatioExpectationsCalculator = this.copyRatioExpectationsCalculator;
    final BiFunction<SexGenotypeData, Target, STATE> referenceStateFactory = this.referenceStateFactory;
    return fetchCopyRatioEmissionDataSpark().mapPartitionsToPair(it -> {
        final List<Tuple2<Integer, CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE>>> newPartitionData = new ArrayList<>();
        while (it.hasNext()) {
            final Tuple2<Integer, List<CoverageModelCopyRatioEmissionData>> prevDatum = it.next();
            final int sampleIndex = prevDatum._1;
            final CopyRatioCallingMetadata copyRatioCallingMetadata = CopyRatioCallingMetadata.builder().sampleName(processedSampleNameList.get(sampleIndex)).sampleSexGenotypeData(processedSampleSexGenotypeData.get(sampleIndex)).sampleCoverageDepth(sampleReadDepths.getDouble(sampleIndex)).emissionCalculationStrategy(EmissionCalculationStrategy.HYBRID_POISSON_GAUSSIAN).build();
            newPartitionData.add(new Tuple2<>(sampleIndex, copyRatioExpectationsCalculator.getCopyRatioHMMResults(copyRatioCallingMetadata, processedTargetList, prevDatum._2)));
        }
        return newPartitionData.iterator();
    }, true).mapPartitionsToPair(it -> {
        final List<Tuple2<Integer, List<HiddenStateSegmentRecord<STATE, Target>>>> newPartitionData = new ArrayList<>();
        while (it.hasNext()) {
            final Tuple2<Integer, CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE>> prevDatum = it.next();
            final int sampleIndex = prevDatum._1;
            final CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE> result = prevDatum._2;
            final HMMSegmentProcessor<CoverageModelCopyRatioEmissionData, STATE, Target> processor = new HMMSegmentProcessor<>(Collections.singletonList(result.getMetaData().getSampleName()), Collections.singletonList(result.getMetaData().getSampleSexGenotypeData()), referenceStateFactory, Collections.singletonList(new HashedListTargetCollection<>(processedTargetList)), Collections.singletonList(result.getForwardBackwardResult()), Collections.singletonList(result.getViterbiResult()));
            newPartitionData.add(new Tuple2<>(sampleIndex, processor.getSegmentsAsList()));
        }
        return newPartitionData.iterator();
    }).collect().stream().sorted(Comparator.comparingInt(t -> t._1)).map(t -> t._2).collect(Collectors.toList());
}
Also used : ScalarProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.ScalarProducer) Function2(org.apache.spark.api.java.function.Function2) HMMSegmentProcessor(org.broadinstitute.hellbender.utils.hmm.segmentation.HMMSegmentProcessor) GermlinePloidyAnnotatedTargetCollection(org.broadinstitute.hellbender.tools.exome.sexgenotyper.GermlinePloidyAnnotatedTargetCollection) HiddenStateSegmentRecordWriter(org.broadinstitute.hellbender.utils.hmm.segmentation.HiddenStateSegmentRecordWriter) BiFunction(java.util.function.BiFunction) GATKException(org.broadinstitute.hellbender.exceptions.GATKException) SexGenotypeData(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeData) ParamUtils(org.broadinstitute.hellbender.utils.param.ParamUtils) CallStringProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.CallStringProducer) StorageLevel(org.apache.spark.storage.StorageLevel) SynchronizedUnivariateSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.SynchronizedUnivariateSolver) CopyRatioExpectationsCalculator(org.broadinstitute.hellbender.tools.coveragemodel.interfaces.CopyRatioExpectationsCalculator) UnivariateSolverSpecifications(org.broadinstitute.hellbender.tools.coveragemodel.math.UnivariateSolverSpecifications) IndexRange(org.broadinstitute.hellbender.utils.IndexRange) Broadcast(org.apache.spark.broadcast.Broadcast) ExitStatus(org.broadinstitute.hellbender.tools.coveragemodel.linalg.IterativeLinearSolverNDArray.ExitStatus) SexGenotypeDataCollection(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeDataCollection) HashPartitioner(org.apache.spark.HashPartitioner) Predicate(java.util.function.Predicate) GeneralLinearOperator(org.broadinstitute.hellbender.tools.coveragemodel.linalg.GeneralLinearOperator) Nd4j(org.nd4j.linalg.factory.Nd4j) INDArrayIndex(org.nd4j.linalg.indexing.INDArrayIndex) FastMath(org.apache.commons.math3.util.FastMath) org.broadinstitute.hellbender.tools.exome(org.broadinstitute.hellbender.tools.exome) Tuple2(scala.Tuple2) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) AbstractUnivariateSolver(org.apache.commons.math3.analysis.solvers.AbstractUnivariateSolver) FourierLinearOperatorNDArray(org.broadinstitute.hellbender.tools.coveragemodel.linalg.FourierLinearOperatorNDArray) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) UserException(org.broadinstitute.hellbender.exceptions.UserException) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) Utils(org.broadinstitute.hellbender.utils.Utils) Function(org.apache.spark.api.java.function.Function) DataBuffer(org.nd4j.linalg.api.buffer.DataBuffer) IntStream(java.util.stream.IntStream) java.util(java.util) NDArrayIndex(org.nd4j.linalg.indexing.NDArrayIndex) JavaSparkContext(org.apache.spark.api.java.JavaSparkContext) AlleleMetadataProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.AlleleMetadataProducer) EmissionCalculationStrategy(org.broadinstitute.hellbender.tools.coveragemodel.CoverageModelCopyRatioEmissionProbabilityCalculator.EmissionCalculationStrategy) RobustBrentSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.RobustBrentSolver) IntervalUtils(org.broadinstitute.hellbender.utils.IntervalUtils) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) HiddenStateSegmentRecord(org.broadinstitute.hellbender.utils.hmm.segmentation.HiddenStateSegmentRecord) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) IterativeLinearSolverNDArray(org.broadinstitute.hellbender.tools.coveragemodel.linalg.IterativeLinearSolverNDArray) GATKProtectedMathUtils(org.broadinstitute.hellbender.utils.GATKProtectedMathUtils) Nd4jIOUtils(org.broadinstitute.hellbender.tools.coveragemodel.nd4jutils.Nd4jIOUtils) IOException(java.io.IOException) JavaPairRDD(org.apache.spark.api.java.JavaPairRDD) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) File(java.io.File) INDArray(org.nd4j.linalg.api.ndarray.INDArray) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Transforms(org.nd4j.linalg.ops.transforms.Transforms) LogManager(org.apache.logging.log4j.LogManager) NoBracketingException(org.apache.commons.math3.exception.NoBracketingException) INDArray(org.nd4j.linalg.api.ndarray.INDArray) Tuple2(scala.Tuple2) SexGenotypeData(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeData) HMMSegmentProcessor(org.broadinstitute.hellbender.utils.hmm.segmentation.HMMSegmentProcessor)

Example 64 with Stream

use of java.util.stream.Stream in project gatk-protected by broadinstitute.

the class CoverageModelEMWorkspace method updateSampleUnexplainedVariance.

/**
     * E-step update of the sample-specific unexplained variance
     *
     * @return a {@link SubroutineSignal} containing the update size (key: "error_norm") and the average
     * number of function evaluations per sample (key: "iterations")
     */
@EvaluatesRDD
@UpdatesRDD
@CachesRDD
public SubroutineSignal updateSampleUnexplainedVariance() {
    mapWorkers(cb -> cb.cloneWithUpdatedCachesByTag(CoverageModelEMComputeBlock.CoverageModelICGCacheTag.E_STEP_GAMMA));
    cacheWorkers("after E-step for sample unexplained variance initialization");
    /* create a compound objective function for simultaneous multi-sample queries */
    final java.util.function.Function<Map<Integer, Double>, Map<Integer, Double>> objFunc = arg -> {
        if (arg.isEmpty()) {
            return Collections.emptyMap();
        }
        final int[] sampleIndices = arg.keySet().stream().mapToInt(i -> i).toArray();
        final INDArray gammaValues = Nd4j.create(Arrays.stream(sampleIndices).mapToDouble(arg::get).toArray(), new int[] { sampleIndices.length, 1 });
        final INDArray eval = mapWorkersAndReduce(cb -> cb.calculateSampleSpecificVarianceObjectiveFunctionMultiSample(sampleIndices, gammaValues), INDArray::add);
        final Map<Integer, Double> output = new HashMap<>();
        IntStream.range(0, sampleIndices.length).forEach(evalIdx -> output.put(sampleIndices[evalIdx], eval.getDouble(evalIdx)));
        return output;
    };
    final java.util.function.Function<UnivariateSolverSpecifications, AbstractUnivariateSolver> solverFactory = spec -> new RobustBrentSolver(spec.getRelativeAccuracy(), spec.getAbsoluteAccuracy(), spec.getFunctionValueAccuracy(), null, config.getSampleSpecificVarianceSolverNumBisections(), config.getSampleSpecificVarianceSolverRefinementDepth());
    /* instantiate a synchronized multi-sample root finder and add jobs */
    final SynchronizedUnivariateSolver syncSolver = new SynchronizedUnivariateSolver(objFunc, solverFactory, numSamples);
    IntStream.range(0, numSamples).forEach(si -> {
        final double x0 = 0.5 * config.getSampleSpecificVarianceUpperLimit();
        syncSolver.add(si, 0, config.getSampleSpecificVarianceUpperLimit(), x0, config.getSampleSpecificVarianceAbsoluteTolerance(), config.getSampleSpecificVarianceRelativeTolerance(), config.getSampleSpecificVarianceMaximumIterations());
    });
    /* solve and collect statistics */
    final INDArray newSampleUnexplainedVariance = Nd4j.create(numSamples, 1);
    final List<Integer> numberOfEvaluations = new ArrayList<>(numSamples);
    try {
        final Map<Integer, SynchronizedUnivariateSolver.UnivariateSolverSummary> newSampleSpecificVarianceMap = syncSolver.solve();
        newSampleSpecificVarianceMap.entrySet().forEach(entry -> {
            final int sampleIndex = entry.getKey();
            final SynchronizedUnivariateSolver.UnivariateSolverSummary summary = entry.getValue();
            double val = 0;
            switch(summary.status) {
                case SUCCESS:
                    val = summary.x;
                    break;
                case TOO_MANY_EVALUATIONS:
                    logger.warn("Could not locate the root of gamma -- increase the maximum number of" + "function evaluations");
                    break;
            }
            newSampleUnexplainedVariance.put(sampleIndex, 0, val);
            numberOfEvaluations.add(summary.evaluations);
        });
    } catch (final InterruptedException ex) {
        throw new RuntimeException("The update of sample unexplained variance was interrupted -- can not continue");
    }
    /* admix */
    final INDArray newSampleUnexplainedVarianceAdmixed = newSampleUnexplainedVariance.mul(config.getMeanFieldAdmixingRatio()).addi(sampleUnexplainedVariance.mul(1 - config.getMeanFieldAdmixingRatio()));
    /* calculate the error */
    final double errorNormInfinity = CoverageModelEMWorkspaceMathUtils.getINDArrayNormInfinity(newSampleUnexplainedVarianceAdmixed.sub(sampleUnexplainedVariance));
    /* update local copy */
    sampleUnexplainedVariance.assign(newSampleUnexplainedVarianceAdmixed);
    /* push to workers */
    pushToWorkers(newSampleUnexplainedVarianceAdmixed, (arr, cb) -> cb.cloneWithUpdatedPrimitive(CoverageModelEMComputeBlock.CoverageModelICGCacheNode.gamma_s, newSampleUnexplainedVarianceAdmixed));
    final int iterations = (int) (numberOfEvaluations.stream().mapToDouble(d -> d).sum() / numSamples);
    return SubroutineSignal.builder().put(StandardSubroutineSignals.RESIDUAL_ERROR_NORM, errorNormInfinity).put(StandardSubroutineSignals.ITERATIONS, iterations).build();
}
Also used : ScalarProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.ScalarProducer) Function2(org.apache.spark.api.java.function.Function2) HMMSegmentProcessor(org.broadinstitute.hellbender.utils.hmm.segmentation.HMMSegmentProcessor) GermlinePloidyAnnotatedTargetCollection(org.broadinstitute.hellbender.tools.exome.sexgenotyper.GermlinePloidyAnnotatedTargetCollection) HiddenStateSegmentRecordWriter(org.broadinstitute.hellbender.utils.hmm.segmentation.HiddenStateSegmentRecordWriter) BiFunction(java.util.function.BiFunction) GATKException(org.broadinstitute.hellbender.exceptions.GATKException) SexGenotypeData(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeData) ParamUtils(org.broadinstitute.hellbender.utils.param.ParamUtils) CallStringProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.CallStringProducer) StorageLevel(org.apache.spark.storage.StorageLevel) SynchronizedUnivariateSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.SynchronizedUnivariateSolver) CopyRatioExpectationsCalculator(org.broadinstitute.hellbender.tools.coveragemodel.interfaces.CopyRatioExpectationsCalculator) UnivariateSolverSpecifications(org.broadinstitute.hellbender.tools.coveragemodel.math.UnivariateSolverSpecifications) IndexRange(org.broadinstitute.hellbender.utils.IndexRange) Broadcast(org.apache.spark.broadcast.Broadcast) ExitStatus(org.broadinstitute.hellbender.tools.coveragemodel.linalg.IterativeLinearSolverNDArray.ExitStatus) SexGenotypeDataCollection(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeDataCollection) HashPartitioner(org.apache.spark.HashPartitioner) Predicate(java.util.function.Predicate) GeneralLinearOperator(org.broadinstitute.hellbender.tools.coveragemodel.linalg.GeneralLinearOperator) Nd4j(org.nd4j.linalg.factory.Nd4j) INDArrayIndex(org.nd4j.linalg.indexing.INDArrayIndex) FastMath(org.apache.commons.math3.util.FastMath) org.broadinstitute.hellbender.tools.exome(org.broadinstitute.hellbender.tools.exome) Tuple2(scala.Tuple2) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) AbstractUnivariateSolver(org.apache.commons.math3.analysis.solvers.AbstractUnivariateSolver) FourierLinearOperatorNDArray(org.broadinstitute.hellbender.tools.coveragemodel.linalg.FourierLinearOperatorNDArray) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) UserException(org.broadinstitute.hellbender.exceptions.UserException) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) Utils(org.broadinstitute.hellbender.utils.Utils) Function(org.apache.spark.api.java.function.Function) DataBuffer(org.nd4j.linalg.api.buffer.DataBuffer) IntStream(java.util.stream.IntStream) java.util(java.util) NDArrayIndex(org.nd4j.linalg.indexing.NDArrayIndex) JavaSparkContext(org.apache.spark.api.java.JavaSparkContext) AlleleMetadataProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.AlleleMetadataProducer) EmissionCalculationStrategy(org.broadinstitute.hellbender.tools.coveragemodel.CoverageModelCopyRatioEmissionProbabilityCalculator.EmissionCalculationStrategy) RobustBrentSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.RobustBrentSolver) IntervalUtils(org.broadinstitute.hellbender.utils.IntervalUtils) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) HiddenStateSegmentRecord(org.broadinstitute.hellbender.utils.hmm.segmentation.HiddenStateSegmentRecord) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) IterativeLinearSolverNDArray(org.broadinstitute.hellbender.tools.coveragemodel.linalg.IterativeLinearSolverNDArray) GATKProtectedMathUtils(org.broadinstitute.hellbender.utils.GATKProtectedMathUtils) Nd4jIOUtils(org.broadinstitute.hellbender.tools.coveragemodel.nd4jutils.Nd4jIOUtils) IOException(java.io.IOException) JavaPairRDD(org.apache.spark.api.java.JavaPairRDD) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) File(java.io.File) INDArray(org.nd4j.linalg.api.ndarray.INDArray) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Transforms(org.nd4j.linalg.ops.transforms.Transforms) LogManager(org.apache.logging.log4j.LogManager) NoBracketingException(org.apache.commons.math3.exception.NoBracketingException) SynchronizedUnivariateSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.SynchronizedUnivariateSolver) AbstractUnivariateSolver(org.apache.commons.math3.analysis.solvers.AbstractUnivariateSolver) RobustBrentSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.RobustBrentSolver) INDArray(org.nd4j.linalg.api.ndarray.INDArray) UnivariateSolverSpecifications(org.broadinstitute.hellbender.tools.coveragemodel.math.UnivariateSolverSpecifications)

Example 65 with Stream

use of java.util.stream.Stream in project Gargoyle by callakrsos.

the class DaoWizardViewController method btnExecOnMouseClick.

/**
	 * 텍스트에 기술된 SQL문을 실행한다. 기본적으로 ROWNUM 기술문을 100개를 감싸서 SQL을 조회한다.
	 *
	 * @작성자 : KYJ
	 * @작성일 : 2015. 10. 21.
	 */
@FXML
public void btnExecOnMouseClick(MouseEvent e) {
    LOGGER.debug("event] btnExecOnMouseClick");
    String velocitySQL = txtSql.getText().trim();
    if (velocitySQL == null || velocitySQL.isEmpty())
        return;
    LOGGER.debug(String.format("velocitySQL : %s", velocitySQL));
    // 파라미터 컬럼값 반환받는다.
    ObservableList<TbpSysDaoFieldsDVO> items = tbParams.getItems();
    Map<String, TbpSysDaoColumnsDVO> unmapping = this.tbMappings.getItems().stream().filter(v -> {
        String lockYn = v.getLockYn();
        if ("Y".equals(lockYn))
            return true;
        return false;
    }).collect(Collectors.toMap(TbpSysDaoColumnsDVO::getColumnName, v -> v));
    Map<String, Object> paramMap = items.stream().filter(vo -> vo.getTestValue() != null && !vo.getTestValue().isEmpty()).collect(Collectors.toMap(TbpSysDaoFieldsDVO::getFieldName, new Function<TbpSysDaoFieldsDVO, Object>() {

        @Override
        public Object apply(TbpSysDaoFieldsDVO t) {
            if ("Arrays".equals(t.getType())) {
                String pattern = "'[^']{0,}'";
                List<String> regexMatchs = ValueUtil.regexMatchs(pattern, t.getTestValue(), str -> {
                    return str.substring(1, str.length() - 1);
                });
                return regexMatchs;
            }
            return t.getTestValue();
        }
    }));
    SimpleSQLResultView simpleSQLResultView = new SimpleSQLResultView(velocitySQL, paramMap);
    try {
        simpleSQLResultView.show();
        List<TableModelDVO> columns = simpleSQLResultView.getColumns();
        List<TbpSysDaoColumnsDVO> resultList = columns.stream().map(vo -> {
            TbpSysDaoColumnsDVO dvo = new TbpSysDaoColumnsDVO();
            dvo.setColumnName(vo.getDatabaseColumnName());
            String databaseTypeName = vo.getDatabaseTypeName();
            dvo.setColumnType(databaseTypeName);
            if (unmapping.containsKey(vo.getDatabaseColumnName())) {
                TbpSysDaoColumnsDVO tmp = unmapping.get(vo.getDatabaseColumnName());
                dvo.setProgramType(tmp.getProgramType());
                dvo.setLockYn(tmp.getLockYn());
            } else {
                String programType = DatabaseTypeMappingResourceLoader.getInstance().get(databaseTypeName);
                dvo.setProgramType(programType);
            }
            return dvo;
        }).collect(Collectors.toList());
        // if (!this.tbMappings.getItems().isEmpty())
        if (!resultList.isEmpty()) {
            try {
                this.tbMappings.getItems().clear();
                getSelectedMethodItem().getTbpSysDaoColumnsDVOList().clear();
                this.tbMappings.getItems().addAll(resultList);
                getSelectedMethodItem().getTbpSysDaoColumnsDVOList().addAll(resultList);
            } catch (NullPointerException n) {
                DialogUtil.showMessageDialog("메소드를 선택해주세요.");
            }
        }
    } catch (IOException e1) {
        LOGGER.error(ValueUtil.toString(e1));
        DialogUtil.showExceptionDailog(e1);
    }
}
Also used : SimpleSQLResultView(com.kyj.fx.voeditor.visual.component.popup.SimpleSQLResultView) Arrays(java.util.Arrays) Menus(com.kyj.fx.voeditor.visual.component.Menus) DbUtil(com.kyj.fx.voeditor.visual.util.DbUtil) NumberingCellValueFactory(com.kyj.fx.voeditor.visual.component.NumberingCellValueFactory) LoggerFactory(org.slf4j.LoggerFactory) NullExpresion(com.kyj.fx.voeditor.visual.util.NullExpresion) MeerketAbstractVoOpenClassResourceView(com.kyj.fx.voeditor.visual.component.popup.MeerketAbstractVoOpenClassResourceView) ReadOnlyObjectWrapper(javafx.beans.property.ReadOnlyObjectWrapper) ContextMenu(javafx.scene.control.ContextMenu) Map(java.util.Map) FileUtil(com.kyj.fx.voeditor.visual.util.FileUtil) TableView(javafx.scene.control.TableView) TbpSysDaoColumnsDVO(kyj.Fx.dao.wizard.core.model.vo.TbpSysDaoColumnsDVO) Path(java.nio.file.Path) EditorUtil(com.kyj.fx.voeditor.util.EditorUtil) DatabaseTypeMappingFunction(com.kyj.fx.voeditor.visual.functions.DatabaseTypeMappingFunction) ClassTypeResourceLoader(com.kyj.fx.voeditor.visual.momory.ClassTypeResourceLoader) TableMasterDVO(kyj.Fx.dao.wizard.core.model.vo.TableMasterDVO) SqlKeywords(com.kyj.fx.voeditor.visual.component.text.SqlKeywords) TextField(javafx.scene.control.TextField) Pair(javafx.util.Pair) MenuItem(javafx.scene.control.MenuItem) QuerygenUtil(kyj.Fx.dao.wizard.core.util.QuerygenUtil) TbpSysDaoMethodsDVO(kyj.Fx.dao.wizard.core.model.vo.TbpSysDaoMethodsDVO) Set(java.util.Set) KeyEvent(javafx.scene.input.KeyEvent) DatabaseTableView(com.kyj.fx.voeditor.visual.component.popup.DatabaseTableView) FxDAOReadFunction(com.kyj.fx.voeditor.visual.functions.FxDAOReadFunction) ConfigResourceLoader(com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader) TableDVO(kyj.Fx.dao.wizard.core.model.vo.TableDVO) Collectors(java.util.stream.Collectors) FXML(javafx.fxml.FXML) FxUtil(com.kyj.fx.voeditor.visual.util.FxUtil) List(java.util.List) ResourceLoader(com.kyj.fx.voeditor.visual.momory.ResourceLoader) Stream(java.util.stream.Stream) Optional(java.util.Optional) ChoiceBoxTableCell(javafx.scene.control.cell.ChoiceBoxTableCell) DateUtil(com.kyj.fx.voeditor.visual.util.DateUtil) CommonsContextMenu(com.kyj.fx.voeditor.visual.component.CommonsContextMenu) ObservableList(javafx.collections.ObservableList) BorderPane(javafx.scene.layout.BorderPane) BaseOpenClassResourceView(com.kyj.fx.voeditor.visual.component.popup.BaseOpenClassResourceView) TextArea(javafx.scene.control.TextArea) MouseEvent(javafx.scene.input.MouseEvent) CommonContextMenuEvent(com.kyj.fx.voeditor.visual.events.CommonContextMenuEvent) FXCollections(javafx.collections.FXCollections) HashMap(java.util.HashMap) TextFieldTableCell(javafx.scene.control.cell.TextFieldTableCell) DialogUtil(com.kyj.fx.voeditor.visual.util.DialogUtil) Function(java.util.function.Function) TbmSysDaoDVO(kyj.Fx.dao.wizard.core.model.vo.TbmSysDaoDVO) TableColumn(javafx.scene.control.TableColumn) Wizardtype(com.kyj.fx.voeditor.visual.framework.daowizard.GargoyleDaoWizardFactory.Wizardtype) FXMLLoader(javafx.fxml.FXMLLoader) FxCollectors(com.kyj.fx.voeditor.visual.util.FxCollectors) JavaTextView(com.kyj.fx.voeditor.visual.component.popup.JavaTextView) DaoWizard(kyj.Fx.dao.wizard.DaoWizard) LinkedHashSet(java.util.LinkedHashSet) ClassMeta(com.kyj.fx.voeditor.core.model.meta.ClassMeta) FxDAOSaveFunction(com.kyj.fx.voeditor.visual.functions.FxDAOSaveFunction) ObjectProperty(javafx.beans.property.ObjectProperty) Logger(org.slf4j.Logger) DaoWizardConverter(com.kyj.fx.voeditor.visual.util.DaoWizardConverter) Label(javafx.scene.control.Label) Iterator(java.util.Iterator) FieldMeta(com.kyj.fx.voeditor.core.model.meta.FieldMeta) DatabaseTypeMappingResourceLoader(kyj.Fx.dao.wizard.memory.DatabaseTypeMappingResourceLoader) IOException(java.io.IOException) LockImagedYnColumn(com.kyj.fx.voeditor.visual.component.LockImagedYnColumn) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) TbpSysDaoFieldsDVO(kyj.Fx.dao.wizard.core.model.vo.TbpSysDaoFieldsDVO) StringConverter(javafx.util.StringConverter) File(java.io.File) ActionEvent(javafx.event.ActionEvent) SelectionMode(javafx.scene.control.SelectionMode) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) TableModelDVO(kyj.Fx.dao.wizard.core.model.vo.TableModelDVO) ResultDialog(com.kyj.fx.voeditor.visual.component.ResultDialog) Collections(java.util.Collections) SharedMemory(com.kyj.fx.voeditor.visual.momory.SharedMemory) SimpleSQLResultView(com.kyj.fx.voeditor.visual.component.popup.SimpleSQLResultView) TableModelDVO(kyj.Fx.dao.wizard.core.model.vo.TableModelDVO) IOException(java.io.IOException) DatabaseTypeMappingFunction(com.kyj.fx.voeditor.visual.functions.DatabaseTypeMappingFunction) FxDAOReadFunction(com.kyj.fx.voeditor.visual.functions.FxDAOReadFunction) Function(java.util.function.Function) FxDAOSaveFunction(com.kyj.fx.voeditor.visual.functions.FxDAOSaveFunction) TbpSysDaoColumnsDVO(kyj.Fx.dao.wizard.core.model.vo.TbpSysDaoColumnsDVO) TbpSysDaoFieldsDVO(kyj.Fx.dao.wizard.core.model.vo.TbpSysDaoFieldsDVO) FXML(javafx.fxml.FXML)

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