Search in sources :

Example 6 with BiPredicate

use of java.util.function.BiPredicate in project cassandra by apache.

the class CustomClassLoader method addClassPath.

public void addClassPath(File dir) {
    if (dir == null || !dir.exists())
        return;
    BiPredicate<File, String> filter = (ignore, name) -> name.endsWith(".jar");
    for (File inputJar : dir.tryList(filter)) {
        File lib = new File(FileUtils.getTempDir(), "lib");
        if (!lib.exists()) {
            lib.tryCreateDirectory();
            lib.deleteOnExit();
        }
        File out = FileUtils.createTempFile("cassandra-", ".jar", lib);
        out.deleteOnExit();
        logger.info("Loading new jar {}", inputJar.absolutePath());
        try {
            copy(inputJar.toPath(), out.toPath());
            addURL(out.toPath().toUri().toURL());
        } catch (IOException ex) {
            throw new FSWriteError(ex, out);
        }
    }
}
Also used : BiPredicate(java.util.function.BiPredicate) URLClassLoader(java.net.URLClassLoader) Logger(org.slf4j.Logger) Files(java.nio.file.Files) URL(java.net.URL) FileUtils(org.apache.cassandra.io.util.FileUtils) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) File(org.apache.cassandra.io.util.File) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) FSWriteError(org.apache.cassandra.io.FSWriteError) FSWriteError(org.apache.cassandra.io.FSWriteError) IOException(java.io.IOException) File(org.apache.cassandra.io.util.File)

Example 7 with BiPredicate

use of java.util.function.BiPredicate in project cassandra by apache.

the class CQLSSTableWriterTest method testSyncWithinPartition.

@Test
public void testSyncWithinPartition() throws Exception {
    // Check that the write respect the buffer size even if we only insert rows withing the same partition (#7360)
    // To do that simply, we use a writer with a buffer of 1MiB, and write 2 rows in the same partition with a value
    // > 1MiB and validate that this created more than 1 sstable.
    String schema = "CREATE TABLE " + qualifiedTable + " (" + "  k int PRIMARY KEY," + "  v blob" + ")";
    String insert = "INSERT INTO " + qualifiedTable + " (k, v) VALUES (?, ?)";
    CQLSSTableWriter writer = CQLSSTableWriter.builder().inDirectory(dataDir).using(insert).forTable(schema).withBufferSizeInMiB(1).build();
    ByteBuffer val = ByteBuffer.allocate(1024 * 1050);
    writer.addRow(0, val);
    writer.addRow(1, val);
    writer.close();
    BiPredicate<File, String> filterDataFiles = (dir, name) -> name.endsWith("-Data.db");
    assert dataDir.tryListNames(filterDataFiles).length > 1 : Arrays.toString(dataDir.tryListNames(filterDataFiles));
}
Also used : org.apache.cassandra.config(org.apache.cassandra.config) java.util(java.util) BeforeClass(org.junit.BeforeClass) File(org.apache.cassandra.io.util.File) CommitLog(org.apache.cassandra.db.commitlog.CommitLog) org.apache.cassandra.cql3.functions.types(org.apache.cassandra.cql3.functions.types) org.apache.cassandra.utils(org.apache.cassandra.utils) ByteBuffer(java.nio.ByteBuffer) org.apache.cassandra.cql3(org.apache.cassandra.cql3) Schema(org.apache.cassandra.schema.Schema) BiPredicate(java.util.function.BiPredicate) ImmutableList(com.google.common.collect.ImmutableList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) UDHelper(org.apache.cassandra.cql3.functions.UDHelper) StreamSupport(java.util.stream.StreamSupport) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) Assert.fail(org.junit.Assert.fail) Keyspace(org.apache.cassandra.db.Keyspace) Before(org.junit.Before) ImmutableMap(com.google.common.collect.ImmutableMap) Util(org.apache.cassandra.Util) StorageService(org.apache.cassandra.service.StorageService) IOException(java.io.IOException) Test(org.junit.Test) org.apache.cassandra.dht(org.apache.cassandra.dht) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) SchemaLoader(org.apache.cassandra.SchemaLoader) Rule(org.junit.Rule) org.apache.cassandra.exceptions(org.apache.cassandra.exceptions) TableMetadataRef(org.apache.cassandra.schema.TableMetadataRef) Assert.assertFalse(org.junit.Assert.assertFalse) TemporaryFolder(org.junit.rules.TemporaryFolder) Assert.assertEquals(org.junit.Assert.assertEquals) ByteBuffer(java.nio.ByteBuffer) File(org.apache.cassandra.io.util.File) Test(org.junit.Test)

Example 8 with BiPredicate

use of java.util.function.BiPredicate in project j2objc by google.

the class BiPredicateTest method testAnd.

public void testAnd() throws Exception {
    Object arg1 = "one";
    Object arg2 = "two";
    AtomicBoolean alwaysTrueInvoked = new AtomicBoolean(false);
    AtomicBoolean alwaysTrue2Invoked = new AtomicBoolean(false);
    AtomicBoolean alwaysFalseInvoked = new AtomicBoolean(false);
    AtomicBoolean alwaysFalse2Invoked = new AtomicBoolean(false);
    AtomicBoolean[] invocationState = { alwaysTrueInvoked, alwaysTrue2Invoked, alwaysFalseInvoked, alwaysFalse2Invoked };
    BiPredicate<Object, Object> alwaysTrue = (x, y) -> {
        alwaysTrueInvoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return true;
    };
    BiPredicate<Object, Object> alwaysTrue2 = (x, y) -> {
        alwaysTrue2Invoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return true;
    };
    BiPredicate<Object, Object> alwaysFalse = (x, y) -> {
        alwaysFalseInvoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return false;
    };
    BiPredicate<Object, Object> alwaysFalse2 = (x, y) -> {
        alwaysFalse2Invoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return false;
    };
    // true && true
    resetToFalse(invocationState);
    assertTrue(alwaysTrue.and(alwaysTrue2).test(arg1, arg2));
    assertTrue(alwaysTrueInvoked.get() && alwaysTrue2Invoked.get());
    // true && false
    resetToFalse(invocationState);
    assertFalse(alwaysTrue.and(alwaysFalse).test(arg1, arg2));
    assertTrue(alwaysTrueInvoked.get() && alwaysFalseInvoked.get());
    // false && false
    resetToFalse(invocationState);
    assertFalse(alwaysFalse.and(alwaysFalse2).test(arg1, arg2));
    assertTrue(alwaysFalseInvoked.get() && !alwaysFalse2Invoked.get());
    // false && true
    resetToFalse(invocationState);
    assertFalse(alwaysFalse.and(alwaysTrue).test(arg1, arg2));
    assertTrue(alwaysFalseInvoked.get() && !alwaysTrueInvoked.get());
}
Also used : BiPredicate(java.util.function.BiPredicate) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TestCase(junit.framework.TestCase) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 9 with BiPredicate

use of java.util.function.BiPredicate in project j2objc by google.

the class BiPredicateTest method testOr.

public void testOr() throws Exception {
    Object arg1 = "one";
    Object arg2 = "two";
    AtomicBoolean alwaysTrueInvoked = new AtomicBoolean(false);
    AtomicBoolean alwaysTrue2Invoked = new AtomicBoolean(false);
    AtomicBoolean alwaysFalseInvoked = new AtomicBoolean(false);
    AtomicBoolean alwaysFalse2Invoked = new AtomicBoolean(false);
    AtomicBoolean[] invocationState = { alwaysTrueInvoked, alwaysTrue2Invoked, alwaysFalseInvoked, alwaysFalse2Invoked };
    BiPredicate<Object, Object> alwaysTrue = (x, y) -> {
        alwaysTrueInvoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return true;
    };
    BiPredicate<Object, Object> alwaysTrue2 = (x, y) -> {
        alwaysTrue2Invoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return true;
    };
    BiPredicate<Object, Object> alwaysFalse = (x, y) -> {
        alwaysFalseInvoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return false;
    };
    BiPredicate<Object, Object> alwaysFalse2 = (x, y) -> {
        alwaysFalse2Invoked.set(true);
        assertSame(arg1, x);
        assertSame(arg2, y);
        return false;
    };
    // true || true
    resetToFalse(invocationState);
    assertTrue(alwaysTrue.or(alwaysTrue2).test(arg1, arg2));
    assertTrue(alwaysTrueInvoked.get() && !alwaysTrue2Invoked.get());
    // true || false
    resetToFalse(invocationState);
    assertTrue(alwaysTrue.or(alwaysFalse).test(arg1, arg2));
    assertTrue(alwaysTrueInvoked.get() && !alwaysFalseInvoked.get());
    // false || false
    resetToFalse(invocationState);
    assertFalse(alwaysFalse.or(alwaysFalse2).test(arg1, arg2));
    assertTrue(alwaysFalseInvoked.get() && alwaysFalse2Invoked.get());
    // false || true
    resetToFalse(invocationState);
    assertTrue(alwaysFalse.or(alwaysTrue).test(arg1, arg2));
    assertTrue(alwaysFalseInvoked.get() && alwaysTrueInvoked.get());
}
Also used : BiPredicate(java.util.function.BiPredicate) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TestCase(junit.framework.TestCase) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 10 with BiPredicate

use of java.util.function.BiPredicate in project GDSC-SMLM by aherbert.

the class TcPalmAnalysis method analyseRois.

/**
 * Analyses all the ROIs in the ROI manager.
 *
 * @param event the event
 */
private void analyseRois(ActionEvent event) {
    final RoiManager manager = RoiManager.getInstance();
    if (manager == null) {
        IJ.error(TITLE, "ROI manager is not open");
        return;
    }
    final LocalList<Roi> rois = Arrays.stream(manager.getRoisAsArray()).filter(Roi::isArea).collect(LocalCollectors.toLocalList());
    if (rois.isEmpty()) {
        IJ.error(TITLE, "No area ROIs");
        return;
    }
    // Check for overlaps.
    if (!settings.getDisableOverlapCheck() && anyOverlap(rois)) {
        final GenericDialog gd = new GenericDialog(TITLE);
        gd.addMessage(TextUtils.wrap("WARNING - Bounding rectangles of ROIs overlap. You can verify " + "the ROIs on the image using the ROI manager 'Show all' function.", 80));
        gd.setOKLabel("Continue");
        gd.showDialog();
        if (gd.wasCanceled()) {
            return;
        }
    }
    // For each ROI:
    // - Extract the current groups
    // - Build the cumulative count plot
    // - Identify the bursts
    // - Extract ClusterData for each burst
    final TcPalmAnalysisSettings settings = this.settings.build();
    final LocalList<ClusterData> allClusters = rois.parallelStream().map(roi -> {
        final Rectangle2D scaledBounds = createScaledBounds(roi);
        final BiPredicate<ClusterData, Rectangle2D> filter = createSelectionFilter(roi, settings);
        // Filter all cluster groups
        final LocalList<ClusterData> clusters = new LocalList<>();
        clusterData.forEach(c -> {
            if (filter.test(c, scaledBounds)) {
                clusters.add(c);
            }
        });
        // Extract activation bursts
        final CumulativeCountData countData = createCumulativeCountData(clusters, false);
        final LocalList<int[]> bursts = runBurstAnalysis(settings, countData);
        final LocalList<LocalList<PeakResult>> burstLocalisations = createBurstLocalisations(clusters, bursts);
        clusters.clear();
        burstLocalisations.forEach(list -> {
            final ClusterData d = new ClusterData(clusters.size() + 1, list);
            // Save this for analysis
            d.sourceRoi = roi;
            d.getArea();
            clusters.add(d);
        });
        return clusters;
    }).collect(LocalList::new, LocalList::addAll, LocalList::addAll);
    // Reorder
    final Counter count = new Counter();
    allClusters.forEach(c -> c.id = count.incrementAndGet());
    // Display in a table
    final ClusterDataTableModelFrame frame = createAllClustersTable();
    frame.getModel().setData(allClusters, dataCalibration);
    // Allow the results to be repeated
    frame.selectedAction = clusters -> {
        // Expecting a single cluster. No clusters occurs when the table (and selection) is cleared.
        if (clusters.size() == 1) {
            final ClusterData c = clusters.get(0);
            // Push the correct ROI and settings to the analysis action.
            // We do not directly update the ROI or dialog settings as
            // these trigger events that are processed to add work with a delay.
            // Updating them at the end should generate events that are
            // ignored when finally executed as the ROI/settings should be the same.
            addWork(0, c.sourceRoi, settings, () -> {
                // When analysis has finished update the settings and image ROI.
                image.getImagePlus().setRoi(c.sourceRoi);
                darkTimeToleranceTextField.setText(Integer.toString(settings.getDarkTimeTolerance()));
                minClusterSizeTextField.setText(Integer.toString(settings.getMinClusterSize()));
                // When analysis has finished the cluster should be selected in the
                // current clusters table.
                final ClusterDataTableModelFrame currentClusters = currentClustersTable.get();
                if (currentClusters != null) {
                    currentClusters.select(c);
                }
            });
        }
    };
    // Show histogram of cluster size/duration
    reportAnalysis(settings, allClusters, dataCalibration);
    // Save clusters to memory
    final Trace[] traces = allClusters.stream().map(c -> {
        final Trace t = new Trace();
        t.setId(c.id);
        c.results.forEach(t::add);
        return t;
    }).toArray(Trace[]::new);
    TraceMolecules.saveResults(results, traces, "TC PALM");
    IJ.showStatus(TITLE + ": " + TextUtils.pleural(allClusters.size(), "cluster"));
}
Also used : Color(java.awt.Color) Arrays(java.util.Arrays) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) IntUnaryOperator(java.util.function.IntUnaryOperator) Rectangle2D(java.awt.geom.Rectangle2D) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) IdFramePeakResultComparator(uk.ac.sussex.gdsc.smlm.results.sort.IdFramePeakResultComparator) UnaryOperator(java.util.function.UnaryOperator) Hull(uk.ac.sussex.gdsc.core.math.hull.Hull) TableCellRenderer(javax.swing.table.TableCellRenderer) ResultsSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsSettings) FloatUnaryOperator(uk.ac.sussex.gdsc.core.utils.function.FloatUnaryOperator) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) RoiManager(ij.plugin.frame.RoiManager) RowSorter(javax.swing.RowSorter) SoftLock(uk.ac.sussex.gdsc.core.utils.SoftLock) JFrame(javax.swing.JFrame) LutHelper(uk.ac.sussex.gdsc.core.ij.process.LutHelper) KeyStroke(javax.swing.KeyStroke) TableModelEvent(javax.swing.event.TableModelEvent) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) KeyEvent(java.awt.event.KeyEvent) WindowAdapter(java.awt.event.WindowAdapter) ConcurrencyUtils(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils) Component(java.awt.Component) Hull2d(uk.ac.sussex.gdsc.core.math.hull.Hull2d) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Plot(ij.gui.Plot) Executors(java.util.concurrent.Executors) CalibrationHelper(uk.ac.sussex.gdsc.smlm.data.config.CalibrationHelper) ImagePlus(ij.ImagePlus) DefaultTableCellRenderer(javax.swing.table.DefaultTableCellRenderer) ToDoubleFunction(java.util.function.ToDoubleFunction) TcPalmAnalysisSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.TcPalmAnalysisSettings) FileUtils(uk.ac.sussex.gdsc.core.utils.FileUtils) PlugIn(ij.plugin.PlugIn) ListSelectionModel(javax.swing.ListSelectionModel) ActionListener(java.awt.event.ActionListener) PolygonRoi(ij.gui.PolygonRoi) StoredData(uk.ac.sussex.gdsc.core.utils.StoredData) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) WindowManager(ij.WindowManager) ConvexHull2d(uk.ac.sussex.gdsc.core.math.hull.ConvexHull2d) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) PointRoi(ij.gui.PointRoi) Trace(uk.ac.sussex.gdsc.smlm.results.Trace) GenericDialog(ij.gui.GenericDialog) AbstractTableModel(javax.swing.table.AbstractTableModel) SortUtils(uk.ac.sussex.gdsc.core.utils.SortUtils) RounderUtils(uk.ac.sussex.gdsc.core.data.utils.RounderUtils) Overlay(ij.gui.Overlay) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) Window(java.awt.Window) IOException(java.io.IOException) JScrollPane(javax.swing.JScrollPane) RoiListener(ij.gui.RoiListener) Paths(java.nio.file.Paths) ConcurrentMonoStack(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrentMonoStack) ListSelectionListener(javax.swing.event.ListSelectionListener) TIntArrayList(gnu.trove.list.array.TIntArrayList) IdentityTypeConverter(uk.ac.sussex.gdsc.core.data.utils.IdentityTypeConverter) Point(java.awt.Point) CoordinatePredicateUtils(uk.ac.sussex.gdsc.core.ij.roi.CoordinatePredicateUtils) ResultsImageSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSettings) ImageJPluginLoggerHelper(uk.ac.sussex.gdsc.core.ij.ImageJPluginLoggerHelper) LocalCollectors(uk.ac.sussex.gdsc.core.utils.LocalCollectors) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) NonBlockingExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog) ScreenDimensionHelper(uk.ac.sussex.gdsc.core.ij.gui.ScreenDimensionHelper) PlotWindow(ij.gui.PlotWindow) ListSelectionEvent(javax.swing.event.ListSelectionEvent) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) JMenuBar(javax.swing.JMenuBar) CoordinatePredicate(uk.ac.sussex.gdsc.core.ij.roi.CoordinatePredicate) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) PeakResultsList(uk.ac.sussex.gdsc.smlm.results.PeakResultsList) JMenu(javax.swing.JMenu) TIntIntHashMap(gnu.trove.map.hash.TIntIntHashMap) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) WindowEvent(java.awt.event.WindowEvent) DoubleStream(java.util.stream.DoubleStream) Objects(java.util.Objects) List(java.util.List) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) JTable(javax.swing.JTable) LUT(ij.process.LUT) TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) Roi(ij.gui.Roi) Rectangle(java.awt.Rectangle) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) AtomicReference(java.util.concurrent.atomic.AtomicReference) SwingConstants(javax.swing.SwingConstants) TextField(java.awt.TextField) Level(java.util.logging.Level) AWTEvent(java.awt.AWTEvent) BiPredicate(java.util.function.BiPredicate) SwingUtilities(javax.swing.SwingUtilities) JMenuItem(javax.swing.JMenuItem) ImagePeakResultsFactory(uk.ac.sussex.gdsc.smlm.ij.results.ImagePeakResultsFactory) UnitHelper(uk.ac.sussex.gdsc.smlm.data.config.UnitHelper) ExecutorService(java.util.concurrent.ExecutorService) LutColour(uk.ac.sussex.gdsc.core.ij.process.LutHelper.LutColour) ActionEvent(java.awt.event.ActionEvent) Rounder(uk.ac.sussex.gdsc.core.data.utils.Rounder) TimeUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.TimeUnit) Consumer(java.util.function.Consumer) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) TableColumnAdjuster(uk.ac.sussex.gdsc.smlm.ij.gui.TableColumnAdjuster) IJ(ij.IJ) DoublePredicate(java.util.function.DoublePredicate) Collections(java.util.Collections) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) Rectangle2D(java.awt.geom.Rectangle2D) PolygonRoi(ij.gui.PolygonRoi) PointRoi(ij.gui.PointRoi) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) Roi(ij.gui.Roi) RoiManager(ij.plugin.frame.RoiManager) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) Trace(uk.ac.sussex.gdsc.smlm.results.Trace) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) GenericDialog(ij.gui.GenericDialog) NonBlockingExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) TcPalmAnalysisSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.TcPalmAnalysisSettings) BiPredicate(java.util.function.BiPredicate)

Aggregations

BiPredicate (java.util.function.BiPredicate)36 List (java.util.List)17 Collectors (java.util.stream.Collectors)16 ArrayList (java.util.ArrayList)14 IOException (java.io.IOException)12 Collections (java.util.Collections)12 Map (java.util.Map)11 Files (java.nio.file.Files)10 Objects (java.util.Objects)8 Set (java.util.Set)8 HashMap (java.util.HashMap)7 Paths (java.nio.file.Paths)6 Arrays (java.util.Arrays)6 HashSet (java.util.HashSet)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 HasContainer (org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer)6 Path (java.nio.file.Path)5 java.util (java.util)5 Collection (java.util.Collection)5 Function (java.util.function.Function)5