text:
package com.rackspacecloud.blueflood.io;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.rackspacecloud.blueflood.cache.MetadataCache;
import com.rackspacecloud.blueflood.io.astyanax.APreaggregatedMetricsRW;
import com.rackspacecloud.blueflood.io.datastax.DDelayedLocatorIO;
import com.rackspacecloud.blueflood.io.datastax.DEnumIO;
import com.rackspacecloud.blueflood.io.datastax.DLocatorIO;
import com.rackspacecloud.blueflood.io.datastax.DPreaggregatedMetricsRW;
import com.rackspacecloud.blueflood.outputs.formats.MetricData;
import com.rackspacecloud.blueflood.rollup.Granularity;
import com.rackspacecloud.blueflood.rollup.SlotKey;
import com.rackspacecloud.blueflood.service.Configuration;
import com.rackspacecloud.blueflood.service.CoreConfig;
import com.rackspacecloud.blueflood.service.SingleRollupWriteContext;
import com.rackspacecloud.blueflood.types.*;
import com.rackspacecloud.blueflood.utils.Clock;
import com.rackspacecloud.blueflood.utils.DefaultClockImpl;
import com.rackspacecloud.blueflood.utils.TimeValue;
import com.rackspacecloud.blueflood.utils.Util;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.joda.time.Instant;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * A class to test the various implementation of PreaggregatedMetricsRW.
 */
public class PreaggregatedMetricsRWIntegrationTest extends IntegrationTestBase {

    private static final String TENANT1 = "123456";
    private static final String TENANT2 = "987654";
    private static final String TENANT3 = "123789";
    private static final TimeValue TTL = new TimeValue(24, TimeUnit.HOURS);

    protected LocatorIO locatorIO = new DLocatorIO();
    protected DelayedLocatorIO delayedLocatorIO = new DDelayedLocatorIO();
    protected DEnumIO enumIO = new DEnumIO();
    protected DPreaggregatedMetricsRW datastaxMetricsRW = new DPreaggregatedMetricsRW(enumIO, locatorIO, delayedLocatorIO, false, new DefaultClockImpl());
    protected APreaggregatedMetricsRW astyanaxMetricsRW = new APreaggregatedMetricsRW(false, new DefaultClockImpl());

    protected static final long MAX_AGE_ALLOWED = Configuration.getInstance().getLongProperty(CoreConfig.ROLLUP_DELAY_MILLIS);

    protected static Granularity DELAYED_METRICS_STORAGE_GRANULARITY =
            Granularity.getRollupGranularity(Configuration.getInstance().getStringProperty(CoreConfig.DELAYED_METRICS_STORAGE_GRANULARITY));

    protected Map<Locator, IMetric>  expectedLocatorMetricMap = new HashMap<Locator, IMetric>();
    protected IMetric timerMetric;
    protected long startTimestamp;

    @Before
    public void generateMetrics() throws Exception {
        startTimestamp = System.currentTimeMillis();

        Locator locator;
        String  className = this.getClass().getSimpleName();
        for ( String tenantId : Arrays.asList(TENANT1, TENANT2, TENANT3) ) {

            // generate counter
            BluefloodCounterRollup counterRollup = new BluefloodCounterRollup()
                    .withCount(RAND.nextInt(10))
                    .withRate(RAND.nextDouble())
                    .withSampleCount(RAND.nextInt(10));
            locator = Locator.createLocatorFromPathComponents(tenantId, className + ".my.metric.counter." + System.currentTimeMillis());
            PreaggregatedMetric pMetric = new PreaggregatedMetric(System.currentTimeMillis(), locator, new TimeValue(1, TimeUnit.DAYS), counterRollup);
            expectedLocatorMetricMap.put(locator, pMetric);
            MetadataCache.getInstance().put(locator, MetricMetadata.TYPE.name().toLowerCase(), null);
            MetadataCache.getInstance().put(locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.COUNTER.toString());

            // generate enum
            pMetric = getEnumMetric(this.getClass().getSimpleName() + ".my.enum.values." + System.currentTimeMillis(), tenantId, startTimestamp);
            expectedLocatorMetricMap.put(pMetric.getLocator(), pMetric);
            MetadataCache.getInstance().put(pMetric.getLocator(), MetricMetadata.TYPE.name().toLowerCase(), null);
            MetadataCache.getInstance().put(pMetric.getLocator(), MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString());

            // generate gauge
            BluefloodGaugeRollup gaugeRollup = new BluefloodGaugeRollup()
                    .withLatest(System.currentTimeMillis(), RAND.nextLong());
            gaugeRollup.setVariance(RAND.nextDouble());
            locator = Locator.createLocatorFromPathComponents(tenantId, className + ".my.metric.gauge." + System.currentTimeMillis());
            pMetric = new PreaggregatedMetric(System.currentTimeMillis(), locator, new TimeValue(1, TimeUnit.DAYS), gaugeRollup);
            expectedLocatorMetricMap.put(locator, pMetric);
            MetadataCache.getInstance().put(locator, MetricMetadata.TYPE.name().toLowerCase(), null);
            MetadataCache.getInstance().put(locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.GAUGE.toString());

            // generate set
            Set aSet = Sets.newHashSet(RAND.nextInt(), RAND.nextInt(), RAND.nextInt());
            BluefloodSetRollup setRollup = new BluefloodSetRollup().withObject(aSet);
            locator = Locator.createLocatorFromPathComponents(tenantId, className + ".my.metric.set." + System.currentTimeMillis());
            pMetric = new PreaggregatedMetric(System.currentTimeMillis(), locator, new TimeValue(1, TimeUnit.DAYS), setRollup);
            expectedLocatorMetricMap.put(locator, pMetric);
            MetadataCache.getInstance().put(locator, MetricMetadata.TYPE.name().toLowerCase(), null);
            MetadataCache.getInstance().put(locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.SET.toString());

            // generate timer
            BluefloodTimerRollup timerRollup = new BluefloodTimerRollup()
                    .withSampleCount(RAND.nextInt(10))
                    .withSum(RAND.nextDouble())
                    .withCountPS(RAND.nextDouble())
                    .withAverage(RAND.nextLong())
                    .withVariance(RAND.nextDouble())
                    .withMinValue(RAND.nextInt())
                    .withMaxValue(RAND.nextInt())
                    .withCount(RAND.nextInt(200));
            locator = Locator.createLocatorFromPathComponents(tenantId, className + ".my.metric.timer." + System.currentTimeMillis());
            timerMetric = new PreaggregatedMetric(System.currentTimeMillis(), locator, new TimeValue(1, TimeUnit.DAYS), timerRollup);
            expectedLocatorMetricMap.put(locator, timerMetric);
            MetadataCache.getInstance().put(locator, MetricMetadata.TYPE.name().toLowerCase(), null);
            MetadataCache.getInstance().put(locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.TIMER.toString());
        }
    }

    /**
     * This method is to supply the granularity parameter to some test methods below
     *
     * @return
     */
    protected Object getGranularitiesToTest() {
        return Granularity.granularities();
    }

    /**
     * Converts the input metrics from a map of locator -> IMetric to a list of
     * {@link com.rackspacecloud.blueflood.service.SingleRollupWriteContext}
     * objects
     *
     * @param inputMetrics
     * @return
     */
    protected List<SingleRollupWriteContext> toWriteContext(Map<Locator, IMetric> inputMetrics, Granularity destGran) {

        List<SingleRollupWriteContext> resultList = new ArrayList<SingleRollupWriteContext>();
        for ( Map.Entry<Locator, IMetric> entry : inputMetrics.entrySet() ) {
            Locator locator = entry.getKey();
            IMetric metric = entry.getValue();

            SingleRollupWriteContext writeContext =
                    new SingleRollupWriteContext(
                            (Rollup) metric.getMetricValue(),
                            locator,
                            destGran,
                            CassandraModel.getPreaggregatedColumnFamily(destGran),
                            metric.getCollectionTime());
            resultList.add(writeContext);
        }
        return resultList;

    }

    protected Collection<IMetric> toIMetricsCollection(Locator locator, Points<BluefloodTimerRollup> points) {
        List<IMetric> list = new ArrayList<IMetric>();
        for (Map.Entry<Long, Points.Point<BluefloodTimerRollup>> entry : points.getPoints().entrySet()) {
            PreaggregatedMetric metric = new PreaggregatedMetric(entry.getKey(), locator, TTL, entry.getValue().getData());
            list.add(metric);
        }
        return list;
    }

    /**
     * For a given list of locators, figure the shard they belong to and for all those shards
     * get all the locators in metric_locator column family
     *
     * @param ingestedLocators
     * @return
     * @throws IOException
     */
    protected Set<Locator> retrieveLocators(Set<Locator> ingestedLocators) throws IOException {

        Set<Long> shards = new HashSet<Long>();
        for (Locator locator: ingestedLocators) {
            long shard = (long) Util.getShard(locator.toString());
            shards.add(shard);
        }

        Set<Locator> locatorsFromDB = new HashSet<Locator>();
        for (Long shard: shards) {
            locatorsFromDB.addAll(locatorIO.getLocators(shard));
        }

        return locatorsFromDB;
    }

    /**
     * For a given list of metrics, figure out the shard and slot they belong to and for those
     * shard and slot combinations, get all the locators from metrics_delayed_locator column family.
     *
     * @param metrics
     * @return
     * @throws IOException
     */
    protected Set<Locator> retrieveLocatorsByShardAndSlot(List<IMetric> metrics) throws IOException {
        Set<String> slotKeys = new HashSet<String>();

        for (IMetric metric: metrics) {
            int shard = Util.getShard(metric.getLocator().toString());
            int slot = DELAYED_METRICS_STORAGE_GRANULARITY.slot(metric.getCollectionTime());
            SlotKey slotKey = SlotKey.of(DELAYED_METRICS_STORAGE_GRANULARITY, slot, shard);

            slotKeys.add(slotKey.toString());
        }

        Set<Locator> locatorsFromDB = new HashSet<Locator>();
        for (String slotKeyStr:  slotKeys) {
            locatorsFromDB.addAll(delayedLocatorIO.getLocators(SlotKey.parse(slotKeyStr)));
        }

        return locatorsFromDB;
    }

    /**
     * A class that test cross-driver data correctness. This one has all the data
     * written using Datastax and read using Astyanax.
     *
     */
    @RunWith(JUnitParamsRunner.class)
    public static class WriteDatastaxReadAstyanax extends PreaggregatedMetricsRWIntegrationTest {

        @Test
        @Parameters(method = "getGranularitiesToTest")
        public void testMultiMetricsDatapointsRange(Granularity granularity) throws Exception {

            // write with datastax
            datastaxMetricsRW.insertMetrics(expectedLocatorMetricMap.values(), granularity);

            // read with astyanaxRW.getDatapointsForRange()
            List<Locator> locators = new ArrayList<Locator>() {{
                addAll(expectedLocatorMetricMap.keySet());
            }};
            Map<Locator, MetricData> results = astyanaxMetricsRW.getDatapointsForRange(
                    locators,
                    getRangeFromMinAgoToNow(5),
                    granularity);

            Assert.assertEquals("number of locators", expectedLocatorMetricMap.keySet().size(), results.keySet().size());

            for ( Map.Entry<Locator, IMetric> entry : expectedLocatorMetricMap.entrySet() ) {
                Locator locator = entry.getKey();

                MetricData metricData = results.get(locator);
                Assert.assertNotNull(String.format("metric data for locator %s exists", locator), metricData);

                Points points = metricData.getData();
                Map<Long, Points.Point> pointMap = points.getPoints();
                Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

                IMetric expectedMetric = entry.getValue();
                Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                        pointMap.get(expectedMetric.getCollectionTime())));

                Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
                Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));
            }

            Set<Locator> ingestedLocators = expectedLocatorMetricMap.keySet();
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));

            Set<Locator> locatorsFromDBByShardAndSlot = retrieveLocatorsByShardAndSlot(new ArrayList<IMetric>(expectedLocatorMetricMap.values()));
            assertTrue("Locators which are not delayed identified as delayed", Collections.disjoint(locatorsFromDBByShardAndSlot, locators));
        }

        @Test
        @Parameters(method = "getGranularitiesToTest")
        public void testMultiMetricsDatapointsRangeWithDelayedMetrics(Granularity granularity) throws Exception {

            Clock clock = mock(Clock.class);
            final Locator locator1 = expectedLocatorMetricMap.keySet().iterator().next();
            when(clock.now()).thenReturn(new Instant(expectedLocatorMetricMap.get(locator1).getCollectionTime() + MAX_AGE_ALLOWED + 1000));

            // write with datastax
            DPreaggregatedMetricsRW datastaxMetricsRW1 = new DPreaggregatedMetricsRW(enumIO, locatorIO, delayedLocatorIO, true, clock);
            datastaxMetricsRW1.insertMetrics(expectedLocatorMetricMap.values(), granularity);

            // read with astyanaxRW.getDatapointsForRange()
            List<Locator> locators = new ArrayList<Locator>() {{
                addAll(expectedLocatorMetricMap.keySet());
            }};
            Map<Locator, MetricData> results = astyanaxMetricsRW.getDatapointsForRange(
                    locators,
                    getRangeFromMinAgoToNow(5),
                    granularity);

            Assert.assertEquals("number of locators", expectedLocatorMetricMap.keySet().size(), results.keySet().size());

            for ( Map.Entry<Locator, IMetric> entry : expectedLocatorMetricMap.entrySet() ) {
                Locator locator = entry.getKey();

                MetricData metricData = results.get(locator);
                Assert.assertNotNull(String.format("metric data for locator %s exists", locator), metricData);

                Points points = metricData.getData();
                Map<Long, Points.Point> pointMap = points.getPoints();
                Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

                IMetric expectedMetric = entry.getValue();
                Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                        pointMap.get(expectedMetric.getCollectionTime())));

                Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
                Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));
            }

            Set<Locator> ingestedLocators = expectedLocatorMetricMap.keySet();
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));

            Set<Locator> locatorsFromDBByShardAndSlot = retrieveLocatorsByShardAndSlot(new ArrayList<IMetric>(expectedLocatorMetricMap.values()));
            locatorsFromDBByShardAndSlot.retainAll(ingestedLocators);
            assertEquals("Locators which are not delayed identified as delayed", locators.size(), locatorsFromDBByShardAndSlot.size());
        }

        @Test
        @Parameters(method = "getGranularitiesToTest")
        public void testInsertRollups(Granularity granularity) throws Exception {

            // write with datastax
            List<SingleRollupWriteContext> writeContexts = toWriteContext(expectedLocatorMetricMap, granularity);
            datastaxMetricsRW.insertRollups(writeContexts);

            List<Locator> locators = new ArrayList<Locator>() {{
                addAll(expectedLocatorMetricMap.keySet());
            }};
            // read with astyanax
            Map<Locator, MetricData> results = astyanaxMetricsRW.getDatapointsForRange(
                    locators,
                    getRangeFromMinAgoToNow(5),
                    granularity);

            Assert.assertEquals("number of locators", expectedLocatorMetricMap.keySet().size(), results.keySet().size());

            for ( Map.Entry<Locator, IMetric> entry : expectedLocatorMetricMap.entrySet() ) {
                Locator locator = entry.getKey();

                MetricData metricData = results.get(locator);
                Assert.assertNotNull(String.format("metric data for locator %s exists", locator), metricData);

                Points points = metricData.getData();
                Map<Long, Points.Point> pointMap = points.getPoints();
                Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

                IMetric expectedMetric = entry.getValue();
                Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                        pointMap.get(expectedMetric.getCollectionTime())));

                Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
                Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));
            }
        }

        @Test
        public void testSingleMetricDatapointForRange() throws Exception {

            // write with datastax
            datastaxMetricsRW.insertMetrics(expectedLocatorMetricMap.values());

            // pick first locator from input metrics, read with Astyanax.getDataToRollup
            final Locator locator = expectedLocatorMetricMap.keySet().iterator().next();
            IMetric expectedMetric = expectedLocatorMetricMap.get(locator);
            MetricData metricData =
                    astyanaxMetricsRW.getDatapointsForRange (locator,
                            getRangeFromMinAgoToNow(5),
                            Granularity.FULL);

            Points points = metricData.getData();
            Map<Long, Points.Point> pointMap = points.getPoints();
            Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

            Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                    pointMap.get(expectedMetric.getCollectionTime())));

            Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
            Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));

            Set<Locator> ingestedLocators = new HashSet<Locator>(){{ add(locator); }};
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));
        }

        @Test
        public void testSingleMetricDatapointForRangeWithDelayedMetrics() throws Exception {

            Clock clock = mock(Clock.class);
            final Locator locator = expectedLocatorMetricMap.keySet().iterator().next();
            when(clock.now()).thenReturn(new Instant(expectedLocatorMetricMap.get(locator).getCollectionTime() + MAX_AGE_ALLOWED + 1));

            // write with datastax
            DPreaggregatedMetricsRW datastaxMetricsRW1 = new DPreaggregatedMetricsRW(enumIO, locatorIO, delayedLocatorIO, true, clock);
            datastaxMetricsRW1.insertMetrics(expectedLocatorMetricMap.values());

            // pick first locator from input metrics, read with Astyanax.getDataToRollup
            IMetric expectedMetric = expectedLocatorMetricMap.get(locator);
            MetricData metricData =
                    astyanaxMetricsRW.getDatapointsForRange (locator,
                            getRangeFromMinAgoToNow(5),
                            Granularity.FULL);

            Points points = metricData.getData();
            Map<Long, Points.Point> pointMap = points.getPoints();
            Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

            Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                    pointMap.get(expectedMetric.getCollectionTime())));

            Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
            Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));

            Set<Locator> ingestedLocators = new HashSet<Locator>(){{ add(locator); }};
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));

            List<IMetric> ingestedDelayedMetrics = new ArrayList<IMetric>(){{ add(expectedLocatorMetricMap.get(locator)); }};
            Set<Locator> ingestedDelayedLocators = new HashSet<Locator>(){{ add(locator); }};
            Set<Locator> locatorsFromDBByShardAndSlot = retrieveLocatorsByShardAndSlot(ingestedDelayedMetrics);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDBByShardAndSlot.containsAll(ingestedDelayedLocators));
        }

        @Test
        public void testSingleMetricDataToRollup() throws Exception {

            // write with datastax
            datastaxMetricsRW.insertMetrics(expectedLocatorMetricMap.values());

            // pick first locator from input metrics, read with Astyanax.getDataToRollup
            Locator locator = expectedLocatorMetricMap.keySet().iterator().next();
            IMetric expectedMetric = expectedLocatorMetricMap.get(locator);
            Points points =
                    astyanaxMetricsRW.getDataToRollup(locator,
                            expectedMetric.getRollupType(),
                            getRangeFromMinAgoToNow(5),
                            CassandraModel.CF_METRICS_PREAGGREGATED_FULL_NAME);

            Map<Long, Points.Point> pointMap = points.getPoints();
            Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

            Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                    pointMap.get(expectedMetric.getCollectionTime())));

            Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
            Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));

        }

    }

    /**
     * A class that test cross-driver data correctness. This one has all the data
     * written using Datastax and read using Astyanax.
     *
     */
    @RunWith(JUnitParamsRunner.class)
    public static class WriteAstyanaxReadDatastax extends PreaggregatedMetricsRWIntegrationTest {

        @Test
        @Parameters(method = "getGranularitiesToTest")
        public void testMultiMetricsDatapointsRange(Granularity granularity) throws Exception {

            // write with astyanax
            astyanaxMetricsRW.insertMetrics(expectedLocatorMetricMap.values(), granularity);

            List<Locator> locators = new ArrayList<Locator>() {{
                addAll(expectedLocatorMetricMap.keySet());
            }};
            // read with datastax
            Map<Locator, MetricData> results = datastaxMetricsRW.getDatapointsForRange(
                    locators,
                    getRangeFromMinAgoToNow(5),
                    granularity);

            Assert.assertEquals("number of locators", expectedLocatorMetricMap.keySet().size(), results.keySet().size());

            for ( Map.Entry<Locator, IMetric> entry : expectedLocatorMetricMap.entrySet() ) {
                Locator locator = entry.getKey();

                MetricData metricData = results.get(locator);
                Assert.assertNotNull(String.format("metric data for locator %s exists", locator), metricData);

                Points points = metricData.getData();
                Map<Long, Points.Point> pointMap = points.getPoints();
                Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

                IMetric expectedMetric = entry.getValue();
                Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                        pointMap.get(expectedMetric.getCollectionTime())));

                Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
                Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));
            }

            Set<Locator> ingestedLocators = expectedLocatorMetricMap.keySet();
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));

            Set<Locator> locatorsFromDBByShardAndSlot = retrieveLocatorsByShardAndSlot(new ArrayList<IMetric>(expectedLocatorMetricMap.values()));
            assertTrue("Locators which are not delayed identified as delayed", Collections.disjoint(locatorsFromDBByShardAndSlot, locators));
        }

        @Test
        @Parameters(method = "getGranularitiesToTest")
        public void testMultiMetricsDatapointsRangeWithDelayedMetrics(Granularity granularity) throws Exception {

            Clock clock = mock(Clock.class);
            final Locator locator1 = expectedLocatorMetricMap.keySet().iterator().next();
            when(clock.now()).thenReturn(new Instant(expectedLocatorMetricMap.get(locator1).getCollectionTime() + MAX_AGE_ALLOWED + 1000));

            // write with astyanax
            APreaggregatedMetricsRW astyanaxMetricsRW1 = new APreaggregatedMetricsRW(true, clock);
            astyanaxMetricsRW1.insertMetrics(expectedLocatorMetricMap.values(), granularity);

            List<Locator> locators = new ArrayList<Locator>() {{
                addAll(expectedLocatorMetricMap.keySet());
            }};
            // read with datastax
            Map<Locator, MetricData> results = datastaxMetricsRW.getDatapointsForRange(
                    locators,
                    getRangeFromMinAgoToNow(5),
                    granularity);

            Assert.assertEquals("number of locators", expectedLocatorMetricMap.keySet().size(), results.keySet().size());

            for ( Map.Entry<Locator, IMetric> entry : expectedLocatorMetricMap.entrySet() ) {
                Locator locator = entry.getKey();

                MetricData metricData = results.get(locator);
                Assert.assertNotNull(String.format("metric data for locator %s exists", locator), metricData);

                Points points = metricData.getData();
                Map<Long, Points.Point> pointMap = points.getPoints();
                Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

                IMetric expectedMetric = entry.getValue();
                Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                        pointMap.get(expectedMetric.getCollectionTime())));

                Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
                Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));
            }

            Set<Locator> ingestedLocators = expectedLocatorMetricMap.keySet();
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));

            Set<Locator> locatorsFromDBByShardAndSlot = retrieveLocatorsByShardAndSlot(new ArrayList<IMetric>(expectedLocatorMetricMap.values()));
            locatorsFromDBByShardAndSlot.retainAll(ingestedLocators);
            assertEquals("Locators which are not delayed identified as delayed", locators.size(), locatorsFromDBByShardAndSlot.size());
        }

        @Test
        @Parameters(method = "getGranularitiesToTest")
        public void testInsertRollups(Granularity granularity) throws Exception {

            // write with astyanax
            List<SingleRollupWriteContext> writeContexts = toWriteContext(expectedLocatorMetricMap, granularity);
            astyanaxMetricsRW.insertRollups(writeContexts);

            // read with datastax
            List<Locator> locators = new ArrayList<Locator>() {{
                addAll(expectedLocatorMetricMap.keySet());
            }};
            // read with datastax
            Map<Locator, MetricData> results = datastaxMetricsRW.getDatapointsForRange(
                    locators,
                    getRangeFromMinAgoToNow(5),
                    granularity);

            Assert.assertEquals("number of locators", expectedLocatorMetricMap.keySet().size(), results.keySet().size());

            for ( Map.Entry<Locator, IMetric> entry : expectedLocatorMetricMap.entrySet() ) {
                Locator locator = entry.getKey();

                MetricData metricData = results.get(locator);
                Assert.assertNotNull(String.format("metric data for locator %s exists", locator), metricData);

                Points points = metricData.getData();
                Map<Long, Points.Point> pointMap = points.getPoints();
                Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

                IMetric expectedMetric = entry.getValue();
                Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                        pointMap.get(expectedMetric.getCollectionTime())));

                Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
                Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));
            }
        }

        @Test
        public void testSingleMetricDatapointForRange() throws Exception {

            // write with astyanax
            astyanaxMetricsRW.insertMetrics(expectedLocatorMetricMap.values());

            // pick first locator from input metrics, read with Astyanax.getDataToRollup
            final Locator locator = expectedLocatorMetricMap.keySet().iterator().next();
            IMetric expectedMetric = expectedLocatorMetricMap.get(locator);
            MetricData metricData =
                    datastaxMetricsRW.getDatapointsForRange (locator,
                            getRangeFromMinAgoToNow(5),
                            Granularity.FULL);

            Points points = metricData.getData();
            Map<Long, Points.Point> pointMap = points.getPoints();
            Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

            Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                    pointMap.get(expectedMetric.getCollectionTime())));

            Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
            Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));

            Set<Locator> ingestedLocators = new HashSet<Locator>(){{ add(locator); }};
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));

            List<IMetric> ingestedDelayedMetrics = new ArrayList<IMetric>(){{ add(expectedLocatorMetricMap.get(locator)); }};
            Set<Locator> locatorsFromDBByShardAndSlot = retrieveLocatorsByShardAndSlot(ingestedDelayedMetrics);
            assertEquals("Locators which are not delayed identified as delayed", 0, locatorsFromDBByShardAndSlot.size());
        }

        @Test
        public void testSingleMetricDatapointForRangeWithDelayedMetrics() throws Exception {

            Clock clock = mock(Clock.class);
            final Locator locator = expectedLocatorMetricMap.keySet().iterator().next();
            when(clock.now()).thenReturn(new Instant(expectedLocatorMetricMap.get(locator).getCollectionTime() + MAX_AGE_ALLOWED + 1));

            // write with astyanax
            APreaggregatedMetricsRW astyanaxMetricsRW1 = new APreaggregatedMetricsRW(true, clock);
            astyanaxMetricsRW1.insertMetrics(expectedLocatorMetricMap.values());

            // pick first locator from input metrics, read with Astyanax.getDataToRollup
            IMetric expectedMetric = expectedLocatorMetricMap.get(locator);
            MetricData metricData =
                    datastaxMetricsRW.getDatapointsForRange (locator,
                            getRangeFromMinAgoToNow(5),
                            Granularity.FULL);

            Points points = metricData.getData();
            Map<Long, Points.Point> pointMap = points.getPoints();
            Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

            Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                    pointMap.get(expectedMetric.getCollectionTime())));

            Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
            Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));

            Set<Locator> ingestedLocators = new HashSet<Locator>(){{ add(locator); }};
            Set<Locator> locatorsFromDB = retrieveLocators(ingestedLocators);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDB.containsAll(ingestedLocators));

            List<IMetric> ingestedDelayedMetrics = new ArrayList<IMetric>(){{ add(expectedLocatorMetricMap.get(locator)); }};
            Set<Locator> ingestedDelayedLocators = new HashSet<Locator>(){{ add(locator); }};
            Set<Locator> locatorsFromDBByShardAndSlot = retrieveLocatorsByShardAndSlot(ingestedDelayedMetrics);
            assertTrue("Some of the ingested locator's missing from db", locatorsFromDBByShardAndSlot.containsAll(ingestedDelayedLocators));
        }

        @Test
        public void testSingleMetricDataToRollup() throws Exception {

            // write with astyanax
            astyanaxMetricsRW.insertMetrics(expectedLocatorMetricMap.values());

            // pick first locator from input metrics, read with datastaxRW.getDataToRollup
            Locator locator = expectedLocatorMetricMap.keySet().iterator().next();
            IMetric expectedMetric = expectedLocatorMetricMap.get(locator);
            Points points =
                    datastaxMetricsRW.getDataToRollup(locator,
                            expectedMetric.getRollupType(),
                            getRangeFromMinAgoToNow(5),
                            CassandraModel.CF_METRICS_PREAGGREGATED_FULL_NAME);

            Map<Long, Points.Point> pointMap = points.getPoints();
            Assert.assertEquals(String.format("number of points for locator %s", locator), 1, pointMap.values().size());

            Assert.assertNotNull(String.format("point for locator %s at timestamp %s exists", locator, expectedMetric.getCollectionTime(),
                    pointMap.get(expectedMetric.getCollectionTime())));

            Points.Point point = pointMap.get(expectedMetric.getCollectionTime());
            Assert.assertTrue(String.format("locator %s data is the same", locator), expectedMetric.getMetricValue().equals(point.getData()));

        }
    }

    @RunWith(JUnitParamsRunner.class)
    public static class OtherFunctionalities extends PreaggregatedMetricsRWIntegrationTest {

        @Test
        @Parameters(method="getGranularitiesToTest")
        public void testSingleMetricTtlWorks(Granularity granularity) throws Exception {

            // pick first locator from input metrics
            Locator locator = expectedLocatorMetricMap.keySet().iterator().next();
            IMetric expectedMetric = expectedLocatorMetricMap.get(locator);

            // put it, with TTL 2 seconds
            expectedMetric.setTtlInSeconds(2);
            datastaxMetricsRW.insertMetrics(Lists.newArrayList(expectedMetric), granularity);

            // read it quickly.
            Points<BluefloodTimerRollup> points =
                    datastaxMetricsRW.getDataToRollup(locator,
                            expectedMetric.getRollupType(),
                            getRangeFromMinAgoToNow(5),
                            CassandraModel.getPreaggregatedColumnFamilyName(granularity));
            Assert.assertEquals("number of points read before TTL", 1, points.getPoints().size());

            // let it time out.
            Thread.sleep(2000);

            // ensure it is gone.
            points = datastaxMetricsRW.getDataToRollup(locator,
                    expectedMetric.getRollupType(),
                    getRangeFromMinAgoToNow(5),
                    CassandraModel.getPreaggregatedColumnFamilyName(granularity));
            Assert.assertEquals("number of points read after TTL", 0, points.getPoints().size());
        }

        @Test
        public void testHigherGranReadWrite() throws Exception {

            // pick a granularity
            Granularity granularity = Granularity.MIN_60;

            // insert metric
            datastaxMetricsRW.insertMetrics(Lists.newArrayList(timerMetric), granularity);

            // read the raw data.
            Points<BluefloodTimerRollup> points =
                    datastaxMetricsRW.getDataToRollup(timerMetric.getLocator(),
                            timerMetric.getRollupType(),
                            getRangeFromMinAgoToNow(5),
                            CassandraModel.getPreaggregatedColumnFamilyName(granularity));
            Assert.assertEquals("number of points read", 1, points.getPoints().size());

            // create the rollup
            final BluefloodTimerRollup rollup = BluefloodTimerRollup.buildRollupFromTimerRollups(points);
            // should be the same as simpletimerRollup   Assert.assertEquals(timerRollup, rollup);

            // assemble it into points, but give it a new timestamp.
            points = new Points<BluefloodTimerRollup>() {{
                add(new Point<BluefloodTimerRollup>(timerMetric.getCollectionTime(), rollup));
            }};
            Collection<IMetric> toWrite = toIMetricsCollection(timerMetric.getLocator(), points);
            datastaxMetricsRW.insertMetrics(toWrite, granularity.coarser());

            // we should be able to read that now.
            Points<BluefloodTimerRollup> pointsCoarser =
                    datastaxMetricsRW.getDataToRollup(
                            timerMetric.getLocator(),
                            RollupType.TIMER,
                            getRangeFromMinAgoToNow(5),
                            CassandraModel.getPreaggregatedColumnFamilyName(granularity.coarser()));

            Assert.assertEquals("number of points read in coarser gran", 1, pointsCoarser.getPoints().size());

            BluefloodTimerRollup rollupCoarser = pointsCoarser.getPoints().values().iterator().next().getData();
            // rollups should be identical since one is just a coarse rollup of the other.
            Assert.assertEquals("rollup read in coarser gran is the same", rollup, rollupCoarser);
        }

        @Test
        public void testLocatorWritten() throws Exception {

            // insert metrics using datastax
            datastaxMetricsRW.insertMetrics(expectedLocatorMetricMap.values());

            LocatorIO locatorIO = IOContainer.fromConfig().getLocatorIO();
            for ( Locator locator : expectedLocatorMetricMap.keySet() ) {
                long shard = Util.getShard(locator.toString());
                Collection<Locator> locators = locatorIO.getLocators(shard);
                Assert.assertTrue(String.format("locator %s should exist", locator), locators.contains(locator));
            }
        }

    }
}


text:
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("react"), require("lcars"));
	else if(typeof define === 'function' && define.amd)
		define(["react", "react"], factory);
	else if(typeof exports === 'object')
		exports["Portal"] = factory(require("react"), require("lcars"));
	else
		root["Portal"] = factory(root["React"], root["LCARS"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_7__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "http://localhost:8180/dist";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = __webpack_require__(8);

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	/**
	 * Copyright 2013-2015, Facebook, Inc.
	 * All rights reserved.
	 *
	 * This source code is licensed under the BSD-style license found in the
	 * LICENSE file in the root directory of this source tree. An additional grant
	 * of patent rights can be found in the PATENTS file in the same directory.
	 *
	 * @providesModule keyMirror
	 * @typechecks static-only
	 */

	'use strict';

	var invariant = __webpack_require__(10);

	/**
	 * Constructs an enumeration with keys equal to their value.
	 *
	 * For example:
	 *
	 *   var COLORS = keyMirror({blue: null, red: null});
	 *   var myColor = COLORS.blue;
	 *   var isColorValid = !!COLORS[myColor];
	 *
	 * The last line could not be performed if the values of the generated enum were
	 * not equal to their keys.
	 *
	 *   Input:  {key1: val1, key2: val2}
	 *   Output: {key1: key1, key2: key2}
	 *
	 * @param {object} obj
	 * @return {object}
	 */
	var keyMirror = function(obj) {
	  var ret = {};
	  var key;
	  (true ? invariant(
	    obj instanceof Object && !Array.isArray(obj),
	    'keyMirror(...): Argument must be an object.'
	  ) : invariant(obj instanceof Object && !Array.isArray(obj)));
	  for (key in obj) {
	    if (!obj.hasOwnProperty(key)) {
	      continue;
	    }
	    ret[key] = key;
	  }
	  return ret;
	};

	module.exports = keyMirror;

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var React = __webpack_require__(4);
	var Freighter = __webpack_require__(9);
	var PortalStore = __webpack_require__(5);
	var PortalActions = __webpack_require__(6);

	var Portal = React.createClass({
	  displayName: 'Portal',

	  mixins: [Freighter],

	  stores: [PortalStore],

	  propTypes: {
	    children: React.PropTypes.element.isRequired,
	    onClose: React.PropTypes.func
	  },

	  getStateFromStores: function getStateFromStores() {
	    return PortalStore.getStoreData();
	  },

	  componentWillMount: function componentWillMount() {
	    if (this.state.active) {
	      this.openPortal();
	    }
	  },

	  componentWillUnmount: function componentWillUnmount() {
	    this.closePortal();
	  },

	  closePortal: function closePortal() {
	    if (this.node) {
	      React.unmountComponentAtNode(this.node);
	      document.body.removeChild(this.node);
	    }
	    this.portal = null;
	    this.node = null;
	  },

	  handleClose: function handleClose() {
	    PortalActions.close();
	  },

	  renderPortal: function renderPortal() {
	    if (!this.node) {
	      this.node = document.createElement('div');
	      document.body.appendChild(this.node);
	      this.portal = React.render(React.cloneElement(this.props.children, { handleClose: this.handleClose }), this.node);
	    }
	    PortalActions.open();
	  },

	  componentDidUpdate: function componentDidUpdate() {
	    switch (this.state.active) {
	      case false:
	        this.closePortal();
	        break;
	      case true:
	        if (this.node) {
	          this.portal = React.render(React.cloneElement(this.props.children, { handleClose: this.handleClose }), this.node);
	        }
	        break;
	    }
	  },

	  openPortal: function openPortal(e) {
	    if (e) {
	      e.preventDefault();
	      e.stopPropagation();
	    }
	    this.renderPortal();
	  },

	  render: function render() {
	    if (this.props.openByClickOn) {
	      return React.createElement(
	        'div',
	        { className: 'Portal__open-by-click-on', onClick: this.openPortal },
	        this.props.openByClickOn
	      );
	    } else {
	      return null;
	    }
	  }

	});

	module.exports = Portal;

/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var keyMirror = __webpack_require__(1);

	var PortalConstants = {
	  PORTAL: keyMirror({
	    OPEN: null,
	    CLOSE: null
	  })
	};

	module.exports = PortalConstants;

/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = __WEBPACK_EXTERNAL_MODULE_4__;

/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var LCARS = __webpack_require__(7);
	var CargoBay = __webpack_require__(12);
	var merge = __webpack_require__(11);
	var PortalConstants = __webpack_require__(3);

	var StoreData = {
	  _data: {
	    active: false
	  },
	  clonedData: function clonedData() {
	    return JSON.parse(JSON.stringify(this._data));
	  }
	};

	var PortalStore = merge(CargoBay, {
	  set: function set(key, value) {
	    StoreData._data[key] = value;
	    return StoreData.clonedData();
	  },
	  getStoreData: function getStoreData() {
	    return StoreData.clonedData();
	  }
	});

	PortalStore.dispatchToken = LCARS.register(function (action) {
	  switch (action.type) {
	    case PortalConstants.PORTAL.OPEN:
	      PortalStore.set('active', true);
	      PortalStore.emitChange();
	      break;
	    case PortalConstants.PORTAL.CLOSE:
	      PortalStore.set('active', false);
	      PortalStore.emitChange();
	      break;
	  }
	});

	module.exports = PortalStore;

/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var LCARS = __webpack_require__(7);
	var PortalConstants = __webpack_require__(3);

	var PortalActions = {
	  open: function open() {
	    LCARS.dispatch({
	      type: PortalConstants.PORTAL.OPEN
	    });
	  },
	  close: function close() {
	    LCARS.dispatch({
	      type: PortalConstants.PORTAL.CLOSE
	    });
	  }
	};

	module.exports = PortalActions;

/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = __WEBPACK_EXTERNAL_MODULE_7__;

/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var PortalComponent = __webpack_require__(2);
	var PortalConstants = __webpack_require__(3);

	module.exports = {
	  component: PortalComponent,
	  constants: PortalConstants
	};

/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var Freighter = {

	  getInitialState: function(){
	    return this.getStateFromStores();
	  },

	  componentDidMount: function(){
	    if (!this.stores){
	      throw new Error('You must have a stores array property https://github.com/sstate/freighter/blob/master/examples/app.js#L12');
	    }
	    this.stores.forEach(function(store){
	      store.addChangeListener(this.handleStoresChanged);
	    }, this);
	  },

	  componentWillUnmount: function(){
	    this.stores.forEach(function(store){
	      store.removeChangeListener(this.handleStoresChanged);
	    }, this);
	  },

	  handleStoresChanged: function(){
	    if (this.isMounted()) {
	      this.setState(this.getStateFromStores());
	    }
	  }

	};

	module.exports = Freighter;

/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {

	/**
	 * Copyright 2013-2015, Facebook, Inc.
	 * All rights reserved.
	 *
	 * This source code is licensed under the BSD-style license found in the
	 * LICENSE file in the root directory of this source tree. An additional grant
	 * of patent rights can be found in the PATENTS file in the same directory.
	 *
	 * @providesModule invariant
	 */

	"use strict";

	/**
	 * Use invariant() to assert state which your program assumes to be true.
	 *
	 * Provide sprintf-style format (only %s is supported) and arguments
	 * to provide information about what broke and what you were
	 * expecting.
	 *
	 * The invariant message will be stripped in production, but the invariant
	 * will remain to ensure logic does not differ in production.
	 */

	var invariant = function(condition, format, a, b, c, d, e, f) {
	  if (true) {
	    if (format === undefined) {
	      throw new Error('invariant requires an error message argument');
	    }
	  }

	  if (!condition) {
	    var error;
	    if (format === undefined) {
	      error = new Error(
	        'Minified exception occurred; use the non-minified dev environment ' +
	        'for the full error message and additional helpful warnings.'
	      );
	    } else {
	      var args = [a, b, c, d, e, f];
	      var argIndex = 0;
	      error = new Error(
	        'Invariant Violation: ' +
	        format.replace(/%s/g, function() { return args[argIndex++]; })
	      );
	    }

	    error.framesToPop = 1; // we don't care about invariant's own frame
	    throw error;
	  }
	};

	module.exports = invariant;

/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {

	var extend = __webpack_require__(14);

	module.exports = function merge() {
	    var args = [].slice.call(arguments);
	    args.unshift({});
	    return extend.apply(this, args);
	};

/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var EventEmitter = __webpack_require__(13).EventEmitter;
	var merge = __webpack_require__(11);
	var CHANGE_EVENT = 'change';
	var _current_cid = 0;

	var CargoBay = merge(EventEmitter.prototype, {

	  emitChange: function() {
	    this.emit(CHANGE_EVENT);
	  },

	  addChangeListener: function(callback) {
	    this.on(CHANGE_EVENT, callback);
	  },

	  removeChangeListener: function(callback) {
	    this.removeListener(CHANGE_EVENT, callback);
	  },

	  generateCID: function() {
	    return _current_cid++;
	  }

	});

	CargoBay.setMaxListeners(50);

	module.exports = CargoBay;

/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {

	// Copyright Joyent, Inc. and other Node contributors.
	//
	// Permission is hereby granted, free of charge, to any person obtaining a
	// copy of this software and associated documentation files (the
	// "Software"), to deal in the Software without restriction, including
	// without limitation the rights to use, copy, modify, merge, publish,
	// distribute, sublicense, and/or sell copies of the Software, and to permit
	// persons to whom the Software is furnished to do so, subject to the
	// following conditions:
	//
	// The above copyright notice and this permission notice shall be included
	// in all copies or substantial portions of the Software.
	//
	// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
	// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
	// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
	// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
	// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
	// USE OR OTHER DEALINGS IN THE SOFTWARE.

	function EventEmitter() {
	  this._events = this._events || {};
	  this._maxListeners = this._maxListeners || undefined;
	}
	module.exports = EventEmitter;

	// Backwards-compat with node 0.10.x
	EventEmitter.EventEmitter = EventEmitter;

	EventEmitter.prototype._events = undefined;
	EventEmitter.prototype._maxListeners = undefined;

	// By default EventEmitters will print a warning if more than 10 listeners are
	// added to it. This is a useful default which helps finding memory leaks.
	EventEmitter.defaultMaxListeners = 10;

	// Obviously not all Emitters should be limited to 10. This function allows
	// that to be increased. Set to zero for unlimited.
	EventEmitter.prototype.setMaxListeners = function(n) {
	  if (!isNumber(n) || n < 0 || isNaN(n))
	    throw TypeError('n must be a positive number');
	  this._maxListeners = n;
	  return this;
	};

	EventEmitter.prototype.emit = function(type) {
	  var er, handler, len, args, i, listeners;

	  if (!this._events)
	    this._events = {};

	  // If there is no 'error' event listener then throw.
	  if (type === 'error') {
	    if (!this._events.error ||
	        (isObject(this._events.error) && !this._events.error.length)) {
	      er = arguments[1];
	      if (er instanceof Error) {
	        throw er; // Unhandled 'error' event
	      }
	      throw TypeError('Uncaught, unspecified "error" event.');
	    }
	  }

	  handler = this._events[type];

	  if (isUndefined(handler))
	    return false;

	  if (isFunction(handler)) {
	    switch (arguments.length) {
	      // fast cases
	      case 1:
	        handler.call(this);
	        break;
	      case 2:
	        handler.call(this, arguments[1]);
	        break;
	      case 3:
	        handler.call(this, arguments[1], arguments[2]);
	        break;
	      // slower
	      default:
	        len = arguments.length;
	        args = new Array(len - 1);
	        for (i = 1; i < len; i++)
	          args[i - 1] = arguments[i];
	        handler.apply(this, args);
	    }
	  } else if (isObject(handler)) {
	    len = arguments.length;
	    args = new Array(len - 1);
	    for (i = 1; i < len; i++)
	      args[i - 1] = arguments[i];

	    listeners = handler.slice();
	    len = listeners.length;
	    for (i = 0; i < len; i++)
	      listeners[i].apply(this, args);
	  }

	  return true;
	};

	EventEmitter.prototype.addListener = function(type, listener) {
	  var m;

	  if (!isFunction(listener))
	    throw TypeError('listener must be a function');

	  if (!this._events)
	    this._events = {};

	  // To avoid recursion in the case that type === "newListener"! Before
	  // adding it to the listeners, first emit "newListener".
	  if (this._events.newListener)
	    this.emit('newListener', type,
	              isFunction(listener.listener) ?
	              listener.listener : listener);

	  if (!this._events[type])
	    // Optimize the case of one listener. Don't need the extra array object.
	    this._events[type] = listener;
	  else if (isObject(this._events[type]))
	    // If we've already got an array, just append.
	    this._events[type].push(listener);
	  else
	    // Adding the second element, need to change to array.
	    this._events[type] = [this._events[type], listener];

	  // Check for listener leak
	  if (isObject(this._events[type]) && !this._events[type].warned) {
	    var m;
	    if (!isUndefined(this._maxListeners)) {
	      m = this._maxListeners;
	    } else {
	      m = EventEmitter.defaultMaxListeners;
	    }

	    if (m && m > 0 && this._events[type].length > m) {
	      this._events[type].warned = true;
	      console.error('(node) warning: possible EventEmitter memory ' +
	                    'leak detected. %d listeners added. ' +
	                    'Use emitter.setMaxListeners() to increase limit.',
	                    this._events[type].length);
	      if (typeof console.trace === 'function') {
	        // not supported in IE 10
	        console.trace();
	      }
	    }
	  }

	  return this;
	};

	EventEmitter.prototype.on = EventEmitter.prototype.addListener;

	EventEmitter.prototype.once = function(type, listener) {
	  if (!isFunction(listener))
	    throw TypeError('listener must be a function');

	  var fired = false;

	  function g() {
	    this.removeListener(type, g);

	    if (!fired) {
	      fired = true;
	      listener.apply(this, arguments);
	    }
	  }

	  g.listener = listener;
	  this.on(type, g);

	  return this;
	};

	// emits a 'removeListener' event iff the listener was removed
	EventEmitter.prototype.removeListener = function(type, listener) {
	  var list, position, length, i;

	  if (!isFunction(listener))
	    throw TypeError('listener must be a function');

	  if (!this._events || !this._events[type])
	    return this;

	  list = this._events[type];
	  length = list.length;
	  position = -1;

	  if (list === listener ||
	      (isFunction(list.listener) && list.listener === listener)) {
	    delete this._events[type];
	    if (this._events.removeListener)
	      this.emit('removeListener', type, listener);

	  } else if (isObject(list)) {
	    for (i = length; i-- > 0;) {
	      if (list[i] === listener ||
	          (list[i].listener && list[i].listener === listener)) {
	        position = i;
	        break;
	      }
	    }

	    if (position < 0)
	      return this;

	    if (list.length === 1) {
	      list.length = 0;
	      delete this._events[type];
	    } else {
	      list.splice(position, 1);
	    }

	    if (this._events.removeListener)
	      this.emit('removeListener', type, listener);
	  }

	  return this;
	};

	EventEmitter.prototype.removeAllListeners = function(type) {
	  var key, listeners;

	  if (!this._events)
	    return this;

	  // not listening for removeListener, no need to emit
	  if (!this._events.removeListener) {
	    if (arguments.length === 0)
	      this._events = {};
	    else if (this._events[type])
	      delete this._events[type];
	    return this;
	  }

	  // emit removeListener for all listeners on all events
	  if (arguments.length === 0) {
	    for (key in this._events) {
	      if (key === 'removeListener') continue;
	      this.removeAllListeners(key);
	    }
	    this.removeAllListeners('removeListener');
	    this._events = {};
	    return this;
	  }

	  listeners = this._events[type];

	  if (isFunction(listeners)) {
	    this.removeListener(type, listeners);
	  } else {
	    // LIFO order
	    while (listeners.length)
	      this.removeListener(type, listeners[listeners.length - 1]);
	  }
	  delete this._events[type];

	  return this;
	};

	EventEmitter.prototype.listeners = function(type) {
	  var ret;
	  if (!this._events || !this._events[type])
	    ret = [];
	  else if (isFunction(this._events[type]))
	    ret = [this._events[type]];
	  else
	    ret = this._events[type].slice();
	  return ret;
	};

	EventEmitter.listenerCount = function(emitter, type) {
	  var ret;
	  if (!emitter._events || !emitter._events[type])
	    ret = 0;
	  else if (isFunction(emitter._events[type]))
	    ret = 1;
	  else
	    ret = emitter._events[type].length;
	  return ret;
	};

	function isFunction(arg) {
	  return typeof arg === 'function';
	}

	function isNumber(arg) {
	  return typeof arg === 'number';
	}

	function isObject(arg) {
	  return typeof arg === 'object' && arg !== null;
	}

	function isUndefined(arg) {
	  return arg === void 0;
	}

/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {

	var isObject = __webpack_require__(15);

	module.exports = function(obj) {
	    if (!isObject(obj)) return obj;
	    var source, prop;
	    for (var i = 1, length = arguments.length; i < length; i++) {
	        source = arguments[i];
	        for (prop in source) {
	            obj[prop] = source[prop];
	        }
	    }
	    return obj;
	};

/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = function isObject(obj) {
	    var type = typeof obj;
	    return !!obj && (type === 'function' || type === 'object');
	};

/***/ }
/******/ ])
});
;

redpajama_set_name: RedPajamaGithub


text:
import { warn, debug } from '../../shared/helper';

const expressionMap = new Map();
const compute = computed => {
    const computedResult = Object.keys(computed).reduce((result, item) => {
        return Object.assign(result, {
            [item]:
                typeof computed[item] === 'function'
                    ? computed[item]()
                    : computed[item]
        });
    }, {});
    return computedResult;
};

export function evalExpression(
    expression,
    { state, methods, context, computed = {} }
) {
    if (!expressionMap.get(expression)) {
        const expr = codeGen(expression);
        const content = `
            with(context) {
                return ${expr};
            }
        `;
        expressionMap.set(expression, new Function('context', content));
    }

    const codeFn = expressionMap.get(expression);
    const scope = Object.assign({}, methods, state, compute(computed));
    debug(codeFn);
    return codeFn.call(context, scope);
}

export function codeGen(expression) {
    const { type } = expression;
    switch (type) {
    case 'Expression':
        return codeGen(expression.value);

    case 'Identifier':
        return expression.name;

    case 'BinaryExpression':
    case 'LogicalExpression': {
        const left = codeGen(expression.left);
        const right = codeGen(expression.right);
        return `${left}${expression.operator}${right}`;
    }

    case 'MemberExpression': {
        const object = codeGen(expression.object);
        let property = codeGen(expression.property);
        property = expression.computed ? property : '"' + property + '"';
        return `${object}[${property}]`;
    }

    case 'Compound': {
        // eslint-disable-next-line
        // debugger
        break;
    }

    case 'Literal':
        return expression.raw;

    case 'CallExpression': {
        const callee = codeGen(expression.callee);
        const args = expression.arguments.map(codeGen);
        return `${callee}(${args.join(',')})`;
    }

    case 'ThisExpression':
        return 'this';

    case 'UnaryExpression': {
        const operator = expression.operator;
        const argument = codeGen(expression.argument);
        return `${operator}(${argument})`;
    }

    case 'ConditionalExpression': {
        const test = codeGen(expression.test);
        const consequent = codeGen(expression.consequent);
        const alternate = codeGen(expression.alternate);
        return `(${test}?${consequent}:${alternate})`;
    }

    case 'ArrayExpression':
        return '[' + expression.elements.map(codeGen).join(',') + ']';

    default:
        warn('unexpected expression:');
        warn(JSON.stringify(expression));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:orientation="vertical">

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/cache_overlay_child_image"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp" />

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_marginTop="13dp"
            android:layout_marginStart="16dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/cache_overlay_child_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/ListTextPrimary" />

            <TextView
                android:id="@+id/cache_overlay_child_info"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/ListTextSecondary" />

        </LinearLayout>

        <CheckBox
            android:id="@+id/cache_overlay_child_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:focusable="false" />

    </LinearLayout>

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="15dp"
        android:background="@drawable/list_inset_divider" />

</LinearLayout>


text:
// Copyright (C) 2012-2013 Weekend Game Studio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

using System.Collections.Generic;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Math;
using WaveEngine.Components;
using WaveEngine.Framework;
using WaveEngine.Materials;
using WaveEngine.Components.Graphics3D;
using WaveEngine.Framework.Graphics;
using WaveEngine.Components.Cameras;

namespace ThirdPersonCameraProject
{
    public class MainScene : Scene
    {
        protected override void CreateScene()
        {
            var player = CreatePlayer();
            ThirdPersonCamera thirdPersonCamera = new ThirdPersonCamera("thirdPerson", player);
            thirdPersonCamera.BackgroundColor = Color.CornflowerBlue;

            EntityManager.Add(thirdPersonCamera);

            CreateCube("Cube2", new Vector3(5f, 0f, 0f));
            CreateCube("Cube3", new Vector3(-5f, 0f, 0f));
            CreateCube("Cube4", new Vector3(5f, 0f, 5f));
            CreateCube("Cube5", new Vector3(-5f, 0f, 5f));
            CreateCube("Cube6", new Vector3(5f, 0f, -5f));
            CreateCube("Cube7", new Vector3(-5f, 0f, -5f));
        }

        private void CreateCube(string cubeName, Vector3 position)
        {
            var cube = new Entity(cubeName)
                                  .AddComponent(new Transform3D() { Position = position })
                                  .AddComponent(Model.CreateCube())
                                  .AddComponent(new MaterialsMap(new BasicMaterial(Color.Red)))
                                  .AddComponent(new ModelRenderer());

            EntityManager.Add(cube);
        }

        private Entity CreatePlayer()
        {
            var player = new Entity("Player")
                                  .AddComponent(new Transform3D())
                                  .AddComponent(Model.CreateCube())
                                  .AddComponent(new MaterialsMap(new BasicMaterial(Color.Yellow)))
                                  .AddComponent(new ModelRenderer())
                                  .AddComponent(new PlayerBehavior());
            EntityManager.Add(player);

            return player;
        }
    }
}


text:
package demojavafx;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * Created by joaolourenco on 25/04/15.
 */
public class SwitchSceneMain extends Application {

    Stage window;
    Scene scene1, scene2;

    public static void main(String [] args){
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        window =  primaryStage;

        Label label1 = new Label("Welcome to the first Scene!");
        Button button1 = new Button("Go to Scene 2");
        button1.setOnAction(event -> window.setScene(scene2) );

        //Layout 1
        VBox layout1 = new VBox(20);
        layout1.getChildren().addAll(label1, button1);
        scene1 = new Scene(layout1, 200, 200);

        //Button 2
        Button button2 = new Button("Go back Scene 1");
        button2.setOnAction(event -> window.setScene(scene1) );

        //Layout 2
        StackPane layout2 = new StackPane();
        layout2.getChildren().add(button2);
        scene2 = new Scene(layout2, 600, 300);

        window.setScene(scene1);
        window.setTitle("Demo - Switch Scene");

        window.show();

    }
}


text:
Rails.application.routes.draw do
  scope '(:locale)' do
    devise_for :admin_users, ActiveAdmin::Devise.config
    ActiveAdmin.routes(self)
    devise_for :users, controllers: {registrations: 'registrations'}

    resources :users do
      match '/users/:id/edit',            to: 'users#edit',            via: 'edit'
      match '/users',                     to: 'users#index',           via: 'get' # API SHOW ALL USERS /users
      match '/users/:id',                 to: 'users#show',            via: 'get' # API SHOW ONE USER  /users/:id
    end

    resources :leads
      get 'leads/show'
      get 'leads/new'
      match '/api_leads',            to: 'leads#api_index',       via: 'get'   #API SHOW ALL LEADS /api_leads
      match '/api_leads/:id',        to: 'leads#api_show',        via: 'get'   #API SHOW ONE LEAD  /api_leads/:id
      #get 'leads/edit' TODO: Enable users to edit their posts

    resources :orders
      get '/address_book'                 => 'orders#address_book'

    resources :static_pages
      root 'static_pages#welcome'
      get '/info'                         => 'static_pages#info'
      get '/new_lead_confirmation'        => 'static_pages#new_lead_confirmation'
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
VTTRoutineLibrary
</TITLE>

<META NAME="date" CONTENT="2013-02-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

fi.vtt.routinelibrary

Class VTTRoutineLibrary

java.lang.Object
  fi.vtt.routinelibrary.VTTRoutineLibrary

public class VTTRoutineLibrary
extends java.lang.Object

VTT Routine Library for Android.

 Version: 1.0

 Provides routine detection methods. A routine comprises of location and application combinations.

Applications

Locations (Cell ID, GPS)

 Usage:

 Include this RoutineLibrary Android project in your Android application project and initialize the library in your application's main class (usually an Android Service):

 private VTTRoutineLibrary routineLibrary = null;

 In your Service class implement the RoutineLibraryCallback...

 public class YourService extends Service implements RoutineLibraryCallback {

     private VTTRoutineLibrary routineLibrary = null;

     @Override
     public void onCreate() {
        super.onCreate();
        Notification notification = new Notification();
        startForeground(0, notification);
        routineLibrary = new VTTRoutineLibrary(this);
        routineLibrary.setRoutineCallback(this);
        routineLibrary.initializeWakeLock(getApplicationContext());
        routineLibrary.startRecognition();
    }

 }

 ...more specifically, implement the callback methods to receive data through the (RoutineLibraryCallback) interface:

 @Override
 public void newRawLoggedData(RawLogData rawLogDataIncoming, long timeStampLongIncoming, String userHashStringIncoming) {
     // Do something with the raw data.
 }

 @Override
 public void newRoutineLearned(RoutineData routineDataIncoming, long timeStampLongIncoming, String userHashStringIncoming) {
     // Do something with the routine data.
 }

 @Override
 public void routineRecognized(RoutineData routineDataIncoming, long timeStampLongIncoming, String userHashStringIncoming) {
     // Do something with the routine data.
 }

 This way, the library will then function as follows:

NewRawLoggedData() will called by the library when new raw data is available,

NewRoutineLearned() will called by the library when new routine data is available and

RoutineRecognized() will called by the library when the current situation is noticed to match a routine.

Field Summary

private  InternalRoutine
internalRoutine

          The internal routine library class.

private  WakeLock
wakeLock

          Basic Android Wakelock.

Constructor Summary

VTTRoutineLibrary(Context contextIncoming)

          Constructor.

Method Summary

 boolean
initializeWakeLock(Context contextIncoming)

          Initializes wakelock for keeping recognition alive when phone screen is turned off.

 void
setRoutineCallback(RoutineLibraryCallback routineLibraryCallbackIncoming)

          Sets the callback for the routine library.

 void
startRecognition()

          Starts recognition algorithms and acquires a Android Wakelock.

 void
stopRecognition()

          Stops recognition algorithms and releases the Android Wakelock.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

internalRoutine

private InternalRoutine internalRoutine

The internal routine library class.

See Also:
InternalRoutine

wakeLock

private WakeLock wakeLock

Basic Android Wakelock.

See Also:
android.os.PowerManager.WakeLock

Constructor Detail

VTTRoutineLibrary

public VTTRoutineLibrary(Context contextIncoming)

Constructor.

 Initializes the internal routine library and provides the application context for it.

Parameters:
contextIncoming - Context of your application.
See Also:
android.content.Context

Method Detail

initializeWakeLock

public boolean initializeWakeLock(Context contextIncoming)

Initializes wakelock for keeping recognition alive when phone screen is turned off.

 Call this from your application's main class (usually an Android Service).

Parameters:
contextIncoming - Context of your application.

Returns:
true  If wakelock initialized, otherwise false.
See Also:
android.content.Context

setRoutineCallback

public void setRoutineCallback(RoutineLibraryCallback routineLibraryCallbackIncoming)

Sets the callback for the routine library.

Parameters:
routineLibraryCallbackIncoming - Your application class that implements the RoutineLibraryCallback.
See Also:
RoutineLibraryCallback

startRecognition

public void startRecognition()

Starts recognition algorithms and acquires a Android Wakelock.

stopRecognition

public void stopRecognition()

Stops recognition algorithms and releases the Android Wakelock.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
Se la risoluzione Y non &eacute impostata, la risoluzione X/Y verr&agrave utilizzata sia per gli assi X che Y.
<br>


text:
using System;
using Abp.Application.Services.Dto;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;

namespace Abp.Notifications
{
    /// <summary>
    /// Represents a published notification for a tenant/user.
    /// </summary>
    [Serializable]
    public class TenantNotification : EntityDto<Guid>, IHasCreationTime
    {
        /// <summary>
        /// Tenant Id.
        /// </summary>
        public int? TenantId { get; set; }

        /// <summary>
        /// Unique notification name.
        /// </summary>
        public string NotificationName { get; set; }

        /// <summary>
        /// Notification data.
        /// </summary>
        public NotificationData Data { get; set; }

        /// <summary>
        /// Gets or sets the type of the entity.
        /// </summary>
        public Type EntityType { get; set; }

        /// <summary>
        /// Name of the entity type (including namespaces).
        /// </summary>
        public string EntityTypeName { get; set; }

        /// <summary>
        /// Entity id.
        /// </summary>
        public object EntityId { get; set; }

        /// <summary>
        /// Severity.
        /// </summary>
        public NotificationSeverity Severity { get; set; }

        public DateTime CreationTime { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="TenantNotification"/> class.
        /// </summary>
        public TenantNotification()
        {
            CreationTime = Clock.Now;
        }
    }
}


text:
package tech.huqi.smartopencv.draw;

import org.opencv.core.Size;

import java.util.List;

/**
 * Created by hzhuqi on 2019/9/3
 */
public interface IPreviewSizeCalculator {
    /**
     * @param supportedSizes 当前设备摄像头所支持的预览大小列表
     * @param surfaceWidth   预览控件的宽度
     * @param surfaceHeight  预览控件的高度
     * @return 设置给摄像头的预览宽高Size
     */
    Size calculateCameraFrameSize(List<Size> supportedSizes, int surfaceWidth, int surfaceHeight);
}


text:
#ifndef CS_IMAGE_DIMENSION_H
#define CS_IMAGE_DIMENSION_H

#include "arch.h"

namespace CombinedSearch {

/**
 * Describes the dimension of a bitmap. Used
 * when specifying which size the images should
 * be requested as.
 */
struct CSImageDimension {

   /// Width of the image
   uint32 width;

   /// Height of the image
   uint32 height;
};

} // End namespace CombinedSearch

#endif // CS_IMAGE_DIMENSION_H


text:
require "rack/chunked"

module ActionController #:nodoc:
  # Allows views to be streamed back to the client as they are rendered.
  #
  # By default, Rails renders views by first rendering the template
  # and then the layout. The response is sent to the client after the whole
  # template is rendered, all queries are made, and the layout is processed.
  #
  # Streaming inverts the rendering flow by rendering the layout first and
  # streaming each part of the layout as they are processed. This allows the
  # header of the HTML (which is usually in the layout) to be streamed back
  # to client very quickly, allowing JavaScripts and stylesheets to be loaded
  # earlier than usual.
  #
  # This approach was introduced in Rails 3.1 and is still improving. Several
  # Rack middlewares may not work and you need to be careful when streaming.
  # Those points are going to be addressed soon.
  #
  # In order to use streaming, you will need to use a Ruby version that
  # supports fibers (fibers are supported since version 1.9.2 of the main
  # Ruby implementation).
  #
  # Streaming can be added to a given template easily, all you need to do is
  # to pass the :stream option.
  #
  #   class PostsController
  #     def index
  #       @posts = Post.all
  #       render stream: true
  #     end
  #   end
  #
  # == When to use streaming
  #
  # Streaming may be considered to be overkill for lightweight actions like
  # +new+ or +edit+. The real benefit of streaming is on expensive actions
  # that, for example, do a lot of queries on the database.
  #
  # In such actions, you want to delay queries execution as much as you can.
  # For example, imagine the following +dashboard+ action:
  #
  #   def dashboard
  #     @posts = Post.all
  #     @pages = Page.all
  #     @articles = Article.all
  #   end
  #
  # Most of the queries here are happening in the controller. In order to benefit
  # from streaming you would want to rewrite it as:
  #
  #   def dashboard
  #     # Allow lazy execution of the queries
  #     @posts = Post.all
  #     @pages = Page.all
  #     @articles = Article.all
  #     render stream: true
  #   end
  #
  # Notice that :stream only works with templates. Rendering :json
  # or :xml with :stream won't work.
  #
  # == Communication between layout and template
  #
  # When streaming, rendering happens top-down instead of inside-out.
  # Rails starts with the layout, and the template is rendered later,
  # when its +yield+ is reached.
  #
  # This means that, if your application currently relies on instance
  # variables set in the template to be used in the layout, they won't
  # work once you move to streaming. The proper way to communicate
  # between layout and template, regardless of whether you use streaming
  # or not, is by using +content_for+, +provide+ and +yield+.
  #
  # Take a simple example where the layout expects the template to tell
  # which title to use:
  #
  #
  #     <title><%= yield :title %></title>
  #     <%= yield %>
  #
  #
  # You would use +content_for+ in your template to specify the title:
  #
  #   <%= content_for :title, "Main" %>
  #   Hello
  #
  # And the final result would be:
  #
  #
  #     <title>Main</title>
  #     Hello
  #
  #
  # However, if +content_for+ is called several times, the final result
  # would have all calls concatenated. For instance, if we have the following
  # template:
  #
  #   <%= content_for :title, "Main" %>
  #   Hello
  #   <%= content_for :title, " page" %>
  #
  # The final result would be:
  #
  #
  #     <title>Main page</title>
  #     Hello
  #
  #
  # This means that, if you have yield :title in your layout
  # and you want to use streaming, you would have to render the whole template
  # (and eventually trigger all queries) before streaming the title and all
  # assets, which kills the purpose of streaming. For this purpose, you can use
  # a helper called +provide+ that does the same as +content_for+ but tells the
  # layout to stop searching for other entries and continue rendering.
  #
  # For instance, the template above using +provide+ would be:
  #
  #   <%= provide :title, "Main" %>
  #   Hello
  #   <%= content_for :title, " page" %>
  #
  # Giving:
  #
  #
  #     <title>Main</title>
  #     Hello
  #
  #
  # That said, when streaming, you need to properly check your templates
  # and choose when to use +provide+ and +content_for+.
  #
  # == Headers, cookies, session and flash
  #
  # When streaming, the HTTP headers are sent to the client right before
  # it renders the first line. This means that, modifying headers, cookies,
  # session or flash after the template starts rendering will not propagate
  # to the client.
  #
  # == Middlewares
  #
  # Middlewares that need to manipulate the body won't work with streaming.
  # You should disable those middlewares whenever streaming in development
  # or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it
  # needs to inject contents in the HTML body.
  #
  # Also <tt>Rack::Cache</tt> won't work with streaming as it does not support
  # streaming bodies yet. Whenever streaming Cache-Control is automatically
  # set to "no-cache".
  #
  # == Errors
  #
  # When it comes to streaming, exceptions get a bit more complicated. This
  # happens because part of the template was already rendered and streamed to
  # the client, making it impossible to render a whole exception page.
  #
  # Currently, when an exception happens in development or production, Rails
  # will automatically stream to the client:
  #
  #   ">
  #
  # The first two characters (">) are required in case the exception happens
  # while rendering attributes for a given tag. You can check the real cause
  # for the exception in your logger.
  #
  # == Web server support
  #
  # Not all web servers support streaming out-of-the-box. You need to check
  # the instructions for each of them.
  #
  # ==== Unicorn
  #
  # Unicorn supports streaming but it needs to be configured. For this, you
  # need to create a config file as follow:
  #
  #   # unicorn.config.rb
  #   listen 3000, tcp_nopush: false
  #
  # And use it on initialization:
  #
  #   unicorn_rails --config-file unicorn.config.rb
  #
  # You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
  # Please check its documentation for more information: https://bogomips.org/unicorn/Unicorn/Configurator.html#method-i-listen
  #
  # If you are using Unicorn with NGINX, you may need to tweak NGINX.
  # Streaming should work out of the box on Rainbows.
  #
  # ==== Passenger
  #
  # To be described.
  #
  module Streaming
    extend ActiveSupport::Concern

    private

      # Set proper cache control and transfer encoding when streaming
      def _process_options(options)
        super
        if options[:stream]
          if request.version == "HTTP/1.0"
            options.delete(:stream)
          else
            headers["Cache-Control"] ||= "no-cache"
            headers["Transfer-Encoding"] = "chunked"
            headers.delete("Content-Length")
          end
        end
      end

      # Call render_body if we are streaming instead of usual +render+.
      def _render_template(options)
        if options.delete(:stream)
          Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
        else
          super
        end
      end
  end
end


text:
package org.gbif.pubindex.service.mapper;

import org.gbif.pubindex.model.Journal;

import org.apache.ibatis.annotations.Param;

public interface JournalMapper {

  String get(@Param("key") int key);

  void update(@Param("j") Journal j);

  Journal getByFeed(@Param("url") String url);

  Journal getNextJournalForHarvesting();

}