text:
package buffer_stubs

import (
	sync "sync"

	alias1 "github.com/momchil-atanasov/go-whiskey-android/gles/buffer"
	alias2 "github.com/momchil-atanasov/go-whiskey-android/gles/client"
)

type FactoryStub struct {
	StubGUID                      int
	CreateVertexBufferStub        func(arg1 int, arg2 alias2.BufferUsage) (result1 alias1.VertexBuffer, result2 error)
	createVertexBufferMutex       sync.RWMutex
	createVertexBufferArgsForCall []struct {
		arg1 int
		arg2 alias2.BufferUsage
	}
	createVertexBufferReturns struct {
		result1 alias1.VertexBuffer
		result2 error
	}
	UpdateVertexBufferStub        func(arg1 alias1.VertexBuffer) (result1 error)
	updateVertexBufferMutex       sync.RWMutex
	updateVertexBufferArgsForCall []struct {
		arg1 alias1.VertexBuffer
	}
	updateVertexBufferReturns struct {
		result1 error
	}
	DeleteVertexBufferStub        func(arg1 alias1.VertexBuffer) (result1 error)
	deleteVertexBufferMutex       sync.RWMutex
	deleteVertexBufferArgsForCall []struct {
		arg1 alias1.VertexBuffer
	}
	deleteVertexBufferReturns struct {
		result1 error
	}
	CreateIndexBufferStub        func(arg1 int, arg2 alias2.BufferUsage) (result1 alias1.IndexBuffer, result2 error)
	createIndexBufferMutex       sync.RWMutex
	createIndexBufferArgsForCall []struct {
		arg1 int
		arg2 alias2.BufferUsage
	}
	createIndexBufferReturns struct {
		result1 alias1.IndexBuffer
		result2 error
	}
	UpdateIndexBufferStub        func(arg1 alias1.IndexBuffer) (result1 error)
	updateIndexBufferMutex       sync.RWMutex
	updateIndexBufferArgsForCall []struct {
		arg1 alias1.IndexBuffer
	}
	updateIndexBufferReturns struct {
		result1 error
	}
	DeleteIndexBufferStub        func(arg1 alias1.IndexBuffer) (result1 error)
	deleteIndexBufferMutex       sync.RWMutex
	deleteIndexBufferArgsForCall []struct {
		arg1 alias1.IndexBuffer
	}
	deleteIndexBufferReturns struct {
		result1 error
	}
}

var _ alias1.Factory = new(FactoryStub)

func (stub *FactoryStub) CreateVertexBuffer(arg1 int, arg2 alias2.BufferUsage) (alias1.VertexBuffer, error) {
	stub.createVertexBufferMutex.Lock()
	defer stub.createVertexBufferMutex.Unlock()
	stub.createVertexBufferArgsForCall = append(stub.createVertexBufferArgsForCall, struct {
		arg1 int
		arg2 alias2.BufferUsage
	}{arg1, arg2})
	if stub.CreateVertexBufferStub != nil {
		return stub.CreateVertexBufferStub(arg1, arg2)
	} else {
		return stub.createVertexBufferReturns.result1, stub.createVertexBufferReturns.result2
	}
}
func (stub *FactoryStub) CreateVertexBufferCallCount() int {
	stub.createVertexBufferMutex.RLock()
	defer stub.createVertexBufferMutex.RUnlock()
	return len(stub.createVertexBufferArgsForCall)
}
func (stub *FactoryStub) CreateVertexBufferArgsForCall(index int) (int, alias2.BufferUsage) {
	stub.createVertexBufferMutex.RLock()
	defer stub.createVertexBufferMutex.RUnlock()
	return stub.createVertexBufferArgsForCall[index].arg1, stub.createVertexBufferArgsForCall[index].arg2
}
func (stub *FactoryStub) CreateVertexBufferReturns(result1 alias1.VertexBuffer, result2 error) {
	stub.createVertexBufferMutex.Lock()
	defer stub.createVertexBufferMutex.Unlock()
	stub.createVertexBufferReturns = struct {
		result1 alias1.VertexBuffer
		result2 error
	}{result1, result2}
}
func (stub *FactoryStub) UpdateVertexBuffer(arg1 alias1.VertexBuffer) error {
	stub.updateVertexBufferMutex.Lock()
	defer stub.updateVertexBufferMutex.Unlock()
	stub.updateVertexBufferArgsForCall = append(stub.updateVertexBufferArgsForCall, struct {
		arg1 alias1.VertexBuffer
	}{arg1})
	if stub.UpdateVertexBufferStub != nil {
		return stub.UpdateVertexBufferStub(arg1)
	} else {
		return stub.updateVertexBufferReturns.result1
	}
}
func (stub *FactoryStub) UpdateVertexBufferCallCount() int {
	stub.updateVertexBufferMutex.RLock()
	defer stub.updateVertexBufferMutex.RUnlock()
	return len(stub.updateVertexBufferArgsForCall)
}
func (stub *FactoryStub) UpdateVertexBufferArgsForCall(index int) alias1.VertexBuffer {
	stub.updateVertexBufferMutex.RLock()
	defer stub.updateVertexBufferMutex.RUnlock()
	return stub.updateVertexBufferArgsForCall[index].arg1
}
func (stub *FactoryStub) UpdateVertexBufferReturns(result1 error) {
	stub.updateVertexBufferMutex.Lock()
	defer stub.updateVertexBufferMutex.Unlock()
	stub.updateVertexBufferReturns = struct {
		result1 error
	}{result1}
}
func (stub *FactoryStub) DeleteVertexBuffer(arg1 alias1.VertexBuffer) error {
	stub.deleteVertexBufferMutex.Lock()
	defer stub.deleteVertexBufferMutex.Unlock()
	stub.deleteVertexBufferArgsForCall = append(stub.deleteVertexBufferArgsForCall, struct {
		arg1 alias1.VertexBuffer
	}{arg1})
	if stub.DeleteVertexBufferStub != nil {
		return stub.DeleteVertexBufferStub(arg1)
	} else {
		return stub.deleteVertexBufferReturns.result1
	}
}
func (stub *FactoryStub) DeleteVertexBufferCallCount() int {
	stub.deleteVertexBufferMutex.RLock()
	defer stub.deleteVertexBufferMutex.RUnlock()
	return len(stub.deleteVertexBufferArgsForCall)
}
func (stub *FactoryStub) DeleteVertexBufferArgsForCall(index int) alias1.VertexBuffer {
	stub.deleteVertexBufferMutex.RLock()
	defer stub.deleteVertexBufferMutex.RUnlock()
	return stub.deleteVertexBufferArgsForCall[index].arg1
}
func (stub *FactoryStub) DeleteVertexBufferReturns(result1 error) {
	stub.deleteVertexBufferMutex.Lock()
	defer stub.deleteVertexBufferMutex.Unlock()
	stub.deleteVertexBufferReturns = struct {
		result1 error
	}{result1}
}
func (stub *FactoryStub) CreateIndexBuffer(arg1 int, arg2 alias2.BufferUsage) (alias1.IndexBuffer, error) {
	stub.createIndexBufferMutex.Lock()
	defer stub.createIndexBufferMutex.Unlock()
	stub.createIndexBufferArgsForCall = append(stub.createIndexBufferArgsForCall, struct {
		arg1 int
		arg2 alias2.BufferUsage
	}{arg1, arg2})
	if stub.CreateIndexBufferStub != nil {
		return stub.CreateIndexBufferStub(arg1, arg2)
	} else {
		return stub.createIndexBufferReturns.result1, stub.createIndexBufferReturns.result2
	}
}
func (stub *FactoryStub) CreateIndexBufferCallCount() int {
	stub.createIndexBufferMutex.RLock()
	defer stub.createIndexBufferMutex.RUnlock()
	return len(stub.createIndexBufferArgsForCall)
}
func (stub *FactoryStub) CreateIndexBufferArgsForCall(index int) (int, alias2.BufferUsage) {
	stub.createIndexBufferMutex.RLock()
	defer stub.createIndexBufferMutex.RUnlock()
	return stub.createIndexBufferArgsForCall[index].arg1, stub.createIndexBufferArgsForCall[index].arg2
}
func (stub *FactoryStub) CreateIndexBufferReturns(result1 alias1.IndexBuffer, result2 error) {
	stub.createIndexBufferMutex.Lock()
	defer stub.createIndexBufferMutex.Unlock()
	stub.createIndexBufferReturns = struct {
		result1 alias1.IndexBuffer
		result2 error
	}{result1, result2}
}
func (stub *FactoryStub) UpdateIndexBuffer(arg1 alias1.IndexBuffer) error {
	stub.updateIndexBufferMutex.Lock()
	defer stub.updateIndexBufferMutex.Unlock()
	stub.updateIndexBufferArgsForCall = append(stub.updateIndexBufferArgsForCall, struct {
		arg1 alias1.IndexBuffer
	}{arg1})
	if stub.UpdateIndexBufferStub != nil {
		return stub.UpdateIndexBufferStub(arg1)
	} else {
		return stub.updateIndexBufferReturns.result1
	}
}
func (stub *FactoryStub) UpdateIndexBufferCallCount() int {
	stub.updateIndexBufferMutex.RLock()
	defer stub.updateIndexBufferMutex.RUnlock()
	return len(stub.updateIndexBufferArgsForCall)
}
func (stub *FactoryStub) UpdateIndexBufferArgsForCall(index int) alias1.IndexBuffer {
	stub.updateIndexBufferMutex.RLock()
	defer stub.updateIndexBufferMutex.RUnlock()
	return stub.updateIndexBufferArgsForCall[index].arg1
}
func (stub *FactoryStub) UpdateIndexBufferReturns(result1 error) {
	stub.updateIndexBufferMutex.Lock()
	defer stub.updateIndexBufferMutex.Unlock()
	stub.updateIndexBufferReturns = struct {
		result1 error
	}{result1}
}
func (stub *FactoryStub) DeleteIndexBuffer(arg1 alias1.IndexBuffer) error {
	stub.deleteIndexBufferMutex.Lock()
	defer stub.deleteIndexBufferMutex.Unlock()
	stub.deleteIndexBufferArgsForCall = append(stub.deleteIndexBufferArgsForCall, struct {
		arg1 alias1.IndexBuffer
	}{arg1})
	if stub.DeleteIndexBufferStub != nil {
		return stub.DeleteIndexBufferStub(arg1)
	} else {
		return stub.deleteIndexBufferReturns.result1
	}
}
func (stub *FactoryStub) DeleteIndexBufferCallCount() int {
	stub.deleteIndexBufferMutex.RLock()
	defer stub.deleteIndexBufferMutex.RUnlock()
	return len(stub.deleteIndexBufferArgsForCall)
}
func (stub *FactoryStub) DeleteIndexBufferArgsForCall(index int) alias1.IndexBuffer {
	stub.deleteIndexBufferMutex.RLock()
	defer stub.deleteIndexBufferMutex.RUnlock()
	return stub.deleteIndexBufferArgsForCall[index].arg1
}
func (stub *FactoryStub) DeleteIndexBufferReturns(result1 error) {
	stub.deleteIndexBufferMutex.Lock()
	defer stub.deleteIndexBufferMutex.Unlock()
	stub.deleteIndexBufferReturns = struct {
		result1 error
	}{result1}
}


text:
import _ from 'lodash';

export default () => _.capitalize;

redpajama_set_name: RedPajamaGithub


text:
package gblib;

import java.util.LinkedList;
import java.util.List;
import static gblib.MessageMgr.message;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static java.util.Objects.nonNull;
import java.util.function.Function;
import java.util.function.Supplier;

public class Util {
    public static <T> List<T> emptyUnmodifiableList() {
        return Collections.unmodifiableList(new LinkedList<>());
    }

    public static <K,V> Map<K,V> emptyUnmodifiableMap() {
        return Collections.unmodifiableMap(new HashMap<>());
    }

    /**
     * Generate non-null value.
     * @param <T> value type of check.
     * @param <R> return value type.
     * @param check check for non-null.
     * @param onNonNull apply function to check if check != null.
     * @param onNull produce value if check or onNonNull return value is null.
     * @return value of type R.
     */
    public static <T,R> R getNonNullValue(T check, Function<T,R> onNonNull, Supplier<R> onNull) {
        R rval = null;
        if (nonNull(check)) {
            rval = onNonNull.apply(check);
        }
        return nonNull(rval) ? rval : onNull.get();
    }

    /**
     * Generate non-null value on 2-step evaluate.
     * @param <T> value type of check.
     * @param <R1> return value type on first evaluate.
     * @param <R2> return value type on second/final evaluate.
     * @param check check for non-null.
     * @param onNonNull1 apply function to check if check != null.
     * @param onNonNull2 apply function if onNonNull1 != null.
     * @param onNull produce value if check or onNonNull[12] return value is null.
     * @return
     */
    public static <T,R1,R2> R2 getNonNullValue(T check, Function<T,R1> onNonNull1, Function<R1,R2> onNonNull2, Supplier<R2> onNull) {
        R2 rval = null;
        if (nonNull(check)) {
            R1 v1 = onNonNull1.apply(check);
            if (nonNull(v1)) {
                rval = onNonNull2.apply(v1);
            }
        }
        return nonNull(rval) ? rval : onNull.get();
    }

    public static <T> T getNonNullValue(T first, T second) {
        return nonNull(first) ? first : second;
    }

    /**
     * Read InputStream and convert to string.
     *
     * @param ins input stream.
     * @param n size of internal buffer.
     * @return contents of stream or null on error.
     * @throws java.io.IOException
     */
    public static String toString(InputStream ins, final int n) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[n];
        while ((nRead = ins.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return new String(buffer.toByteArray(), "UTF-8");
    }

    public static String toString(InputStream ins) throws IOException {
        return toString(ins, 16384);
    }

    public static boolean isUpperCase(final String s) {
        return s.equals(s.toUpperCase());
    }

    public static String escape(final char c) {
        String s = "";
        switch (c) {
            case '\n':
                s = "\\n";
                break;
            case '\t':
                s = "\\t";
                break;
            case '\\':
                s = "\\\\";
                break;
            default:
                s = Character.toString(c);
        }
        return s;
    }

    public static String escape(final String s) {
        return s.replace("\n", "\\n");
    }

    public static char unescape(final String s) {
        invariant((2 == s.length()) && (s.charAt(0) == '\\'));
        char c = 0;
        switch (s) {
            case "\\n":
                c = '\n';
                break;
            case "\\r":
                c = '\r';
                break;
            case "\\'":
                c = '\'';
                break;
            case "\\t":
                c = '\t';
                break;
            case "\\":
                c = '\\';
                break;
            default:
                invariant(false);
        }
        return c;
    }

    public static String stripDoubleQuotes(final String s) {
        int len = s.length();
        String ns = s.substring(1, len - 1);
        return ns;
    }

    public static void invariant(boolean c) {
        if (false == c) {
            Thread.dumpStack();
            System.exit(1);
        }
    }

    private final static String stDOT = ".";

    public static String getToolRoot() {
        String root = System.getProperty("tool.root");
        if (null == root) {
            root = stDOT;
        }
        return root;
    }

    public static void fatal(Exception ex) {
        PrintStream err = System.err;
        err.print(ex.getMessage());
        ex.printStackTrace(err);
        System.exit(1);
    }

    /**
     * Lookup property value.
     *
     * @param prop property name
     * @return true if property exists and set to "true" or else false.
     */
    public static boolean getPropertyAsBool(String prop) {
        String pv = System.getProperty(prop);
        boolean v = (null == pv) ? false : Boolean.parseBoolean(pv);
        return v;
    }

    public static int getPropertyAsInt(String nm) {
        int rval = Integer.MIN_VALUE;
        String str = System.getProperty(nm);
        if (null != str) {
            rval = Integer.parseInt(str);
        }
        return rval;
    }

    public static void abnormalExit(Exception ex) {
        System.err.println(ex.getMessage());
        ex.printStackTrace(System.err);
        System.exit(1);
    }

    public static List<String> arrayToList(String s[]) {
        return Arrays.asList(s);
    }

    public static <T> List<T> createList(T... items) {
        return Arrays.asList(items);
    }

    public static <T> int linearSearch(final T[] eles, final T ele) {
        for (int i = 0; i < eles.length; i++) {
            if (eles[i] == ele) {
                return i;
            }
        }
        return -1;
    }

    @FunctionalInterface
    public interface ListProvider<F, T> {
        public List<T> get(F from);
    }

    /**
     * Return an unmodifiable list: empty or otherwise.
     * @param <F> type of list provider.
     * @param <T> type of list element.
     * @param from list provider (or null).
     * @param ifNonNull call from's list provider function (for from != null).
     * @return from's list or empty list.
     */
    public static <F,T> List<T> getUnModifiableList(F from, ListProvider<F,T> ifNonNull) {
        return Collections.unmodifiableList(getList(from, ifNonNull));
    }

    public static <F,T> List<T> getList(F from, ListProvider<F,T> ifNonNull) {
        List<T> list = nonNull(from) ? ifNonNull.get(from) : Collections.emptyList();
        return list;
    }

    /**
     * Return a null x as an empty collection.
     */
    public static <T> T asEmpty(T x, T empty) {
        return (null != x) ? x : empty;
    }

    public static <T> T downCast(Object o) {
        return (T) o;
    }

    /**
     * Add only new elements to list.
     *
     * @param <T> type of list element.
     * @param to list to update with only new elements.
     * @param from list to get new elements from.
     */
    public static <T> void addAllNoDups(List<T> to, List<T> from) {
        for (T ele : from) {
            if (!to.contains(ele)) {
                to.add(ele);
            }
        }
    }

    private final static String m_nl = System.getProperty("line.separator");

    public static int streamCopy(BufferedInputStream from, BufferedOutputStream to) throws IOException {
        final int bufSz = 2048;
        byte buf[] = new byte[bufSz];
        int tlCnt = 0, cnt = 0;
        while (0 <= (cnt = from.read(buf, 0, bufSz))) {
            tlCnt += cnt;
            to.write(buf, 0, cnt);
        }
        to.flush();
        return tlCnt;
    }

    public static String nl() {
        return m_nl;
    }

    public static interface Equals<T> {

        public boolean equals(T a, T b);
    }

    /**
     * Check if objects are equal.
     *
     * @param <T> type of objects.
     * @param a 1st object (could be null).
     * @param b 2ns object (could be null).
     * @param eq optional interface to provide equals method.
     * @return true iff. both objects are null or both are non-null and equal.
     */
    public static <T> boolean equalsInclNull(T a, T b, Equals<T> eq) {
        if ((null == a) && (null == b)) {
            return true;
        }
        if ((null != a) && (null != b)) {
            if (null != eq) {
                return eq.equals(a, b);
            } else {
                return a.equals(b);
            }
        }
        return false;
    }

    public static <T> boolean equalsInclNull(T a, T b) {
        return equalsInclNull(a, b, null);
    }

    public static char intToChar(int l) throws ConversionException {
        if (l < Character.MIN_VALUE) {
            throw new ConversionException(l + "<" + Character.MIN_VALUE);
        } else if (l > Character.MAX_VALUE) {
            throw new ConversionException(l + ">" + Character.MAX_VALUE);
        }
        return (char) l;
    }

    public static int longToInt(long l) throws ConversionException {
        if (l < Integer.MIN_VALUE) {
            throw new ConversionException(l + "<" + Integer.MIN_VALUE);
        } else if (l > Integer.MAX_VALUE) {
            throw new ConversionException(l + ">" + Integer.MAX_VALUE);
        }
        return (int) l;
    }

    public static class ConversionException extends RuntimeException {

        public ConversionException(String msg) {
            super(msg);
        }
    }

    public static class Triplet<T1, T2, T3> extends Pair<T1, T2> {

        public Triplet() {
        }

        public Triplet(T1 a1, T2 a2, T3 a3) {
            super(a1, a2);
            e3 = a3;
        }
        public T3 e3;
    }

    /**
     * Generate comma separated String of list elements.
     *
     * @param <T> element type (must has toString() method).
     * @param eles list of elements.
     * @return comma separated String of list elements.
     */
    public static <T> String toCommaSeparatedString(final Collection<T> eles) {
        return join(eles, ",");
    }

    public static <T> String toCSV(final Collection<T> eles) {
        return toCommaSeparatedString(eles);
    }

    public static <T> String join(Collection<T> eles, String sep) {
         StringBuilder s = new StringBuilder();
        if (null != eles) {
            for (T ele : eles) {
                if (0 < s.length()) {
                    s.append(sep);
                }
                s.append(ele.toString());
            }
        }
        return s.toString();
    }

    public static String toString(StringBuilder s) {
        return (null != s) ? s.toString() : "";
    }

    /**
     * Return union of 2 lists.
     *
     * @param <T>
     * @param l1 first list.
     * @param l2 second list.
     * @param allowDups true to allow duplicates.
     * @return union of lists.
     */
    public static <T> List<T> union(final List<T> l1, final List<T> l2, boolean allowDups) {
        LinkedList<T> u = new LinkedList<>(l1);
        for (T e : l2) {
            if (allowDups || (0 > u.indexOf(e))) {
                u.add(e);
            }
        }
        return u;
    }

    public static <T> List<T> union(final List<T> l1, final List<T> l2) {
        return union(l1, l2, false);
    }

    public static void assertTrue(boolean cond, String msg) {
        if (!cond) {
            abnormalExit(new RuntimeException(msg));
        }
    }

    public static void assertFalse(boolean cond, String msg) {
        assertTrue(!cond, msg);
    }

    public static void assertNever(String msg) {
        abnormalExit(msg);
    }

    public static void abnormalExit(String msg) {
        abnormalExit(new Exception(msg));
    }

    public static void info(String code, Object... args) {
        message('I', code, args);
    }

    public static void warn(String code, Object... args) {
        message('W', code, args);
    }

    public static void info(int minLvl, String code, Object... args) {
        message(minLvl, 'I', code, args);
    }

    public static void warn(int minLvl, String code, Object... args) {
        message(minLvl, 'W', code, args);
    }

    public static void error(String code, Object... args) {
        message('E', code, args);
    }

    /**
     * Check if 2 files/dirs refer to same (physical file/dir).
     *
     * @param f1 first file/dir.
     * @param f2 second file/dir.
     * @return true if both refer to same physical location.
     */
    public static boolean filesAreSame(String f1, String f2) {
        return (new gblib.File(f1)).equals(new gblib.File(f2));
    }

    /**
     * Append join+s2 to s1 iff. s2 != null.
     *
     * @param s1 prefix.
     * @param join join s2 with this (iff. s2 != null).
     * @param s2 append join + s2 iff. s2 != null.
     * @return s1 with optional join+s2.
     */
    public static String appendIfNotNull(String s1, String join, String s2) {
        StringBuilder s = new StringBuilder(s1);
        if (null != s2) {
            s.append(join).append(s2);
        }
        return s.toString();
    }

    public static <T> Collection<T> replicate(T item, int ntimes) {
        List<T> items = new LinkedList<>();
        for (int i = 0; i < ntimes; i++) {
            items.add(item);
        }
        return items;
    }
}


text:
'use strict';

module.exports = function(Target) {
var _ = require('lodash');
var SqlString = require('./dialects/mysql/string');

Target.prototype.toQuery = function(tz) {
  var data = this.toSQL(this._method);
  if (this._errors && this._errors.length > 0) throw this._errors[0];
  if (!_.isArray(data)) data = [data];
  return _.map(data, function(statement) {
    return this._formatQuery(statement.sql, statement.bindings, tz);
  }, this).join(';\n');
};

// Format the query as sql, prepping bindings as necessary.
Target.prototype._formatQuery = function(sql, bindings, tz) {
  if (this.client && this.client.prepBindings) {
    bindings = this.client.prepBindings(bindings, tz);
  }
  return SqlString.format(sql, bindings, true, tz);
};

// Create a new instance of the `Runner`, passing in the current object.
Target.prototype.then = function(onFulfilled, onRejected) {
  var Runner = this.client.Runner;
  return new Runner(this).run().then(onFulfilled, onRejected);
};

// Add additional "options" to the builder. Typically used for client specific
// items, like the `mysql` and `sqlite3` drivers.
Target.prototype.options = function(opts) {
  this._options = this._options || [];
  this._options.push(_.clone(opts) || {});
  return this;
};

// Sets an explicit "connnection" we wish to use for this query.
Target.prototype.connection = function(connection) {
  this._connection = connection;
  return this;
};

// Set a debug flag for the current schema query stack.
Target.prototype.debug = function(val) {
  this._debug = (val === undefined || val === null) ? true : val;
  return this;
};

// Set the transaction object for this query.
Target.prototype.transacting = function(t) {
  this._transacting = t;
  return this;
};

// Initializes a stream.
Target.prototype.stream = function(options) {
  var Runner = this.client.Runner;
  return new Runner(this).stream(options);
};

// Initialize a stream & pipe automatically.
Target.prototype.pipe = function(writable) {
  var Runner = this.client.Runner;
  return new Runner(this).pipe(writable);
};

// Creates a method which "coerces" to a promise, by calling a
// "then" method on the current `Target`
_.each(['bind', 'catch', 'spread', 'otherwise', 'map', 'reduce', 'tap', 'thenReturn',
  'return', 'yield', 'ensure', 'nodeify', 'exec'], function(method) {
  Target.prototype[method] = function() {
    var then = this.then();
    return then[method].apply(then, arguments);
  };
});

};


text:
using System.Linq;
using Utilities.DataTypes;
using Xunit;

namespace UnitTests.DataTypes
{
    public class ListMapping
    {
        [Fact]
        public void ContainsTest()
        {
            var TestObject = new ListMapping<string, int>();
            TestObject.Add("A", 0);
            TestObject.Add("A", 1);
            Assert.True(TestObject.Contains("A", 0));
            Assert.False(TestObject.Contains("A", 2));
        }

        [Fact]
        public void RandomTest()
        {
            var TestObject = new ListMapping<string, int>();
            var Rand = new System.Random();
            for (int x = 0; x < 10; ++x)
            {
                string Name = x.ToString();
                for (int y = 0; y < 5; ++y)
                {
                    int Value = Rand.Next();
                    TestObject.Add(Name, Value);
                    Assert.Equal(y + 1, TestObject[Name].Count());
                    Assert.True(TestObject[Name].Contains(Value));
                }
            }
            Assert.Equal(10, TestObject.Count);
        }

        [Fact]
        public void RemoveTest()
        {
            var TestObject = new ListMapping<string, int>();
            TestObject.Add("A", 0);
            TestObject.Add("A", 1);
            TestObject.Remove("A", 0);
            Assert.Equal(1, TestObject["A"].Count());
            Assert.Equal(1, TestObject["A"].FirstOrDefault());
        }
    }
}


text:
from setuptools import find_packages, setup
import os

# You need install_requires if you don't have a ROS environment
install_requires = [] if os.environ.get('CATKIN_BINARY_DIR') else [
    # build
    'setuptools',
    # runtime
    'enum34;python_version<"3.4"',
    'pydot'
]

tests_require = ['nose', 'pydot', 'pytest', 'flake8', 'yanc', 'nose-htmloutput']

extras_require = {} if os.environ.get('CATKIN_BINARY_DIR') else {
    'test': tests_require,
    'docs': ["Sphinx", "sphinx-argparse", "sphinx-rtd-theme"],
    'debs': ['stdeb', 'twine']
}

##############################
# Pull in __version__
##############################

project_dir = os.path.abspath(
    os.path.join(
        os.path.abspath(__file__),
        os.pardir))
version_file = os.path.join(project_dir, 'py_trees', 'version.py')
with open(version_file) as f:
    exec(f.read())

# Some duplication of properties here and in package.xml.
# Make sure to update them both.
# That is the price paid for a pypi and catkin package.
d = setup(
    name='py_trees',
    version=__version__,
    packages=find_packages(exclude=['tests*', 'docs*']),
    install_requires=install_requires,
    extras_require=extras_require,
    author='Daniel Stonier, Naveed Usmani, Michal Staniaszek',
    maintainer='Daniel Stonier <d.stonier@gmail.com>, Naveed Usmani <naveedhd@gmail.com>',
    url='http://github.com/stonier/py_trees',
    keywords='behaviour-trees',
    zip_safe=True,
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering :: Artificial Intelligence',
        'Topic :: Software Development :: Libraries'
    ],
    description="pythonic implementation of behaviour trees",
    long_description="A behaviour tree implementation for rapid development of small scale decision making engines that don't need to be real time reactive.",
    license='BSD',
    test_suite='nose.collector',
    tests_require=tests_require,
    # test_suite='tests',
    # Unfortunately catkin builds do not like this
    #     entry_points={
    #         'console_scripts': [
    #             'py-trees-demo-action-behaviour = py_trees.demos.action:main',
    #             'py-trees-demo-behaviour-lifecycle = py_trees.demos.lifecycle:main',
    #             'py-trees-demo-blackboard = py_trees.demos.blackboard:main',
    #             'py-trees-demo-context-switching = py_trees.demos.context_switching:main',
    #             'py-trees-demo-dot-graphs = py_trees.demos.dot_graphs:main',
    #             'py-trees-demo-selector = py_trees.demos.selector:main',
    #             'py-trees-demo-sequence = py_trees.demos.sequence:main',
    #             'py-trees-demo-tree-stewardship = py_trees.demos.stewardship:main',
    #         ],
    #     },
    # So we do the tedious way
    scripts=['scripts/py-trees-demo-action-behaviour',
             'scripts/py-trees-demo-behaviour-lifecycle',
             'scripts/py-trees-demo-blackboard',
             'scripts/py-trees-demo-context-switching',
             'scripts/py-trees-demo-dot-graphs',
             'scripts/py-trees-demo-selector',
             'scripts/py-trees-demo-sequence',
             'scripts/py-trees-demo-tree-stewardship',
             'scripts/py-trees-render'
             ],
)


text:
'use strict';

const fs = require('fs');
const md5 = require('md5');
const path = require('path');
const assert = require('assert');
const server = require('./server');
const {isFunc} = require('../lib/utilities');
const fileFactory = require('../lib/fileFactory');

const mockFileName = 'basketball.png';
const mockFile = path.join(server.fileDir, mockFileName);
const mockBuffer = fs.readFileSync(mockFile);
const mockMd5 = md5(mockBuffer);

const mockFileOpts = {
  name: mockFileName,
  buffer: mockBuffer,
  encoding: 'utf-8',
  mimetype: 'image/png',
  hash: mockMd5,
  tempFilePath: mockFile
};

describe('Test of the fileFactory factory', function() {
  beforeEach(() => server.clearUploadsDir());

  it('return a file object', () => assert.ok(fileFactory(mockFileOpts)));

  describe('Properties', function() {
    it('contains the name property', () => {
      assert.equal(fileFactory(mockFileOpts).name, mockFileName);
    });
    it('contains the data property', () => assert.ok(fileFactory(mockFileOpts).data));
    it('contains the encoding property', () => {
      assert.equal(fileFactory(mockFileOpts).encoding, 'utf-8');
    });
    it('contains the mimetype property', () => {
      assert.equal(fileFactory(mockFileOpts).mimetype, 'image/png');
    });
    it('contains the md5 property', () => assert.equal(fileFactory(mockFileOpts).md5, mockMd5));
    it('contains the mv method', () => assert.equal(isFunc(fileFactory(mockFileOpts).mv), true));
  });

  describe('File object behavior for in memory upload', function() {
    const file = fileFactory(mockFileOpts);
    it('move the file to the specified folder', (done) => {
      file.mv(path.join(server.uploadDir, mockFileName), (err) => {
        assert.ifError(err);
        done();
      });
    });
    it('reject the mv if the destination does not exists', (done) => {
      file.mv(path.join(server.uploadDir, 'unknown', mockFileName), (err) => {
        assert.ok(err);
        done();
      });
    });
  });

  describe('File object behavior for upload into temporary file', function() {
    const file = fileFactory(mockFileOpts, { useTempFiles: true });
    it('move the file to the specified folder', (done) => {
      file.mv(path.join(server.uploadDir, mockFileName), (err) => {
        assert.ifError(err);
        // Place back moved file.
        fs.renameSync(path.join(server.uploadDir, mockFileName), mockFile);
        done();
      });
    });
    it('reject the mv if the destination does not exists', (done) => {
      file.mv(path.join(server.uploadDir, 'unknown', mockFileName), (err) => {
        assert.ok(err);
        done();
      });
    });
  });
});


text:
<?php

namespace Arrilot\BitrixMigrations\BaseMigrations;

use Arrilot\BitrixMigrations\Exceptions\MigrationException;
use Arrilot\BitrixMigrations\Interfaces\MigrationInterface;
use Bitrix\Main\Application;
use Bitrix\Main\DB\Connection;
use CIBlock;
use CIBlockProperty;
use CUserTypeEntity;

class BitrixMigration implements MigrationInterface
{
    /**
     * DB connection.
     *
     * @var Connection
     */
    protected $db;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->db = Application::getConnection();
    }

    /**
     * Run the migration.
     *
     * @return mixed
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migration.
     *
     * @return mixed
     */
    public function down()
    {
        //
    }

    /**
     * Find iblock id by its code.
     *
     * @param string      $code
     * @param null|string $iBlockType
     *
     * @throws MigrationException
     *
     * @return int
     */
    protected function getIblockIdByCode($code, $iBlockType = null)
    {
        if (!$code) {
            throw new MigrationException('Не задан код инфоблока');
        }

        $filter = array(
            'CODE'              => $code,
            'CHECK_PERMISSIONS' => 'N',
        );

        if ($iBlockType !== null) {
            $filter['TYPE'] = $iBlockType;
        }

        $cIBlockRepo = new CIBlock();
        $iblock = $cIBlockRepo->GetList(array(), $filter)->fetch();

        if (!$iblock['ID']) {
            throw new MigrationException("Не удалось найти инфоблок с кодом '{$code}'");
        }

        return $iblock['ID'];
    }

    /**
     * Delete iblock by its code.
     *
     * @param string $code
     *
     * @throws MigrationException
     *
     * @return void
     */
    protected function deleteIblockByCode($code)
    {
        $id = $this->getIblockIdByCode($code);

        $this->db->startTransaction();
        if (!CIBlock::Delete($id)) {
            $this->db->rollbackTransaction();
            throw new MigrationException('Ошибка при удалении инфоблока');
        }

        $this->db->commitTransaction();
    }

    /**
     * Add iblock element property.
     *
     * @param array $fields
     *
     * @throws MigrationException
     *
     * @return int
     */
    public function addIblockElementProperty($fields)
    {
        $ibp = new CIBlockProperty();
        $propId = $ibp->add($fields);

        if (!$propId) {
            throw new MigrationException('Ошибка при добавлении свойства инфоблока ' . $ibp->LAST_ERROR);
        }

        return $propId;
    }

    /**
     * Delete iblock element property.
     *
     * @param string     $code
     * @param string|int $iblockId
     *
     * @throws MigrationException
     */
    public function deleteIblockElementPropertyByCode($iblockId, $code)
    {
        if (!$iblockId) {
            throw new MigrationException('Не задан ID инфоблока');
        }

        if (!$code) {
            throw new MigrationException('Не задан код свойства');
        }

        $id = $this->getIblockPropIdByCode($code, $iblockId);

        CIBlockProperty::Delete($id);
    }

    /**
     * Add User Field.
     *
     * @param $fields
     *
     * @throws MigrationException
     *
     * @return int
     */
    public function addUF($fields)
    {
        if (!$fields['FIELD_NAME']) {
            throw new MigrationException('Не заполнен FIELD_NAME');
        }

        if (!$fields['ENTITY_ID']) {
            throw new MigrationException('Не заполнен код ENTITY_ID');
        }

        $oUserTypeEntity = new CUserTypeEntity();

        $fieldId = $oUserTypeEntity->Add($fields);

        if (!$fieldId) {
            throw new MigrationException("Не удалось создать пользовательское свойство с FIELD_NAME = {$fields['FIELD_NAME']} и ENTITY_ID = {$fields['ENTITY_ID']}");
        }

        return $fieldId;
    }

    /**
     * Get UF by its code.
     *
     * @param string $entity
     * @param string $code
     *
     * @throws MigrationException
     */
    public function getUFIdByCode($entity, $code)
    {
        if (!$entity) {
            throw new MigrationException('Не задана сущность свойства');
        }

        if (!$code) {
            throw new MigrationException('Не задан код свойства');
        }

        $filter = array(
            'ENTITY_ID'  => $entity,
            'FIELD_NAME' => $code,
        );

        $arField = CUserTypeEntity::GetList(array('ID' => 'ASC'), $filter)->fetch();
        if (!$arField || !$arField['ID']) {
            throw new MigrationException("Не найдено свойство с FIELD_NAME = {$filter['FIELD_NAME']} и ENTITY_ID = {$filter['ENTITY_ID']}");
        }

        return $arField['ID'];
    }

    /**
     * @param $code
     * @param $iblockId
     *
     * @throws MigrationException
     *
     * @return array
     */
    protected function getIblockPropIdByCode($code, $iblockId)
    {
        $filter = array(
            'CODE'      => $code,
            'IBLOCK_ID' => $iblockId,
        );

        $prop = CIBlockProperty::getList(array('sort' => 'asc', 'name' => 'asc'), $filter)->getNext();
        if (!$prop || !$prop['ID']) {
            throw new MigrationException("Не удалось найти свойство с кодом '{$code}'");
        }

        return $prop['ID'];
    }
}


text:
public class Pathogen : WhiteBloodCell
{
    public override string GetTypeName()
    {
        return "Pathogen";
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DalSic;
using Consultorio.Utilidades;

namespace Consultorio.ConsultaAmbulatoria.ControlMenor
{
    public class ResultadoControlOdontologico
    {
        public MessageStatus Estado = MessageStatus.ok;
        public List<string> mensaje = new List<string>();
        public string profesional = "";
        public Int32? idDiagnostico = null;
        public string observacion = "";
    }

    public partial class ControlOdontologico : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            LoadDiagnosticos();
            SysUsuario oUsuario = new SysUsuario(Session["idUsuario"]);
            if (oUsuario.IsNew) return;
            getMedicos(oUsuario.SysEfector);
        }

        private void LoadDiagnosticos()
        {
            ddlDiagnostico.DataSource = new AprDiagnosticoControlOdontologicoCollection().Load();
            ddlDiagnostico.DataTextField = AprDiagnosticoControlOdontologico.Columns.Nombre;
            ddlDiagnostico.DataValueField = AprDiagnosticoControlOdontologico.Columns.IdDiagnosticoControlOdontologico;
            ddlDiagnostico.DataBind();

            ddlDiagnostico.Items.Insert(0, Utils.getEmptyListItem());
        }

        private void getMedicos(SysEfector oEfector)
        {
            //Obtengo los medicos de acuerdo al hospital del usuario logueado

            ddlProfesional.DataSource = new SysProfesionalCollection().
                Where(SysProfesional.Columns.IdEfector, oEfector.IdEfector).OrderByAsc(SysProfesional.Columns.Apellido).Load();
            ddlProfesional.DataTextField = SysProfesional.Columns.NombreCompleto;
            ddlProfesional.DataValueField = SysProfesional.Columns.NombreCompleto;
            ddlProfesional.DataBind();
        }

        public ResultadoControlOdontologico getDatos()
        {
            ResultadoControlOdontologico oResultado = new ResultadoControlOdontologico();

            if (ddlDiagnostico.SelectedValue.Length > 0)
            {
                oResultado.idDiagnostico = Convert.ToInt32(ddlDiagnostico.SelectedValue);
            }
            else
            {
                oResultado.Estado = MessageStatus.error;
                oResultado.mensaje.Add("Debe seleccionar un diagnostico.");
            }
            oResultado.profesional = ddlProfesional.SelectedValue;
            if (txtObservacion.Text.Length > 0)
            {
                oResultado.observacion = txtObservacion.Text;
            }
            return oResultado;
        }
    }
}


text:
/* Common app functionality */

var app = (function () {
    "use strict";

    var app = {};

    // Common initialization function (to be called from each page)
    app.initialize = function () {
        $('body').append(
            '
' +
                '
' +
                    '

' +
                    '

' +
                    '

' +
                '
' +
            '
');

        $('#notification-message-close').click(function () {
            $('#notification-message').hide();
        });

        // After initialization, expose a common notification function
        app.showNotification = function (header, text) {
            $('#notification-message-header').text(header);
            $('#notification-message-body').text(text);
            $('#notification-message').slideDown('fast');
        };

        // helper to grab the senders email address
        app.getSendersEmailAddress = function(item) {

            var from = "";

            if (item.itemType === Office.MailboxEnums.ItemType.Message) {
                from = Office.cast.item.toMessageRead(item).from;
            } else if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {
                from = Office.cast.item.toAppointmentRead(item).organizer;
            }

            return from;
        }
    };

    return app;
})();


text:
package com.thoughtworks.go.server.presentation.html;

public interface Htmlable {
    HtmlRenderable toHtml();
}


text:
package org.carbon.web.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Note: currently supported {@link String} only
 * @author Shota Oda 2016/10/05.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface PathVariable {
    String value();
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface JSFunctionForAAOptionsVC : AABaseChartVC

@end

NS_ASSUME_NONNULL_END


text:
package net.caprazzi.reusables.threading;

import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public abstract class SingleThreadQueueExecutor<TElement> implements QueueExecutor<TElement> {

    private final Logger Log;

    private final BlockingQueue<ElementListenableFuture<TElement>> queue;

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public SingleThreadQueueExecutor() {
        this(Integer.MAX_VALUE);
    }

    public SingleThreadQueueExecutor(int capacity) {
        queue = new LinkedBlockingQueue<ElementListenableFuture<TElement>>(capacity);
        Log = LoggerFactory.getLogger(this.getClass());
    }

    @Override
    public ListenableConfirmation enqueue(TElement element) {
        Preconditions.checkNotNull(element, "Can't enqueue null elements");

        if (Log.isDebugEnabled())
            Log.debug("Adding element to queue: {}", element);

        ElementListenableFuture future = ElementListenableFuture.create(element);

        try {
            queue.put(future);
        } catch (InterruptedException e) {
            Log.warn("Interrupted Exception while adding an element to internal queue.");
            Thread.currentThread().interrupt();
        }

        return future;
    }

    protected abstract void doProcess(TElement element);

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

    @Override
    public void start() {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                while(!Thread.currentThread().isInterrupted() && !executor.isShutdown()) {
                    try {
                        ElementListenableFuture<TElement> element = queue.take();
                        if (element == null) {

                            if (Log.isTraceEnabled())
                                Log.trace("Element is null, not processing");

                            continue;
                        }

                        if (Log.isTraceEnabled())
                            Log.trace("Processing element {}", element);

                        try {
                            doProcess(element.getElement());
                            element.setResult();
                            Log.trace("Processing complete for element {}", element);

                        }
                        catch (Exception ex) {
                            Log.error("Error while processing element {}: {}", element, ex);
                            element.setException(ex);
                        }
                    } catch (InterruptedException e) {
                        // it's ok, we are shutting down now
                        break;
                    }
                }
            }
        });
    }

    @Override
    public void stop() {
        ExecutorUtils.shutdown(Log, executor, 2, TimeUnit.SECONDS);
    }
}


text:
// Type definitions for @loadable/component 5.13
// Project: https://github.com/smooth-code/loadable-components
// Definitions by: Martynas Kadiša <https://github.com/martynaskadisa>
//                 Daniel Playfair Cal <https://github.com/hedgepigdaniel>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8

import * as React from 'react';

export interface DefaultImportedComponent<Props> {
    default: React.ComponentType<Props>;
}

export type DefaultComponent<Props> = React.ComponentType<Props> | DefaultImportedComponent<Props>;

/**
 * Synchronous function that returns the component from the
 * imported module.
 *
 * The default works with default exports, both CommonJS or ESM
 */
export type ComponentResolver<Props, Module = DefaultComponent<Props>> = (
    module: Module,
    props: Props,
) => React.ComponentType<Props>;

export interface OptionsWithoutResolver<Props> {
    cacheKey?(props: Props): any;
    fallback?: JSX.Element;
    ssr?: boolean;
}

export interface Options<Props, Module = DefaultComponent<Props>> extends OptionsWithoutResolver<Props> {
    resolveComponent?: ComponentResolver<Props, Module>;
}

export interface OptionsWithResolver<Props, Module = DefaultComponent<Props>> extends OptionsWithoutResolver<Props> {
    resolveComponent: ComponentResolver<Props, Module>;
}

export interface LoadableReadyOptions {
    namespace?: string;
}

export interface LoadableComponentMethods<Props> {
    preload(props?: Props): void;
    load(props?: Props): Promise<React.ComponentType<Props>>;
}

export type LoadableComponent<Props> = React.ComponentType<Props & { fallback?: JSX.Element }> &
    LoadableComponentMethods<Props>;

export type LoadableLibrary<Module> = React.ComponentType<{
    fallback?: JSX.Element;
    children?: (module: Module) => React.ReactNode;
    ref?: React.Ref<Module>;
}> &
    Module &
    LoadableComponentMethods<object>;

declare function lib<Props, Module>(
    loadFn: (props: Props) => Promise<Module>,
    options?: OptionsWithoutResolver<Props>,
): LoadableLibrary<Module>;

declare function loadableFunc<Props, Module = DefaultComponent<Props>>(
    loadFn: (props: Props) => Promise<Module>,
    options: OptionsWithResolver<Props, Module>,
): LoadableComponent<Props>;

declare function loadableFunc<Props>(
    loadFn: (props: Props) => Promise<DefaultComponent<Props>>,
    options?: OptionsWithoutResolver<Props>,
): LoadableComponent<Props>;

declare const loadable: typeof loadableFunc & { lib: typeof lib };

export default loadable;

export namespace lazy {
    function lib<Module>(loadFn: (props: object) => Promise<Module>): LoadableLibrary<Module>;
}

export function lazy<Props>(loadFn: (props: Props) => Promise<DefaultComponent<Props>>): LoadableComponent<Props>;

export function loadableReady(done?: () => any, options?: LoadableReadyOptions): Promise<void>;


text:
<!-- nprogress plugin -->
<link rel="stylesheet" type="text/css" href="__CDN__/nprogress/nprogress.css" />
<script type="text/javascript" src="__CDN__/nprogress/nprogress.js"></script>
<!-- scojs plugin -->
<link rel="stylesheet" type="text/css" href="__CDN__/sco1.0.2-8/css/scojs.css" />
<script type="text/javascript" src="__CDN__/sco1.0.2-8/js/sco.modal.js"></script>
<script type="text/javascript" src="__CDN__/sco1.0.2-8/js/sco.confirm.js"></script>
<script type="text/javascript" src="__CDN__/sco1.0.2-8/js/sco.message.js"></script>

<!-- 自定义模块通用样式 -->
<link rel="stylesheet" type="text/css" href="__CSS__/layout.css?v=__APP_VERSION__" />
<script type="text/javascript" src="__CDN__/common/common.js?v=__APP_VERSION__"></script>


text:
package codility

/*
The equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal
to the sum of elements at higher indexes. For example, in a sequence A:
A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0
3 is an equilibrium index, because:
A[0]+A[1]+A[2]=A[4]+A[5]+A[6]
6 is also an equilibrium index, because:
A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0
(The sum of zero elements is zero) 7 is not an equilibrium index - because it is not a valid index
of sequence A. If you still have doubts, here is a precise definition: The integer k is an equilibrium
index of a sequence A[0],A[1]..,A[n-1] if and only if 0<= k and sum(A[0..(k-1)])=sum(A[(k+1)..(n-1)]).
Assume the sum of zero elements is equal to zero.

Write a function
int equi(int A[], int n)
that, given a sequence, returns its equilibrium index (any) or -1 if no equilibrium index exists.
Assume that the sequence may be very long.
 */

object Equilibrium {
  def solution(A: Array[Int]): Int = {
    equi(A, A.size)
  }

  def equi(arr: Array[Int], n: Int): Int = {
    if (n == 0) return -1

    val sum = arr.fold(0)(_+_)

    var sum_left = 0
    arr.foreach { current =>
      val sum_right = sum - sum_left - current
      if (sum_right == sum_left) return arr.indexOf(current)
      sum_left = sum_left + current
    }
    return -1
  }
}


text:
package com.adaptris.interlok.resolver;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

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

public class ExternalResolverTest {

  @Before
  public void setUp() throws Exception {
  }

  @After
  public void tearDown() throws Exception {
  }

  @Test
  public void testResolve() {
    assertNull(ExternalResolver.resolve(null));
    assertNull(ExternalResolver.resolve(null, null));
    assertNotEquals("%env{PATH}", ExternalResolver.resolve("%env{PATH}"));
    assertNotEquals("%sysprop{java.version}", ExternalResolver.resolve("%sysprop{java.version}"));
    assertNotEquals("%sysprop{java.version}", ExternalResolver.resolve("%sysprop{java.version}", null));
    assertEquals("hello", ExternalResolver.resolve("hello"));
    assertEquals("NOT_A_ENVVAR", ExternalResolver.resolve("%env{NOT_A_ENVVAR}"));
  }

  @Test
  public void testResolveWithNullPayload() {
    assertEquals("%payload{NOT_FOUND}", ExternalResolver.resolve("%payload{NOT_FOUND}", null));
    Exception e = new UnresolvableException();
    assertTrue(e instanceof UnresolvableException);
    e = new UnresolvableException("Some message");
    assertEquals("Some message", e.getMessage());
    e = new UnresolvableException(new Exception());
    assertNotNull(e.getCause());
  }
}


text:
package org.springframework.osgi;

import java.util.Dictionary;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.osgi.util.test.AbstractDependencyInjectionSpringContextTests;

public class DictionaryEditorTest extends AbstractDependencyInjectionSpringContextTests {

	private Dictionary dictionary;

	protected void prepareTestInstance() throws Exception {
		setAutowireMode(AbstractDependencyInjectionSpringContextTests.AUTOWIRE_BY_NAME);
		super.prepareTestInstance();
	}

	/**
	 * @param dictionary The dictionary to set.
	 */
	public void setDictionary(Dictionary property) {
		this.dictionary = property;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.springframework.test.AbstractSingleSpringContextTests#customizeBeanFactory(org.springframework.beans.factory
	 * .support.DefaultListableBeanFactory)
	 */
	protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
		// beanFactory.registerCustomEditor(Dictionary.class, new PropertiesEditor());
		beanFactory.registerCustomEditor(Dictionary.class, PropertiesEditor.class);
		super.customizeBeanFactory(beanFactory);
	}

	protected String[] getConfigLocations() {
		return new String[] { "/org/springframework/osgi/dict-editor.xml" };
	}

	public void testInjection() {
		assertNotNull(dictionary);
	}

	public void testInjectedValue() {
		assertSame(applicationContext.getBean("dictionary"), dictionary);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>rss-manager-feature</artifactId>
        <groupId>org.wso2.carbon.storagemgt</groupId>
        <version>4.3.5-SNAPSHOT</version>
	<relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.wso2.carbon.storagemgt</groupId>
    <version>4.3.5-SNAPSHOT</version>
    <artifactId>org.wso2.carbon.rssmanager.feature</artifactId>
    <name>RSS Manager Feature</name>
    <packaging>pom</packaging>
    <url>http://wso2.org</url>
    <description>This Feature Contains The Frond End And Back End Bundles Required For RSS Manager</description>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon.storagemgt</groupId>
            <artifactId>org.wso2.carbon.rssmanager.server.feature</artifactId>
            <type>zip</type>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.storagemgt</groupId>
            <artifactId>org.wso2.carbon.rssmanager.ui.feature</artifactId>
            <type>zip</type>
        </dependency>
	<dependency>
            <groupId>org.wso2.carbon.storagemgt</groupId>
            <artifactId>org.wso2.carbon.rssmanager.data.mgt.feature</artifactId>
            <type>zip</type>
        </dependency>
    </dependencies>

     <build>
      <plugins>
            <plugin>
                <groupId>org.wso2.maven</groupId>
                <artifactId>carbon-p2-plugin</artifactId>
                <version>${carbon.p2.plugin.version}</version>
                <executions>
                    <execution>
                        <id>p2-feature-generation</id>
                        <phase>package</phase>
                        <goals>
                            <goal>p2-feature-gen</goal>
                        </goals>
                        <configuration>
                            <id>org.wso2.carbon.rssmanager</id>
                            <propertiesFile>../../etc/feature.properties</propertiesFile>
                            <adviceFile>
                                <properties>
                                    <propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
                                </properties>
                            </adviceFile>
                            <importFeatures>
                               <importFeatureDef>org.wso2.carbon.transaction.manager:${carbon.commons.version}</importFeatureDef>
			    </importFeatures>
                            <includedFeatures>
                                <includedFeatureDef>org.wso2.carbon.storagemgt:org.wso2.carbon.rssmanager.server.feature:${carbon.storage.management.version}</includedFeatureDef>
                                <includedFeatureDef>org.wso2.carbon.storagemgt:org.wso2.carbon.rssmanager.ui.feature:${carbon.storage.management.version}</includedFeatureDef>
				<includedFeatureDef>org.wso2.carbon.storagemgt:org.wso2.carbon.rssmanager.data.mgt.feature:${carbon.storage.management.version}</includedFeatureDef>
                            </includedFeatures>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Datastructure.Rete;

import Entity.Atom;
import Entity.Constant;
import Entity.FuncTerm;
import Entity.Instance;
import Entity.Variable;
import Interfaces.Term;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author Gerald Weidinger 0526105
 *
 * This is a static helper class that provides methods for unification
 *
 */
public class Unifyer {

    /**
     *
     * unifies an Atom with the given variable assignment
     *
     * @param a the atom you to unify
     * @param variableAssignment the variable assignment you want the atom to unify with
     * @param varPos a HashMap mapping Variables of the atom to the position of the variable assignment instance
     * @return the instance resulting from this unification
     */
    public static Instance unifyAtom(Atom a, Instance variableAssignment,HashMap<Variable,Integer> varPositionMapping){
        Term[] retTerms = new Term[a.getArity()];
        for(int i = 0; i < a.getArity();i++){
            //We go through all the terms of the atom
            Term t = a.getTerms()[i];
            if(t.getClass().equals(Variable.class)){
                //if the actual term is a variable we set the corresponding position of the instance we want to return to the the value that is within the variabel assignment at the position
                //of that variable within the mapping
                /*System.err.println("VARAS: " + variableAssignment);
                System.err.println("Atom: " + a);
                System.err.println("Variable: " + t);
                System.err.println("Mapping: " + varPositionMapping);
                System.err.println("WARPOS: " + varPositionMapping.get((Variable)t));*/
                retTerms[i] = variableAssignment.get(varPositionMapping.get((Variable)t));
            }else{
                if (t.getClass().equals(Constant.class)){
                    //if the actual term is a constant we simply put that constant into our instance we want to return.
                    retTerms[i] = t;
                }else{
                    //if the actual term is a functerm we have to unify that functerm and put that result at the corresponding position of our insatnce to return
                    retTerms[i] = unifyFuncTerm((FuncTerm)t, variableAssignment,varPositionMapping);
                }
            }
        }
        Instance ret = Instance.getInstance(retTerms);
        return ret;
    }

    /**
     *
     * unifies a function term with the given variable assignment
     *
     * @param f the function term you want to unify
     * @param variableAssignment the variable assignment you want the atom to unify with
     * @param varPos a HashMap mapping Variables of the atom to the position of the variable assignment instance
     * @return the unified function term resulting from this unification
     */
    private static FuncTerm unifyFuncTerm(FuncTerm f, Instance variableAssignment,HashMap<Variable,Integer> varPositionMapping){
        ArrayList<Term> fchildren = new ArrayList<Term>();
        for(int i = 0; i < f.getChildren().size();i++){
            //we go through all the children(=terms) of the given function term
            Term t = f.getChildren().get(i);
            if(t.getClass().equals(Variable.class)){
                //if the actual term is a variable we add the corresponding constant, defined by the mapping and the variable assignment, to the children
                //of the function term we want to return.
                fchildren.add(variableAssignment.get(varPositionMapping.get((Variable)t)));
            }else{
                if (t.getClass().equals(Constant.class)){
                    //if the actual term is a constant we simply add that constant to the children of the functerm we will return
                    fchildren.add(t);
                }else{
                    //if the actual term again is a function term we have to unify it as well and then add him to the actual fucntion terms children
                    fchildren.add(unifyFuncTerm((FuncTerm)t, variableAssignment, varPositionMapping));
                }
            }
        }
        FuncTerm ret = FuncTerm.getFuncTerm(f.getName(), fchildren);
        return ret;
    }

}


text:
---
title: useEffect Hook
---

[React.js docs for useEffect](https://reactjs.org/docs/hooks-reference.html#useeffect)

Here's a simple example of how to use React's `useState` with `useEffects`.

### Cleaning up an Effect

```reason
[@react.component]
let make = () => {
    React.useEffect0(() => {
        let id = subscription.subscribe();
        /* clean up the subscription */
        Some(() => subscription.unsubscribe(id));
    });
}
```

### Conditionally Firing an Effect

With this, the subscription will only be recreated when `~source` changes

```reason
[@react.component]
let make = (~source) => {
    React.useEffect1(() => {
        let id = subscription.subscribe();
        /* clean up the subscription */
        Some(() => subscription.unsubscribe(id));
    }, [|source|]);
}
```


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="ch.hesso.master.sweetcity.activity.tag.TagSelectionActivity">

    <Button
        android:id="@+id/btn_submit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/submit" />

    <ListView
        android:id="@+id/lv_tag"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/btn_submit"
        android:layout_alignParentTop="true" />

</RelativeLayout>


text:
package org.ebayopensource.fido.uaf.ri.client;

import org.apache.commons.codec.binary.Base64;
import org.ebayopensource.fido.uaf.msg.AuthenticationRequest;
import org.ebayopensource.fido.uaf.msg.AuthenticationResponse;
import org.ebayopensource.fido.uaf.msg.AuthenticatorSignAssertion;
import org.ebayopensource.fido.uaf.msg.FinalChallengeParams;
import org.ebayopensource.fido.uaf.msg.OperationHeader;

import com.google.gson.Gson;

public class AuthenticationRequestProcessing {

	public AuthenticationResponse processRequest(AuthenticationRequest request) {
		AuthenticationResponse response = new AuthenticationResponse();
		Gson gson = new Gson();
		setAppId(request, response);
		response.header = new OperationHeader();
		response.header.serverData = request.header.serverData;
		response.header.op = request.header.op;
		response.header.upv = request.header.upv;

		FinalChallengeParams fcParams = new FinalChallengeParams();
		fcParams.appID = Constants.APP_ID;
		fcParams.facetID = Constants.FACET_ID;
		fcParams.challenge = request.challenge;
		response.fcParams = Base64.encodeBase64URLSafeString(gson.toJson(
				fcParams).getBytes());
		setAssertions(response);
		return response;
	}

	private void setAssertions(AuthenticationResponse response) {
		AuthenticatorSignAssertion assertion = new AuthenticatorSignAssertion();
		assertion.assertionScheme = "UAFV1TLV";
		// Example from specs doc
		assertion.assertion = "Aj7WAAQ-jgALLgkAQUJDRCNBQkNEDi4FAAABAQEADy4gAHwyJAEX8t1b2wOxbaKOC5ZL7ACqbLo_TtiQfK3DzDsHCi4gAFwCUz-dOuafXKXJLbkUrIzjAU6oDbP8B9iLQRmCf58fEC4AAAkuIABkwI-f3bIe_Uin6IKIFvqLgAOrpk6_nr0oVAK9hIl82A0uBAACAAAABi5AADwDOcBvPslX2bRNy4SvFhAwhEAoBSGUitgMUNChgUSMxss3K3ukekq1paG7Fv1v5mBmDCZVPt2NCTnjUxrjTp4";
		AuthenticatorSignAssertion[] assertions = new AuthenticatorSignAssertion[1];
		assertions[0] = assertion;
		response.assertions = assertions;
	}

	private void setAppId(AuthenticationRequest request,
			AuthenticationResponse response) {
		if (request.header.appID == null && request.header.appID.isEmpty()) {
			response.header.appID = Constants.APP_ID;
		} else {
			setAppID(request, response);
		}
	}

	private void setAppID(AuthenticationRequest request,
			AuthenticationResponse response) {
		// TODO Auto-generated method stub

	}
}


text:
package com.xoozi.apiguides.gl.glutil;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import static android.opengl.GLES30.GL_TEXTURE_2D;
import static android.opengl.GLES30.GL_TEXTURE_MIN_FILTER;
import static android.opengl.GLES30.GL_TEXTURE_MAG_FILTER;
import static android.opengl.GLES30.GL_LINEAR_MIPMAP_LINEAR;
import static android.opengl.GLES30.GL_LINEAR;
import static android.opengl.GLES30.glGenTextures;
import static android.opengl.GLES30.glDeleteTextures;
import static android.opengl.GLES30.glBindTexture;
import static android.opengl.GLES30.glTexParameteri;
import static android.opengl.GLES30.glGenerateMipmap;
import static android.opengl.GLUtils.texImage2D;

public class TextureHelper{

    public static int loadTexture(Context context, int resourceId){
        int ret = 0;
        do{
            final int[] textureObjectIds = new int[1];
            glGenTextures(1, textureObjectIds, 0);

            if(0 == textureObjectIds[0]){
                break;
            }

            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inScaled = false;
            final Bitmap bitmap = BitmapFactory.decodeResource(
                    context.getResources(), resourceId, options);
            if(null == bitmap){
                glDeleteTextures(1, textureObjectIds, 0);
                break;
            }

            glBindTexture(GL_TEXTURE_2D, textureObjectIds[0]);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

            texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);
            bitmap.recycle();

            glGenerateMipmap(GL_TEXTURE_2D);

            glBindTexture(GL_TEXTURE_2D, 0);

            ret = textureObjectIds[0];
        }while(false);

        return ret;
    }
}


text:
    User Menu

Action

Another action

Something else here

Separated link

One more separated link


text:
import assert from 'assert';
import fetchResourcesForProducts from '../src/fetch-resources-for-products';

suite('fetch-resources-for-product-test', () => {
  test('it returns an empty array when no product is found', () => {
    return fetchResourcesForProducts(null).then((result) => {

      assert.deepStrictEqual(result, []);
    });
  });

  test('it fetches all pages of images and for a single product', () => {
    const imagesArray = ['images'];
    const variantsArray = ['variants'];
    const fixture = {
      images: imagesArray,
      variants: variantsArray,
      attrs: {
        images: imagesArray,
        variants: variantsArray
      }
    };
    let fetchAllPagesCounter = 0;
    const itemsList = [];

    const client = {
      fetchAllPages(items) {
        fetchAllPagesCounter++;
        itemsList.push(items);

        return Promise.resolve(['reassigned-array']);
      }
    };

    return fetchResourcesForProducts(fixture, client).then(() => {
      assert.equal(fetchAllPagesCounter, 2);
      assert.deepEqual(fixture.attrs.images, ['reassigned-array']);
      assert.deepEqual(fixture.attrs.variants, ['reassigned-array']);
    });
  });

  test('it fetches all pages of images and for an array of products', () => {
    const imagesArray = ['images'];
    const variantsArray = ['variants'];
    const fixture = {
      images: imagesArray,
      variants: variantsArray,
      attrs: {
        images: imagesArray,
        variants: variantsArray
      }
    };
    let fetchAllPagesCounter = 0;
    const itemsList = [];

    const client = {
      fetchAllPages(items) {
        fetchAllPagesCounter++;
        itemsList.push(items);

        return Promise.resolve(['reassigned-array']);
      }
    };

    return fetchResourcesForProducts([fixture], client).then(() => {
      assert.equal(fetchAllPagesCounter, 2);
      assert.deepEqual(fixture.attrs.images, ['reassigned-array']);
      assert.deepEqual(fixture.attrs.variants, ['reassigned-array']);
    });
  });
});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Symplocos parvifolia var. subcuneata Herzog

### Remarks
null


text:
'use strict';

//Setting up route
angular.module('kinds').config(['$stateProvider',
	function($stateProvider) {
		// Kinds state routing
		$stateProvider.
		state('listKinds', {
			url: '/kinds',
			templateUrl: 'modules/kinds/views/list-kinds.client.view.html'
		}).
		state('createKind', {
			url: '/kinds/create',
			templateUrl: 'modules/kinds/views/create-kind.client.view.html'
		}).
		state('viewKind', {
			url: '/kinds/:kindId',
			templateUrl: 'modules/kinds/views/view-kind.client.view.html'
		}).
		state('editKind', {
			url: '/kinds/:kindId/edit',
			templateUrl: 'modules/kinds/views/edit-kind.client.view.html'
		});
	}
]);


text:
namespace OpenApi.Generator.UnitTests
{
    using System.IO;
    using Crest.OpenApi.Generator;
    using FluentAssertions;
    using Xunit;

    public class JsonWriterTests
    {
        private readonly FakeJsonWriter writer = new FakeJsonWriter();

        public sealed class Write : JsonWriterTests
        {
            [Fact]
            public void ShouldEscapeTheData()
            {
                this.writer.Write(@"\");

                this.writer.Output.Should().Be(@"\\");
            }

            [Fact]
            public void WriteShouldWriteTheCharacter()
            {
                this.writer.Write('"');

                this.writer.Output.Should().Be("\"");
            }
        }

        public sealed class WriteRaw : JsonWriterTests
        {
            [Fact]
            public void ShouldNotEscapeTheData()
            {
                this.writer.WriteRaw(@"\");

                this.writer.Output.Should().Be(@"\");
            }
        }

        public sealed class WriteString : JsonWriterTests
        {
            [Fact]
            public void ShouldEscapeTheData()
            {
                this.writer.WriteString(@"\");

                this.writer.Output.Should().Be(@"""\\""");
            }
        }

        public sealed class WriteValue : JsonWriterTests
        {
            [Fact]
            public void ShouldWriteBooleanValues()
            {
                this.writer.WriteValue(false);
                this.writer.Write(' ');
                this.writer.WriteValue(true);

                this.writer.Output.Should().Be("false true");
            }

            [Fact]
            public void ShouldWriteNullValues()
            {
                this.writer.WriteValue(null);

                this.writer.Output.Should().Be("null");
            }

            [Fact]
            public void ShouldWriteNumbers()
            {
                this.writer.WriteValue(123);

                this.writer.Output.Should().Be("123");
            }

            [Fact]
            public void ShouldWriteStrings()
            {
                this.writer.WriteValue(@"test\");

                this.writer.Output.Should().Be(@"""test\\""");
            }
        }

        private class FakeJsonWriter : JsonWriter
        {
            private readonly StringWriter writer;

            public FakeJsonWriter()
                : this(new StringWriter())
            {
            }

            private FakeJsonWriter(StringWriter writer)
                : base(writer)
            {
                this.writer = writer;
            }

            internal string Output => this.writer.ToString();

            internal new void Write(char value)
            {
                base.Write(value);
            }

            internal new void Write(string value)
            {
                base.Write(value);
            }

            internal new void WriteRaw(string value)
            {
                base.WriteRaw(value);
            }

            internal new void WriteString(string value)
            {
                base.WriteString(value);
            }

            internal new void WriteValue(object value)
            {
                base.WriteValue(value);
            }
        }
    }
}


text:
import {
  ancestorsOf,
  catchError,
  classOf,
  deepClone,
  deepMerge,
  getClassOrSymbol,
  isClass,
  isFunction,
  isInheritedFrom,
  Metadata,
  nameOf,
  prototypeOf,
  Store
} from "@tsed/core";
import {DI_PARAM_OPTIONS, INJECTABLE_PROP} from "../constants";
import {Configuration} from "../decorators/configuration";
import {Injectable} from "../decorators/injectable";
import {DIContext, InjectablePropertyType, ProviderScope} from "../domain";
import {Container} from "../domain/Container";
import {LocalsContainer} from "../domain/LocalsContainer";
import {Provider} from "../domain/Provider";
import {InjectionError} from "../errors/InjectionError";
import {UndefinedTokenError} from "../errors/UndefinedTokenError";
import {
  DILogger,
  InjectableProperties,
  InjectablePropertyOptions,
  InjectablePropertyValue,
  InterceptorContext,
  InterceptorMethods,
  InvokeOptions,
  IProvider,
  TokenProvider
} from "../interfaces";
import {GlobalProviders} from "../registries/GlobalProviders";
import {createContainer} from "../utils/createContainer";
import {DIConfiguration} from "./DIConfiguration";
import {ResolvedInvokeOptions} from "../interfaces/ResolvedInvokeOptions";

/**
 * This service contain all services collected by `@Service` or services declared manually with `InjectorService.factory()` or `InjectorService.service()`.
 *
 * ### Example:
 *
 * ```typescript
 * import {InjectorService} from "@tsed/di";
 *
 * // Import the services (all services are decorated with @Service()";
 * import MyService1 from "./services/service1";
 * import MyService2 from "./services/service2";
 * import MyService3 from "./services/service3";
 *
 * // When all services is imported you can load InjectorService.
 * const injector = new InjectorService()
 *
 * await injector.load();
 *
 * const myService1 = injector.get<MyService1>(MyServcice1);
 * ```
 */
@Injectable({
  scope: ProviderScope.SINGLETON,
  global: true
})
export class InjectorService extends Container {
  public settings: TsED.Configuration & DIConfiguration = new DIConfiguration() as any;
  public logger: DILogger = console;
  private resolvedConfiguration: boolean = false;
  #cache = new LocalsContainer();

  constructor() {
    super();
    this.#cache.set(InjectorService, this);
  }

  get resolvers() {
    return this.settings.resolvers!;
  }

  get scopes() {
    return this.settings.scopes || {};
  }

  /**
   * Retrieve default scope for a given provider.
   * @param provider
   */
  public scopeOf(provider: Provider) {
    return provider.scope || this.scopes[provider.type] || ProviderScope.SINGLETON;
  }

  /**
   * Clone a provider from GlobalProviders and the given token. forkProvider method build automatically the provider if the instance parameter ins't given.
   * @param token
   * @param settings
   * @deprecated
   */
  public forkProvider(token: TokenProvider, settings: Partial<IProvider<any>> = {}): Provider {
    if (!this.hasProvider(token)) {
      this.addProvider(token);
    }

    const provider = this.getProvider(token)!;

    Object.assign(provider, settings);

    this.#cache.set(token, this.invoke(token));

    return provider;
  }

  /**
   * Return a list of instance build by the injector.
   */
  public toArray(): any[] {
    return this.#cache.toArray();
  }

  /**
   * Get a service or factory already constructed from his symbol or class.
   *
   * #### Example
   *
   * ```typescript
   * import {InjectorService} from "@tsed/di";
   * import MyService from "./services";
   *
   * class OtherService {
   *      constructor(injectorService: InjectorService) {
   *          const myService = injectorService.get<MyService>(MyService);
   *      }
   * }
   * ```
   *
   * @param token The class or symbol registered in InjectorService.
   * @param options
   * @returns {boolean}
   */
  get<T = any>(token: TokenProvider, options: any = {}): T | undefined {
    const instance = this.getInstance(token);

    if (instance !== undefined) {
      return instance;
    }

    if (!this.hasProvider(token)) {
      for (const resolver of this.resolvers) {
        const result = resolver.get(token, options);

        if (result !== undefined) {
          return result;
        }
      }
    }
  }

  /**
   * The has() method returns a boolean indicating whether an element with the specified key exists or not.
   * @returns {boolean}
   * @param token
   */
  has(token: TokenProvider): boolean {
    return this.#cache.get(token) !== undefined;
  }

  /**
   * Invoke the class and inject all services that required by the class constructor.
   *
   * #### Example
   *
   * ```typescript
   * import {InjectorService} from "@tsed/di";
   * import MyService from "./services";
   *
   * class OtherService {
   *     constructor(injectorService: InjectorService) {
   *          const myService = injectorService.invoke<MyService>(MyService);
   *      }
   *  }
   * ```
   *
   * @param token The injectable class to invoke. Class parameters are injected according constructor signature.
   * @param locals  Optional object. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
   * @param options
   * @returns {T} The class constructed.
   */
  public invoke<T>(
    token: TokenProvider,
    locals: Map<TokenProvider, any> = new LocalsContainer(),
    options: Partial<InvokeOptions<T>> = {}
  ): T {
    const provider = this.ensureProvider(token);
    let instance: any;

    !locals.has(Configuration) && locals.set(Configuration, this.settings);

    if (locals.has(token)) {
      return locals.get(token);
    }

    if (token === DI_PARAM_OPTIONS) {
      return {} as T;
    }

    if (!provider || options.rebuild) {
      instance = this.resolve(token, locals, options);

      if (this.hasProvider(token)) {
        this.#cache.set(token, instance);
      }

      return instance;
    }

    switch (this.scopeOf(provider)) {
      case ProviderScope.SINGLETON:
        if (!this.has(token)) {
          this.#cache.set(token, this.resolve(token, locals, options));

          if (provider.isAsync()) {
            this.#cache.get(token).then((instance: any) => {
              this.#cache.set(token, instance);
            });
          }
        }

        instance = this.get<T>(token)!;
        break;

      case ProviderScope.REQUEST:
        instance = this.resolve(token, locals, options);
        locals.set(token, instance);
        break;

      case ProviderScope.INSTANCE:
        instance = this.resolve(provider.provide, locals, options);
        break;
    }

    return instance;
  }

  /**
   * Build only providers which are asynchronous.
   */
  async loadAsync(locals: LocalsContainer = new LocalsContainer()) {
    for (const [, provider] of this) {
      if (!locals.has(provider.token)) {
        if (provider.isAsync()) {
          await this.invoke(provider.token, locals);
        }

        const instance = this.#cache.get(provider.token);
        if (instance !== undefined) {
          locals.set(provider.token, instance);
        }
      }
    }

    return locals;
  }

  loadSync(locals: LocalsContainer<any> = new LocalsContainer()) {
    for (const [, provider] of this) {
      if (!locals.has(provider.token) && this.scopeOf(provider) === ProviderScope.SINGLETON) {
        this.invoke(provider.token, locals);
      }

      const instance = this.#cache.get(provider.token);
      if (instance !== undefined) {
        locals.set(provider.token, instance);
      }
    }

    return locals;
  }

  /**
   * Boostrap injector from container and resolve configuration.
   *
   * @param container
   */
  bootstrap(container: Container = createContainer()) {
    // Clone all providers in the container
    this.addProviders(container);

    // Resolve all configuration
    this.resolveConfiguration();

    return this;
  }

  /**
   * Build all providers from given container (or GlobalProviders) and emit `$onInit` event.
   *
   * @param container
   * @param rootModule
   */
  async load(container: Container = createContainer(), rootModule?: TokenProvider): Promise<LocalsContainer<any>> {
    this.bootstrap(container);

    // build async and sync provider
    let locals = await this.loadAsync();

    if (rootModule) {
      await this.invoke(rootModule);
    }

    // load sync provider
    locals = this.loadSync(locals);

    await locals.emit("$beforeInit");
    await locals.emit("$onInit");

    return locals;
  }

  /**
   * Load all configurations registered on providers
   */
  resolveConfiguration() {
    if (this.resolvedConfiguration) {
      return;
    }
    const mergedConfiguration = new Map();

    super.forEach((provider) => {
      if (provider.configuration && provider.type !== "server:module") {
        Object.entries(provider.configuration).forEach(([key, value]) => {
          value = mergedConfiguration.has(key) ? deepMerge(mergedConfiguration.get(key), value) : deepClone(value);
          mergedConfiguration.set(key, value);
        });
      }
      if (provider.resolvers) {
        this.resolvers.push(...provider.resolvers);
      }
    });

    mergedConfiguration.forEach((value, key) => {
      this.settings[key] = deepMerge(value, this.settings[key]);
    });

    this.settings.build();

    this.resolvedConfiguration = true;
  }

  /**
   *
   * @param instance
   * @param locals
   * @param options
   */
  public bindInjectableProperties(instance: any, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions>) {
    const properties: InjectableProperties = ancestorsOf(classOf(instance)).reduce((properties: any, target: any) => {
      const store = Store.from(target);

      return {
        ...properties,
        ...(store.get(INJECTABLE_PROP) || {})
      };
    }, {});

    Object.values(properties).forEach((definition) => {
      switch (definition.bindingType) {
        case InjectablePropertyType.METHOD:
          this.bindMethod(instance, definition);
          break;
        case InjectablePropertyType.PROPERTY:
          this.bindProperty(instance, definition, locals, options);
          break;
        case InjectablePropertyType.CONSTANT:
          this.bindConstant(instance, definition);
          break;
        case InjectablePropertyType.VALUE:
          this.bindValue(instance, definition);
          break;
        case InjectablePropertyType.INTERCEPTOR:
          this.bindInterceptor(instance, definition);
          break;
      }
    });
  }

  /**
   *
   * @param instance
   * @param {string} propertyKey
   */
  public bindMethod(instance: any, {propertyKey}: InjectablePropertyOptions) {
    const target = classOf(instance);
    const originalMethod = instance[propertyKey];
    const deps = Metadata.getParamTypes(prototypeOf(target), propertyKey);

    instance[propertyKey] = () => {
      const services = deps.map((dependency: any) => this.get(dependency));

      return originalMethod.call(instance, ...services);
    };
  }

  /**
   * Create an injectable property.
   *
   * @param instance
   * @param {string} propertyKey
   * @param {any} useType
   * @param resolver
   * @param options
   * @param locals
   * @param invokeOptions
   */
  public bindProperty(
    instance: any,
    {propertyKey, resolver, options = {}}: InjectablePropertyOptions,
    locals: Map<TokenProvider, any>,
    invokeOptions: Partial<InvokeOptions>
  ) {
    let get: () => any;

    get = resolver(this, locals, {...invokeOptions, options});

    catchError(() =>
      Object.defineProperty(instance, propertyKey, {
        get
      })
    );
  }

  /**
   *
   * @param instance
   * @param {string} propertyKey
   * @param {any} useType
   */
  public bindValue(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {
    const descriptor = {
      get: () => this.settings.get(expression) || defaultValue,
      set: (value: any) => this.settings.set(expression, value),
      enumerable: true,
      configurable: true
    };

    catchError(() => Object.defineProperty(instance, propertyKey, descriptor));
  }

  /**
   *
   * @param instance
   * @param {string} propertyKey
   * @param {any} useType
   */
  public bindConstant(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {
    let bean: any;

    const get = () => {
      if (bean !== undefined) {
        return bean;
      }

      const value = this.settings.get(expression, defaultValue);
      bean = Object.freeze(deepClone(value));

      return bean;
    };

    const descriptor = {
      get,
      enumerable: true,
      configurable: true
    };

    catchError(() => Object.defineProperty(instance, propertyKey, descriptor));
  }

  /**
   *
   * @param instance
   * @param propertyKey
   * @param useType
   * @param options
   */
  public bindInterceptor(instance: any, {propertyKey, useType, options}: InjectablePropertyOptions) {
    const target = classOf(instance);
    const originalMethod = instance[propertyKey];

    instance[propertyKey] = (...args: any[]) => {
      const next = (err?: Error) => {
        if (!err) {
          return originalMethod.apply(instance, args);
        }

        throw err;
      };

      const context: InterceptorContext<any> = {
        target,
        propertyKey,
        args,
        options,
        next
      };

      const interceptor = this.get<InterceptorMethods>(useType)!;

      return interceptor.intercept!(
        {
          ...context,
          options
        },
        next
      );
    };
  }

  /**
   * Allow handler hack for AsyncHookContext plugin.
   * @param ctx
   * @param cb
   * @protected
   */
  runInContext(ctx: DIContext, cb: any) {
    return cb();
  }

  async lazyInvoke<T = any>(token: TokenProvider) {
    let instance = this.getInstance(token);

    if (!instance) {
      instance = await this.invoke<T>(token);

      if (isFunction(instance?.$onInit)) {
        await instance.$onInit();
      }
    }

    return instance;
  }

  /**
   * Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).
   * @param eventName The event name to emit at all services.
   * @param args List of the parameters to give to each services.
   * @returns {Promise<any[]>} A list of promises.
   */
  public async emit(eventName: string, ...args: any[]) {
    return this.#cache.emit(eventName, ...args);
  }

  /**
   * @param eventName
   * @param value
   * @param args
   */
  public alter<T = any>(eventName: string, value: any, ...args: any[]): T {
    return this.#cache.alter(eventName, value, ...args);
  }

  /**
   * @param eventName
   * @param value
   * @param args
   */
  public async alterAsync<T = any>(eventName: string, value: any, ...args: any[]): Promise<T> {
    return this.#cache.alterAsync(eventName, value, ...args);
  }

  async destroy() {
    await this.#cache.destroy();
  }

  protected ensureProvider(token: TokenProvider): Provider | undefined {
    if (!this.hasProvider(token) && GlobalProviders.has(token)) {
      this.addProvider(token);
    }

    return this.getProvider(token)!;
  }

  protected getInstance(token: any) {
    return this.#cache.get(getClassOrSymbol(token));
  }

  /**
   * Invoke a class method and inject service.
   *
   * #### IInjectableMethod options
   *
   * * **target**: Optional. The class instance.
   * * **methodName**: `string` Optional. The method name.
   * * **designParamTypes**: `any[]` Optional. List of injectable types.
   * * **locals**: `Map<Function, any>` Optional. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
   *
   * #### Example
   *
   * @param target
   * @param locals
   * @param options
   * @private
   */
  private resolve<T>(target: TokenProvider, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions<T>> = {}): Promise<T> {
    const resolvedOpts = this.mapInvokeOptions(target, locals, options);
    const {token, deps, construct, imports, provider} = resolvedOpts;

    if (provider) {
      GlobalProviders.onInvoke(provider, locals, {...resolvedOpts, injector: this});
    }

    let instance: any;
    let currentDependency: any = false;

    try {
      const invokeDependency = (parent?: any) => (token: any, index: number): any => {
        currentDependency = {token, index, deps};

        if (token !== DI_PARAM_OPTIONS) {
          const options = provider?.store?.get(`${DI_PARAM_OPTIONS}:${index}`);

          locals.set(DI_PARAM_OPTIONS, options || {});
        }

        return isInheritedFrom(token, Provider, 1) ? provider : this.invoke(token, locals, {parent});
      };

      // Invoke manually imported providers
      imports.forEach(invokeDependency());

      // Inject dependencies
      const services = deps.map(invokeDependency(token));

      currentDependency = false;

      instance = construct(services);
    } catch (error) {
      InjectionError.throwInjectorError(token, currentDependency, error);
    }

    if (instance === undefined) {
      throw new InjectionError(
        token,
        `Unable to create new instance from undefined value. Check your provider declaration for ${nameOf(token)}`
      );
    }

    if (instance && isClass(classOf(instance))) {
      this.bindInjectableProperties(instance, locals, options);
    }

    return instance;
  }

  /**
   * Create options to invoke a provider or class.
   * @param token
   * @param locals
   * @param options
   */
  private mapInvokeOptions(token: TokenProvider, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions>): ResolvedInvokeOptions {
    let imports: TokenProvider[] | undefined = options.imports;
    let deps: TokenProvider[] | undefined = options.deps;
    let scope = options.scope;
    let construct;

    if (!token) {
      throw new UndefinedTokenError();
    }

    let provider: Provider;

    if (!this.hasProvider(token)) {
      provider = new Provider(token);

      this.resolvers.forEach((resolver) => {
        const result = resolver.get(token, locals.get(DI_PARAM_OPTIONS));

        if (result !== undefined) {
          provider.useFactory = () => result;
        }
      });
    } else {
      provider = this.getProvider(token)!;
    }

    scope = scope || this.scopeOf(provider);
    deps = deps || provider.deps;
    imports = imports || provider.imports;

    if (provider.useValue !== undefined) {
      construct = () => (isFunction(provider.useValue) ? provider.useValue() : provider.useValue);
    } else if (provider.useFactory) {
      construct = (deps: TokenProvider[]) => provider.useFactory(...deps);
    } else if (provider.useAsyncFactory) {
      construct = async (deps: TokenProvider[]) => {
        deps = await Promise.all(deps);
        return provider.useAsyncFactory(...deps);
      };
    } else {
      // useClass
      deps = deps || Metadata.getParamTypes(provider.useClass);
      construct = (deps: TokenProvider[]) => new provider.useClass(...deps);
    }

    return {
      token,
      scope: scope || Store.from(token).get("scope") || ProviderScope.SINGLETON,
      deps: deps! || [],
      imports: imports || [],
      construct,
      provider
    };
  }
}


text:
var socket = io();
var questionsArray = [];

socket.on("generate tree", initTree);
socket.on("questionDeleted", questionDeleted);

function initQuestionTree(){
	socket.emit('getQuestions');

	$('#jstree').on("changed.jstree", function (e, data) {
		makeSelection(data);
	});
}

function deleteQuestion(){
	var questionToDelete = $("#parentID").val();
	if(questionToDelete == ""){
		alert("select a question to delete");
	}else{

		var txt;
		var r = confirm("Are you sure you want to delete this question?");
		if (r == true) {
			socket.emit("deleteQuestion", {id: questionToDelete});
		}
	}

}

function questionDeleted(data){
	if(data.success == false){
		alert("Please select a question with no sub-questions");
	}else if(data.success == true){
		alert("Question deleted");
	}
}

function makeSelection(data){
	console.log(data.selected[0]);
	$("#parentID").val(data.selected[0]);
}

function submitQuestion(){
	var parent = $("#parentID").val();
	var id = $("#key").val() + $("#qNumber").val();
	var text = $("#text").val();
	var answer = $("#answer").val();

	socket.emit("submitQuestion", {parent: parent, id: id, text: text, answer: answer});

	alert("question submitted");
	//init();
}

function initTree(data){
	for(var i = 0; i < data.array.length; i++){
		data.array[i].text = "(" + data.array[i].id + ") " + "(" + data.array[i].answer + ") " + data.array[i].text;
	}
	$('#jstree').jstree('destroy');
	$('#jstree').jstree({
		'core': {
			'check_callback' : true,
			'data': data.array
		}
	});
	$('#jstree').jstree('refresh');

}

function openAll(){
	var tree = $("#jstree");
    tree.bind("loaded.jstree", function (event, data) {
        tree.jstree("open_all");
    });
}

initQuestionTree();


text:
package com.norsez.dsp.block.filter;

import com.norsez.dsp.block.DSPBlock;

public class Delay
        extends DSPBlock {
    private final static int LENGTH = 44100 * 2;
    private double[] buffer;
    private int length;
    private int inPoint, outPoint;
    private double delayTime;

    public Delay() {

        buffer = new double[LENGTH];
    }

    public Delay(int buflength) {
        buffer = new double[buflength];
        length = buflength;
        clear();

        lastValue = 0;

        setDelay(1);

        inPoint = 0;
    }

    public void clear() {
        int i;
        for (i = 0; i < length; i++) {
            buffer[i] = 0;
        }
    }

    public double getLastValue() {
        return lastValue;
    }

    public double getDelayTime() {
        return delayTime;
    }

    public int getLength() {
        return length;
    }

    public void setDelay(double d) {
        if (d > 1) {
            d = 1;
        }
        if (d < 0) {
            d = 0;
        }
        delayTime = d;
        int lag = (int) (d * (length >> 1));
        outPoint = inPoint - lag;

        while (outPoint < 0) {
            outPoint += length;
        }
    }

    public double tick() {
        throw new java.lang.UnsupportedOperationException("tick () doesn't work in Delay, use tick (double) instead.");
    }

    public double tick(double in) {
        buffer[inPoint++] = in;

        // Check for end condition
        if (inPoint == length) {
            inPoint -= length;
            // Read out next value
        }
        lastValue = buffer[outPoint++];

        if (outPoint >= length) {
            outPoint -= length;

        }

        return lastValue;
    }
}


text:
'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license']
});

module.exports = function (options) {

  gulp.task('html', ['inject'], function () {

    var htmlFilter = $.filter('**/*.html');
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');
    var assets;

    return gulp.src(options.tmp +  '/'+options.namespace + '/**/*.html')
      .pipe(assets = $.useref.assets({searchPath: [options.tmp, options.src]}))
      .pipe($.rev())
      .pipe(jsFilter)
      .pipe($.ngAnnotate())
      .pipe($.uglify({preserveComments: $.uglifySaveLicense})).on('error', options.errorHandler('Uglify'))
      .pipe(jsFilter.restore())
      .pipe(cssFilter)
      .pipe($.csso())
      .pipe(cssFilter.restore())
      .pipe(assets.restore())
      .pipe($.useref())
      .pipe($.revReplace())
      //.pipe(htmlFilter)
      //.pipe($.minifyHtml({
      //  empty: true,
      //  spare: true,
      //  quotes: true,
      //  conditionals: true
      //}))
      //.pipe(htmlFilter.restore())
      .pipe(gulp.dest(options.dist + '/' + options.namespace))
      .pipe($.size({title: 'release', showFiles: true}));
  });

  // Only applies for fonts from bower dependencies
  // Custom fonts are handled by the "other" task
  gulp.task('fonts', function () {
    return gulp.src($.mainBowerFiles())
      .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
      .pipe($.flatten())
      .pipe(gulp.dest(options.dist + '/' + options.namespace + '/fonts/'));
  });

  gulp.task('other', function () {
    return gulp.src([
      options.src + '/**/*',
      '!' + options.src + '/**/*.{jade,less,js}'
    ]).pipe(gulp.dest(options.dist + '/' + options.namespace + '/'));
  });

  gulp.task('clean', function () {
    return gulp.src([options.dist, options.tmp])
      .pipe($.clean());
  });

  gulp.task('release', ['html', 'fonts', 'other']);

};