text:
define([
    "dojo/_base/declare",
    "dojo/_base/array",
    "dojo/_base/lang",
    "dojo/ready",
    "dojo/Stateful",
    "dojo/Evented",
    "dojo/on",
    "dojo/date/locale",
    "esri/InfoTemplate",
    "esri/layers/FeatureLayer",
    "esri/geometry/mathUtils",
    "esri/geometry/webMercatorUtils",
    "esri/geometry/Point",
    "esri/request",
    "esri/graphic",
    "esri/symbols/PictureMarkerSymbol"
],
function (
    declare, array, lang,
    ready,
    Stateful, Evented, on,
    locale,
    InfoTemplate,
    FeatureLayer,
    mathUtils,
    webMercatorUtils,
    Point,
    esriRequest,
    Graphic,
    PictureMarkerSymbol
) {
    return declare("application.InstagramLayer", [Stateful, Evented], {
        options: {
            map: null,
            filterUsers: [],
            filterWords: [],
            autopage: true,
            visible: true,
            maxpage: 1,
            limit: 100,
            title: 'Instagram',
            id: 'instagram',
            datePattern: "MMM d, yyyy",
            timePattern: "h:mma",
            minScale: null,
            maxScale: null,
            symbol: null,
            infoTemplate: null,
            key: '',
            refreshTime: 4000,
            url : 'https://api.instagram.com/v1/media/search/'
        },
        constructor: function (options) {
            // mixin options
            var defaults = lang.mixin({}, this.options, options);
            // properties
            this.set("map", defaults.map);
            this.set("filterUsers", defaults.filterUsers);
            this.set("filterWords", defaults.filterWords);
            this.set("autopage", defaults.autopage);
            this.set("visible", defaults.visible);
            this.set("maxpage", defaults.maxpage);
            this.set("limit", defaults.limit);
            this.set("title", defaults.title);
            this.set("id", defaults.id);
            this.set("datePattern", defaults.datePattern);
            this.set("timePattern", defaults.timePattern);
            this.set("symbol", defaults.symbol);
            this.set("infoTemplate", defaults.infoTemplate);
            this.set("key", defaults.key);
            this.set("url", defaults.url);
            this.set("minScale", defaults.minScale);
            this.set("maxScale", defaults.maxScale);
            this.set("refreshTime", defaults.refreshTime);
            this.set("graphics", []);
            this.set("noGeo", []);
            // listeners
            this.watch("visible", this._visible);
            // private vars
            this._deferreds = [];
            this._events = [];
            this._dataIds = {};
            // classes
            this._css = {
                container: "instagram-popup",
                imageAnchor: "image-anchor",
                image: "image",
                location: "location",
                ownername: "ownername",
                ownerAnchor: "owner-anchor",
                content: "content",
                date: "date"
            };
            // map required
            if (!this.map) {
                console.log('Instagram::Reference to esri.Map object required');
                return;
            }
            // default symbol
            if (!this.symbol) {
                this.set("symbol", new PictureMarkerSymbol('images/map/instagram25x30.png', 25, 30).setOffset(0,7));
            }
            // default infoTemplate
            if (!this.infoTemplate) {
                this.set("infoTemplate", new InfoTemplate('Instagram', '

${descriptionText}

${location_name}

${full_name}

${dateformatted}

'));
            }
            // layer
            this.featureCollection = {
                layerDefinition: {
                    "geometryType": "esriGeometryPoint",
                    "drawingInfo": {
                        "renderer": {
                            "type": "simple",
                            "symbol": this.symbol
                        }
                    },
                    "fields": [{
                        "name": "OBJECTID",
                        "type": "esriFieldTypeOID"
                    }],
                    "globalIdField": "id",
                    "displayField": "title"
                },
                featureSet: {
                    "features": [],
                    "geometryType": "esriGeometryPoint"
                }
            };
            // layer
            this.featureLayer = new FeatureLayer(this.featureCollection, {
                id: this.id,
                title: this.title,
                minScale: this.minScale,
                maxScale: this.maxScale,
                outFields: ["*"],
                infoTemplate: this.infoTemplate,
                visible: this.visible
            });
            // add to map
            this.map.addLayer(this.featureLayer);
            // dom ready
            ready(lang.hitch(this, function(){
                // query when map loads
                if(this.map.loaded){
                    this._init();
                }
                else{
                    var onLoad = on.once(this.map, "load", lang.hitch(this, function () {
                        this._init();
                    }));
                    this._events.push(onLoad);
                }
                // loaded
                this.set("loaded", true);
                this.emit("load", {});
            }));
        },
        /* ---------------- */
        /* Public Events */
        /* ---------------- */
        // load
        // clear
        // update
        // update-end
        // error
        /* ---------------- */
        /* Public Functions */
        /* ---------------- */
        destroy: function(){
            // remove events
            if (this._events && this._events.length) {
                for (var i = 0; i < this._events.length; i++) {
                    this._events[i].remove();
                }
            }
            // clear data
            this.clear();
            // remove layer
            this.map.removeLayer(this.featureLayer);
        },
        update: function (ms) {
            if(this.featureLayer && this.featureLayer.visibleAtMapScale && this.featureLayer.visible){
                if(this._refreshTimer){
                    clearTimeout(this._refreshTimer);
                }
                // default to refresh time
                var refresh = this.refreshTime;
                // use param time if set
                if(typeof ms !== 'undefined'){
                    refresh = ms;
                }
                this._refreshTimer = setTimeout(lang.hitch(this, function() {
                    this._constructQuery();
                }), refresh);
            }
        },
        clear: function () {
            // remove timer
            if(this._refreshTimer){
                clearTimeout(this._refreshTimer);
            }
            // cancel any outstanding requests
            this.query = null;
            array.forEach(this._deferreds, function (def) {
                def.cancel();
            });
            this._deferreds = [];
            if (this.featureLayer.graphics.length > 0) {
                this.featureLayer.applyEdits(null, null, this.featureLayer.graphics);
            }
            this.set("graphics", []);
            this._dataIds = {};
            this.emit("clear", {});
        },
        show: function () {
            this.featureLayer.setVisibility(true);
        },
        hide: function () {
            this.featureLayer.setVisibility(false);
        },
        setVisibility: function (val) {
            if (val) {
                this.show();
            } else {
                this.hide();
            }
        },
        /* ---------------- */
        /* Private Functions */
        /* ---------------- */
        _init: function(){
            // Events
            var extentChange = on(this.map, "extent-change", lang.hitch(this, function () {
                this.update();
            }));
            this._events.push(extentChange);
            var visChange = on(this.featureLayer, "visibility-change", lang.hitch(this, function () {
                this.clear();
                this.update(0);
            }));
            this._events.push(visChange);
            this.update();
        },
        // Format Date Object
        _formatDate: function (dateObj) {
            if (dateObj) {
                return locale.format(dateObj, {
                    datePattern: this.timePattern,
                    selector: "date"
                }).toLowerCase() + ' · ' + locale.format(dateObj, {
                    datePattern: this.datePattern,
                    selector: "date"
                });
            }
        },
        _getRadius: function () {
            var map = this.map;
            var extent = this.map.extent;
            var center = extent.getCenter();
            this.maxRadius = 5000; // 5km max
            var radius = Math.min(this.maxRadius, Math.ceil(mathUtils.getLength(Point(extent.xmin, extent.ymin, map.spatialReference), Point(extent.xmax, extent.ymin, map.spatialReference)) / 10));
            radius = Math.floor(radius);
            return {
                lat : Math.round(center.getLatitude() * 100) / 100,
				lng : Math.round(center.getLongitude() * 100) / 100,
				distance : radius
            };
        },
        _constructQuery: function () {
            var radius = this._getRadius();
            this.query = {
                client_id: this.key,
                count: this.limit,
				lat: radius.lat,
				lng: radius.lng,
				distance: radius.distance,
                page: 1,
                format: "json"
            };
            // make the actual API call
            this.pageCount = 1;
            this._sendRequest(this.url, this.query);
        },
        _sendRequest: function (url, content) {
            // get the results for each page
            var deferred = esriRequest({
                url: url,
                handleAs: "json",
                timeout: 10000,
                content: content,
                callbackParamName: "callback",
                preventCache: true,
                load: lang.hitch(this, function (data) {
                    if (data.meta && data.meta.code === 200) {
                        if (data.data.length > 0) {
                            this._mapResults(data);
                            // display results for multiple pages
                            if ((this.autopage) && (this.maxpage > this.pageCount) && (data.data.length === this.limit) && (this.query)) {
                                this.pageCount++;
                                this.query.page++;
                                this._sendRequest(this.url, this.query);
                            } else {
                                this._updateEnd();
                            }
                        } else {
                            // No results found, try another search term
                            this._updateEnd();
                        }
                    } else {
                        if(data.meta){
                            console.log('Instagram::' + data.meta.code + ' - ' + this.title + ': ' + data.meta.error_message);
                        }
                        // No results found, try another search term
                        this._updateEnd();
                    }
                }),
                error: lang.hitch(this, function (e) {
                    if (deferred.canceled) {
                        console.log('Instagram::Search Cancelled');
                    } else {
                        console.log('Instagram::Search error' + ": " + e.message.toString());
                    }
                    this._error(e);
                })
            });
            this._deferreds.push(deferred);
        },
		_findWordInText: function (word, text) {
            if(word && text) {
                // text
                var searchString = text.toLowerCase();
                // word
                var badWord = ' ' + word.toLowerCase() + ' ';
                // if found
                if(searchString.indexOf(badWord) > -1) {
                    return true;
                }
            }
            return false;
        },
        _mapResults: function (j) {
            if (j.error) {
                console.log("Instagram::_mapResults error: " + j.error);
                this._error(j.error);
                return;
            }
            var b = [];
            var ng = [];
            var k = j.data;
            array.forEach(k, lang.hitch(this, function (result) {
                // add social media type/id for filtering
                result.smType = this.id;
                result.filterType = 6;
                result.filterContent = result.link;
                result.filterAuthor = result.user.username;
                // add date to result
                var date = new Date(parseInt(result.created_time * 1000, 10));
                result.dateformatted = this._formatDate(date);
                // text
                result.descriptionText = result.caption? result.caption.text : '';
                // add location protocol to result
                result.protocol = location.protocol;
                result.thumbnail = result.images.thumbnail.url;
                result.width = result.images.thumbnail.width;
                result.height = result.images.thumbnail.height;
                result.username = result.user.username;
                result.full_name = result.user.full_name;
                result.location_name = result.location.name;
                // eliminate geo photos which we already have on the map
                if (this._dataIds[result.id]) {
                    return;
                }
				// filter variable
				var filter = false, i;
				// check for filterd user
				if(this.filterUsers && this.filterUsers.length){
					for(i = 0; i < this.filterUsers.length; i++){
						if(this.filterUsers[i].toString() === result.username.toString()){
							filter = true;
							break;
						}
					}
				}
				// check if contains bad word
				if(!filter && this.filterWords && this.filterWords.length){
					for(i = 0; i < this.filterWords.length; i++){
						if(this._findWordInText(this.filterWords[i], result.descriptionText)){
							filter = true;
							break;
						}
					}
				}
				// if this feature needs to be filtered
				if(filter){
                    //console.log('filtered', result);
					return;
				}
                this._dataIds[result.id] = true;
                var geoPoint = null;
                if (result.location) {
                    var g = [result.location.latitude, result.location.longitude];
                    geoPoint = Point(parseFloat(g[1]), parseFloat(g[0]));
                }
                if (geoPoint && geoPoint.hasOwnProperty('x') && geoPoint.hasOwnProperty('y')) {
                    // convert the Point to WebMercator projection
                    var a = webMercatorUtils.geographicToWebMercator(geoPoint);
                    // make the Point into a Graphic
                    var graphic = new Graphic(a, this.symbol, result, this.infoTemplate);
                    b.push(graphic);
                }
                else{
                    ng.push(result);
                }
            }));
            // add new graphics to widget
            var graphics = this.get("graphics");
            graphics = graphics.concat(b);
            this.set("graphics", graphics);
            // add non geocode results to noGeo
            var noGeo = this.get("noGeo");
            noGeo.concat(ng);
            this.set("noGeo", noGeo);
            // add new graphics to layer
            this.featureLayer.applyEdits(b, null, null);
            // update event with new graphics
            this.emit("update", {
                graphics: b,
                noGeo: ng
            });
        },
        _visible: function() {
            this.setVisibility(this.get("visible"));
        },
        _error: function(e){
            this._updateEnd();
            this.emit("error", e);
        },
        _updateEnd: function () {
            this.query = null;
            this.emit("update-end", {});
        }
    });
});


text:
package org.drools.chance.distribution.probability.discrete;

import org.drools.chance.degree.DegreeType;
import org.drools.chance.degree.ChanceDegreeTypeRegistry;
import org.drools.chance.degree.simple.SimpleDegree;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class DiscreteDistributionStrategyTest {

    private static DiscreteDistribution<String> sortMapDistrCurr = new DiscreteDistribution<String>();
    private static DiscreteDistribution<String> sortMapDistrNew = new DiscreteDistribution<String>();
    private static DiscreteDistributionStrategy<String> DisDisStrategy=new DiscreteDistributionStrategy<String>( DegreeType.SIMPLE ,String.class);

    @Test
    public void testMerge() throws Exception {
        sortMapDistrCurr.put("one", new SimpleDegree(0.2));
        sortMapDistrCurr.put("two", new SimpleDegree(0.5));
        sortMapDistrCurr.put("three", new SimpleDegree(0.3));

        sortMapDistrNew.put("one", new SimpleDegree(0.3));
        sortMapDistrNew.put("two", new SimpleDegree(0.4));
        sortMapDistrNew.put("three", new SimpleDegree(0.3));

        DiscreteDistribution<String> ret=(DiscreteDistribution<String>) DisDisStrategy.merge(sortMapDistrCurr, sortMapDistrNew);

        //System.out.println(ret.getDegree("one").getValue());
        assertEquals((0.06/0.35),ret.getDegree("one").getValue(),1e-12);
        assertEquals((0.2/0.35),ret.getDegree("two").getValue(),1e-12);
        assertEquals((0.09/0.35),ret.getDegree("three").getValue(),1e-12);

    }

    @Test
    public void testNewDistribution() throws Exception {

    }

    @Test
    public void testToCrispValue() throws Exception {
        sortMapDistrCurr.put("one", new SimpleDegree(0.2));
        sortMapDistrCurr.put("two", new SimpleDegree(0.5));
        sortMapDistrCurr.put("three", new SimpleDegree(0.3));

        assertEquals("two",DisDisStrategy.toCrispValue(sortMapDistrCurr));
    }

    @Test
    public void testSample() throws Exception {

    }

    @Test
    public void testToDistribution() throws Exception {

    }

    @Test
    public void testParse() throws Exception {
        ChanceDegreeTypeRegistry.getSingleInstance().registerDegreeType(DegreeType.SIMPLE, SimpleDegree.class);

        DiscreteDistribution<String> dd= (DiscreteDistribution<String>) DisDisStrategy.parse("john/0.3, mark/0.7");
        assertEquals(0.3,dd.getDegree("john").getValue(),0);
        assertEquals(0.7,dd.getDegree("mark").getValue(),0);

        DiscreteDistributionStrategy<Integer> DisDisStrategyInt=new DiscreteDistributionStrategy<Integer>(DegreeType.SIMPLE,Integer.class);
        DiscreteDistribution<Integer> ddI= (DiscreteDistribution<Integer>) DisDisStrategyInt.parse("5/0.3, 6/0.7");
        assertEquals(0.3,ddI.getDegree(5).getValue(),0);
        assertEquals(0.7,ddI.getDegree(6).getValue(),0);

    }

    @Test
    public void testNewParametricDistribution() throws Exception {

    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.tscfdi.comprobante.nomina;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import java.math.BigDecimal;

/**
 * Created by lugty on 12/9/16.
 */
@XmlAccessorType(XmlAccessType.FIELD)
public class DataDeduccion {

    @XmlAttribute(name = "TipoDeduccion", required = true)
    private String tipoDeduccion;

    @XmlAttribute(name = "Clave", required = true)
    private String clave;

    @XmlAttribute(name = "Concepto", required = true)
    private String concepto;

    @XmlAttribute(name = "Importe", required = true)
    private BigDecimal importe;

    public String getTipoDeduccion() {
        return tipoDeduccion;
    }

    public void setTipoDeduccion(String tipoDeduccion) {
        this.tipoDeduccion = tipoDeduccion;
    }

    public String getClave() {
        return clave;
    }

    public void setClave(String clave) {
        this.clave = clave;
    }

    public String getConcepto() {
        return concepto;
    }

    public void setConcepto(String concepto) {
        this.concepto = concepto;
    }

    public BigDecimal getImporte() {
        return importe;
    }

    public void setImporte(BigDecimal importe) {
        this.importe = importe;
    }
}


text:
package org.camunda.bpm.engine.rest.util.container;

import java.io.File;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider;
import org.camunda.bpm.engine.rest.spi.impl.MockedProcessEngineProvider;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage;
import org.jboss.shrinkwrap.resolver.api.maven.ScopeType;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependencies;

public abstract class TomcatServerBootstrap extends EmbeddedServerBootstrap {

  private Tomcat tomcat;
  private String workingDir;
  private String webXmlPath;

  public TomcatServerBootstrap(String webXmlPath) {
    this.webXmlPath = webXmlPath;
  }

  public void start() {
    Properties serverProperties = readProperties();
    int port = Integer.parseInt(serverProperties.getProperty(PORT_PROPERTY));

    tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(getWorkingDir());

    tomcat.getHost().setAppBase(getWorkingDir());
    tomcat.getHost().setAutoDeploy(true);
    tomcat.getHost().setDeployOnStartup(true);

    String contextPath = "/" + getContextPath();

    // 1) Must not use shrinkwrap offline mode (see longer explanation at the end of the file)
    // 2) Must use configuration via Shrinkwrap Maven plugin (see pom.xml for plugin definition);
    //    This forwards things like the location of the settings.xml file to Shrinkwrap. We need
    //    that for our CI where settings.xml is not in the default location.
    PomEquippedResolveStage resolver = Maven.configureResolver()
      .useLegacyLocalRepo(true).configureViaPlugin();

    WebArchive wa = ShrinkWrap.create(WebArchive.class, "rest-test.war").setWebXML(webXmlPath)
        .addAsLibraries(resolver.addDependencies(
            MavenDependencies.createDependency("org.mockito:mockito-core", ScopeType.TEST, false,
            MavenDependencies.createExclusion("org.hamcrest:hamcrest-core"))).resolve()
              .withTransitivity().asFile())

        .addAsServiceProvider(ProcessEngineProvider.class, MockedProcessEngineProvider.class)
        .add(new ClassLoaderAsset("runtime/tomcat/context.xml"), "META-INF/context.xml")
        .addPackages(true, "org.camunda.bpm.engine.rest");

    addRuntimeSpecificLibraries(wa, resolver);
    wa.setWebXML(webXmlPath);

    String webAppPath = getWorkingDir() + "/" + getContextPath() + ".war";

    wa.as(ZipExporter.class).exportTo(new File(webAppPath), true);

    tomcat.addWebapp(tomcat.getHost(), contextPath, webAppPath);

    try {
      tomcat.start();
    } catch (LifecycleException e) {
      throw new RuntimeException(e);
    }
  }

  protected abstract void addRuntimeSpecificLibraries(WebArchive wa, PomEquippedResolveStage resolver);

  private String getContextPath() {
    return "rest-test";
  }

  public void stop() {
    try {
      try {
        tomcat.stop();
      } catch (Exception e) {
        Logger.getLogger(getClass().getName()).log(Level.WARNING, "Failed to stop tomcat instance", e);
      }

      try {
        tomcat.destroy();
      } catch (Exception e) {
        Logger.getLogger(getClass().getName()).log(Level.WARNING, "Failed to destroy instance", e);
      }

      tomcat = null;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public String getWorkingDir() {
    if (workingDir == null) {
      workingDir = System.getProperty("java.io.tmpdir");
    }
    return workingDir;
  }

  public void setWorkingDir(String workingDir) {
    this.workingDir = workingDir;
  }

  /*
   * Must not use Shrinkwrap offline mode or else some Maven builds can fail. In particular, a
   * Maven build will fail with offline mode in the following circumstances:
   *
   * - The BOM is part of the Maven reactor (e.g. if we build the root pom)
   * - The Maven build does not install its modules (e.g. we run mvn clean verify)
   * - There is no BOM snapshot in the local repository yet (this is mostly the case in CI)
   *
   * Why?
   *
   * - The BOM is imported in the dependencyManagement section of this pom (via camunda-parent)
   * - As the BOM is part of the reactor, it will not be fetched from remote by the Maven build
   * - As we do not run "install", Maven does not put the BOM into the local repository
   * - Shrinkwrap will not be able to resolve the BOM then; note: this is different if a pom is referenced
   *   as a parent; in that case, Shrinkwrap will navigate the relativePaths towards the local pom
   *
   * Impact
   *
   * - By enabling remote fetching in Shrinkwrap, a remote snapshot BOM will be fetched in this case
   * - While counter-intuitive, we consider this an ok solution; other solution options were disallowing
   *   "mvn clean verify" in these circumstances (and changing CI builds accordingly), or reverting the
   *   changes made in CAM-11345.
   *
   * This change was made with CAM-11345. See the discussion there for more details.
   */
}


text:
package com.palantir.atlasdb.keyvalue;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.primitives.UnsignedBytes;
import com.palantir.atlasdb.keyvalue.api.Cell;
import com.palantir.atlasdb.keyvalue.api.ColumnSelection;
import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.atlasdb.keyvalue.api.RangeRequest;
import com.palantir.atlasdb.keyvalue.api.RowResult;
import com.palantir.atlasdb.keyvalue.api.Value;
import com.palantir.atlasdb.keyvalue.impl.InMemoryKeyValueService;
import com.palantir.atlasdb.keyvalue.impl.TieredKeyValueService;
import com.palantir.common.base.ClosableIterator;
import com.palantir.util.paging.TokenBackedBasicResultsPage;

public class TieredKvsTest {

    private final String tieredTable = "tiered_table";
    private final String untieredTable = "untiered_table";
    private TieredKeyValueService tieredKvs;
    private KeyValueService primaryKvs;
    private KeyValueService secondaryKvs;

    @Before
    public void setup() {
        primaryKvs = new InMemoryKeyValueService(true);
        secondaryKvs = new InMemoryKeyValueService(true);
        tieredKvs = TieredKeyValueService.create(ImmutableSet.of(tieredTable), primaryKvs, secondaryKvs);

        Multimap<Cell, Value> values = ArrayListMultimap.create();
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                values.put(getCell(row, col), getValue(4*row + col, 4*row + col));
            }
        }
        secondaryKvs.putWithTimestamps(tieredTable, values);

        values = ArrayListMultimap.create();
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                if ((row + col) % 2 == 0) {
                    values.put(getCell(row, col), getValue(4*row + col, 100 + 4*row + col));
                }
            }
        }
        secondaryKvs.putWithTimestamps(tieredTable, values);

        values = ArrayListMultimap.create();
        for (int row = 0; row < 2; row++) {
            for (int col = 0; col < 4; col++) {
                values.put(getCell(row, col), getValue(4*row + col, 200 + 4*row + col));
            }
        }
        primaryKvs.putWithTimestamps(tieredTable, values);

        values = ArrayListMultimap.create();
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 2; col++) {
                values.put(getCell(row, col), getValue(4*row + col, 300 + 4*row + col));
            }
        }
        primaryKvs.putWithTimestamps(tieredTable, values);

        values = ArrayListMultimap.create();
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                if ((row + col) % 2 == 0) {
                    values.put(getCell(row, col), getValue(4*row + col, 4*row + col));
                }
            }
        }
        primaryKvs.putWithTimestamps(untieredTable, values);
    }

    @After
    public void tearDown() {
        tieredKvs.teardown();
        primaryKvs.teardown();
        secondaryKvs.teardown();
    }

    @Test
    public void testGet() {
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                Map<Cell, Value> result0 = tieredKvs.get(tieredTable, ImmutableMap.of(getCell(row, col), 0L));
                Map<Cell, Value> result100 = tieredKvs.get(tieredTable, ImmutableMap.of(getCell(row, col), 100L));
                Map<Cell, Value> result200 = tieredKvs.get(tieredTable, ImmutableMap.of(getCell(row, col), 200L));
                Map<Cell, Value> result300 = tieredKvs.get(tieredTable, ImmutableMap.of(getCell(row, col), 300L));
                Map<Cell, Value> result400 = tieredKvs.get(tieredTable, ImmutableMap.of(getCell(row, col), 400L));

                Assert.assertEquals(ImmutableMap.of(), result0);

                assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 4*row + col)), result100);

                if ((row + col) % 2 == 0) {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 100 + 4*row + col)), result200);
                } else {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 4*row + col)), result200);
                }

                if (row < 2) {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 200 + 4*row + col)), result300);
                } else if ((row + col) % 2 == 0) {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 100 + 4*row + col)), result300);
                } else {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 4*row + col)), result300);
                }

                if (col < 2) {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 300 + 4*row + col)), result400);
                } else if (row < 2) {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 200 + 4*row + col)), result400);
                } else if ((row + col) % 2 == 0) {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 100 + 4*row + col)), result400);
                } else {
                    assertEquals(ImmutableMap.of(getCell(row, col), getValue(4*row + col, 4*row + col)), result400);
                }
            }
        }
    }

    @Test
    public void testGetRows() {
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                Map<Cell, Value> rows0 = tieredKvs.getRows(tieredTable, ImmutableList.of(getRow(row)), ColumnSelection.all(), 0L);
                Map<Cell, Value> rows100 = tieredKvs.getRows(tieredTable, ImmutableList.of(getRow(row)), ColumnSelection.all(), 100L);
                Map<Cell, Value> rows200 = tieredKvs.getRows(tieredTable, ImmutableList.of(getRow(row)), ColumnSelection.all(), 200L);
                Map<Cell, Value> rows300 = tieredKvs.getRows(tieredTable, ImmutableList.of(getRow(row)), ColumnSelection.all(), 300L);
                Map<Cell, Value> rows400 = tieredKvs.getRows(tieredTable, ImmutableList.of(getRow(row)), ColumnSelection.all(), 400L);

                assertEquals(ImmutableMap.of(), rows0);

                assertEquals(ImmutableMap.of(
                        getCell(row, 0), getValue(4*row + 0, 4*row + 0),
                        getCell(row, 1), getValue(4*row + 1, 4*row + 1),
                        getCell(row, 2), getValue(4*row + 2, 4*row + 2),
                        getCell(row, 3), getValue(4*row + 3, 4*row + 3)), rows100);

                if (row % 2 == 0) {
                    assertEquals(ImmutableMap.of(
                            getCell(row, 0), getValue(4*row + 0, 100 + 4*row + 0),
                            getCell(row, 1), getValue(4*row + 1, 4*row + 1),
                            getCell(row, 2), getValue(4*row + 2, 100 + 4*row + 2),
                            getCell(row, 3), getValue(4*row + 3, 4*row + 3)), rows200);
                    if (row < 2) {
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 200 + 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 200 + 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 200 + 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 200 + 4*row + 3)), rows300);
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 300 + 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 300 + 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 200 + 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 200 + 4*row + 3)), rows400);
                    } else {
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 100 + 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 100 + 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 4*row + 3)), rows300);
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 300 + 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 300 + 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 100 + 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 4*row + 3)), rows400);
                    }
                } else {
                    assertEquals(ImmutableMap.of(
                            getCell(row, 0), getValue(4*row + 0, 4*row + 0),
                            getCell(row, 1), getValue(4*row + 1, 100 + 4*row + 1),
                            getCell(row, 2), getValue(4*row + 2, 4*row + 2),
                            getCell(row, 3), getValue(4*row + 3, 100 + 4*row + 3)), rows200);
                    if (row < 2) {
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 200 + 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 200 + 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 200 + 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 200 + 4*row + 3)), rows300);
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 300 + 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 300 + 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 200 + 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 200 + 4*row + 3)), rows400);
                    } else {
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 100 + 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 100 + 4*row + 3)), rows300);
                        assertEquals(ImmutableMap.of(
                                getCell(row, 0), getValue(4*row + 0, 300 + 4*row + 0),
                                getCell(row, 1), getValue(4*row + 1, 300 + 4*row + 1),
                                getCell(row, 2), getValue(4*row + 2, 4*row + 2),
                                getCell(row, 3), getValue(4*row + 3, 100 + 4*row + 3)), rows400);
                    }
                }
            }
        }
    }

    @Test
    public void testGetRange() {
        List<RowResult<Value>> range0 = ImmutableList.copyOf(tieredKvs.getRange(tieredTable, RangeRequest.all(), 0L));
        List<RowResult<Value>> range100 = ImmutableList.copyOf(tieredKvs.getRange(tieredTable, RangeRequest.all(), 100L));
        List<RowResult<Value>> range200 = ImmutableList.copyOf(tieredKvs.getRange(tieredTable, RangeRequest.all().withBatchHint(3), 200L));
        List<RowResult<Value>> range300 = ImmutableList.copyOf(tieredKvs.getRange(tieredTable, RangeRequest.all().withBatchHint(2), 300L));
        List<RowResult<Value>> range400 = ImmutableList.copyOf(tieredKvs.getRange(tieredTable, RangeRequest.all().withBatchHint(1), 400L));

        List<RowResult<Value>> expected;
        expected = Lists.newArrayList();
        assertEquals(expected, range0);

        expected = Lists.newArrayList();
        for (int row = 0; row < 4; row++) {
            SortedMap<byte[], Value> cols = Maps.newTreeMap(UnsignedBytes.lexicographicalComparator());
            for (int col = 0; col < 4; col++) {
                cols.put(getCol(col), getValue(4*row + col, 4*row + col));
            }
            expected.add(RowResult.create(getRow(row), cols));
        }
        assertEquals(expected, range100);

        expected = Lists.newArrayList();
        for (int row = 0; row < 4; row++) {
            SortedMap<byte[], Value> cols = Maps.newTreeMap(UnsignedBytes.lexicographicalComparator());
            for (int col = 0; col < 4; col++) {
                if ((row + col) % 2 == 0) {
                    cols.put(getCol(col), getValue(4*row + col, 100 + 4*row + col));
                } else {
                    cols.put(getCol(col), getValue(4*row + col, 4*row + col));
                }
            }
            expected.add(RowResult.create(getRow(row), cols));
        }
        assertEquals(expected, range200);

        expected = getExpectedRange300();
        assertEquals(expected, range300);

        expected = Lists.newArrayList();
        for (int row = 0; row < 4; row++) {
            SortedMap<byte[], Value> cols = Maps.newTreeMap(UnsignedBytes.lexicographicalComparator());
            for (int col = 0; col < 4; col++) {
                if (col < 2) {
                    cols.put(getCol(col), getValue(4*row + col, 300 + 4*row + col));
                } else if (row < 2) {
                    cols.put(getCol(col), getValue(4*row + col, 200 + 4*row + col));
                } else if ((row + col) % 2 == 0) {
                    cols.put(getCol(col), getValue(4*row + col, 100 + 4*row + col));
                } else {
                    cols.put(getCol(col), getValue(4*row + col, 4*row + col));
                }
            }
            expected.add(RowResult.create(getRow(row), cols));
        }
        assertEquals(expected, range400);
    }

    @Test
    public void testGetRangeWithCopy() {
        testGetRangeWithAction(new Runnable() {
            @Override
            public void run() {
                ClosableIterator<RowResult<Value>> iter = primaryKvs.getRange(tieredTable, RangeRequest.all(), Long.MAX_VALUE);
                while (iter.hasNext()) {
                    RowResult<Value> next = iter.next();
                    for (Entry<Cell, Value> entry : next.getCells()) {
                        secondaryKvs.putWithTimestamps(tieredTable, ImmutableMultimap.of(entry.getKey(), entry.getValue()));
                    }
                }
            }
        });
    }

    private void testGetRangeWithAction(Runnable action) {
        List<RowResult<Value>> expected = getExpectedRange300();
        for (int i = 0; i < expected.size(); i++) {
            ClosableIterator<RowResult<Value>> range300 = tieredKvs.getRange(tieredTable, RangeRequest.all().withBatchHint(2), 300L);
            for (int j = 0; j < expected.size(); j++) {
                if (i == j) {
                    action.run();
                }
                assertEquals(expected.get(j), range300.next());
            }
            assertFalse(range300.hasNext());
            tearDown();
            setup();
        }
    }

    @Test
    public void testGetRanges() {
        List<RowResult<Value>> expected = getExpectedRange300();
        List<Map<RangeRequest, TokenBackedBasicResultsPage<RowResult<Value>, byte[]>>> results = Lists.newArrayListWithCapacity(20);
        List<RangeRequest> requests = Lists.newArrayList(
                RangeRequest.builder().prefixRange(getRow(0)).build(),
                RangeRequest.builder().prefixRange(getRow(1)).build(),
                RangeRequest.builder().prefixRange(getRow(2)).build(),
                RangeRequest.builder().prefixRange(getRow(3)).build());
        for (int i = 0; i < 20; i++) {
            results.add(tieredKvs.getFirstBatchForRanges(tieredTable, requests, 300));
        }
        for (int i = 0; i < 20; i++) {
            List<RowResult<Value>> actual = Lists.newArrayList();
            actual.addAll(results.get(i).get(requests.get(0)).getResults());
            actual.addAll(results.get(i).get(requests.get(1)).getResults());
            actual.addAll(results.get(i).get(requests.get(2)).getResults());
            actual.addAll(results.get(i).get(requests.get(3)).getResults());
            assertEquals(expected, actual);
        }
    }

    private List<RowResult<Value>> getExpectedRange300() {
        List<RowResult<Value>> expected = Lists.newArrayList();
        for (int row = 0; row < 4; row++) {
            SortedMap<byte[], Value> cols = Maps.newTreeMap(UnsignedBytes.lexicographicalComparator());
            for (int col = 0; col < 4; col++) {
                if (row < 2) {
                    cols.put(getCol(col), getValue(4*row + col, 200 + 4*row + col));
                } else if ((row + col) % 2 == 0) {
                    cols.put(getCol(col), getValue(4*row + col, 100 + 4*row + col));
                } else {
                    cols.put(getCol(col), getValue(4*row + col, 4*row + col));
                }
            }
            expected.add(RowResult.create(getRow(row), cols));
        }
        return expected;
    }

    @Test
    public void testSetup() {
        ClosableIterator<RowResult<Value>> range;
        Set<RowResult<Value>> results;
        Map<Cell, Value> cells;
        range = primaryKvs.getRange(tieredTable, RangeRequest.all(), 200);
        assertFalse(range.hasNext());

        range = primaryKvs.getRange(tieredTable, RangeRequest.all(), 300);
        results = Sets.newHashSet(range);
        assertEquals(2, results.size());
        cells = getCells(results);
        assertEquals(8, cells.size());
        for (int row = 0; row < 2; row++) {
            for (int col = 0; col < 4; col++) {
                assertEquals(getValue(4*row + col, 200 + 4*row + col), cells.get(getCell(row, col)));
            }
        }

        range = primaryKvs.getRange(tieredTable, RangeRequest.all(), 400);
        results = Sets.newHashSet(range);
        assertEquals(4, results.size());
        cells = getCells(results);
        assertEquals(12, cells.size());
        for (int row = 0; row < 2; row++) {
            for (int col = 0; col < 2; col++) {
                assertEquals(getValue(4*row + col, 300 + 4*row + col), cells.get(getCell(row, col)));
            }
        }
        for (int row = 0; row < 2; row++) {
            for (int col = 2; col < 4; col++) {
                assertEquals(getValue(4*row + col, 200 + 4*row + col), cells.get(getCell(row, col)));
            }
        }
        for (int row = 2; row < 4; row++) {
            for (int col = 0; col < 2; col++) {
                assertEquals(getValue(4*row + col, 300 + 4*row + col), cells.get(getCell(row, col)));
            }
        }

        range = secondaryKvs.getRange(tieredTable, RangeRequest.all(), 100);
        results = Sets.newHashSet(range);
        assertEquals(4, results.size());
        cells = getCells(results);
        assertEquals(16, cells.size());
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                assertEquals(getValue(4*row + col, 4*row + col), cells.get(getCell(row, col)));
            }
        }

        range = secondaryKvs.getRange(tieredTable, RangeRequest.all(), 200);
        results = Sets.newHashSet(range);
        assertEquals(4, results.size());
        cells = getCells(results);
        assertEquals(16, cells.size());
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                if ((row + col) % 2 == 0) {
                    assertEquals(getValue(4*row + col, 100 + 4*row + col), cells.get(getCell(row, col)));
                } else {
                    assertEquals(getValue(4*row + col, 4*row + col), cells.get(getCell(row, col)));
                }
            }
        }
    }

    private Map<Cell, Value> getCells(Set<RowResult<Value>> rowResults) {
        Map<Cell, Value> cells = Maps.newHashMap();
        for (RowResult<Value> result : rowResults) {
            for (Entry<Cell, Value> entry : result.getCells()) {
                cells.put(entry.getKey(), entry.getValue());
            }
        }
        return cells;
    }

    private Cell getCell(int row, int col) {
        return Cell.create(("row" + row).getBytes(), ("col" + col).getBytes());
    }

    private Value getValue(int val, long timestamp) {
        return Value.create(("val" + val).getBytes(), timestamp);
    }

    private byte[] getRow(int row) {
        return ("row" + row).getBytes();
    }

    private byte[] getCol(int col) {
        return ("col" + col).getBytes();
    }
}


text:
package org.swellrt.beta.model.local;

import java.util.ArrayList;
import java.util.List;

import org.swellrt.beta.common.SException;
import org.swellrt.beta.model.SMutationHandler;
import org.swellrt.beta.model.SList;
import org.swellrt.beta.model.SMap;
import org.swellrt.beta.model.SNode;
import org.swellrt.beta.model.SText;
import org.swellrt.beta.model.SUtils;
import org.swellrt.beta.model.SVisitor;
import org.swellrt.beta.model.js.HasJsProxy;
import org.swellrt.beta.model.js.Proxy;
import org.swellrt.beta.model.js.SListProxyHandler;

import jsinterop.annotations.JsIgnore;

public class SListLocal implements SList<SNode>, HasJsProxy {

  private List<SNode> list = new ArrayList<SNode>();
  private Proxy proxy = null;

  @Override
  public SNode pick(int index) throws SException {
    return list.get(index);
  }

  @Override
  public SList<SNode> add(Object object) throws SException {
    SNode node = SUtils.castToSNode(object);
    list.add(node);
    return this;
  }

  @Override
  public SList<SNode> addAt(Object object, int index) throws SException {
    SNode node = SUtils.castToSNode(object);
    list.add(index, node);
    return this;
  }

  @Override
  public SList<SNode> remove(int index) throws SException {
    list.remove(index);
    return this;
  }

  @Override
  public int indexOf(SNode node) throws SException {
    return list.indexOf(node);
  }

  @Override
  public void clear() throws SException {
    list.clear();
  }

  @Override
  public boolean isEmpty() {
    return list.isEmpty();
  }

  @Override
  public int size() {
    return list.size();
  }

  @Override
  public Iterable<SNode> values() {
    return list;
  }

  public Object js() {
    if (proxy == null)
      proxy = new Proxy(this, new SListProxyHandler());
    return proxy;
  }

  //
  // Js Proxy
  //

  @Override
  public Proxy getJsProxy() {
    return proxy;
  }

  @Override
  public void setJsProxy(Proxy proxy) {
    this.proxy = proxy;
  }

  @SuppressWarnings({ "rawtypes", "unchecked" })
  @JsIgnore
  @Override
  public void accept(SVisitor visitor) {
    visitor.visit(this);
  }

  //
  // -----------------------------------------------------
  //

  @Override
  public void set(String path, Object value) {
    SNode.set(this, path, value);
  }

  @Override
  public void push(String path, Object value) {
    SNode.push(this, path, value);
  }

  @Override
  public Object pop(String path) {
    return SNode.pop(this, path);
  }

  @Override
  public int length(String path) {
    return SNode.length(this, path);
  }

  @Override
  public boolean contains(String path, String property) {
    return SNode.contains(this, path, property);
  }

  @Override
  public void delete(String path) {
    SNode.delete(this, path);
  }

  @Override
  public Object get(String path) {
    return SNode.get(this, path);
  }

  @Override
  public SNode node(String path) throws SException {
    return SNode.node(this, path);
  }

  @Override
  public SMap asMap() {
    throw new IllegalStateException("Node is not a map");
  }

  @Override
  public SList<? extends SNode> asList() {
    return this;
  }

  @Override
  public String asString() {
    throw new IllegalStateException("Node is not a string");
  }

  @Override
  public double asDouble() {
    throw new IllegalStateException("Node is not a number");
  }

  @Override
  public int asInt() {
    throw new IllegalStateException("Node is not a number");
  }

  @Override
  public boolean asBoolean() {
    throw new IllegalStateException("Node is not a boolean");
  }

  @Override
  public SText asText() {
    throw new IllegalStateException("Node is not a text");
  }

  @Override
  public void addListener(SMutationHandler h, String path) throws SException {
    throw new IllegalStateException("Local nodes don't support event listeners");
  }

  @Override
  public void listen(SMutationHandler h) throws SException {
    throw new IllegalStateException("Local nodes don't support event listeners");
  }

  @Override
  public void removeListener(SMutationHandler h, String path) throws SException {
    throw new IllegalStateException("Local nodes don't support event listeners");
  }

  @Override
  public void unlisten(SMutationHandler h) throws SException {
    throw new IllegalStateException("Local nodes don't support event listeners");
  }

}


text:
//
// Copyright(c) 2016-2017 benikabocha.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

#ifndef SABA_GL_GLOBJECT_H_
#define SABA_GL_GLOBJECT_H_

#include <atomic>
#include <GL/gl3w.h>

namespace saba
{

	template <GLenum ShaderType>
	struct GLShaderTraits
	{
		static GLuint Create()
		{
			return glCreateShader(ShaderType);
		}

		static void Destroy(GLuint shader)
		{
			glDeleteShader(shader);
		}
	};

	using GLVertexShaderTraits = GLShaderTraits<GL_VERTEX_SHADER>;
	using GLFragmentShaderTraits = GLShaderTraits<GL_FRAGMENT_SHADER>;
	using GLTessControlShaderTraits = GLShaderTraits<GL_TESS_CONTROL_SHADER>;
	using GLTessEvaluationShaderTraits = GLShaderTraits<GL_TESS_EVALUATION_SHADER>;
	using GLGeometryShaderTraits = GLShaderTraits<GL_GEOMETRY_SHADER>;
	using GLComputeShaderTraits = GLShaderTraits<GL_COMPUTE_SHADER>;

	struct GLProgramTraits
	{
		static GLuint Create()
		{
			return glCreateProgram();
		}

		static void Destroy(GLuint program)
		{
			glDeleteProgram(program);
		}
	};

	struct GLBufferTraits
	{
		static GLuint Create()
		{
			GLuint buf;
			glGenBuffers(1, &buf);
			return buf;
		}

		static void Destroy(GLuint buf)
		{
			glDeleteBuffers(1, &buf);
		}
	};

	struct GLVertexArrayTraits
	{
		static GLuint Create()
		{
			GLuint vertexArray;
			glGenVertexArrays(1, &vertexArray);
			return vertexArray;
		}

		static void Destroy(GLuint vertexArray)
		{
			glDeleteVertexArrays(1, &vertexArray);
		}
	};

	struct GLTextureTraits
	{
		static GLuint Create()
		{
			GLuint tex;
			glGenTextures(1, &tex);
			return tex;
		}

		static void Destroy(GLuint tex)
		{
			glDeleteTextures(1, &tex);
		}
	};

	struct GLFramebufferTraits
	{
		static GLuint Create()
		{
			GLuint fb;
			glGenFramebuffers(1, &fb);
			return fb;
		}

		static void Destroy(GLuint fb)
		{
			glDeleteFramebuffers(1, &fb);
		}
	};

	struct GLRenderbufferTraits
	{
		static GLuint Create()
		{
			GLuint rb;
			glGenRenderbuffers(1, &rb);
			return rb;
		}

		static void Destroy(GLuint rb)
		{
			glDeleteRenderbuffers(1, &rb);
		}
	};

	template <typename GLTraits>
	class GLObject
	{
	public:
		using GLObjectType = GLObject<GLTraits>;

		GLObject()
			: m_obj(0)
		{
		}

		explicit GLObject(GLuint obj)
			: m_obj(obj)
		{
		}

		GLObject(GLObjectType&& rhs)
		{
			m_obj = rhs.m_obj;
			rhs.m_obj = 0;
		}

		GLObjectType& operator =(GLObjectType&& rhs)
		{
			m_obj = rhs.m_obj;
			rhs.m_obj = 0;
			return *this;
		}

		GLObject(const GLObjectType& rhs) = delete;
		GLObjectType& operator =(const GLObjectType& rhs) = delete;

		~GLObject()
		{
			Destroy();
		}

		bool Create()
		{
			Destroy();
			m_obj = GLTraits::Create();
			return m_obj != 0;
		}

		void Destroy()
		{
			if (m_obj != 0)
			{
				GLTraits::Destroy(m_obj);
				m_obj = 0;
			}
		}

		void Reset(GLuint obj)
		{
			Destroy();
			m_obj = obj;
		}

		GLuint Release()
		{
			GLuint ret = m_obj;
			m_obj = 0;
			return ret;
		}

		GLuint Get() const
		{
			return m_obj;
		}

		operator GLuint() const { return m_obj; }

	private:
		GLuint	m_obj;
	};

	template <typename GLTraits>
	class GLRef
	{
	private:
		class GLRefCount
		{
		public:
			GLRefCount(GLuint obj)
				: m_counter(1)
				, m_obj(obj)
			{
			}

			GLRefCount(const GLRefCount&) = delete;
			GLRefCount& operator = (const GLRefCount&) = delete;

			void IncRef()
			{
				m_counter.fetch_add(1);
			}

			void DecRef()
			{
				if (--m_counter == 0)
				{
					if (m_obj != 0)
					{
						GLTraits::Destroy(m_obj);
						m_obj = 0;
						delete this;
					}
				}
			}

			GLuint Get() const
			{
				return m_obj;
			}

			operator GLuint() const { return m_obj; }

			int GetCount() const { return m_counter; }

		private:
			std::atomic<int>	m_counter;
			GLuint				m_obj;
		};

	public:
		using Type = GLTraits;
		using RefType = GLRef<GLTraits>;

		GLRef()
			: m_ref(nullptr)
		{
		}

		~GLRef()
		{
			if (m_ref)
			{
				m_ref->DecRef();
			}
		}

		GLRef(GLuint obj)
			: m_ref(nullptr)
		{
			Reset(obj);
		}

		GLRef(RefType&& rhs)
			: m_ref(nullptr)
		{
			Reset(rhs.m_ref);
			rhs.Reset();
		}

		GLRef(GLObject<GLTraits>&& rhs)
			: m_ref(nullptr)
		{
			Reset(rhs.Release());
		}

		RefType& operator =(RefType&& rhs)
		{
			Reset(rhs.m_ref);
			rhs.Reset();
			return *this;
		}

		RefType& operator =(GLObject<GLTraits>&& rhs)
		{
			Reset(rhs.Release());
			return *this;
		}

		GLRef(const RefType& rhs)
			: m_ref(nullptr)
		{
			Reset(const_cast<GLRefCount*>(rhs.m_ref));
		}

		RefType& operator =(const RefType& rhs)
		{
			Reset(const_cast<GLRefCount*>(rhs.m_ref));
			return *this;
		}

		GLuint Get() const
		{
			if (m_ref != nullptr)
			{
				return m_ref->Get();
			}
			return 0;
		}

		operator GLuint() const
		{
			if (m_ref != nullptr)
			{
				return m_ref->Get();
			}
			else
			{
				return 0;
			}
		}

		int GetRefCount() const
		{
			if (m_ref != nullptr)
			{
				return m_ref->GetCount();
			}
			else
			{
				return 0;
			}
		}

		void Release()
		{
			Reset();
		}

	private:
		void Reset()
		{
			if (m_ref != nullptr)
			{
				m_ref->DecRef();
				m_ref = nullptr;
			}
		}

		void Reset(GLuint obj)
		{
			Reset();
			if (obj != 0)
			{
				m_ref = new GLRefCount(obj);
			}
		}

		void Reset(GLRefCount* refobj)
		{
			Reset();
			if (refobj != nullptr)
			{
				m_ref = refobj;
				m_ref->IncRef();
			}
		}
	private:
		GLRefCount*	m_ref;
	};

	template <GLenum ShaderType>
	using GLShaderObject = GLObject< GLShaderTraits<ShaderType> >;

	using GLVertexShaderObject = GLShaderObject<GL_VERTEX_SHADER>;
	using GLFragmentShaderObject = GLShaderObject<GL_FRAGMENT_SHADER>;
	using GLProgramObject = GLObject<GLProgramTraits>;
	using GLBufferObject = GLObject<GLBufferTraits>;
	using GLVertexArrayObject = GLObject<GLVertexArrayTraits>;
	using GLTextureObject = GLObject<GLTextureTraits>;
	using GLFramebufferObject = GLObject<GLFramebufferTraits>;
	using GLRenderbufferObject = GLObject<GLRenderbufferTraits>;

	template <GLenum ShaderType>
	using GLShaderRef = GLRef< GLShaderTraits<ShaderType> >;

	using GLVertexShaderRef = GLShaderRef<GL_VERTEX_SHADER>;
	using GLFragmentShaderRef = GLShaderRef<GL_FRAGMENT_SHADER>;
	using GLProgramRef = GLRef<GLProgramTraits>;
	using GLBufferRef = GLRef<GLBufferTraits>;
	using GLVertexArrayRef = GLRef<GLVertexArrayTraits>;
	using GLTextureRef = GLRef<GLTextureTraits>;
	using GLFramebufferRef = GLRef<GLFramebufferTraits>;
	using GLRenderbufferRef = GLRef<GLRenderbufferTraits>;
}

#endif // !SABA_GL_GLOBJECT_H_


text: A Star Wars: Rebellion clone using Meteor and SVG (maybe)


text:
//: holding/StackCollision.java
package holding; /* Added by Eclipse.py */
import net.mindview.util.*;

public class StackCollision {
  public static void main(String[] args) {
    net.mindview.util.Stack<String> stack =
      new net.mindview.util.Stack<String>();
    for(String s : "My dog has fleas".split(" "))
      stack.push(s);
    while(!stack.empty())
      System.out.print(stack.pop() + " ");
    System.out.println();
    java.util.Stack<String> stack2 =
      new java.util.Stack<String>();
    for(String s : "My dog has fleas".split(" "))
      stack2.push(s);
    while(!stack2.empty())
      System.out.print(stack2.pop() + " ");
  }
} /* Output:
fleas has dog My
fleas has dog My
*///:~


text:
emberdemo
=========

Learning Ember & Laravel


text:
'''
Created on 2014年6月15日

@author: kerry
'''

from twisted.internet import reactor, protocol
from base.miglog import miglog
from base.net_work import NetData
from scheudler.SchedulerCenter import RobotScheduler
import struct

class MIGBaseSchedulerClient(protocol.Protocol):

    def connectionMade(self):
        miglog.log().debug(" Scheduler connection success")
        self.transport.write(self.scheduler.SchdulerLogin(self.platform_id, self.machine_id))

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        pack_stream,result = self.netdata.net_wok(data)
        miglog.log().debug("result %d",result)
        if(result==0):
            return
        packet_length,operate_code,data_length = self.scheduler.UnpackHead(pack_stream)
        miglog.log().debug("packet_length %d operate_code %d data_length %d",packet_length,operate_code,data_length)
        if(packet_length - 31 <> data_length):
            return
        if(packet_length<=31):
            return
        if (operate_code==1000):
            self.scheduler.NoticeRobotInfo(pack_stream)
        elif(operate_code==2100):
            self.scheduler.NoticeAssistantInfo(pack_stream)
        elif(operate_code==1004):
            self.scheduler.NoticeRobotChatLogin(pack_stream)

    def connectionLost(self, reason):
        print "connection lost"

    def dataWrite(self,data):
        self.transport.write(data)

    def __init__(self):
        print "MIGBaseSchedulerClient:init"
        self.netdata = NetData()
        self.scheduler = RobotScheduler()

    def set_platform_id(self,platform_id):
        self.platform_id = platform_id

    def set_machine_id(self,machine_id):
        self.machine_id = machine_id

    def net_work(self,data):
        #取前4个字节
        alldata = self._unprocessed + data
        currentOffset = 0
        fmt = self.structFormat
        self._unprocessed = alldata

        while len(alldata) >=(currentOffset + self.prefixLength):
            messageStart = currentOffset + self.prefixLength
            length, = struct.unpack(fmt,alldata[currentOffset:messageStart])
            if length > self.PACKET_MAX_LENGTH:
                self._unprocessed = alldata
                self.lenthLimitExceeded(length)
                return
            messageEnd = currentOffset + length
            if len(alldata) < messageEnd:
                break
            packet = alldata[currentOffset:messageEnd]
            currentOffset = messageEnd

        self._unprocessed = alldata[currentOffset:]

        return packet

class MIGBaseSchedulerFactory(protocol.ClientFactory):

    def __init__(self,platformid,machine_id):
        print "MIGBaseSchedulerFactory:__init__"
        self.protocol = MIGBaseSchedulerClient
        self.platformid = platformid
        self.machine_id = machine_id

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()

    def buildProtocol(self, addr):
        p = protocol.ClientFactory.buildProtocol(self, addr)
        p.set_platform_id(self.platformid)
        p.set_machine_id(self.machine_id)
        return p

class MIGInitialScheduler():
    def Connection(self,host,port):
        f = MIGBaseSchedulerFactory(self.platform_id,self.machine_id)
        reactor.connectTCP(host, int(port), f)

    def set_platform_id(self,platform_id):
        self.platform_id = platform_id

    def set_machine_id(self,machine_id):
        self.machine_id = machine_id

    def start_run(self):
        reactor.run()


text:
import { CustomError } from '@twurple/common';

/**
 * Thrown whenever a different token type (user vs. app) is expected in the method you're calling.
 */
export class InvalidTokenTypeError extends CustomError {}


text:
namespace IdentityModel.OidcClient.Results
{
    public class AuthorizeResult : Result
    {
        public string Data { get; set; }
        public AuthorizeState State { get; set; }
    }
}


text:
'use strict'

var path    = require('path')
  , request = require('request')
  , helper  = require('../../lib/agent_helper.js')

// bootstrap instrumentation
helper.instrumentMockedAgent()

// once instrumentation is bootstrapped
var express = require('express')
  , app     = express()
  , server  = require('http').createServer(app)

app.get('/test/:id', function (req, res, next) {
  process.nextTick(function cb_nextTick() { throw new Error('threw in a timer', next); })
})

server.listen(8089, function () {
  process.on('message', function (code) {
    request.get('http://localhost:8089/test/31337', function () {
      process.exit(code)
    })
  })
  process.send('ready')
})


text:
angular.module('focus.v2.controllers')
  .controller('FocusController', ['$scope', '$stateParams', '$modal', 'Core','AssociationMap', 'Argument', 'Logger', 'Bibtex', 'Paper', 'User', 'Bookmark',
  function($scope, $stateParams, $modal, Core, AssociationMap, Argument, Logger, Bibtex, Paper, User, Bookmark) {
    $scope.selectedParagraph = -1;
    $scope.selectedEvidence = null;
    $scope.selectedWords= [];
    $scope.selectedTopic= null;
    $scope.activeParagraphs = [];
    $scope.hasUnsavedChanges = false;
    $scope.recommendedEvidence = [];
    $scope.citedEvidence = [];
    $scope.paragraphInformation =[];
    $scope.paragraphCitation = [];

    $scope.editHistory = [];

    $scope.loadingTexts = true;
    $scope.loadingStatement = 'Retrieving proposals and bookmarked evidence...';

    $scope.loadingRecommendedEvidence = false;
    $scope.selectedEvidenceCiteStatus = 'uncited';
    $scope.savingStatus = 'saved';
    $scope.citationTabs = {
      'recommended':{active: true},
      'cited': {active: false},
      'bookmarked': {active: false}
    };

    var currentText = '';
    var previousText = '';

    $scope.logStateTransition = function() {
      Logger.logAction($scope.userId, 'explore recommended citation', 'v2','1', 'focus', {
      }, function(response) {
        if (isDebug)
          console.log('action logged: explore recommended citation');
      });
    }

    $scope.selectText = function(text, userInitiated) {
      if (userInitiated) {
        Logger.logAction($scope.userId, 'select proposal', 'v2','1', 'focus', {
          proposal: text.id,
          contentLength: text.content.split(' ').length
        }, function(response) {
          if (isDebug)
            console.log('action logged: select proposal');
        });
      }

      $scope.selectedText = text;
      User.activeProposal($scope.selectedText);
      $scope.paragraphInformation= [];
      $scope.paragraphCitation = [];
      $scope.activeParagraphs = _.filter(text.content.split('\n'), function(text){
        return text !== '';
      }).map(function(p, i) {
        $scope.paragraphInformation.push({});
        $scope.paragraphCitation.push([]);
        $scope.editHistory.push([]);
        updateRecommendedCitations(p, i);
        var timestamps = [];
        p.split('').forEach(function() {
          timestamps.push(new Date());
        });
        return {
          text: p,
          timestamps: timestamps
        };
      });
      User.activeParagraphs($scope.activeParagraphs);
      User.paragraphCitation($scope.paragraphCitation);
      updateCitedEvidence();
    };

    var blob = null;
    var textEvidenceAssociations = null;
    var evidenceIdMap = null;
    var isDebug = true;
    $scope.evidence = null;

    User.updateSessionInfo($stateParams.userId, $stateParams.collectionId, function(userId, collection) {
      $scope.userId = userId;
      $scope.collection = collection;

      Paper.initializeCitationMap($scope.collection.id, $scope.userId);

      AssociationMap.initialize($scope.userId, function() {
        textEvidenceAssociations = AssociationMap.getAssociationsOfType('evidence', 'text');
        updateCitedEvidence();
      });

      loadEvidence();
    });

    // Check if the current text have changed every 10 secondsand save the contents.
    // if there are changes,
    setInterval(function(){
      if ($scope.hasUnsavedChanges) {
        $scope.saveText();
      }
    }, 5000);

    function loadEvidence() {
      Bookmark
        .userId($scope.userId)
        .evidence(function(evidence, idMap) {
          $scope.evidence = evidence;
          evidenceIdMap = idMap;
          updateCitedEvidence();
          loadTexts();
        });

      var newParagraphIndex = -1;

      $scope.$watch(function() {
        return d3.selectAll('.text-paragraph')[0].length;
      }, function(newValue, oldValue) {
        if (isDebug)
          console.log('watch on # of .text-paragraph executing...')
        var el =document.getElementById('ap-' +newParagraphIndex);
        if (el !== null && newValue > oldValue){
          el.innerText = '';
          el.focus();
        }
      });
    }

    function loadTexts() {
      User.proposals(function(proposals) {
        $scope.texts = proposals;
        if ($scope.texts.length > 0) {
          $scope.selectText(User.activeProposal(), false);
        }
        $scope.loadingTexts = false;
        Logger.logAction($scope.userId, 'load focus view', 'v2','1', 'focus', {
          numProposals: $scope.texts.length
        }, function(response) {
          if (isDebug)
            console.log('action logged: load view');
        });
      });
    }

    // TODO: known bug: if 1) add a new paragraph at the end of the proposal (it's fine if the paragraph is added in the middle),
    // 2) download the proposal, then the new paragraph will beome invisible in the text area
    // (the sorrounding spans are removed somehow), but it will appear if refresh the page (i.e. the paragraph itself is stored)
    function prepareProposalDownload() {
      var content = '';
      for (var i = 0; i < $scope.activeParagraphs.length; ++i) {
        var paragraph = $scope.activeParagraphs[i];
        var citations = $scope.paragraphCitation[i].map(function(c) {
          return c.index;
        }).sort();
        content += paragraph.text;
        for (var j = 0; j < citations.length; ++j) {
          content += '[' + (citations[j] + 1) + ']';
        }
        content += '\n';
      }
      for (var i = 0; i < $scope.activeParagraphs.length; ++i) {
        console.assert($scope.paragraphCitation[i] !== undefined);
      }
      content += '\nReferences\n'
      for (var i = 0; i < $scope.citedEvidence.length; ++i) {
        var evidence = $scope.citedEvidence[i];
        if (evidence.metadata === undefined) continue;
        content += (i+1) + '. ';
        content += evidence.metadata.AUTHOR + ' ';
        content += evidence.title + '. ';
        if (evidence.metadata.JOURNAL !== undefined) {
          content += evidence.metadata.JOURNAL + ' ';
        }
        if (evidence.metadata.DATE !== undefined) {
          content += evidence.metadata.DATE + ' ';
        }
        content += '\n';
      }

      blob = new Blob([ content ], { type : 'text/plain' });
      $scope.proposalUrl = (window.URL || window.webkitURL).createObjectURL( blob );
    };

    // TODO
    $scope.loadPlainTextProposalFile = function() {
    };

    // TODO
    $scope.loadLatexProposalFile = function() {
      // Need to find and remove latex commands...
    }

    $scope.selectEvidence = function(evidence, sourceList, userInitiated) {
      if (userInitiated) {
        Logger.logAction($scope.userId, 'select evidence', 'v2', '1', 'focus', {
          evidence: evidence.id,
          sourceList: sourceList
        }, function(response) {
          if (isDebug)
            console.log('action logged: select evidence');
        });
      }

      $scope.selectedEvidence = evidence;
      User.selectedEvidence($scope.selectedEvidence);
      $scope.selectedWords = evidence.abstract.split(' ');

      var textParaId = $scope.selectedText.id+ '-' + $scope.selectedParagraph;
      if (AssociationMap.hasAssociation('evidence', 'text', $scope.selectedEvidence.id, textParaId)) {
        $scope.selectedEvidenceCiteStatus = 'cited';
      }
      else {
        $scope.selectedEvidenceCiteStatus = 'uncited';
      }

    };

    $scope.selectParagraph = function(index, clickTarget) {
      if (index!== $scope.selectedParagraph) {
        Logger.logAction($scope.userId, 'select paragraph', 'v2', '1', 'focus', {
          proposal: $scope.selectedText.id,
          paragraph: index,
          clickTarget: clickTarget
        }, function(response) {
          if (isDebug)
            console.log('action logged: select paragraph');
        });

        $scope.selectedParagraph =index;
//        currentParagraph = $scope.activeParagraphs[$scope.selectedParagraph];
        updateRecommendedCitations($scope.activeParagraphs[index].text, index);
      }
    };

    $scope.flipBookmark = function(e, source) {
      Bookmark.flipBookmark(e, 'focus', source);
    }

    $scope.bookmarkEvidence = function(e, source) {
      Logger.logAction($scope.userId, 'bookmark evidence', 'v2', '1', 'focus', {
        evidence: e.id,
        numDocuments: $scope.evidence.length,
        source: source
      }, function(response) {
        console.log('action logged: bookmark evidence');
      });
      Core.addBookmark($scope.userId, e.id, function(response) {
        $scope.evidence.push(e);
        e.bookmarked = true;
        console.log('bookmark evidence success');
      }, function(errorResponse) {
        console.log(errorResponse);
      });
    }

    $scope.unbookmarkEvidence = function(e, source) {
      Logger.logAction($scope.userId, 'remove evidence bookmark', 'v2', '1', 'focus', {
        evidence: e.id,
        numDocuments: $scope.evidence.length,
        source: source
      }, function(response) {
        console.log('action logged: remove evidence bookmark');
      });
      Core.deleteBookmark($scope.userId, e.id, function(response) {
        $scope.evidence = _.without($scope.evidence, e);
        e.bookmarked = false;
        console.log('remove evidence bookmark success');
      }, function(errorResponse) {
        console.log(errorResponse);
      });
    }

    $scope.citeEvidence = function(evidence, sourceList) {
      var textParaId = $scope.selectedText.id+ '-' + $scope.selectedParagraph;
      if (AssociationMap.hasAssociation('evidence', 'text', evidence.id, textParaId)) {
        return;
      }
      Logger.logAction($scope.userId, 'cite evidence', 'v2', '1', 'focus', {
        proposal: $scope.selectedText.id,
        paragraph: $scope.selectedParagraph,
        evidence: evidence.id,
        sourceList: sourceList
      }, function(response) {
        if (isDebug)
          console.log('action logged: cite evidence');
      });
      //Add association
      AssociationMap.addAssociation($scope.userId,'evidence', 'text', evidence.id, textParaId, function(association) {
        // Add evidence to the list of cited evidence
        var index = $scope.citedEvidence.map(function(e) {
          return e.id;
        }).indexOf(evidence.id);
        if (index === -1) {
          $scope.citedEvidence.push(evidence);
          index = $scope.citedEvidence.length - 1;
          Bookmark.addBookmark(evidence, 'focus', 'cite');
        }
        // Add the association to text evidence association for book-keeping (since we need to update the association entry
        // when new paragraphs are added)
        textEvidenceAssociations.push(association);
        $scope.paragraphCitation[$scope.selectedParagraph].push({
          index: index,
          evidence: evidence
        });
        prepareProposalDownload();
      });
    };

    $scope.unciteEvidence = function(evidence, sourceList) {
      console.log('unciting')
      var textParaId = $scope.selectedText.id+ '-' + $scope.selectedParagraph;
      Logger.logAction($scope.userId, 'uncite evidence', 'v2', '1', 'focus', {
        proposal: $scope.selectedText.id,
        paragraph: $scope.selectedParagraph,
        evidence: evidence.id,
        sourceList: sourceList
      }, function(response) {
        if (isDebug)
          console.log('action logged: uncite evidence');
      });
      //Add association
      AssociationMap.removeAssociation($scope.userId,'evidence', 'text', evidence.id, textParaId, function(association) {
        // Add evidence to the list of cited evidence
        var index = $scope.citedEvidence.map(function(e) {
          return e.id;
        }).indexOf(evidence.id);
        var lengthBefore = textEvidenceAssociations.length;
        _.pull(textEvidenceAssociations, _.findWhere(textEvidenceAssociations, {sourceId: evidence.id.toString(), targetId: textParaId}))
        console.assert(textEvidenceAssociations.length === lengthBefore - 1);
        var lengthBefore = $scope.paragraphCitation[$scope.selectedParagraph].length;
        _.pull($scope.paragraphCitation[$scope.selectedParagraph], _.findWhere($scope.paragraphCitation[$scope.selectedParagraph], {index: index, evidence: evidence}));
        console.assert($scope.paragraphCitation[$scope.selectedParagraph].length === lengthBefore - 1);
        prepareProposalDownload();
      });
    }

    $scope.showCitation = function(citation) {
      Logger.logAction($scope.userId, 'show citation', 'v2', '1', 'focus', {
        proposal: $scope.selectedText.id,
        paragraph: $scope.selectedParagraph,
        citation: citation.evidence.id
      }, function(response) {
        if (isDebug)
          console.log('action logged: show citation');
      });

      $scope.selectEvidence(citation.evidence, null, false);
      $scope.citationTabs['cited'].active= true;
    }

    $scope.openUploadBibtexWindow = function() {
      Logger.logAction($scope.userId, 'open upload bibtex window', 'v2', '1', 'focus', {
      }, function(response) {
        if (isDebug)
          console.log('action logged: open upload bibtex window');
      });

      var modalInstance = $modal.open({
        templateUrl: 'modal/uploadBibtexModal.html',
        controller: 'UploadBibtexModalController',
        resolve: {
          userId: function() {
            return $scope.userId;
          },
          collectionId: function() {
            return $scope.collection.id;
          },
          existingEvidence: function() {
            return $scope.evidence.map(function(e) {
              return e.title;
            });
          }
        }
      });

      modalInstance.result.then(function (uploadedEvidence) {
        $scope.evidence = $scope.evidence.concat(uploadedEvidence);
      });
    }

    $scope.processBibtexFile = function() {
      var selectedFile = document.getElementById('bibtex-input').files[0];
      var reader = new FileReader();
      reader.onload = function(file) {
        var fileContent = file.currentTarget.result;
        var evidenceList = Bibtex.parseBibtexFile(fileContent);
        var storedEvidence = [];

        var evidenceIndex = 0;
        var totalAbstractFound = 0;
        var uploadFunction = setInterval(function() {
          console.log(evidenceIndex);
          if (evidenceIndex >= evidenceList.length) {
            clearInterval(uploadFunction);
            return;
          }
          var evidence = evidenceList[evidenceIndex];
          Core.postEvidenceByUserId($scope.userId, evidence.title, evidence.abstract, JSON.stringify(evidence.metadata),
            function(response) {
              // TODO: probably more efficient to deal with this server side
              if ($scope.evidence.indexOf(response.data[0]) > -1 || storedEvidence.indexOf(response.data[0]) > -1) {
                return;
              }
              storedEvidence.push(response.data[0]);
              if (evidence.abstract === '' && response.data[0].abstract !== '') {
                totalAbstractFound += 1;
              }
              if (storedEvidence.length === evidenceList.length) {
                $scope.evidence = $scope.evidence.concat(storedEvidence);
                console.log('total bibtex entry processed: ' + evidenceList.length);
                console.log('total abstracts found: ' + totalAbstractFound);
//                extendEvidenceMap(storedEvidence, 1);
              }
            }, function(response) {
              console.log('server error when saving new evidence');
              console.log(response);
            });

          evidenceIndex += 1;
        }, 3000);
      };
      reader.readAsText(selectedFile);
    };

    $scope.addTextEntry = function() {
      Logger.logAction($scope.userId, 'initiate proposal creation', 'v2','1', 'focus', {
        totalProposals: $scope.texts.length
      }, function(response) {
        if (isDebug)
          console.log('action logged:initiate proposal creation');
      });

      var modalInstance = $modal.open({
        templateUrl: 'modal/textsModal.html',
        controller: 'TextsModalController',
        resolve: {
          textsInfo: function() {
            return {
              id: -1,
              title: "",
              content: ""
            }
          },
          concepts: function() {
            return null;
          },
          evidence: function() {
            return $scope.evidence;
          },
          userId: function() {
            return $scope.userId;
          }
        }
      });

      modalInstance.result.then(function (newEntry){
        Logger.logAction($scope.userId, 'proposal created', 'v2','1', 'focus', {
          proposal: newEntry.id,
          contentLength: newEntry.content.split(' ').length,
          totalProposals: $scope.texts.length
        },function(response) {
          if (isDebug)
            console.log('action logged: proposal created');
        });

        $scope.texts.push(newEntry);
        $scope.selectText(newEntry, false);
      });
    }

    // WIP: this function needs to do the following:
    // 1. for every user keystroke, figure out which words is being updated
    // 2. update the timestamp for the corresponding word
    // We could use a diff here. Every time the user makes a change (not necessarily changing one character),
    // we compute the diff, and figure out indexes for the words that have been changed; then we update the timestamp
    // in the corresponding container
    function updateTextAge(paraIndex) {
      var currentText = document.getElementById('ap-' + paraIndex).innerText;
      var startDiffPos = 0;
      var prevChars = previousText.split('');
      var currentChars = currentText.split('');
      var maxTextLength = Math.max(prevChars.length, currentChars.length);
      var minTextLength = Math.min(prevChars.length, currentChars.length);
      for (var i = 0; i < maxTextLength; ++i) {
        if (prevChars[i] !== currentChars[i]) {
          startDiffPos = i;
          break;
        }
      }
      var endDiffPosPrev = prevChars.length;
      var endDiffPosNow = currentChars.length;
      for (var delta = 0; delta < minTextLength; ++delta) {
        if (prevChars[endDiffPosPrev-delta] !== currentChars[endDiffPosNow-delta]) {
          endDiffPosPrev -= delta;
          endDiffPosNow -= delta;
          break;
        }
      }
      // everything was changed in place
      if (endDiffPosPrev === endDiffPosNow) {
        for (var counter = endDiffPosPrev; counter < endDiffPosNow; ++counter) {
          $scope.activeParagraphs[paraIndex].timestamps[counter] = new Date();
        }
      }
      else if (endDiffPosPrev > endDiffPosNow) {// some characters are deleted
        $scope.activeParagraphs[paraIndex].timestamps.splice(endDiffPosNow, endDiffPosPrev - endDiffPosNow);
        if (startDiffPos <= endDiffPosNow) {
          for (var counter = startDiffPos; counter < endDiffPosPrev; ++counter) {
            $scope.activeParagraphs[paraIndex].timestamps[counter] = new Date();
          }
        }
      }
      else { // some characters were added
        for (var counter = endDiffPosPrev; counter < endDiffPosNow; ++counter) {
          $scope.activeParagraphs[paraIndex].timestamps.splice(counter, 0, new Date());
        }
        if (startDiffPos <= endDiffPosPrev) {
          for (var counter = startDiffPos; counter < endDiffPosPrev; ++counter) {
            $scope.activeParagraphs[paraIndex].timestamps[counter] = new Date();
          }
        }
      }
//      User.activeParagraphs($scope.activeParagraphs);
    }

    function updateCitedEvidence() {
      if ($scope.selectedText === undefined) return;
      if (textEvidenceAssociations === null || _.size(evidenceIdMap) === 0) {
        $scope.citedEvidence = [];
        User.citedEvidence($scope.citedEvidence);
        return;
      }

      $scope.citedEvidence = _.without(_.uniq(_.filter(textEvidenceAssociations, function(a) {
        var textId = a.targetId.toString().split('-');
        return textId[0] == $scope.selectedText.id && textId.length===2;
      }).map(function(a) {
        if (evidenceIdMap[a.sourceId] === undefined) {
          console.log(a.sourceId)
          console.log(evidenceIdMap)
          console.log('Warning: inconsistency between citations and bookmarks detected.');
        }
        return evidenceIdMap[a.sourceId];
      })), undefined);

      User.citedEvidence($scope.citedEvidence);

      // Identify citations for each paragraph
      textEvidenceAssociations.forEach(function(a) {
        var textId = a.targetId.toString().split('-');
        if (textId[0] != $scope.selectedText.id || textId.length>2) return;
        var paragraphIndex = parseInt(textId[1]);
        if (paragraphIndex >= $scope.paragraphCitation.length) return;
        var e = evidenceIdMap[a.sourceId];
        var evidenceIndex = $scope.citedEvidence.indexOf(e);
        $scope.paragraphCitation[paragraphIndex].push({
          index: evidenceIndex,
          evidence: e
        });
      });
      prepareProposalDownload();
    }

    function insertTextAtCursor(text) {
      var sel, range, html;
      sel = window.getSelection();
      range = sel.getRangeAt(0);
      range.deleteContents();
      var textNode = document.createTextNode(text);
      range.insertNode(textNode);
      range.setStartAfter(textNode);
      sel.removeAllRanges();
      sel.addRange(range);
    }

    $scope.cites = function(t, i, e) {
      if (e ===null || t === null) {
        return false;
      }
      return AssociationMap.hasAssociation('evidence', 'text', e.id, t.id + '-' + i);
    };

    $scope.checkEnter= function(i, e){
      if (e.keyCode === 13) {
        Logger.logAction($scope.userId, 'create new paragraph', 'v2', '1', 'focus', {
          proposal: $scope.selectedText.id,
          totalParagraphs: $scope.activeParagraphs.length
        }, function(response) {
          if (isDebug)
            console.log('action logged: create new paragraph');
        });
        e.preventDefault();
        var enterPosition = getCaretCharacterOffsetWithin(document.getElementById('ap-' + i));
        if (enterPosition === 0) {
          newParagraphIndex = i;
        }
        else {
          newParagraphIndex = i+1;
          // TODO: handle enter in the middle of paragraph
        }
        updateParagraphs(newParagraphIndex, i, true);
        updateTextEvidenceAssociations(newParagraphIndex, true);
        return;
      }
      // Delete a paragraph if user presses backspace when it's already empty
      // Known issue: Does not move the cursor anywhere if the first paragraph is deleted
      else if (e.keyCode === 8 && $scope.activeParagraphs[i].text.trim().length === 0) {
        e.preventDefault();
        newParagraphIndex = Math.max(0, i-1);
        updateParagraphs(newParagraphIndex, i, false);
        updateTextEvidenceAssociations(i, false);
        // We are forcing a focus here instead of waiting for the watch on d3.selectAll('.text-paragraph') to trigger,
        // because it does not trigger sometimes or has a delay. Can't tell when it is triggered immediately when it is not
        var el =document.getElementById('ap-' +newParagraphIndex);
        if (el !== null){
          el.focus();
          setEndOfContenteditable(el);
        }
        return;
        // TODO: update citedEvidence, textEvidenceAssociations
      }
      else {
        previousText = document.getElementById('ap-' + i).innerText;
        Logger.logAction($scope.userId, 'edit paragraph', 'v2', '1', 'focus', {
          proposal:$scope.selectedText.id,
          paragraph: $scope.selectedParagraph
        }, function(response) {
          if (isDebug)
            console.log('action logged: edit paragraph');
        },function(response) {
          if (isDebug)
            console.log('error occurred during logging: edit paragraph')
        }, true);
        return;
      }
    };

    function compareString( s1, s2, splitChar ){
        if ( typeof splitChar == "undefined" ){
            splitChar = " ";
        }
        var string1 = new Array();
        var string2 = new Array();

        string1 = s1.split( splitChar );
        string2 = s2.split( splitChar );
        var diff = new Array();

        if(s1.length>s2.length){
            var long = string1;
        }
        else {
            var long = string2;
        }
        for(x=0;x<long.length;x++){
            if(string1[x]!=string2[x]){
                diff.push(string2[x]);
            }
        }

        return diff;
    }

    function updateParagraphs(newParagraphIndex, i, add) {
      if (add) {
        $scope.activeParagraphs.splice(newParagraphIndex, 0, {text: '', timestamps: []});
        $scope.paragraphInformation.splice(newParagraphIndex, 0,{});
        $scope.paragraphCitation.splice(newParagraphIndex, 0, []);
        $scope.editHistory.splice(newParagraphIndex, 0, []);
        updateRecommendedCitations($scope.activeParagraphs[i].text, i);
      }
      else {
        $scope.activeParagraphs.splice(i, 1);
        $scope.paragraphInformation.splice(i, 1);
        $scope.paragraphCitation.splice(i, 1);
        $scope.editHistory.splice(i, 1);
        updateRecommendedCitations($scope.activeParagraphs[newParagraphIndex].text, newParagraphIndex);
      }
      $scope.selectedParagraph = newParagraphIndex;
//      currentParagraph = $scope.activeParagraphs[$scope.selectedParagraph];
    }

    function updateTextEvidenceAssociations(startIndex, shiftRight) {
      if (!shiftRight) {
        var deletedAssociations = [];
        textEvidenceAssociations.forEach(function(association) {
          var ids = association.targetId.split('-');
          var textId = parseInt(ids[0]);
          var paragraphId = parseInt(ids[1]);
          if (paragraphId === startIndex) {
            console.log('ready to delete citation')
            console.log(association)
            AssociationMap.removeAssociationById(association.id, function(response) {
              console.log('association with evidence ' + association.sourceId + ' deleted')
              deletedAssociations.push(association.id);
            });
          }
        });
        textEvidenceAssociations = _.reject(textEvidenceAssociations, function(association) {
          return deletedAssociations.indexOf(association.id) > -1;
        })
      }
      console.log(textEvidenceAssociations)
      // Update evidence association for all shifted paragraphs
      textEvidenceAssociations.forEach(function(association) {
        var ids = association.targetId.split('-');
        var textId = parseInt(ids[0]);
        var paragraphId = parseInt(ids[1]);

        if (textId === $scope.selectedText.id && paragraphId > startIndex) {
          var offset = shiftRight ? 1 : -1;
          var newTargetId = $scope.selectedText.id + '-' + (paragraphId + offset);
          AssociationMap.updateAssociation(association.id, association.sourceId, newTargetId);
        }
      });
    }

    function setEndOfContenteditable(contentEditableElement) {
        var range,selection;
        if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
        {
            range = document.createRange();//Create a range (a range is a like the selection but invisible)
            range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            selection = window.getSelection();//get the selection object (allows you to change selection)
            selection.removeAllRanges();//remove any selections already made
            selection.addRange(range);//make the range you have just created the visible selection
        }
        else if(document.selection)//IE 8 and lower
        {
            range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
            range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            range.select();//Select the range (make it the visible selection
        }
    }

    function getCaretCharacterOffsetWithin(element) {
        var caretOffset = 0;
        var doc = element.ownerDocument || element.document;
        var win = doc.defaultView || doc.parentWindow;
        var sel;
        if (typeof win.getSelection != "undefined") {
            sel = win.getSelection();
            if (sel.rangeCount > 0) {
                var range = win.getSelection().getRangeAt(0);
                var preCaretRange = range.cloneRange();
                preCaretRange.selectNodeContents(element);
                preCaretRange.setEnd(range.endContainer, range.endOffset);
                caretOffset = preCaretRange.toString().length;
            }
        } else if ( (sel = doc.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            var preCaretTextRange = doc.body.createTextRange();
            preCaretTextRange.moveToElementText(element);
            preCaretTextRange.setEndPoint("EndToEnd", textRange);
            caretOffset = preCaretTextRange.text.length;
        }
        return caretOffset;
    }

    $scope.hasMadeChanges = function(i,e) {
      $scope.savingStatus = 'unsaved';
      $scope.hasUnsavedChanges = true;
      $scope.activeParagraphs[i].text = document.getElementById('ap-' + i).innerText;
      // Hacky: relying on the assumption that the value equality test fails only when the user enters anything in the new
      // paragraph for the firs time.
      if (document.getElementById('ap-' + i).childNodes[0].nodeValue !== '') {
        document.getElementById('ap-' + i).childNodes[0].nodeValue = '';
      }
//      previousText = currentParagraph.text;
//      currentParagraph = $scope.activeParagraphs[i];
      updateTextAge(i)
    };

    $scope.downloadText = function() {
      Logger.logAction($scope.userId, 'download proposal', 'v2', '1', 'focus', {
        length:$scope.selectedText.content.split(' ').length,
        totalProposals: $scope.texts.length
      }, function(response) {
        if (isDebug)
          console.log('action logged: download proposal');
      });
    };

    $scope.deleteText = function() {
      Logger.logAction($scope.userId, 'initiate proposal deletion', 'v2', '1', 'focus', {
        length:$scope.selectedText.content.split(' ').length,
        totalProposals: $scope.texts.length
      }, function(response) {
        if (isDebug)
          console.log('action logged: initiate proposal deletion');
      });

      var modalInstance = $modal.open({
        templateUrl: 'modal/deleteModal.html',
        controller: 'DeleteModalController',
        resolve: {
          content: function() {
            return $scope.selectedText.title;
          },
          ids: function() {
            return[$scope.selectedText.id];
          },
          type: function() {
            return 'text';
          },
          userId: function() {
            return $scope.userId;
          }
        }
      });

      var target = $scope.texts;
      modalInstance.result.then(function (deletedEntryId) {
        Logger.logAction($scope.userId, 'proposal deleted', 'v2','1', 'focus', {
          length: $scope.selectedText.content.split(' ').length,
          totalProposals: $scope.texts.length
        },function(response) {
          if (isDebug)
            console.log('action logged: proposal delete');
        });
        for (var i = 0; i < deletedEntryId.length; ++i) {
          var entryId = deletedEntryId[i];
          _.remove(target, function(elem) {
            return elem.id == entryId;
          })
        };
      });
    };

    $scope.isTopicTerm = function(w) {
      if (w === 'of') {
        return false;
      }
      if ($scope.selectedTopic === null) return false;
      var topicTerms = _.take($scope.selectedTopic.terms, 10);
      for (var i = 0; i < topicTerms.length;++i) {
        var term = topicTerms[i].term;
        var term_parts = term.split(' ');
        var word_parts = w.split('-');
        if (term_parts.indexOf(w) > -1) {
          return true;
        }
        for (var j = 0;j < word_parts.length; ++j) {
          var wp= word_parts[j];
          if(term_parts.indexOf(wp) > -1) {
            return true;
          }
        }
      }
      return false;
    };

    // Check every 15 seconds if there is unsaved changes; ifthere is, .
    // call this function to save the content.
    $scope.saveText = function(userInitiated) {
      $scope.savingStatus = 'saving';
      if (isDebug) {
        console.log('saving text...');
        console.log($scope.savingStatus)
      }

      var newContent = $scope.activeParagraphs.map(function(p) {
        return p.text;
      }).join('\n');

      if (userInitiated) {
        Logger.logAction($scope.userId, 'save proposal', 'v2','1', 'focus', {
          proposal: $scope.selectedText.id,
          contentLength: newContent.split(' ').length
        }, function(response) {
          if (isDebug)
            console.log('action logged: save proposal');
        });
      }

      Core.postTextByUserId($scope.userId, $scope.selectedText.title, newContent, false, $scope.selectedText.id, function(response){
        $scope.texts.forEach(function(t) {
          if (t.id === response.data[0].id){
            t.content = newContent;
          }
        })
        $scope.hasUnsavedChanges = false;
        $scope.savingStatus = 'saved';
      }, function(response) {
        console.log('server error when saving new concept');
        console.log(response);
        $scope.savingStatus = 'failed';
      });
    }

    function updateRecommendedCitations(text,index) {
      if (text.split(' ').length < 5) {
        console.log('not enough information to update evidence recommendation');
        return;
      }
      if ($scope.loadingRecommendedEvidence) {
          console.log('updating already in progress');
          return;
      }
      if (isDebug)
        console.log('updating evidence recommendations..');
      $scope.loadingRecommendedEvidence = true;

      Argument.getEvidenceRecommendation(text, $scope.collection.id, function(results) {
        $scope.recommendedEvidence = results.evidence;
        var bookmarkedEvidenceIds = $scope.evidence === null ? [] : $scope.evidence.map(function(e) { return e.id; })
        $scope.recommendedEvidence.forEach(function(e) {
          if ($scope.evidence !== null) {
            e.bookmarked = bookmarkedEvidenceIds.indexOf(e.id) > -1;
          }
          else {
            e.bookmarked = false;
          }
        })
        $scope.paragraphInformation[index].topic = results.topic;
        if (results.topic.terms !== '') {
          $scope.paragraphInformation[index].topicString = results.topic.terms.map(function(term) {
            return term[0];
          }).join(' ');
        }
        else {
          $scope.paragraphInformation[index].topicString = '';
        }
        $scope.loadingRecommendedEvidence = false;
      }, function(errorResponse) {
          console.log('error occurred while recommending citations');
          console.log(errorResponse);
      });
  }

}]);


text:
package cromwell.backend.google.pipelines.v2alpha1.api

//noinspection TypeAnnotation
object ActionFlag extends Enumeration {
  type ActionFlag = Value

  val FlagUnspecified = Value("FLAG_UNSPECIFIED")
  val IgnoreExitStatus = Value("IGNORE_EXIT_STATUS")
  val RunInBackground = Value("RUN_IN_BACKGROUND")
  val AlwaysRun = Value("ALWAYS_RUN")
  val EnableFuse = Value("ENABLE_FUSE")
  val PublishExposedPorts = Value("PUBLISH_EXPOSED_PORTS")
  val DisableImagePrefetch = Value("DISABLE_IMAGE_PREFETCH")
}