text:
//https://people.mozilla.org/~jorendorff/es6-draft.html#sec-map-objects

(function () {
    var NativeMap = window.Map;
    var NativeSet = window.Set;

    var toString = Object.prototype.toString;
    var defineProperty = Object.defineProperty;
    var defineProperties = Object.defineProperties;

    function toStrTag(object) {
        return toString.call(object).slice(8, -1);
    }

    function toInt(val) {
        return val >> 0;
    }

    function toLen(val) {
        return val >= 0 ? val >> 0 : 0;
    }

    var isArray = Array.isArray;

    function isArrayLike(object) {
        return object.length && typeof object.length === 'number';
    }

    function isFn(fn) {
        return typeof fn === 'function' || toStrTag(fn) === 'Function';
    }

    function isDef(val) {
        return typeof val !== 'undefined';
    }

    function isMap(map) {
        return map instanceof Map || NativeMap && map instanceof NativeMap || toStrTag(map) === 'Map';
    }

    function isSet(set) {
        return set instanceof Set || NativeSet && set instanceof NativeSet || toStrTag(set) === 'Set';
    }

    function isStr(object) {
        return typeof object == 'string';
    }

    function isIterator(object) {
        return object && isFn(object.next);
    }

    function isIterable(o) {
        return isArray(o) || isStr(o) || isMap(o) || isSet(o) || isIterator(o);
    }

    function iterate(o, fn) {
        var it = isIterator(o) ? o : isMap(o) ? o.entries() : o.values(),
            res = it.next();
        while (!res.done) {
            fn(res.value);
            res = it.next();
        }
    }

    function isEntry(object) {
        var type = typeof object;
        return type != 'number' && type != 'string';
    }

    function isNull(object) {
        return object == null;
    }

    function isEntryOrDie(value) {
        if (!isEntry(value))
            fail("Iterator value " + value + " is not an entry object");
        return true;
    }

    function fail(m) {
        throw new TypeError(m);
    }

    function guardType(isType, object, typeName) {
        if (!isType(object))
            fail(toStrTag(object) + ' is not an instance of ' + typeName + '.');
    }

    function guardMethod(isType, obj, meth) {
        if (!isType(obj))
            fail(meth + ' method called on incompatible ' + toStrTag(obj));
    }

    function toObject(obj) {
        if(obj == null) fail('Value is undefinied or null.')
        return Object(obj);
    }

    function iterNext(value) {
        return {
            value: value,
            done: false
        }
    }

    function iterDone() {
        return {
            value: void 0,
            done: true
        }
    }

    function mapAdd(ent) {
        this.set(ent[0], ent[1]);
    }

    function toPos(i, len) {
        i = i | 0;
        return  i < 0 ? max(0, len + i) : min(i, len);
    }

    // FEATURE DETECTION
    function testConst(C) {
        return (new C([[0,0]])).size > 0;
    }

    function testIsIterable(o) {
        return (isFn(o.entries) && isFn(o.values) && isFn(o.keys));
    }

    if (!Object.is)
        defineProperty(Object, 'is', {
            //Object.is
            value: function is(a, b) {
                return a === 0 && b === 0
                    ? 1 / a === 1 / b
                    : a === b || a !== a && b !== b;
            }
        });

    var is = Object.is;
    var max = Math.max;
    var min = Math.min;

    // Array.from
    if (!Array.from)
        defineProperty(Array, 'from', {
            value: function from(source /*, mapFn, thisArg*/) {
                var mapFn = arguments[1],
                    thisArg = arguments[2];

                if (source == null)
                    fail("Array.from requires an array-like object - not null or undefined");

                if (isDef(mapFn) && !isFn(mapFn))
                    fail('Array.from: when provided, the second argument must be a function');

                var len = toLen(source.length || source.size);
                var result = isFn(this) ? new this(len) : new Array(len);
                var hasThisArg = arguments.length > 2;

                var iterator =
                    isMap(source) ? source.entires() :
                    isSet(source) ? source.values() :
                    isIterator(source) ? source :
                    void 0;
                var i = 0;
                if (iterator) {
                    var itRes = iterator.next();
                    while(!itRes.done) {
                        result[i] = mapFn ? (hasThisArg ? mapFn.call(thisArg, itRes.value, i) : mapFn(itRes.value, i)) : itRes.value;
                        itRes = iterator.next();
                        i++;
                    }
                } else {
                    while (i < len) {
                        result[i] = mapFn ? (hasThisArg ? mapFn.call(thisArg, source[i], i) : mapFn(source[i], i)) : source[i];
                        i++;
                    }
                }
                return result;
            }
        });

    // Array.of
    if (!Array.of)
        defineProperty(Array, 'of', {
            value: function of() {
                return Array.prototype.slice.call(arguments);
            }
        });

    // Array#copyWithin
    if (!Array.prototype.copyWithin)
        defineProperty(Array.prototype, 'copyWithin', {
            value: function copyWithin(target, start/*, end*/) {
                var self = toObject(this),
                    len = toLen(self.length),
                    end = arguments.length >= 3 ? toPos(arguments[2], len) : len,
                    to = toPos(target, len),
                    from = toPos(start, len),
                    count = min(end - from, len - to),
                    direction = 1;

                if (from < to && to < (from + count)) {
                    direction = -1;
                    from += count - 1;
                    to += count - 1;
                }

                while (count > 0) {
                    if (from in self)
                        self[to] = self[from];
                    else
                        delete self[to];

                    from += direction;
                    to += direction;
                    count--;
                }

                return self;
            }
        });

    // Array#fill
    if (!Array.prototype.fill)
        defineProperty(Array.prototype, 'fill', {
            value: function fill(value/*, start, end*/) {
                var start = arguments[1],
                    self = toObject(this),
                    len = toLen(self.length),
                    end = arguments.length >= 3 ? arguments[2] : len;

                start = toPos(start, len);
                end = toPos(end, len);

                while (start < end) self[start++] = value;

                return self;
            }
        });

    // Array#find
    if (!Array.prototype.find)
        defineProperty(Array.prototype, 'find', {
            value: function find(predicate/*, thisArg */) {
                if (!isFn(predicate))
                    fail('predicate must be a function');

                var thisArg = arguments[1],
                    hasThisArg = arguments.length >= 2,
                    self = toObject(this),
                    len = toLen(this.length),
                    value;

                for (var i = 0; i < len; i++) {
                    value = self[i];
                    if (hasThisArg ? predicate.call(thisArg, value, i, self) : predicate(value, i, self))
                        return value;
                }
                return void 0;
            }
        });

    //Array#findIndex
    if (!Array.prototype.findIndex)
        defineProperty(Array.prototype, 'findIndex', {
            value: function findIndex(predicate/*, thisArg */) {
                if (!isFun(predicate))
                    fail('predicate must be a function');

                var thisArg = arguments[1],
                    hasThisArg = arguments.length >= 2,
                    self = toObject(this),
                    len = toLen(this.length),
                    value;

                for (var i = 0; i < len; i++) {
                    value = self[i];
                    if (hasThisArg ? predicate.call(thisArg, value, i, self) : predicate(value, i, self))
                        return i;
                }
                return -1;
            }
        });

    // Array#includes
    if (!Array.prototype.includes)
        defineProperty(Array.prototype, 'includes', {
            value: function includes(search/*, fromIndex*/) {
                var self = toObject(this),
                    len = toLen(this.length),
                    i = toPos(arguments[1], len);
                while(i < len) {
                    if (is(search, this[i++]))
                        return true;
                }
                return false;
            }
        });

    if (!testIsIterable(window.Array.prototype)) {
            var ArrayIterator = function ArrayIterator(array, kind) {
                guardType(isArray, array, 'Array');
                defineProperties(this, {
                    _array: { value: array },
                    _index: { value: 0, writable: true },
                    _kind: { value: kind }
                });
            }
            var isArrayIterator = function(iterator) {
                return iterator instanceof ArrayIterator;
            }

            defineProperty(ArrayIterator.prototype, 'next', {
                value: function next() {
                    guardMethod(isArrayIterator, this, 'ArrayIterator#next');

                    var array = this._array;

                    if (!isArray(array))
                        return iterDone();

                    var kind = this._kind,
                        i = this._index;

                    if (i < array.length) {
                        ++this._index;
                        return iterNext(kind == 'key' ? i : kind == 'value' ? array[i] : [i, array[i]]);
                    }

                    this._array = void 0;
                    return iterDone();
                }
            });

            defineProperties(window.Array.prototype, {
                //Array#entries
                entries: {
                    value: function entries() {
                        guardMethod(isArray, this, 'Array.prototype.entries');
                        return new ArrayIterator(this, 'key+value');
                    }
                },

                //Array#keys
                keys: {
                    value: function keys() {
                        guardMethod(isArray, this, 'Array.prototype.keys');
                        return new ArrayIterator(this, 'key');
                    }
                },

                //Array#values
                values: {
                    value: function values() {
                        guardMethod(isArray, this, 'Array.prototype.values');
                        return new ArrayIterator(this, 'value');
                    }
                }
            });

    }

    // Map ------------------------------------------------

    if (!NativeMap) {
        window.Map = function Map(entries) {
            guardType(isMap, this, 'Map');

            defineProperties(this, {
                _entries: { value: [] },
                _size: {
                    value: 0,
                    writable: true
                }
            });
            if (isDef(entries)) {
                guardType(isArray, entries, 'Array');
                for (var i = 0, n = entries.length; i < n; i++) {
                    this.set(entries[i][0], entries[i][1]);
                }
            }
        }
        defineProperties(window.Map.prototype, {
            //Map#clear
            clear: {
                value: function clear() {
                    var ents = this._entries;
                    for (var i = 0, n = ents.length; i < n; i++) {
                        delete ents[i];
                    }
                    this._size = 0;
                }
            },

            //Map#delete
            'delete': {
                value: function delete_(key) {
                    var ents = this._entries;
                    for (var i = 0, n = ents.length; i < n; i++) {
                        if (ents[i] && is(key, ents[i][0])) {
                            delete ents[i];
                            --this._size;
                            return true;
                        }
                    }
                    return false;
                }
            },

            //Map#forEach
            forEach: {
                value: function forEach(callback/*, thisArg*/) {
                    var thisArg = arguments[1],
                        hasThisArg = arguments.length >= 2;
                        ents = this._entries;
                    for (var i = 0; i < ents.length; i++) {
                        if (ents[i]) {
                            if (hasThisArg)
                                callback.call(thisArg, ents[i][1], ents[i][0], this);
                            else
                                callback(ents[i][1], ents[i][0], this);
                        }
                    }
                }
            },

            //Map#get
            get: {
                value: function get(key) {
                    var ents = this._entries;
                    for (var i = 0, n = ents.length; i < n; i++) {
                        if (ents[i] && is(key, ents[i][0])) {
                            return ents[i][1];
                        }
                    }
                }
            },

            //Map#has
            has: {
                value: function has(key) {
                    var ents = this._entries;
                    for (var i = 0, n = ents.length; i < n; i++) {
                        if (ents[i] && is(key, ents[i][0])) {
                            return true;
                        }
                    }
                    return false;
                }
            },

            //Map#set
            set: {
                value: function set(key, value) {
                    var ents = this._entries;
                    for (var i = 0, n = ents.length; i < n; i++) {
                        if (ents[i] && is(key, ents[i][0])) {
                            ents[i][1] = value;
                            return this;
                        }
                    }
                    ents.push([key, value]);
                    ++this._size;
                    return this;
                }
            },

            //Map#size
            size: {
                get: function size() {
                    return this._size;
                }
            }
        });

    } else {
        if (!testConst(NativeMap)) {
            window.Map = function Map(source) {
                var self = new NativeMap();
                if (isIterable(source))
                    iterate(source, mapAdd.bind(self));
                else if (!isNull(source))
                    fail(toString(source) + ' is not iterable');
                return self;
            };
        }
    }

    if (!testIsIterable(window.Map.prototype)) {
        var MapIterator = function MapIterator(map, kind) {
            guardType(isMap, map, 'Map');
            defineProperties(this, {
                _map: { value: map, writable: true },
                _index: { value: 0, writable: true },
                _kind: { value: kind }
            });
        }
        defineProperty(MapIterator.prototype, 'next', {
            value: function next() {
                var map = this._map,
                    kind = this._kind;

                if (!map)
                    return iterDone();

                var entries = map._entries;

                for (var i = this._index ; i < entries.length; i++) {
                    if (entries[i]) {
                        var entry = entries[i];
                        this._index = i + 1;
                        return iterNext(kind == 'key' ? entry[0] : kind == 'value' ? entry[1] : entry)
                    }
                }

                this._map = void 0;
                return iterDone();
            }
        });

        if (NativeMap) {
            var nativeMap_clear = NativeMap.prototype.clear,
                nativeMap_delete = NativeMap.prototype.delete,
                nativeMap_set = NativeMap.prototype.set;
            defineProperties(NativeMap.prototype, {
                _entries: {
                    get: function() {
                        guardType(isMap, this, 'Map');
                        if (!this.hasOwnProperty('_entries'))
                            defineProperty(this, '_entries', { value: [] });
                        return this._entries;
                    }
                },
                _indexed: {
                    get: function() {
                        guardType(isMap, this, 'Map');
                        if (!this.hasOwnProperty('_indexed'))
                            defineProperty(this, '_indexed', { value: new NativeMap() });
                        return this._indexed;
                    }
                },
                clear: {
                    value: function clear() {
                        for (var i = 0, n = this._entries.length; i < n; i++)
                            delete this._entries[i];
                        nativeMap_clear.call(this._indexed);
                        return nativeMap_clear.call(this);
                    }
                },
                'delete': {
                    value: function delete_(key) {
                        var i = this._indexed.get(key);
                        if (1 >= 0)
                            delete this._entries[i];
                        nativeMap_delete.call(this._indexed, key);
                        return nativeMap_delete.call(this, key);
                    }
                },
                set: {
                    value: function set(key, value) {
                        var i = this._indexed.get(key);
                        if (i >= 0)
                            this._entries[i][1] = value;
                        else
                            nativeMap_set.call(this._indexed, key, this._entries.push([key, value]) - 1);
                        nativeMap_set.call(this, key, value);
                        return this;
                    }
                }
            });
        }

        defineProperties(NativeMap ? NativeMap.prototype : window.Map.prototype, {
            //Map#entries
            entries: {
                value: function entries() {
                    guardMethod(isMap, this, 'Map.prototype.entries');
                    return new MapIterator(this, 'key+value');
                }
            },

            //Map#keys
            keys: {
                value: function keys() {
                    guardMethod(isMap, this, 'Map.prototype.keys');
                    return new MapIterator(this, 'key');
                }
            },

            //Map#values
            values: {
                value: function values() {
                    guardMethod(isMap, this, 'Map.prototype.values');
                    return new MapIterator(this, 'value');
                }
            }
        });
    }

    // Set ------------------------------------------------

    if (!NativeSet) {
        window.Set = function Set() {
            guardType(isSet, this, 'Set');
            defineProperties(this, {
                _values: { value: [] },
                _size: {
                    value: 0,
                    writable: true
                }
            });
        }
        defineProperties(window.Set.prototype, {
            //Set#add
            add: {
                value: function add(val) {
                    var vals = this._values;
                    for (var i = 0, n = vals.length; i < n; i++) {
                        if (i in vals && is(val, vals[i])) {
                            vals[i] = val;
                            return this;
                        }
                    }
                    vals.push(val);
                    ++this._size;
                    return this;
                }
            },

            //Set#clear
            clear: {
                value: function clear() {
                    var vals = this._values;
                    for (var i = 0, n = vals.length; i < n; i++) {
                        delete vals[i];
                    }
                    this._size = 0;
                }
            },

            //Set#delete
            'delete': {
                value: function delete_(val) {
                    var vals = this._values;
                    for (var i = 0, n = vals.length; i < n; i++) {
                        if (i in vals && is(val, vals[i])) {
                            delete vals[i];
                            --this._size;
                            return true;
                        }
                    }
                    return false;
                }
            },

            //Set#forEach
            forEach: {
                value: function forEach(callback/*, thisArg*/) {
                    var thisArg = arguments[1]
                        hasThisArg = arguments.length >= 2,
                        vals = this._values;
                    for (var i = 0; i < vals.length; i++) {
                        if (i in vals) {
                            if (hasThisArg)
                                callback.call(thisArg, vals[i], vals[i], this);
                            else
                                callback(vals[i], vals[i], this);
                        }
                    }
                }
            },

            //Set#has
            has: {
                value: function has(val) {
                    return this._values.includes(key);
                }
            },

            //Set#size
            size: {
                get: function size() {
                    return this._size;
                }
            }
        });

    } else {
        if (!testConst(NativeSet)) {
            window.Set = function Set(source) {
                var self = new NativeSet();
                if (isIterable(source))
                    iterate(source, self.add.bind(self));
                else if (!isNull(source))
                    fail(toString(source) + ' is not iterable');
                return self;
            };
        }
    }

    if (!testIsIterable(window.Set.prototype)) {
        var SetIterator = function SetIterator(set, kind) {
            guardType(isSet, set, 'Set');
            defineProperties(this, {
                _set: { value: set, writable: true },
                _index: { value: 0, writable: true },
                _kind: { value: kind }
            });
        }

        defineProperty(SetIterator.prototype, 'next', {
            value: function next() {
                var set = this._set,
                    kind = this._kind;

                if (!set)
                    return iterDone();

                var vals = set._values;

                for (var i = this._index, n = vals.length; i < n; i++) {
                    if (i in vals) {
                        var val = vals[i];
                        this._index = i + 1;
                        return iterNext(kind == 'key+value' ? [val, val] : val);
                    }
                }

                this._set = void 0;
                return iterDone();
            }
        });

        if (NativeSet) {
            var nativeSet_add = NativeSet.prototype.add
                nativeSet_clear = NativeSet.prototype.clear,
                nativeSet_delete = NativeSet.prototype.delete;

            defineProperties(NativeSet.prototype, {
                _values: {
                    get: function() {
                        guardType(isSet, this, 'Set');
                        if (!this.hasOwnProperty('_values'))
                            defineProperty(this, '_values', { value: [] });
                        return this._values;
                    }
                },
                _indexed: {
                    get: function() {
                        guardType(isSet, this, 'Set');
                        if (!this.hasOwnProperty('_indexed'))
                            defineProperty(this, '_indexed', { value: new NativeMap() });
                        return this._indexed;
                    }
                },
                add: {
                    value: function add(value) {
                        var i = this._indexed.get(value);
                        if (i >= 0)
                            this._values[i] = value;
                        else
                            nativeMap_set.call(this._indexed, value, this._values.push(value) - 1);
                        nativeSet_add.call(this, value);
                        return this;
                    }
                },
                clear: {
                    value: function clear() {
                        for (var i = 0, n = this._values.length; i < n; i++)
                            delete this._values[i];
                        nativeMap_clear.call(this._indexed);
                        return nativeSet_clear.call(this);
                    }
                },
                'delete': {
                    value: function delete_(value) {
                        var i = this._indexed.get(value);
                        if (1 >= 0)
                            delete this._values[i];
                        nativeMap_delete.call(this._indexed, value);
                        return nativeSet_delete.call(this, value);
                    }
                }
            });
        }

        defineProperties(NativeSet ? NativeSet.prototype : window.Set.prototype, {
            //Set#entries
            entries: {
                value: function entries() {
                    guardMethod(isSet, this, 'Set', 'entries');
                    return new SetIterator(this, 'key+value');
                }
            },

            //Set#keys
            keys: {
                value: function keys() {
                    guardMethod(isSet, this, 'Set', 'keys');
                    return new SetIterator(this, 'key');
                }
            },

            //Set#values
            values: {
                value: function values() {
                    guardMethod(isSet, this, 'Set', 'values');
                    return new SetIterator(this, 'value');
                }
            }
        });
    }

})();


text:
package com.tinkerpop.blueprints.impls.dex;

import com.sparsity.dex.gdb.AttributeKind;
import com.sparsity.dex.gdb.ObjectType;
import com.tinkerpop.blueprints.CloseableIterable;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Features;
import com.tinkerpop.blueprints.GraphQuery;
import com.tinkerpop.blueprints.KeyIndexableGraph;
import com.tinkerpop.blueprints.MetaGraph;
import com.tinkerpop.blueprints.Parameter;
import com.tinkerpop.blueprints.TransactionalGraph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.util.DefaultGraphQuery;
import com.tinkerpop.blueprints.util.ExceptionFactory;
import com.tinkerpop.blueprints.util.MultiIterable;
import com.tinkerpop.blueprints.util.PropertyFilteredIterable;
import com.tinkerpop.blueprints.util.StringFactory;
import org.apache.commons.configuration.Configuration;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Dex is a graph database developed by Sparsity Technologies.
 *

 * Dex natively supports the property graph data model defined by Blueprints.
 * However, there are a few peculiarities. No user defined element identifiers:
 * Dex is the gatekeeper and creator of vertex and edge identifiers. Thus, when
 * creating a new vertex or edge instance, the provided object identifier is
 * ignored.
 *

 * Vertices are labeled too: When adding vertices, the user can set
 * {@link DexGraph#label} to be used as the label of the vertex to be created.
 * Also, the label of a vertex (or even an element) can be retrieved through the
 * {@link StringFactory#LABEL} property.
 *

 * DexGraph implements {@link KeyIndexableGraph} with some particularities on
 * the way it can be used. As both vertices and edges are labeled when working
 * with Dex, the use of some APIs may require previously setting the label (by
 * means of {@link DexGraph#label}). Those APIs are:
 * {@link #getVertices(String, Object)}, {@link #getEdges(String, Object)}, and
 * {@link #createKeyIndex(String, Class)}.
 *

 * When working with DexGraph, all methods having as a result a collection
 * actually return a {@link CloseableIterable} collection. Thus users can
 * {@link CloseableIterable#close()} the collection to free resources.
 * Otherwise, all those collections will automatically be closed when the
 * transaction is stopped ({@link #stopTransaction(com.tinkerpop.blueprints.TransactionalGraph.Conclusion)}
 * or if the database is stopped ( {@link #shutdown()}).
 *
 * @author Sparsity
 *         Technologies
 */
public class DexGraph implements MetaGraph<com.sparsity.dex.gdb.Graph>, KeyIndexableGraph, TransactionalGraph {

    /**
     * Default Vertex label.
     */
    public static final String DEFAULT_DEX_VERTEX_LABEL = "VERTEX_LABEL";

    /**
     * This is a "bypass" to set the Dex vertex label (node type).
     *

     * Dex vertices belong to a vertex/node type (thus all of them have a label).
     * By default, all vertices will have the {@link #DEFAULT_DEX_VERTEX_LABEL} label.
     * The user may set a different vertex label by setting this property when calling
     * {@link #addVertex(Object)}.
     *

     * Moreover, this value will also be used for the KeyIndex-related methods.
     *
     * @see #addVertex(Object)
     * @see #createKeyIndex(String, Class)
     * @see #getVertices(String, Object)
     * @see #getEdges(String, Object)
     */
    public ThreadLocal<String> label = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return null;
        }
    };

    /**
     * Database persistent file.
     */
    private File dbFile = null;

    private com.sparsity.dex.gdb.Dex dex = null;
    private com.sparsity.dex.gdb.Database db = null;

    private class Metadata {
        com.sparsity.dex.gdb.Session session = null;
        List<DexIterable<? extends Element>> collection = null;
    }

    ;

    private ThreadLocal<Metadata> sessionData = new ThreadLocal<Metadata>() {
        @Override
        protected Metadata initialValue() {
            return new Metadata();
        }
    };

    private static final Features FEATURES = new Features();

    static {
        FEATURES.supportsDuplicateEdges = true;
        FEATURES.supportsSelfLoops = true;
        FEATURES.isPersistent = true;
        FEATURES.supportsVertexIteration = true;
        FEATURES.supportsEdgeIteration = true;
        FEATURES.supportsVertexIndex = false;
        FEATURES.supportsEdgeIndex = false;
        FEATURES.ignoresSuppliedIds = true;
        FEATURES.supportsEdgeRetrieval = true;
        FEATURES.supportsVertexProperties = true;
        FEATURES.supportsEdgeProperties = true;
        FEATURES.supportsTransactions = false;
        FEATURES.supportsIndices = false;

        FEATURES.supportsSerializableObjectProperty = false;
        FEATURES.supportsBooleanProperty = true;
        FEATURES.supportsDoubleProperty = true;
        FEATURES.supportsFloatProperty = true;
        FEATURES.supportsIntegerProperty = true;
        FEATURES.supportsPrimitiveArrayProperty = false;
        FEATURES.supportsUniformListProperty = false;
        FEATURES.supportsMixedListProperty = false;
        FEATURES.supportsLongProperty = true;
        FEATURES.supportsMapProperty = false;
        FEATURES.supportsStringProperty = true;

        FEATURES.isWrapper = false;
        FEATURES.supportsKeyIndices = true;
        FEATURES.supportsVertexKeyIndex = true;
        FEATURES.supportsEdgeKeyIndex = true;
        FEATURES.supportsThreadedTransactions = false;
    }

    /**
     * Gets the Dex raw graph.
     *
     * @return Dex raw graph.
     */
    public com.sparsity.dex.gdb.Graph getRawGraph() {
        com.sparsity.dex.gdb.Session sess = getRawSession(false);
        if (sess == null) {
            throw new IllegalStateException("Transaction has not been started");
        }
        return sess.getGraph();
    }

    /**
     * Gets the Dex Session
     *
     * @return The Dex Session
     */
    com.sparsity.dex.gdb.Session getRawSession() {
        return getRawSession(true);
    }

    /**
     * Gets the Dex Session
     *
     * @return The Dex Session
     */
    com.sparsity.dex.gdb.Session getRawSession(boolean exception) {
        com.sparsity.dex.gdb.Session sess = sessionData.get().session;
        if (sess == null && exception) {
            throw new IllegalStateException("Transaction has not been started");
        }
        return sess;
    }

    /**
     * Registers a collection.
     *
     * @param col Collection to be registered.
     */
    protected void register(final DexIterable<? extends Element> col) {
        if (sessionData.get().collection == null) {
            sessionData.get().collection = new ArrayList<DexIterable<? extends Element>>();
        }
        sessionData.get().collection.add(col);
        //System.out.println("> register " + sess + ":" + col);
    }

    /**
     * Unregisters a collection.
     *
     * @param col Collection to be unregistered
     */
    protected void unregister(final DexIterable<? extends Element> col) {
        if (sessionData.get().collection == null) {
            throw new IllegalStateException("Session with no collections");
        }
        sessionData.get().collection.remove(col);
        //System.out.println("< unregister " + sess + ":" + col);
    }

    /**
     * Creates a new instance.
     *
     * @param fileName Database persistent file.
     */
    public DexGraph(final String fileName) {
        this(fileName, null);
    }

    /**
     * Creates a new instance.
     *
     * @param fileName Database persistent file.
     * @param config   Dex configuration file.
     */
    public DexGraph(final String fileName, final String config) {
        try {
            this.dbFile = new File(fileName);
            final File dbPath = dbFile.getParentFile();

            if (!dbPath.exists()) {
                if (!dbPath.mkdirs()) {
                    throw new RuntimeException("Could not create directory");
                }
            }

            final boolean create = !dbFile.exists();

            if (config != null) com.sparsity.dex.gdb.DexProperties.load(config);
            dex = new com.sparsity.dex.gdb.Dex(new com.sparsity.dex.gdb.DexConfig());
            db = (create ? dex.create(dbFile.getPath(), dbFile.getName()) : dex.open(dbFile.getPath(), false));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public DexGraph(final Configuration configuration) {
        this(configuration.getString("blueprints.dex.directory", null), configuration.getString("blueprints.dex.config", null));
    }

    /**
     * Creates a new Vertex.
     *

     * Given identifier is ignored.
     *

     * Use {@link #label} to specify the label for the new Vertex.
     * If no label is given, {@value #DEFAULT_DEX_VERTEX_LABEL} will be used.
     *
     * @param id It is ignored.
     * @return Added Vertex.
     * @see com.tinkerpop.blueprints.Graph#addVertex(java.lang.Object)
     * @see #label
     */
    @Override
    public Vertex addVertex(final Object id) {
        autoStartTransaction();

        String label = this.label.get() == null ? DEFAULT_DEX_VERTEX_LABEL : this.label.get();
        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();
        int type = rawGraph.findType(label);
        if (type == com.sparsity.dex.gdb.Type.InvalidType) {
            // First instance of this type, let's create it
            type = rawGraph.newNodeType(label);
        }
        assert type != com.sparsity.dex.gdb.Type.InvalidType;
        // create object instance
        long oid = rawGraph.newNode(type);
        return new DexVertex(this, oid);
    }

    /*
      * (non-Javadoc)
      *
      * @see com.tinkerpop.blueprints.Graph#getVertex(java.lang.Object)
      */
    @Override
    public Vertex getVertex(final Object id) {
        autoStartTransaction();

        if (null == id)
            throw ExceptionFactory.vertexIdCanNotBeNull();
        try {
            final Long longId = Double.valueOf(id.toString()).longValue();
            com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();
            final int type = rawGraph.getObjectType(longId);
            if (type != com.sparsity.dex.gdb.Type.InvalidType)
                return new DexVertex(this, longId);
            else
                return null;
        } catch (NumberFormatException e) {
            return null;
        } catch (RuntimeException re) {
            // dex throws a runtime exception => [DEX: 12] Invalid object identifier.
            return null;
        }
    }

    /*
      * (non-Javadoc)
      *
      * @see
      * com.tinkerpop.blueprints.Graph#removeVertex(com.tinkerpop.blueprints
      * .pgm.Vertex)
      */
    @Override
    public void removeVertex(final Vertex vertex) {
        autoStartTransaction();

        if (getVertex(vertex.getId()) == null)
            throw ExceptionFactory.vertexWithIdDoesNotExist(vertex.getId());

        assert vertex instanceof DexVertex;

        try {
            getRawGraph().drop((Long) vertex.getId());
        } catch (RuntimeException re) {
            ExceptionFactory.vertexWithIdDoesNotExist(vertex.getId());
        }
    }

    /*
      * (non-Javadoc)
      *
      * @see com.tinkerpop.blueprints.Graph#getVertices()
      */
    @Override
    public CloseableIterable<Vertex> getVertices() {
        autoStartTransaction();

        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();
        com.sparsity.dex.gdb.TypeList tlist = rawGraph.findNodeTypes();
        List<Iterable<Vertex>> vertices = new ArrayList<Iterable<Vertex>>();
        for (Integer type : tlist) {
            com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
            vertices.add(new DexIterable<Vertex>(this, objs, Vertex.class));
        }
        tlist.delete();
        tlist = null;
        return new MultiIterable<Vertex>(vertices);
    }

    /**
     * Returns an iterable to all the vertices in the graph that have a particular key/value property.
     *

     * In case key is {@link StringFactory#LABEL}, it returns an iterable of all the vertices having
     * the given value as the label (therefore, belonging to the given type).
     *

     * In case {@link #label} is null, it will return all vertices having a particular
     * key/value no matters the type.
     * In case {@link #label} is not null, it will return all vertices having a particular
     * key/value belonging to the given type.
     *
     * @see com.tinkerpop.blueprints.Graph#getVertices(String, Object)
     * @see #label
     */
    @Override
    public CloseableIterable<Vertex> getVertices(final String key, final Object value) {
        autoStartTransaction();

        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();

        if (key.compareTo(StringFactory.LABEL) == 0) { // label is "indexed"

            int type = rawGraph.findType(value.toString());
            if (type != com.sparsity.dex.gdb.Type.InvalidType) {
                com.sparsity.dex.gdb.Type tdata = rawGraph.getType(type);
                if (tdata.getObjectType() == ObjectType.Node) {
                    com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
                    return new DexIterable<Vertex>(this, objs, Vertex.class);
                }
            }
            return null;
        }

        String label = this.label.get();
        if (label == null) { // all vertex types

            com.sparsity.dex.gdb.TypeList tlist = rawGraph.findNodeTypes();
            List<Iterable<Vertex>> vertices = new ArrayList<Iterable<Vertex>>();
            for (Integer type : tlist) {
                int attr = rawGraph.findAttribute(type, key);
                if (com.sparsity.dex.gdb.Attribute.InvalidAttribute != attr) {
                    com.sparsity.dex.gdb.Attribute adata = rawGraph.getAttribute(attr);
                    if (adata.getKind() == AttributeKind.Basic) { // "table" scan
                        com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
                        vertices.add(new PropertyFilteredIterable<Vertex>(key, value, new DexIterable<Vertex>(this, objs, Vertex.class)));
                    } else { // use the index
                        vertices.add(new DexIterable<Vertex>(this, this.rawGet(adata, value), Vertex.class));
                    }
                }
            }
            tlist.delete();
            tlist = null;

            if (vertices.size() > 0) return new MultiIterable<Vertex>(vertices);
            else throw new IllegalArgumentException("The given attribute '" + key + "' does not exist");

        } else { // restricted to a type

            int type = rawGraph.findType(label);
            if (type == com.sparsity.dex.gdb.Type.InvalidType) {
                throw new IllegalArgumentException("Unnexisting vertex label: " + label);
            }
            com.sparsity.dex.gdb.Type tdata = rawGraph.getType(type);
            if (tdata.getObjectType() != com.sparsity.dex.gdb.ObjectType.Node) {
                throw new IllegalArgumentException("Given label is not a vertex label: " + label);
            }

            int attr = rawGraph.findAttribute(type, key);
            if (com.sparsity.dex.gdb.Attribute.InvalidAttribute == attr) {
                throw new IllegalArgumentException("The given attribute '" + key
                        + "' does not exist for the given node label '" + label + "'");
            }

            com.sparsity.dex.gdb.Attribute adata = rawGraph.getAttribute(attr);
            if (adata.getKind() == AttributeKind.Basic) { // "table" scan
                com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
                return new PropertyFilteredIterable<Vertex>(key, value, new DexIterable<Vertex>(this, objs, Vertex.class));
            } else { // use the index
                return new DexIterable<Vertex>(this, this.rawGet(adata, value), Vertex.class);
            }
        }
    }

    /*
      * (non-Javadoc)
      *
      * @see com.tinkerpop.blueprints.Graph#addEdge(java.lang.Object,
      * com.tinkerpop.blueprints.Vertex, com.tinkerpop.blueprints.Vertex,
      * java.lang.String)
      */
    @Override
    public Edge addEdge(final Object id, final Vertex outVertex, final Vertex inVertex, final String label) {
        if (label == null)
            throw ExceptionFactory.edgeLabelCanNotBeNull();

        autoStartTransaction();

        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();
        int type = rawGraph.findType(label);
        if (type == com.sparsity.dex.gdb.Type.InvalidType) {
            // First instance of this type, let's create it
            type = rawGraph.newEdgeType(label, true, true);
        }
        assert type != com.sparsity.dex.gdb.Type.InvalidType;
        // create object instance
        assert outVertex instanceof DexVertex && inVertex instanceof DexVertex;
        long oid = rawGraph.newEdge(type, (Long) outVertex.getId(), (Long) inVertex.getId());
        return new DexEdge(this, oid);
    }

    /*
      * (non-Javadoc)
      *
      * @see com.tinkerpop.blueprints.Graph#getEdge(java.lang.Object)
      */
    @Override
    public Edge getEdge(final Object id) {
        autoStartTransaction();

        if (null == id)
            throw ExceptionFactory.edgeIdCanNotBeNull();
        try {
            com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();
            Long longId = Double.valueOf(id.toString()).longValue();
            int type = rawGraph.getObjectType(longId);
            if (type != com.sparsity.dex.gdb.Type.InvalidType)
                return new DexEdge(this, longId);
            else
                return null;
        } catch (NumberFormatException e) {
            return null;
        } catch (RuntimeException re) {
            // dex throws an runtime exception => [DEX: 12] Invalid object identifier.
            return null;
        }

    }

    /*
      * (non-Javadoc)
      *
      * @see
      * com.tinkerpop.blueprints.Graph#removeEdge(com.tinkerpop.blueprints
      * .pgm.Edge)
      */
    @Override
    public void removeEdge(final Edge edge) {
        autoStartTransaction();

        assert edge instanceof DexEdge;
        getRawGraph().drop((Long) edge.getId());
    }

    /*
      * (non-Javadoc)
      *
      * @see com.tinkerpop.blueprints.Graph#getEdges()
      */
    @Override
    public CloseableIterable<Edge> getEdges() {
        autoStartTransaction();

        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();
        com.sparsity.dex.gdb.TypeList tlist = rawGraph.findEdgeTypes();
        List<Iterable<Edge>> edges = new ArrayList<Iterable<Edge>>();
        for (Integer type : tlist) {
            com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
            edges.add(new DexIterable<Edge>(this, objs, Edge.class));
        }
        tlist.delete();
        tlist = null;
        return new MultiIterable<Edge>(edges);
    }

    /**
     * Returns an iterable to all the edges in the graph that have a particular key/value property.
     *

     * In case key is {@link StringFactory#LABEL}, it returns an iterable of all the edges having
     * the given value as the label (therefore, belonging to the given type).
     *

     * In case {@link #label} is null, it will return all edges having a particular
     * key/value no matters the type.
     * In case {@link #label} is not null, it will return all edges having a particular
     * key/value belonging to the given type.
     *
     * @see com.tinkerpop.blueprints.Graph#getEdges(String, Object)
     * @see #label
     */
    @Override
    public CloseableIterable<Edge> getEdges(final String key, final Object value) {
        autoStartTransaction();

        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();

        if (key.compareTo(StringFactory.LABEL) == 0) { // label is "indexed"

            int type = rawGraph.findType(value.toString());
            if (type != com.sparsity.dex.gdb.Type.InvalidType) {
                com.sparsity.dex.gdb.Type tdata = rawGraph.getType(type);
                if (tdata.getObjectType() == ObjectType.Edge) {
                    com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
                    return new DexIterable<Edge>(this, objs, Edge.class);
                }
            }
            return null;
        }

        String label = this.label.get();
        if (label == null) { // all vertex types

            com.sparsity.dex.gdb.TypeList tlist = rawGraph.findEdgeTypes();
            List<Iterable<Edge>> edges = new ArrayList<Iterable<Edge>>();
            for (Integer type : tlist) {
                int attr = rawGraph.findAttribute(type, key);
                if (com.sparsity.dex.gdb.Attribute.InvalidAttribute != attr) {
                    com.sparsity.dex.gdb.Attribute adata = rawGraph.getAttribute(attr);
                    if (adata.getKind() == AttributeKind.Basic) { // "table" scan
                        com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
                        edges.add(new PropertyFilteredIterable<Edge>(key, value, new DexIterable<Edge>(this, objs, Edge.class)));
                    } else { // use the index
                        edges.add(new DexIterable<Edge>(this, this.rawGet(adata, value), Edge.class));
                    }
                }
            }
            tlist.delete();
            tlist = null;

            if (edges.size() > 0) return new MultiIterable<Edge>(edges);
            else throw new IllegalArgumentException("The given attribute '" + key + "' does not exist");

        } else { // restricted to a type

            int type = rawGraph.findType(label);
            if (type == com.sparsity.dex.gdb.Type.InvalidType) {
                throw new IllegalArgumentException("Unnexisting edge label: " + label);
            }
            com.sparsity.dex.gdb.Type tdata = rawGraph.getType(type);
            if (tdata.getObjectType() != com.sparsity.dex.gdb.ObjectType.Edge) {
                throw new IllegalArgumentException("Given label is not a edge label: " + label);
            }

            int attr = rawGraph.findAttribute(type, key);
            if (com.sparsity.dex.gdb.Attribute.InvalidAttribute == attr) {
                throw new IllegalArgumentException("The given attribute '" + key
                        + "' does not exist for the given edge label '" + label + "'");
            }

            com.sparsity.dex.gdb.Attribute adata = rawGraph.getAttribute(attr);
            if (adata.getKind() == AttributeKind.Basic) { // "table" scan
                com.sparsity.dex.gdb.Objects objs = rawGraph.select(type);
                return new PropertyFilteredIterable<Edge>(key, value, new DexIterable<Edge>(this, objs, Edge.class));
            } else { // use the index
                return new DexIterable<Edge>(this, this.rawGet(adata, value), Edge.class);
            }
        }
    }

    /**
     * Closes all non-closed iterables.
     */
    protected void closeAllSessionCollections() {
        if (sessionData.get().collection != null) {
            for (DexIterable<? extends Element> elem : sessionData.get().collection) {
                elem.close(false);
            }
            sessionData.get().collection.clear();
        }
    }

    /*
      * (non-Javadoc)
      *
      * @see com.tinkerpop.blueprints.Graph#shutdown()
      */
    @Override
    public void shutdown() {
        commit();

        db.close();
        dex.close();
    }

    @Override
    public String toString() {
        return StringFactory.graphString(this, dbFile.getPath());
    }

    public Features getFeatures() {
        return FEATURES;
    }

    private com.sparsity.dex.gdb.Objects rawGet(final com.sparsity.dex.gdb.Attribute adata, final Object value) {
        com.sparsity.dex.gdb.Value v = new com.sparsity.dex.gdb.Value();
        switch (adata.getDataType()) {
            case Boolean:
                v.setBooleanVoid((Boolean) value);
                break;
            case Integer:
                v.setIntegerVoid((Integer) value);
                break;
            case Long:
                v.setLongVoid((Long) value);
                break;
            case String:
                v.setStringVoid((String) value);
                break;
            case Double:
                if (value instanceof Double) {
                    v.setDoubleVoid((Double) value);
                } else if (value instanceof Float) {
                    v.setDoubleVoid(((Float) value).doubleValue());
                }
                break;
            default:
                throw new UnsupportedOperationException();
        }
        return this.getRawGraph().select(adata.getId(), com.sparsity.dex.gdb.Condition.Equal, v);
    }

    @Override
    public <T extends Element> void dropKeyIndex(String key,
                                                 Class<T> elementClass) {
        if (elementClass == null)
            throw ExceptionFactory.classForElementCannotBeNull();

        throw new UnsupportedOperationException();
    }

    /**
     * Create an automatic indexing structure for indexing provided key for element class.
     *

     * Dex attributes are restricted to an specific vertex/edge type. The property
     * {@link #label} must be used to specify the vertex/edge label.
     *

     * The index could be created even before the vertex/edge label
     * had been created (that is, there are no instances for the given vertex/edge label).
     * If so, this will create the vertex/edge type automatically.
     * The same way, if necessary the attribute will be created automatically.
     *

     * FIXME: In case the attribute is created, this always creates an String
     * attribute, could this be set somehow?
     */
    @Override
    public <T extends Element> void createKeyIndex(String key, Class<T> elementClass, final Parameter... indexParameters) {
        if (elementClass == null)
            throw ExceptionFactory.classForElementCannotBeNull();

        autoStartTransaction();

        String label = this.label.get();
        if (label == null) {
            throw new IllegalArgumentException("Label must be given");
        }

        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();

        int type = rawGraph.findType(label);
        if (type == com.sparsity.dex.gdb.Type.InvalidType) {
            // create the node/edge type
            if (Vertex.class.isAssignableFrom(elementClass)) {
                type = rawGraph.newNodeType(label);
            } else if (Edge.class.isAssignableFrom(elementClass)) {
                type = rawGraph.newEdgeType(label, true, true);
            } else {
                throw ExceptionFactory.classIsNotIndexable(elementClass);
            }
        } else {
            // validate the node/edge type
            com.sparsity.dex.gdb.Type tdata = rawGraph.getType(type);
            if (tdata.getObjectType() == ObjectType.Node) {
                if (!Vertex.class.isAssignableFrom(elementClass)) {
                    throw new IllegalArgumentException("Given element class '"
                            + elementClass.getName()
                            + "' is not valid for the given node type '"
                            + label + "'");
                }
            } else if (tdata.getObjectType() == ObjectType.Edge) {
                if (!Edge.class.isAssignableFrom(elementClass)) {
                    throw new IllegalArgumentException("Given element class '"
                            + elementClass.getName()
                            + "' is not valid for the given edge type '"
                            + label + "'");
                }
            }
        }

        int attr = rawGraph.findAttribute(type, key);
        if (com.sparsity.dex.gdb.Attribute.InvalidAttribute == attr) {
            // create the attribute (indexed)
            attr = rawGraph.newAttribute(type, key,
                    com.sparsity.dex.gdb.DataType.String,
                    com.sparsity.dex.gdb.AttributeKind.Indexed);
        } else {
            // it already exists, let's indexe it if necessary
            com.sparsity.dex.gdb.Attribute adata = rawGraph.getAttribute(attr);
            if (adata.getKind() == AttributeKind.Indexed || adata.getKind() == AttributeKind.Unique) {
                throw ExceptionFactory.indexAlreadyExists(label + " " + key);
            }
            rawGraph.indexAttribute(attr,
                    com.sparsity.dex.gdb.AttributeKind.Indexed);
        }
    }

    @Override
    public <T extends Element> Set<String> getIndexedKeys(Class<T> elementClass) {
        if (elementClass == null)
            throw ExceptionFactory.classForElementCannotBeNull();

        autoStartTransaction();

        com.sparsity.dex.gdb.TypeList tlist = null;
        com.sparsity.dex.gdb.Graph rawGraph = getRawGraph();
        if (Vertex.class.isAssignableFrom(elementClass)) {
            tlist = rawGraph.findNodeTypes();
        } else if (Edge.class.isAssignableFrom(elementClass)) {
            tlist = rawGraph.findEdgeTypes();
        } else {
            throw ExceptionFactory.classIsNotIndexable(elementClass);
        }
        Set<String> ret = new HashSet<String>();
        for (Integer type : tlist) {
            com.sparsity.dex.gdb.AttributeList alist = rawGraph.findAttributes(type);
            for (Integer attr : alist) {
                com.sparsity.dex.gdb.Attribute adata = rawGraph.getAttribute(attr);
                if (adata.getKind() == AttributeKind.Indexed || adata.getKind() == AttributeKind.Unique) {
                    ret.add(adata.getName());
                }
            }
            alist.delete();
            alist = null;
        }
        tlist.delete();
        tlist = null;
        return ret;
    }

    void autoStartTransaction() {
        if (sessionData.get().session == null) {
            sessionData.get().session = db.newSession();
            //System.out.println("> th=" + Thread.currentThread().getId() + " starts tx with sess=" + sess);
        } else {
            assert !sessionData.get().session.isClosed();
        }
    }

    public void commit() {
        if (sessionData.get().session == null) {
            // already closed session
            return;
        }
        closeAllSessionCollections();
        if (sessionData.get().session != null && !sessionData.get().session.isClosed()) {
            sessionData.get().session.close();
        }
        sessionData.get().session = null;
    }

    public void rollback() {
        throw new UnsupportedOperationException("Rollback is not supported");
    }

    @Override
    public void stopTransaction(Conclusion conclusion) {
        if (Conclusion.SUCCESS == conclusion)
            commit();
        else
            rollback();
    }

    public GraphQuery query() {
        return new DefaultGraphQuery(this);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react'
import { shallow } from 'enzyme'

import { Warning } from '../Warning'

describe('Warning', () => {
  it('component renders', () => {
    const wrapper = shallow(<Warning>AH!!!</Warning>)

    expect(wrapper).toMatchSnapshot()
  })
})


text:
In order to integrate custom widgets and themes its necessary to host applications on your own web server.  In this lab you will download Web AppBuilder Developer Edition and configure it to run on your local machine.

1. Download Web AppBuilder Dev Edition from [here](https://developers.arcgis.com/web-appbuilder/) and select download. Unzip it in the folder of your choice.

2. Follow the instructions [here](https://developers.arcgis.com/web-appbuilder/guide/getstarted.htm) to confirm the builder is running.

3. Create an *AppID* for Web AppBuilder in [arcgis.com](http://www.arcgis.com) so that you can leverage OAuth to sign into ArcGIS Online (more info can be found [here](https://developers.arcgis.com/web-appbuilder/guide/getstarted.htm))

Now you are able to start creating new applications in the browser on your development machine by visiting http://yourmachinename:3344/webappbuilder.

![Running](wab_running.png)


text:
from plasTeX.Base.TeX.Primitives import BoxCommand

class text(BoxCommand):
    args = 'self'


text:
<?php
namespace Concrete\Core\Command\Task\Input;

use Symfony\Component\Serializer\Normalizer\DenormalizableInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

defined('C5_EXECUTE') or die("Access Denied.");

class Field implements FieldInterface, DenormalizableInterface
{

    /**
     * @var string
     */
    protected $key;

    /**
     * @var string
     */
    protected $value;

    /**
     * AbstractField constructor.
     * @param string $key
     * @param string $value
     */
    public function __construct(string $key = null, string $value = null)
    {
        $this->key = $key;
        $this->value = $value;
    }

    /**
     * @return string
     */
    public function getKey(): string
    {
        return $this->key;
    }

    /**
     * @return string
     */
    public function getValue(): string
    {
        return $this->value;
    }

    public function jsonSerialize()
    {
        return [
            'key' => $this->getKey(),
            'value' => $this->getValue(),
        ];
    }

    public function denormalize(DenormalizerInterface $denormalizer, $data, string $format = null, array $context = [])
    {
        $this->key = $data['key'];
        $this->value = $data['value'];
    }

}


text:
package com.example.cfp.web;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.example.cfp.integration.github.Commit;
import com.example.cfp.integration.github.GithubClient;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@Navigation(Section.NEWS)
public class NewsController {

	private final GithubClient githubClient;

	public NewsController(GithubClient githubClient) {
		this.githubClient = githubClient;
	}

	@RequestMapping("/news")
	public String home(Model model) {
		model.addAttribute("latestFrameworkCommits",
				getRecentCommits("spring-projects", "spring-framework"));
		model.addAttribute("latestBootCommits",
				getRecentCommits("spring-projects", "spring-boot"));
		model.addAttribute("daysSinceLastPolish", daysSinceLastPolishCommit());
		return "news";
	}

	private List<Commit> getRecentCommits(String organization, String project) {
		return this.githubClient
				.getRecentCommits(organization, project)
				.stream().limit(5).collect(Collectors.toList());
	}

	private long daysSinceLastPolishCommit() {
		Commit fwkCommit = this.githubClient.getRecentPolishCommit("spring-projects", "spring-framework");
		Commit bootCommit = this.githubClient.getRecentPolishCommit("spring-projects", "spring-boot");
		Instant instant = Stream.of(fwkCommit, bootCommit)
				.filter(Objects::nonNull)
				.map(Commit::getDate)
				.max(Instant::compareTo).get();
		return Duration.between(instant, Instant.now()).toDays();
	}

}


text:
class AddCoulmnsToMessages < ActiveRecord::Migration
  def change
    add_column :messages, :deleted_by_sender, :boolean, :default => 0
    add_column :messages, :deleted_by_recipient, :boolean, :default => 0
    add_column :messages, :unread, :boolean, :default => 1
  end
end


text:
#include "tscore/ink_platform.h"
#include "tscore/ink_sock.h"
#include "tscore/ink_string.h"
#include "tscore/ink_memory.h"

#include "CoreAPIShared.h"
#include "MgmtSocket.h"

// Forward declarations, used to be in the CoreAPIShared.h include file but
// that doesn't make any sense since these are both statically declared. /leif
static int poll_write(int fd, int timeout);
static int poll_read(int fd, int timeout);

/* parseHTTPResponse
 * - parse the response buffer into header and body and calculate
 *   the correct size of the header and body.
 * INPUT:  buffer   -- response buffer to be parsed
 *         header   -- pointer to the head of the header
 *         hdr_size -- size of the header
 *         body     -- pointer to the head of the body
 *         bdy_size -- size of the body
 * OUTPUT: TSMgmtError -- error status
 */
TSMgmtError
parseHTTPResponse(char *buffer, char **header, int *hdr_size, char **body, int *bdy_size)
{
  TSMgmtError err = TS_ERR_OKAY;
  char *buf;

  // locate HTTP divider
  if (!(buf = strstr(buffer, HTTP_DIVIDER))) {
    err = TS_ERR_FAIL;
    goto END;
  }
  // calculate header info
  if (header) {
    *header = buffer;
  }
  if (hdr_size) {
    *hdr_size = buf - buffer;
  }

  // calculate body info
  buf += strlen(HTTP_DIVIDER);
  if (body) {
    *body = buf;
  }
  if (bdy_size) {
    *bdy_size = strlen(buf);
  }

END:
  return err;
}

/* readHTTPResponse
 * - read from an opened socket to memory-allocated buffer and close the
 *   socket regardless success or failure.
 * INPUT:  sock -- the socket to read the response from
 *         buffer -- the buffer to be filled with the HTTP response
 *         bufsize -- the size allocated for the buffer
 * OUTPUT: bool -- true if everything went well. false otherwise
 */
TSMgmtError
readHTTPResponse(int sock, char *buffer, int bufsize, uint64_t timeout)
{
  int64_t err, idx;

  idx = 0;
  for (;;) {
    //      printf("%d\n", idx);
    if (idx >= bufsize) {
      //      printf("(test) response is too large [%d] %d\n", idx, bufsize);
      goto error;
    }
    //      printf("before poll_read\n");
    err = poll_read(sock, timeout);
    if (err < 0) {
      //      printf("(test) poll read failed [%d '%s']\n", errno, strerror (errno));
      goto error;
    } else if (err == 0) {
      //      printf("(test) read timeout\n");
      goto error;
    }
    //      printf("before do\n");
    do {
      //      printf("in do\n");
      err = read(sock, &buffer[idx], bufsize - idx);
    } while ((err < 0) && ((errno == EINTR) || (errno == EAGAIN)));
    //       printf("content: %s\n", buffer);

    if (err < 0) {
      //      printf("(test) read failed [%d '%s']\n", errno, strerror (errno));
      goto error;
    } else if (err == 0) {
      buffer[idx] = '\0';
      close(sock);
      return TS_ERR_OKAY;
    } else {
      idx += err;
    }
  }

error: /* "Houston, we have a problem!" (Apollo 13) */
  if (sock >= 0) {
    close_socket(sock);
  }
  return TS_ERR_NET_READ;
}

/* sendHTTPRequest
 * - Compose a HTTP GET request and sent it via an opened socket.
 * INPUT:  sock -- the socket to send the message to
 *         req  -- the request to send
 * OUTPUT: bool -- true if everything went well. false otherwise (and sock is
 *                 closed)
 */
TSMgmtError
sendHTTPRequest(int sock, char *req, uint64_t timeout)
{
  char request[BUFSIZ];
  char *requestPtr;
  size_t length = 0;

  memset(request, 0, BUFSIZ);
  snprintf(request, BUFSIZ, "GET %s HTTP/1.0\r\n\r\n", req);
  length = strlen(request);

  int err = poll_write(sock, timeout);
  if (err < 0) {
    //      printf("(test) poll write failed [%d '%s']\n", errno, strerror (errno));
    goto error;
  } else if (err == 0) {
    //      printf("(test) write timeout\n");
    goto error;
  }
  // Write the request to the server.
  requestPtr = request;
  while (length > 0) {
    do {
      err = write(sock, request, length);
    } while ((err < 0) && ((errno == EINTR) || (errno == EAGAIN)));

    if (err < 0) {
      //      printf("(test) write failed [%d '%s']\n", errno, strerror (errno));
      goto error;
    }
    requestPtr += err;
    length -= err;
  }

  /* everything went well */
  return TS_ERR_OKAY;

error: /* "Houston, we have a problem!" (Apollo 13) */
  if (sock >= 0) {
    close_socket(sock);
  }
  return TS_ERR_NET_WRITE;
}

int
connectDirect(const char *host, int port, uint64_t /* timeout ATS_UNUSED */)
{
  int sock;

  // Create a socket
  do {
    sock = socket(AF_INET, SOCK_STREAM, 0);
  } while ((sock < 0) && ((errno == EINTR) || (errno == EAGAIN)));

  if (sock < 0) {
    //        printf("(test) unable to create socket [%d '%s']\n", errno, strerror(errno));
    goto error;
  }

  struct sockaddr_in name;
  memset((void *)&name, 0, sizeof(sockaddr_in));

  int err;

  // Put the socket in non-blocking mode...just to be extra careful
  // that we never block.
  do {
    err = fcntl(sock, F_SETFL, O_NONBLOCK);
  } while ((err < 0) && ((errno == EINTR) || (errno == EAGAIN)));

  if (err < 0) {
    //        printf("(test) unable to put socket in non-blocking mode [%d '%s']\n", errno, strerror (errno));
    goto error;
  }
  // Connect to the specified port on the machine we're running on.
  name.sin_family = AF_INET;
  name.sin_port   = htons(port);

  struct hostent *pHostent;
  pHostent = gethostbyname(host);
  if (!pHostent) {
    goto error;
  }
  memcpy(reinterpret_cast<caddr_t>(&(name.sin_addr)), pHostent->h_addr, pHostent->h_length);

  do {
    err = connect(sock, reinterpret_cast<struct sockaddr *>(&name), sizeof(name));
  } while ((err < 0) && ((errno == EINTR) || (errno == EAGAIN)));

  if ((err < 0) && (errno != EINPROGRESS)) {
    //        printf("(test) unable to connect to server [%d '%s'] at port %d\n", errno, strerror (errno), port);
    goto error;
  }
  return sock;

error:
  if (sock >= 0) {
    close_socket(sock);
  }
  return -1;
} /* connectDirect */

static int
poll_read(int fd, int timeout)
{
  struct pollfd info;
  int err;

  info.fd      = fd;
  info.events  = POLLIN;
  info.revents = 0;

  do {
    err = poll(&info, 1, timeout);
  } while ((err < 0) && ((errno == EINTR) || (errno == EAGAIN)));

  if ((err > 0) && (info.revents & POLLIN)) {
    return 1;
  }

  return err;
}

static int
poll_write(int fd, int timeout)
{
  struct pollfd info;
  int err;

  info.fd      = fd;
  info.events  = POLLOUT;
  info.revents = 0;

  do {
    err = poll(&info, 1, timeout);
  } while ((err < 0) && ((errno == EINTR) || (errno == EAGAIN)));

  if ((err > 0) && (info.revents & POLLOUT)) {
    return 1;
  }

  return err;
}

/**********************************************************************
 * Events
 **********************************************************************/
/**********************************************************************
 * get_event_id
 *
 * Purpose: Given the event_name, returns the event's corresponding
 *          event id
 * Note: this conversion is based on list defined in Alarms.h and
 *       the identical list defined in CoreAPIShared.cc
 *********************************************************************/
int
get_event_id(const char *event_name)
{
  if (strcmp("MGMT_ALARM_PROXY_PROCESS_DIED", event_name) == 0) {
    return MGMT_ALARM_PROXY_PROCESS_DIED;
  } else if (strcmp("MGMT_ALARM_PROXY_PROCESS_BORN", event_name) == 0) {
    return MGMT_ALARM_PROXY_PROCESS_BORN;
  } else if (strcmp("MGMT_ALARM_PROXY_CONFIG_ERROR", event_name) == 0) {
    return MGMT_ALARM_PROXY_CONFIG_ERROR;
  } else if (strcmp("MGMT_ALARM_PROXY_SYSTEM_ERROR", event_name) == 0) {
    return MGMT_ALARM_PROXY_SYSTEM_ERROR;
  } else if (strcmp("MGMT_ALARM_PROXY_CACHE_ERROR", event_name) == 0) {
    return MGMT_ALARM_PROXY_CACHE_ERROR;
  } else if (strcmp("MGMT_ALARM_PROXY_CACHE_WARNING", event_name) == 0) {
    return MGMT_ALARM_PROXY_CACHE_WARNING;
  } else if (strcmp("MGMT_ALARM_PROXY_LOGGING_ERROR", event_name) == 0) {
    return MGMT_ALARM_PROXY_LOGGING_ERROR;
  } else if (strcmp("MGMT_ALARM_PROXY_LOGGING_WARNING", event_name) == 0) {
    return MGMT_ALARM_PROXY_LOGGING_WARNING;
  } else if (strcmp("MGMT_ALARM_CONFIG_UPDATE_FAILED", event_name) == 0) {
    return MGMT_ALARM_CONFIG_UPDATE_FAILED;
  }

  return -1;
}

/**********************************************************************
 * get_event_id
 *
 * Purpose: based on alarm_id, determine the corresponding alarm name
 * Note:    allocates memory for the name returned
 *********************************************************************/
char *
get_event_name(int id)
{
  char name[MAX_EVENT_NAME_SIZE];

  memset(name, 0, MAX_EVENT_NAME_SIZE);
  switch (id) {
  case MGMT_ALARM_PROXY_PROCESS_DIED:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_PROCESS_DIED", sizeof(name));
    break;
  case MGMT_ALARM_PROXY_PROCESS_BORN:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_PROCESS_BORN", sizeof(name));
    break;
  case MGMT_ALARM_PROXY_CONFIG_ERROR:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_CONFIG_ERROR", sizeof(name));
    break;
  case MGMT_ALARM_PROXY_SYSTEM_ERROR:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_SYSTEM_ERROR", sizeof(name));
    break;
  case MGMT_ALARM_PROXY_CACHE_ERROR:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_CACHE_ERROR", sizeof(name));
    break;
  case MGMT_ALARM_PROXY_CACHE_WARNING:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_CACHE_WARNING", sizeof(name));
    break;
  case MGMT_ALARM_PROXY_LOGGING_ERROR:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_LOGGING_ERROR", sizeof(name));
    break;
  case MGMT_ALARM_PROXY_LOGGING_WARNING:
    ink_strlcpy(name, "MGMT_ALARM_PROXY_LOGGING_WARNING", sizeof(name));
    break;
  case MGMT_ALARM_CONFIG_UPDATE_FAILED:
    ink_strlcpy(name, "MGMT_ALARM_CONFIG_UPDATE_FAILED", sizeof(name));
    break;
  default:
    return nullptr;
  }

  return ats_strdup(name);
}


text:
In order to access Chronos's staging server to test Chronos locally one must do a number of things.

1. Enter or sync the osfio_preprints_1 container and set config/environment.js to include the desired preprint provider in the `chronosProviders`
list.

2. Make sure that your desired journal has an id listed in config/environment.js's approvedChronosJournalIds, or create a new journal and add that to the list.

3. Go to website/settings/local.py and add the following

VERIFY_CHRONOS_SSL_CERT = False
CHRONOS_USE_FAKE_FILE = True
CHRONOS_FAKE_FILE_URL = <any publicly accessible file I used https://github.com/CenterForOpenScience/centerforopenscience.org/blob/master/TERMS_OF_USE.md>
CHRONOS_HOST = 'https://staging-api.chronos-oa.com'
CHRONOS_USERNAME = <ask a dev for staging creds to put here>
CHRONOS_PASSWORD =  <ask a dev for staging creds to put here>
CHRONOS_API_KEY =  <ask a dev for staging creds to put here>

The link 'Submit to an APA-published journal' should appear when looking at a accepted preprint in the provider you've added to config/environment.js.


text: ENV['APP_NAME'] = 'App Name'


text:
namespace System {

template<typename T> class OperationTimeout {
public:
  OperationTimeout(Dispatcher& dispatcher, T& object, std::chrono::nanoseconds timeout) :
    object(object), timerContext(dispatcher), timeoutTimer(dispatcher) {
    timerContext.spawn([this, timeout]() {
      try {
        timeoutTimer.sleep(timeout);
        timerContext.interrupt();
      } catch (std::exception&) {
      }
    });
  }

  ~OperationTimeout() {
    timerContext.interrupt();
    timerContext.wait();
  }

private:
  T& object;
  ContextGroup timerContext;
  Timer timeoutTimer;
};

}


text:
package org.sirix.node.interfaces.immutable;

/**
 * Immutable structural node (for instance element-, text-, PI-, document-node...).
 *
 * @author Johannes Lichtenberger
 *
 */
public interface ImmutableStructNode extends ImmutableNode {
  /**
   * Declares, whether the item has a first child.
   *
   * @return true, if item has a first child, otherwise false
   */
  boolean hasFirstChild();

  /**
   * Declares, whether the item has a last child.
   *
   * @return true, if item has a last child, otherwise false
   */
  boolean hasLastChild();

  /**
   * Declares, whether the item has a left sibling.
   *
   * @return true, if item has a left sibling, otherwise false
   */
  boolean hasLeftSibling();

  /**
   * Declares, whether the item has a right sibling.
   *
   * @return true, if item has a right sibling, otherwise false
   */
  boolean hasRightSibling();

  /**
   * Get the number of children of the node.
   *
   * @return node's number of children
   */
  long getChildCount();

  /**
   * Get the number of descendants of the node.
   *
   * @return node's number of descendants
   */
  long getDescendantCount();

  /**
   * Gets key of the context item's first child.
   *
   * @return first child's key
   */
  long getFirstChildKey();

  /**
   * Gets key of the context item's last child.
   *
   * @return last child's key
   */
  long getLastChildKey();

  /**
   * Gets key of the context item's left sibling.
   *
   * @return left sibling key
   */
  long getLeftSiblingKey();

  /**
   * Gets key of the context item's right sibling.
   *
   * @return right sibling key
   */
  long getRightSiblingKey();
}


text:
package iso20022

// Choice between a standard code or a proprietary code for specifying the processing type of a corporate action event.
type CorporateActionEventProcessingTypeChoice struct {

	// Standard code to specify the processing type of a corporate action event.
	Code *CorporateActionEventProcessingType1Code `xml:"Cd"`

	// Proprietary identification of the processing type of a corporate action event.
	Proprietary *GenericIdentification20 `xml:"Prtry"`
}

func (c *CorporateActionEventProcessingTypeChoice) SetCode(value string) {
	c.Code = (*CorporateActionEventProcessingType1Code)(&value)
}

func (c *CorporateActionEventProcessingTypeChoice) AddProprietary() *GenericIdentification20 {
	c.Proprietary = new(GenericIdentification20)
	return c.Proprietary
}


text:
require "array_in_file/version"

module ArrayInFile

  # Reads contents of file into a string
  # Newlines denote the break between array elements
  def self.read (path)
    array1 = File.open(path, "r").read.split("\n")
    array1.delete ''
    return array1
  end

  # Writes an array into a file
  # Newlines denote the break between array elements
  def self.write (array_to_write, path)
     f = File.open(path, 'w')
     array_to_write.each do |element|
       f.puts (element.to_s)
     end
     f.close
  end

end


text:
using GalaSoft.MvvmLight;
using System;

namespace derpirc.ViewModels
{
    public interface IViewModelResolver
    {
        ViewModelBase Resolve(Type viewModelType);
    }
}


text:
@interface DQCommentUploadController ()

@property (nonatomic, weak) DQAccountController *accountController;

@end

@implementation DQCommentUploadController
{
    NSString *_uploadsPath;
}

- (id)initWithUploadsPath:(NSString *)uploadsPath accountController:(DQAccountController *)accountController delegate:(id<DQControllerDelegate>)delegate
{
    self = [super initWithDelegate:delegate];
    if (self)
    {
        _uploadsPath = [uploadsPath copy];
        _accountController = accountController;
        // taking this out of the background, I'd rather have this done synchronously and not worry about race conditions
        [self.dataStoreController markAllUploadingCommentUploadsFailed];
    }
    return self;
}

#pragma mark -
#pragma mark Public API

- (void)retryCommentUpload:(DQCommentUpload *)commentUpload
{
    [self _processCommentUpload:commentUpload];
}

- (BOOL)uploadDraftAtPath:(NSString *)draftPath forQuestWithServerID:(NSString *)questID title:(NSString *)questTitle shareFlags:(NSArray *)shareFlags facebookAccessToken:(NSString *)facebookAccessToken twitterAccessToken:(NSString *)twitterAccessToken twitterAccessTokenSecret:(NSString *)twitterAccessTokenSecret emailList:(NSArray *)emailList
{
    // Create a comment upload object in the data store
    DQDataStoreController *dataStoreController = self.dataStoreController;
    DQCommentUpload *commentUpload = [dataStoreController createCommentUploadForQuestWithServerID:questID shareFlags:shareFlags facebookToken:facebookAccessToken twitterToken:twitterAccessToken twitterTokenSecret:twitterAccessTokenSecret emailList:emailList];
    if (commentUpload)
    {
        // Move the draft into the uploading area
        NSString *uploadPath = [self _pathForCommentUpload:commentUpload];
        NSError *error = nil;
        NSFileManager *fm = [[NSFileManager alloc] init];
        if ([fm moveItemAtPath:draftPath toPath:uploadPath error:&error])
        {
            // Analytics
            NSString *publishEvent = self.loggedInAccount.hasPublishedAComment ? DQAnalyticsEventPublishComment : DQAnalyticsEventViewFTEPublish;
            [self logEvent:publishEvent withParameters:nil];

            if ([shareFlags containsObject:DQAPIValueShareChannelTypeFacebook])
            {
                [self logEvent:DQAnalyticsEventShareCommentToFacebook withParameters:nil];
            }
            if ([shareFlags containsObject:DQAPIValueShareChannelTypeTwitter])
            {
                [self logEvent:DQAnalyticsEventShareCommentToTwitter withParameters:nil];
            }
            [self _processCommentUpload:commentUpload];
            return YES;
        }
        else
        {
            [self _showPostingErrorWithText:nil error:error];
            return NO;
        }
    }
    else
    {
        [self _showPostingErrorWithText:nil error:nil];
        return NO;
    }
}

#pragma mark -
#pragma mark Private API

- (NSNumber *)_percentCompleteForCommentUpload:(DQCommentUpload *)cu requestPercentComplete:(CGFloat)requestPercentComplete
{
    CGFloat imageSize = [cu.imageSize floatValue];
    CGFloat playbackDataSize = [cu.playbackDataSize floatValue];
    CGFloat totalSize = imageSize + playbackDataSize;
    if (totalSize == 0.0) // shouldn't happen but hey
    {
        return @(0.0); // avoid divide by zero
    }
    else
    {
        if (cu.status == DQCommentUploadStatusUploadingImage)
        {
            CGFloat result = (imageSize * requestPercentComplete) / totalSize;
            return @(result * 100);
        }
        else if (cu.status == DQCommentUploadStatusUploadingPlaybackData)
        {
            CGFloat result = (imageSize + (playbackDataSize * requestPercentComplete)) / totalSize;
            return @(result * 100);
        }
        return cu.uploadProgress;
    }
}

- (NSString *)_pathForCommentUpload:(DQCommentUpload *)cu
{
    return [_uploadsPath stringByAppendingPathComponent:cu.identifier];
}

- (void)_processCommentUpload:(DQCommentUpload *)inCommentUpload
{
    DQPrivateServiceController *privateServiceController = self.privateServiceController;

    if (inCommentUpload.status == DQCommentUploadStatusNew)
    {
        [self.dataStoreController saveStatus:DQCommentUploadStatusUploadingImage forCommentUpload:inCommentUpload];
    } // purposely not using else if here so New (which is processed synchronously) can cascade into UploadingImage without recursing

    if (inCommentUpload.status == DQCommentUploadStatusUploadingImage)
    {
        NSData *imageData = inCommentUpload.imageData;
        if (imageData)
        {
            __weak typeof(self) weakSelf = self;
            [privateServiceController requestUploadOfImageData:imageData withTag:inCommentUpload.identifier progressBlock:^(DQHTTPRequest *request) {
                // Update the progress as the upload continues
                // Send progress changed notification
                NSNumber *percentComplete = [weakSelf _percentCompleteForCommentUpload:inCommentUpload requestPercentComplete:request.uploadPercentComplete];
                [weakSelf.dataStoreController takeProgress:percentComplete forCommentUpload:inCommentUpload];
                [weakSelf _handleProgressChangeForCommentUpload:inCommentUpload];
            } completionBlock:^(DQHTTPRequest *imageRequest, NSDictionary *contentDictionary, NSString *contentID) {
                if (imageRequest)
                {
                    if (imageRequest.error)
                    {
                        [self _handleFailureForCommentUpload:inCommentUpload
                                                  withStatus:DQCommentUploadStatusFailedUploadingImage];
                    }
                    else
                    {
                        [weakSelf.dataStoreController saveContentID:contentID forCommentUpload:inCommentUpload];
                        [self _processCommentUpload:inCommentUpload];
                    }
                }
                else
                {
                    [self _handleFailureForCommentUpload:inCommentUpload
                                              withStatus:DQCommentUploadStatusFailedUploadingImage];
                }
            }];
        }
        else
        {
            [self _handleFailureForCommentUpload:inCommentUpload
                                     withStatus:DQCommentUploadStatusFailedUploadingImage];
        }
    }
    else if (inCommentUpload.status == DQCommentUploadStatusPostingComment)
    {
        __weak typeof(self) weakSelf = self;
        [privateServiceController requestPostCommentUpload:inCommentUpload completionBlock:^(NSDictionary *commentInfo) {
            // there's nowhere to save the commentInfo in the DQCommentUpload so save it to disk
            NSData *commentInfoJSONData = [NSJSONSerialization dataWithJSONObject:commentInfo options:0 error:nil];
            NSError *error = nil;
            NSString *commentInfoPath = [[weakSelf _pathForCommentUpload:inCommentUpload] stringByAppendingPathComponent:@"comment.json"];
            if ([commentInfoJSONData writeToFile:commentInfoPath options:NSDataWritingAtomic error:&error])
            {
                NSURL *url = [NSURL fileURLWithPath:commentInfoPath];
                [url setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
                [weakSelf.dataStoreController saveStatus:DQCommentUploadStatusUploadingPlaybackData forCommentUpload:inCommentUpload];
                [self _processCommentUpload:inCommentUpload];
            }
            else
            {
                [self _handleFailureForCommentUpload:inCommentUpload
                                         withStatus:DQCommentUploadStatusFailedPostingComment];
            }
        } failureBlock:^(NSString *errorType) {
            if ([errorType isEqualToString:DQAPIErrorTypeInvalidFacebookToken])
            {
                [self _handleInvalidFacebookToken:inCommentUpload];
            }
            else if ([errorType isEqualToString:DQAPIErrorTypeInvalidTwitterToken])
            {
                [self _handleInvalidTwitterToken:inCommentUpload];
            }
            else
            {
                [self _handleFailureForCommentUpload:inCommentUpload
                                         withStatus:DQCommentUploadStatusFailedPostingComment];
            }
        }];
    }
    else if (inCommentUpload.status == DQCommentUploadStatusUploadingPlaybackData)
    {
        NSString *commentInfoPath = [[self _pathForCommentUpload:inCommentUpload] stringByAppendingPathComponent:@"comment.json"];
        NSData *commentInfoJSONData = [NSData dataWithContentsOfFile:commentInfoPath];
        NSDictionary *commentInfo = [NSJSONSerialization JSONObjectWithData:commentInfoJSONData options:0 error:nil];

        // Send the playback data
        NSString *playbackDataPath = [inCommentUpload playbackDataPath];

        __weak typeof(self) weakSelf = self;
        [privateServiceController requestSetPlaybackDataFromFileAtPath:playbackDataPath forCommentWithServerID:commentInfo.dq_serverID progressBlock:^(DQHTTPRequest *request) {
            NSNumber *percentComplete = [self _percentCompleteForCommentUpload:inCommentUpload requestPercentComplete:request.uploadPercentComplete];
            [weakSelf.dataStoreController takeProgress:percentComplete forCommentUpload:inCommentUpload];
            [self _handleProgressChangeForCommentUpload:inCommentUpload];
        } completionBlock:^(DQHTTPRequest *request) {
            [self _handleCommentUploadSucceeded:inCommentUpload commentInfo:commentInfo];
        } failureBlock:^(DQHTTPRequest *request) {
            [self _handleFailureForCommentUpload:inCommentUpload
                                     withStatus:DQCommentUploadStatusFailedUploadingPlaybackData];
        }];
    }
    else if (inCommentUpload.status == DQCommentUploadStatusFailedNew)
    {
        [self.dataStoreController saveStatus:DQCommentUploadStatusNew forCommentUpload:inCommentUpload];
        [self _processCommentUpload:inCommentUpload];
    }
    else if (inCommentUpload.status == DQCommentUploadStatusFailedWithInvalidFacebookToken)
    {
        [self.dataStoreController saveStatus:DQCommentUploadStatusPostingComment forCommentUpload:inCommentUpload];
        [self _processCommentUpload:inCommentUpload];
    }
    else if (inCommentUpload.status == DQCommentUploadStatusFailedWithInvalidTwitterToken)
    {
        [self.dataStoreController saveStatus:DQCommentUploadStatusPostingComment forCommentUpload:inCommentUpload];
        [self _processCommentUpload:inCommentUpload];
    }
    else if (inCommentUpload.status == DQCommentUploadStatusFailedUploadingImage)
    {
        [self.dataStoreController saveStatus:DQCommentUploadStatusUploadingImage forCommentUpload:inCommentUpload];
        [self _processCommentUpload:inCommentUpload];
    }
    else if (inCommentUpload.status == DQCommentUploadStatusFailedPostingComment)
    {
        [self.dataStoreController saveStatus:DQCommentUploadStatusPostingComment forCommentUpload:inCommentUpload];
        [self _processCommentUpload:inCommentUpload];
    }
    else if (inCommentUpload.status == DQCommentUploadStatusFailedUploadingPlaybackData)
    {
        [self.dataStoreController saveStatus:DQCommentUploadStatusUploadingPlaybackData forCommentUpload:inCommentUpload];
        [self _processCommentUpload:inCommentUpload];
    }
}

- (void)_handleProgressChangeForCommentUpload:(DQCommentUpload *)inCommentUpload
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary *userInfo = @{DQCommentUploadObjectNotificationKey : inCommentUpload};
        NSNotification *progressChangedNotification = [NSNotification notificationWithName:DQCommentUploadProgressChangedNotification object:nil userInfo:userInfo];
        [[NSNotificationCenter defaultCenter] postNotification:progressChangedNotification];
    });
}

- (void)_handleInvalidFacebookToken:(DQCommentUpload *)inCommentUpload
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.dataStoreController saveStatus:DQCommentUploadStatusFailedWithInvalidFacebookToken forCommentUpload:inCommentUpload];
    });
}

- (void)_handleInvalidTwitterToken:(DQCommentUpload *)inCommentUpload
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.dataStoreController saveStatus:DQCommentUploadStatusFailedWithInvalidTwitterToken forCommentUpload:inCommentUpload];
    });
}

- (void)_handleFailureForCommentUpload:(DQCommentUpload *)inCommentUpload withStatus:(DQCommentUploadStatus)status
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.dataStoreController saveStatus:status forCommentUpload:inCommentUpload];
    });
}

- (void)_handleCommentUploadSucceeded:(DQCommentUpload *)inCommentUpload commentInfo:(NSDictionary *)commentInfo
{
    NSLog(@"Comment upload succeeded");
    dispatch_async(dispatch_get_main_queue(), ^{
        DQComment *comment = [self.dataStoreController createOrUpdateCommentWithJSONInfo:commentInfo];
        // Save the quest ID so we have it after we delete the comment upload
        NSString *questID = [inCommentUpload.questID copy];
        DQRequestUpdateStarState(comment.serverID, DQStarStateNotStarred);

        NSDictionary *userInfo = @{DQCommentUploadObjectNotificationKey : inCommentUpload,
                                   DQCommentObjectNotificationKey : comment };
        NSNotification *completeNotification = [NSNotification notificationWithName:DQCommentUploadCompletedNotification object:nil userInfo:userInfo];
        [[NSNotificationCenter defaultCenter] postNotification:completeNotification];

        NSFileManager *fm = [[NSFileManager alloc] init];
        NSError *error = nil;
        if (![fm removeItemAtPath:[self _pathForCommentUpload:inCommentUpload] error:&error])
        {
            NSLog(@"Failed to remove the upload directory for %@", inCommentUpload.identifier);
        }
        [self.dataStoreController deleteCommentUpload:inCommentUpload];
        [self.dataStoreController markQuestIDCompleted:questID];
    });
}

- (void)_showPostingErrorWithText:(NSString *)inText error:(NSError *)error
{
    NSString *messageText = inText;
    if (!messageText) {
        messageText = DQLocalizedString(@"There was an unexpected problem and DrawQuest is unable to post.", @"Unknown DrawQuest upload error message");
    }

    if (error)
    {
        NSString *reason = [error localizedFailureReason] ?: [error localizedDescription];
        messageText = [messageText stringByAppendingFormat:@"\n\n%@", reason];
    }
    UIAlertView *noImageAlert = [[UIAlertView alloc] initWithTitle:DQLocalizedString(@"Posting Error", @"Upload error alert title") message:messageText delegate:nil cancelButtonTitle:DQLocalizedStringWithDefaultValue(@"AlertViewButtonTitleDismiss", nil, nil, @"Dismiss", @"Dismiss button for alert view") otherButtonTitles:nil];
    [noImageAlert show];
}

@end


text:
class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  rescue_from CanCan::AccessDenied do |exception|
    render file: "#{Rails.root}/public/403.html", status: 403, layout: false
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :password, :password_confirmation, :current_password) }
  end
end