text:
// context for simple expression
// context means:
// - the local variables
// - the local variable names
// - the lookup-input variables

package cgeo.geocaching.brouter.expressions;

import cgeo.geocaching.brouter.util.BitCoderContext;
import cgeo.geocaching.brouter.util.Crc32Utils;
import cgeo.geocaching.brouter.util.IByteArrayUnifier;
import cgeo.geocaching.brouter.util.LruMap;
import cgeo.geocaching.storage.ContentStorage;

import android.net.Uri;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;

public abstract class BExpressionContext implements IByteArrayUnifier {
    private static final String CONTEXT_TAG = "---context:";
    private static final String MODEL_TAG = "---model:";
    public boolean useKinematicModel;
    public BExpressionMetaData meta;
    private String context;
    private boolean inOurContext = false;
    private BufferedReader br = null;
    private boolean readerDone = false;
    private final Map<String, Integer> lookupNumbers = new HashMap<>();
    private final ArrayList<BExpressionLookupValue[]> lookupValues = new ArrayList<>();
    private final ArrayList<String> lookupNames = new ArrayList<>();
    private final ArrayList<int[]> lookupHistograms = new ArrayList<>();
    private boolean[] lookupIdxUsed;
    private boolean lookupDataFrozen = false;
    private int[] lookupData = new int[0];
    private final byte[] abBuf = new byte[256];
    private final BitCoderContext ctxEndode = new BitCoderContext(abBuf);
    private final BitCoderContext ctxDecode = new BitCoderContext(new byte[0]);
    private final Map<String, Integer> variableNumbers = new HashMap<>();
    private float[] variableData;
    // hash-cache for function results
    private final CacheNode probeCacheNode = new CacheNode();
    private LruMap cache;
    private final VarWrapper probeVarSet = new VarWrapper();
    private LruMap resultVarCache;
    private List<BExpression> expressionList;
    private int minWriteIdx;
    // build-in variable indexes for fast access
    private int[] buildInVariableIdx;
    private int nBuildInVars;
    private float[] currentVars;
    private int currentVarOffset;
    private BExpressionContext foreignContext;
    private int linenr;
    private boolean lookupDataValid = false;
    private int parsedLines = 0;
    private boolean fixTagsWritten = false;
    private long requests;
    private long requests2;
    private long cachemisses;
    private CacheNode lastCacheNode = new CacheNode();

    protected BExpressionContext(final String context, final BExpressionMetaData meta) {
        this(context, 4096, meta);
    }

    /**
     * Create an Expression-Context for the given node
     *
     * @param context  global, way or node - context of that instance
     * @param hashSize size of hashmap for result caching
     */
    protected BExpressionContext(final String context, int hashSize, final BExpressionMetaData meta) {
        this.context = context;
        this.meta = meta;

        if (meta != null) {
            meta.registerListener(context, this);
        }

        if (Boolean.getBoolean("disableExpressionCache")) {
            hashSize = 1;
        }

        // create the expression cache
        if (hashSize > 0) {
            cache = new LruMap(4 * hashSize, hashSize);
            resultVarCache = new LruMap(4096, 4096);
        }
    }

    protected void setInverseVars() {
        currentVarOffset = nBuildInVars;
    }

    protected abstract String[] getBuildInVariableNames();

    public final float getBuildInVariable(final int idx) {
        return currentVars[idx + currentVarOffset];
    }

    /**
     * encode internal lookup data to a byte array
     */
    public byte[] encode() {
        if (!lookupDataValid) {
            throw new IllegalArgumentException("internal error: encoding undefined data?");
        }
        return encode(lookupData);
    }

    public byte[] encode(final int[] ld) {
        final BitCoderContext ctx = ctxEndode;
        ctx.reset();

        int skippedTags = 0;
        int nonNullTags = 0;

        // (skip first bit ("reversedirection") )

        // all others are generic
        for (int inum = 1; inum < lookupValues.size(); inum++) { // loop over lookup names
            final int d = ld[inum];
            if (d == 0) {
                skippedTags++;
                continue;
            }
            ctx.encodeVarBits(skippedTags + 1);
            nonNullTags++;
            skippedTags = 0;

            // 0 excluded already, 1 (=unknown) we rotate up to 8
            // to have the good code space for the popular values
            final int dd = d < 2 ? 7 : (d < 9 ? d - 2 : d - 1);
            ctx.encodeVarBits(dd);
        }
        ctx.encodeVarBits(0);

        if (nonNullTags == 0) {
            return null;
        }

        final int len = ctx.closeAndGetEncodedLength();
        final byte[] ab = new byte[len];
        System.arraycopy(abBuf, 0, ab, 0, len);

        // crosscheck: decode and compare
        final int[] ld2 = new int[lookupValues.size()];
        decode(ld2, false, ab);
        for (int inum = 1; inum < lookupValues.size(); inum++) { // loop over lookup names (except reverse dir)
            if (ld2[inum] != ld[inum]) {
                throw new RuntimeException("assertion failed encoding inum=" + inum + " val=" + ld[inum] + " " + getKeyValueDescription(false, ab));
            }
        }

        return ab;
    }

    /**
     * decode byte array to internal lookup data
     */
    public void decode(final byte[] ab) {
        decode(lookupData, false, ab);
        lookupDataValid = true;
    }

    /**
     * decode a byte-array into a lookup data array
     */
    // external code, do not refactor
    @SuppressWarnings("PMD.NPathComplexity")
    private void decode(final int[] ld, final boolean inverseDirection, final byte[] ab) {
        final BitCoderContext ctx = ctxDecode;
        ctx.reset(ab);

        // start with first bit hardwired ("reversedirection")
        ld[0] = inverseDirection ? 2 : 0;

        // all others are generic
        int inum = 1;
        for (; ; ) {
            int delta = ctx.decodeVarBits();
            if (delta == 0) {
                break;
            }
            if (inum + delta > ld.length) {
                break; // higher minor version is o.k.
            }

            while (delta-- > 1) {
                ld[inum++] = 0;
            }

            // see encoder for value rotation
            final int dd = ctx.decodeVarBits();
            int d = dd == 7 ? 1 : (dd < 7 ? dd + 2 : dd + 1);
            if (d >= lookupValues.get(inum).length && d < 1000) { // map out-of-range to unknown
                d = 1; // map out-of-range to unknown
            }
            ld[inum++] = d;
        }
        while (inum < ld.length) {
            ld[inum++] = 0;
        }
    }

    public String getKeyValueDescription(final boolean inverseDirection, final byte[] ab) {
        final StringBuilder sb = new StringBuilder(200);
        decode(lookupData, inverseDirection, ab);
        for (int inum = 0; inum < lookupValues.size(); inum++) { // loop over lookup names
            final BExpressionLookupValue[] va = lookupValues.get(inum);
            final int val = lookupData[inum];
            final String value = (val >= 1000) ? Float.toString((val - 1000) / 100f) : va[val].toString();
            if (value != null && value.length() > 0) {
                if (sb.length() > 0) {
                    sb.append(' ');
                }
                sb.append(lookupNames.get(inum)).append("=").append(value);
            }
        }
        return sb.toString();
    }

    public List<String> getKeyValueList(final boolean inverseDirection, final byte[] ab) {
        final ArrayList<String> res = new ArrayList<>();
        decode(lookupData, inverseDirection, ab);
        for (int inum = 0; inum < lookupValues.size(); inum++) { // loop over lookup names
            final BExpressionLookupValue[] va = lookupValues.get(inum);
            final int val = lookupData[inum];
            // no negative values
            final String value = (val >= 1000) ? Float.toString((val - 1000) / 100f) : va[val].toString();
            if (value != null && value.length() > 0) {
                res.add(lookupNames.get(inum));
                res.add(value);
            }
        }
        return res;
    }

    public int getLookupKey(String name) {
        int res = -1;
        try {
            res = lookupNumbers.get(name);
        } catch (Exception ignore) {
            // ignore
        }
        return res;
    }

    public float getLookupValue(int key) {
        float res = 0f;
        final int val = lookupData[key];
        if (val == 0) {
            return Float.NaN;
        }
        res = (val - 1000) / 100f;
        return res;
    }

    public float getLookupValue(boolean inverseDirection, byte[] ab, int key) {
        float res = 0f;
        decode(lookupData, inverseDirection, ab);
        final int val = lookupData[key];
        if (val == 0) {
            return Float.NaN;
        }
        res = (val - 1000) / 100f;
        return res;
    }

    public void parseMetaLine(final String line) {
        parsedLines++;
        final StringTokenizer tk = new StringTokenizer(line, " ");
        String name = tk.nextToken();
        final String value = tk.nextToken();
        final int idx = name.indexOf(';');
        if (idx >= 0) {
            name = name.substring(0, idx);
        }

        if (!fixTagsWritten) {
            fixTagsWritten = true;
            if ("way".equals(context)) {
                addLookupValue("reversedirection", "yes", null);
            } else if ("node".equals(context)) {
                addLookupValue("nodeaccessgranted", "yes", null);
            }
        }
        if ("reversedirection".equals(name)) {
            return; // this is hardcoded
        }
        if ("nodeaccessgranted".equals(name)) {
            return; // this is hardcoded
        }
        final BExpressionLookupValue newValue = addLookupValue(name, value, null);

        // add aliases
        while (newValue != null && tk.hasMoreTokens()) {
            newValue.addAlias(tk.nextToken());
        }
    }

    public void finishMetaParsing() {
        if (parsedLines == 0 && !"global".equals(context)) {
            throw new IllegalArgumentException("lookup table does not contain data for context " + context + " (old version?)");
        }

        // post-process metadata:
        lookupDataFrozen = true;

        lookupIdxUsed = new boolean[lookupValues.size()];
    }

    public final void evaluate(final int[] lookupData2) {
        lookupData = lookupData2;
        evaluate();
    }

    private void evaluate() {
        final int n = expressionList.size();
        for (int expidx = 0; expidx < n; expidx++) {
            expressionList.get(expidx).evaluate(this);
        }
    }

    public String cacheStats() {
        return "requests=" + requests + " requests2=" + requests2 + " cachemisses=" + cachemisses;
    }

    // @Override
    public final byte[] unify(final byte[] ab, final int offset, final int len) {
        probeCacheNode.ab = null; // crc based cache lookup only
        probeCacheNode.hash = Crc32Utils.crc(ab, offset, len);

        CacheNode cn = (CacheNode) cache.get(probeCacheNode);
        if (cn != null) {
            final byte[] cab = cn.ab;
            if (cab.length == len) {
                for (int i = 0; i < len; i++) {
                    if (cab[i] != ab[i + offset]) {
                        cn = null;
                        break;
                    }
                }
                if (cn != null) {
                    lastCacheNode = cn;
                    return cn.ab;
                }
            }
        }
        final byte[] nab = new byte[len];
        System.arraycopy(ab, offset, nab, 0, len);
        return nab;
    }

    public final void evaluate(final boolean inverseDirection, final byte[] ab) {
        requests++;
        lookupDataValid = false; // this is an assertion for a nasty pifall

        if (cache == null) {
            decode(lookupData, inverseDirection, ab);
            if (currentVars == null || currentVars.length != nBuildInVars) {
                currentVars = new float[nBuildInVars];
            }
            evaluateInto(currentVars, 0);
            currentVarOffset = 0;
            return;
        }

        CacheNode cn;
        if (lastCacheNode.ab == ab) {
            cn = lastCacheNode;
        } else {
            probeCacheNode.ab = ab;
            probeCacheNode.hash = Crc32Utils.crc(ab, 0, ab.length);
            cn = (CacheNode) cache.get(probeCacheNode);
        }

        if (cn == null) {
            cachemisses++;

            cn = (CacheNode) cache.removeLru();
            if (cn == null) {
                cn = new CacheNode();
            }
            cn.hash = probeCacheNode.hash;
            cn.ab = ab;
            cache.put(cn);

            if (probeVarSet.vars == null) {
                probeVarSet.vars = new float[2 * nBuildInVars];
            }

            // forward direction
            decode(lookupData, false, ab);
            evaluateInto(probeVarSet.vars, 0);

            // inverse direction
            lookupData[0] = 2; // inverse shortcut: reuse decoding
            evaluateInto(probeVarSet.vars, nBuildInVars);

            probeVarSet.hash = Arrays.hashCode(probeVarSet.vars);

            // unify the result variable set
            VarWrapper vw = (VarWrapper) resultVarCache.get(probeVarSet);
            if (vw == null) {
                vw = (VarWrapper) resultVarCache.removeLru();
                if (vw == null) {
                    vw = new VarWrapper();
                }
                vw.hash = probeVarSet.hash;
                vw.vars = probeVarSet.vars;
                probeVarSet.vars = null;
                resultVarCache.put(vw);
            }
            cn.vars = vw.vars;
        } else {
            if (ab == cn.ab) {
                requests2++;
            }

            cache.touch(cn);
        }

        currentVars = cn.vars;
        currentVarOffset = inverseDirection ? nBuildInVars : 0;
    }

    private void evaluateInto(final float[] vars, final int offset) {
        evaluate();
        for (int vi = 0; vi < nBuildInVars; vi++) {
            final int idx = buildInVariableIdx[vi];
            vars[vi + offset] = idx == -1 ? 0.f : variableData[idx];
        }
    }

    public void dumpStatistics() {
        final TreeMap<String, String> counts = new TreeMap<>();
        // first count
        for (String name : lookupNumbers.keySet()) {
            int cnt = 0;
            final int inum = lookupNumbers.get(name);
            final int[] histo = lookupHistograms.get(inum);
//    if ( histo.length == 500 ) continue;
            for (int i = 2; i < histo.length; i++) {
                cnt += histo[i];
            }
            counts.put("" + (1000000000 + cnt) + "_" + name, name);
        }

        while (counts.size() > 0) {
            final String key = counts.lastEntry().getKey();
            final String name = counts.get(key);
            counts.remove(key);
            final int inum = lookupNumbers.get(name);
            final BExpressionLookupValue[] values = lookupValues.get(inum);
            final int[] histo = lookupHistograms.get(inum);
            if (values.length == 1000) {
                continue;
            }
            final String[] svalues = new String[values.length];
            for (int i = 0; i < values.length; i++) {
                String scnt = "0000000000" + histo[i];
                scnt = scnt.substring(scnt.length() - 10);
                svalues[i] = scnt + " " + values[i].toString();
            }
            Arrays.sort(svalues);
            for (int i = svalues.length - 1; i >= 0; i--) {
                System.out.println(name + ";" + svalues[i]);
            }
        }
    }

    /**
     * @return a new lookupData array, or null if no metadata defined
     */
    public int[] createNewLookupData() {
        if (lookupDataFrozen) {
            return new int[lookupValues.size()];
        }
        return null;
    }

    /**
     * generate random values for regression testing
     */
    public int[] generateRandomValues(final Random rnd) {
        final int[] data = createNewLookupData();
        data[0] = 2 * rnd.nextInt(2); // reverse-direction = 0 or 2
        for (int inum = 1; inum < data.length; inum++) {
            final int nvalues = lookupValues.get(inum).length;
            data[inum] = 0;
            if (inum > 1 && rnd.nextInt(10) > 0) {
                continue; // tags other than highway only 10%
            }
            data[inum] = rnd.nextInt(nvalues);
        }
        lookupDataValid = true;
        return data;
    }

    public void assertAllVariablesEqual(final BExpressionContext other) {
        final int nv = variableData.length;
        final int nv2 = other.variableData.length;
        if (nv != nv2) {
            throw new RuntimeException("mismatch in variable-count: " + nv + "<->" + nv2);
        }
        for (int i = 0; i < nv; i++) {
            if (variableData[i] != other.variableData[i]) {
                throw new RuntimeException("mismatch in variable " + variableName(i) + " " + variableData[i] + "<->" + other.variableData[i]
                        + "\ntags = " + getKeyValueDescription(false, encode()));
            }
        }
    }

    public String variableName(final int idx) {
        for (Map.Entry<String, Integer> e : variableNumbers.entrySet()) {
            if (e.getValue().intValue() == idx) {
                return e.getKey();
            }
        }
        throw new RuntimeException("no variable for index" + idx);
    }

    /**
     * add a new lookup-value for the given name to the given lookupData array.
     * If no array is given (null value passed), the value is added to
     * the context-binded array. In that case, unknown names and values are
     * created dynamically.
     *
     * @return a newly created value element, if any, to optionally add aliases
     */
    // external code, do not refactor
    @SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"})
    public BExpressionLookupValue addLookupValue(final String name, final String value, final int[] lookupData2) {
        String valueMutable = value;
        BExpressionLookupValue newValue = null;
        Integer num = lookupNumbers.get(name);
        if (num == null) {
            if (lookupData2 != null) {
                // do not create unknown name for external data array
                return newValue;
            }

            // unknown name, create
            num = lookupValues.size();
            lookupNumbers.put(name, num);
            lookupNames.add(name);
            lookupValues.add(new BExpressionLookupValue[]{new BExpressionLookupValue("")
                    , new BExpressionLookupValue("unknown")});
            lookupHistograms.add(new int[2]);
            final int[] ndata = new int[lookupData.length + 1];
            System.arraycopy(lookupData, 0, ndata, 0, lookupData.length);
            lookupData = ndata;
        }

        // look for that value
        final int inum = num;
        BExpressionLookupValue[] values = lookupValues.get(inum);
        int[] histo = lookupHistograms.get(inum);
        int i = 0;
        boolean bFoundAsterix = false;
        for (; i < values.length; i++) {
            final BExpressionLookupValue v = values[i];
            if (v.equals("*")) {
                bFoundAsterix = true;
            }
            if (v.matches(valueMutable)) {
                break;
            }
        }
        if (i == values.length) {
            if (lookupData2 != null) {
                // do not create unknown value for external data array,
                // record as 'other' instead
                lookupData2[inum] = 0;
                if (bFoundAsterix) {
                    // found value for lookup *
                    //System.out.println( "add unknown " + name + "  " + value );
                    final String org = valueMutable;
                    try {
                        // remove some unused characters
                        valueMutable = valueMutable.replace(",", ".");
                        valueMutable = valueMutable.replace(">", "");
                        valueMutable = valueMutable.replace("_", "");
                        if (valueMutable.indexOf("-") == 0) {
                            valueMutable = valueMutable.substring(1);
                        }
                        if (valueMutable.indexOf("~") == 0) {
                            valueMutable = valueMutable.substring(1);
                        }
                        if (valueMutable.contains("-")) {    // replace eg. 1.4-1.6 m
                            final String tmp = valueMutable.substring(valueMutable.indexOf("-") + 1).replaceAll("[0-9.,-]", "");
                            valueMutable = valueMutable.substring(0, valueMutable.indexOf("-")) + tmp;
                        }
                        // do some value conversion
                        if (valueMutable.toLowerCase().contains("ft")) {
                            float foot = 0f;
                            int inch = 0;
                            final String[] sa = valueMutable.toLowerCase().trim().split("ft");
                            if (sa.length >= 1) {
                                foot = Float.parseFloat(sa[0].trim());
                            }
                            if (sa.length == 2) {
                                valueMutable = sa[1];
                                if (valueMutable.indexOf("in") > 0) {
                                    valueMutable = valueMutable.substring(0, valueMutable.indexOf("in"));
                                }
                                inch = Integer.parseInt(valueMutable.trim());
                                foot += inch / 12f;
                            }
                            valueMutable = String.format(Locale.US, "%3.1f", foot * 0.3048f);
                        }
                        if (valueMutable.toLowerCase().contains("'")) {
                            float foot = 0f;
                            int inch = 0;
                            final String[] sa = valueMutable.toLowerCase().trim().split("'");
                            if (sa.length >= 1) {
                                foot = Float.parseFloat(sa[0].trim());
                            }
                            if (sa.length == 2) {
                                valueMutable = sa[1];
                                if (valueMutable.indexOf("''") > 0) {
                                    valueMutable = valueMutable.substring(0, valueMutable.indexOf("''"));
                                }
                                if (valueMutable.indexOf("\"") > 0) {
                                    valueMutable = valueMutable.substring(0, valueMutable.indexOf("\""));
                                }
                                inch = Integer.parseInt(valueMutable.trim());
                                foot += inch / 12f;
                            }
                            valueMutable = String.format(Locale.US, "%3.1f", foot * 0.3048f);
                        } else if (valueMutable.contains("in") || valueMutable.contains("\"")) {
                            float inch = 0f;
                            if (valueMutable.indexOf("in") > 0) {
                                valueMutable = valueMutable.substring(0, valueMutable.indexOf("in"));
                            }
                            if (valueMutable.indexOf("\"") > 0) {
                                valueMutable = valueMutable.substring(0, valueMutable.indexOf("\""));
                            }
                            inch = Float.parseFloat(valueMutable.trim());
                            valueMutable = String.format(Locale.US, "%3.1f", inch * 0.0254f);
                        } else if (valueMutable.toLowerCase().contains("feet") || valueMutable.toLowerCase().contains("foot")) {
                            float feet = 0f;
                            final String s = valueMutable.substring(0, valueMutable.toLowerCase().indexOf("f"));
                            feet = Float.parseFloat(s.trim());
                            valueMutable = String.format(Locale.US, "%3.1f", feet * 0.3048f);
                        } else if (valueMutable.toLowerCase().contains("fathom") || valueMutable.toLowerCase().contains("fm")) {
                            float fathom = 0f;
                            final String s = valueMutable.substring(0, valueMutable.toLowerCase().indexOf("f"));
                            fathom = Float.parseFloat(s.trim());
                            valueMutable = String.format(Locale.US, "%3.1f", fathom * 1.8288f);
                        } else if (valueMutable.contains("cm")) {
                            final String[] sa = valueMutable.trim().split("cm");
                            if (sa.length == 1) {
                                valueMutable = sa[0].trim();
                            }
                            final float cm = Float.parseFloat(valueMutable.trim());
                            valueMutable = String.format(Locale.US, "%3.1f", cm * 100f);
                        } else if (valueMutable.toLowerCase().contains("meter")) {
                            final String s = valueMutable.substring(0, valueMutable.toLowerCase().indexOf("m"));
                            valueMutable = s.trim();
                        } else if (valueMutable.toLowerCase().contains("mph")) {
                            valueMutable = valueMutable.replace("_", "");
                            final String[] sa = valueMutable.trim().toLowerCase().split("mph");
                            if (sa.length >= 1) {
                                valueMutable = sa[0].trim();
                            }
                            final float mph = Float.parseFloat(valueMutable.trim());
                            valueMutable = String.format(Locale.US, "%3.1f", mph * 1.609344f);
                        } else if (valueMutable.toLowerCase().contains("knot")) {
                            final String[] sa = valueMutable.trim().toLowerCase().split("knot");
                            if (sa.length >= 1) {
                                valueMutable = sa[0].trim();
                            }
                            final float nm = Float.parseFloat(valueMutable.trim());
                            valueMutable = String.format(Locale.US, "%3.1f", nm * 1.852f);
                        } else if (valueMutable.contains("kmh") || valueMutable.contains("km/h") || valueMutable.contains("kph")) {
                            final String[] sa = valueMutable.trim().split("k");
                            if (sa.length == 1) {
                                valueMutable = sa[0].trim();
                            }
                        } else if (valueMutable.contains("m")) {
                            final String s = valueMutable.substring(0, valueMutable.toLowerCase().indexOf("m"));
                            valueMutable = s.trim();
                        } else if (valueMutable.contains("(")) {
                            final String s = valueMutable.substring(0, valueMutable.toLowerCase().indexOf("("));
                            valueMutable = s.trim();
                        }
                        // found negative maxdraft values
                        // no negative values
                        // values are float with 2 decimals
                        lookupData2[inum] = 1000 + (int) (Math.abs(Float.parseFloat(valueMutable)) * 100f);
                    } catch (Exception e) {
                        // ignore errors
                        System.err.println("error for " + name + "  " + org + " trans " + valueMutable + " " + e.getMessage());
                        lookupData2[inum] = 0;
                    }
                }
                return newValue;
            }

            if (i == 500) {
                return newValue;
            }
            // unknown value, create
            final BExpressionLookupValue[] nvalues = new BExpressionLookupValue[values.length + 1];
            final int[] nhisto = new int[values.length + 1];
            System.arraycopy(values, 0, nvalues, 0, values.length);
            System.arraycopy(histo, 0, nhisto, 0, histo.length);
            values = nvalues;
            histo = nhisto;
            newValue = new BExpressionLookupValue(value);
            values[i] = newValue;
            lookupHistograms.set(inum, histo);
            lookupValues.set(inum, values);
        }

        histo[i]++;

        // finally remember the actual data
        if (lookupData2 != null) {
            lookupData2[inum] = i;
        } else {
            lookupData[inum] = i;
        }
        return newValue;
    }

    /**
     * add a value-index to to internal array
     * value-index means 0=unknown, 1=other, 2=value-x, ...
     */
    public void addLookupValue(final String name, final int valueIndex) {
        final Integer num = lookupNumbers.get(name);
        if (num == null) {
            return;
        }

        // look for that value
        final int inum = num;
        final int nvalues = lookupValues.get(inum).length;
        if (valueIndex < 0 || valueIndex >= nvalues) {
            throw new IllegalArgumentException("value index out of range for name " + name + ": " + valueIndex);
        }
        lookupData[inum] = valueIndex;
    }

    public int getOutputVariableIndex(final String name, final boolean mustExist) {
        final int idx = getVariableIdx(name, false);
        if (idx < 0) {
            if (mustExist) {
                throw new IllegalArgumentException("unknown variable: " + name);
            }
        } else if (idx < minWriteIdx) {
            throw new IllegalArgumentException("bad access to global variable: " + name);
        }
        for (int i = 0; i < nBuildInVars; i++) {
            if (buildInVariableIdx[i] == idx) {
                return i;
            }
        }
        final int[] extended = new int[nBuildInVars + 1];
        System.arraycopy(buildInVariableIdx, 0, extended, 0, nBuildInVars);
        extended[nBuildInVars] = idx;
        buildInVariableIdx = extended;
        return nBuildInVars++;
    }

    public void setForeignContext(final BExpressionContext foreignContext) {
        this.foreignContext = foreignContext;
    }

    public float getForeignVariableValue(final int foreignIndex) {
        return foreignContext.getBuildInVariable(foreignIndex);
    }

    public int getForeignVariableIdx(final String context, final String name) {
        if (foreignContext == null || !context.equals(foreignContext.context)) {
            throw new IllegalArgumentException("unknown foreign context: " + context);
        }
        return foreignContext.getOutputVariableIndex(name, true);
    }

    public void parseFile(final Uri uri, final String readOnlyContext) {
        final InputStream is = ContentStorage.get().openForRead(uri);
        if (is == null) {
            throw new IllegalArgumentException("profile " + uri + " does not exist");
        }
        try {
            if (readOnlyContext != null) {
                linenr = 1;
                final String realContext = context;
                context = readOnlyContext;

                final InputStream is2 = ContentStorage.get().openForRead(uri);
                expressionList = parseFileHelper(is2);
                variableData = new float[variableNumbers.size()];
                evaluate(lookupData); // lookupData is dummy here - evaluate just to create the variables
                context = realContext;
            }
            linenr = 1;
            minWriteIdx = variableData == null ? 0 : variableData.length;

            expressionList = parseFileHelper(is);

            // determine the build-in variable indices
            final String[] varNames = getBuildInVariableNames();
            nBuildInVars = varNames.length;
            buildInVariableIdx = new int[nBuildInVars];
            for (int vi = 0; vi < varNames.length; vi++) {
                buildInVariableIdx[vi] = getVariableIdx(varNames[vi], false);
            }

            final float[] readOnlyData = variableData;
            variableData = new float[variableNumbers.size()];
            for (int i = 0; i < minWriteIdx; i++) {
                variableData[i] = readOnlyData[i];
            }
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("ParseException " + uri.toString() + " at line " + linenr + ": " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (expressionList.size() == 0) {
            throw new IllegalArgumentException("profile does not contain expressions for context " + context + " (old version?)");
        }
    }

    private List<BExpression> parseFileHelper(final InputStream is) throws Exception {
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        readerDone = false;
        final List<BExpression> result = new ArrayList<>();
        for (; ; ) {
            final BExpression exp = BExpression.parse(this, 0);
            if (exp == null) {
                break;
            }
            result.add(exp);
        }
        br.close();
        br = null;
        return result;
    }

    public void setVariableValue(String name, float value, boolean create) {
        final Integer num = variableNumbers.get(name);
        if (num != null) {
            variableData[num] = value;
        }
    }

    public float getVariableValue(final String name, final float defaultValue) {
        final Integer num = variableNumbers.get(name);
        return num == null ? defaultValue : getVariableValue(num.intValue());
    }

    public float getVariableValue(final int variableIdx) {
        return variableData[variableIdx];
    }

    public int getVariableIdx(final String name, final boolean create) {
        Integer num = variableNumbers.get(name);
        if (num == null) {
            if (create) {
                num = variableNumbers.size();
                variableNumbers.put(name, num);
            } else {
                return -1;
            }
        }
        return num.intValue();
    }

    public int getMinWriteIdx() {
        return minWriteIdx;
    }

    public float getLookupMatch(final int nameIdx, final int[] valueIdxArray) {
        for (int i = 0; i < valueIdxArray.length; i++) {
            if (lookupData[nameIdx] == valueIdxArray[i]) {
                return 1.0f;
            }
        }
        return 0.0f;
    }

    public int getLookupNameIdx(final String name) {
        final Integer num = lookupNumbers.get(name);
        return num == null ? -1 : num.intValue();
    }

    public final void markLookupIdxUsed(final int idx) {
        lookupIdxUsed[idx] = true;
    }

    public final boolean isLookupIdxUsed(final int idx) {
        return idx < lookupIdxUsed.length && lookupIdxUsed[idx];
    }

    public final void setAllTagsUsed() {
        for (int i = 0; i < lookupIdxUsed.length; i++) {
            lookupIdxUsed[i] = true;
        }
    }

    public int getLookupValueIdx(final int nameIdx, final String value) {
        final BExpressionLookupValue[] values = lookupValues.get(nameIdx);
        for (int i = 0; i < values.length; i++) {
            if (values[i].equals(value)) {
                return i;
            }
        }
        return -1;
    }

    public String parseToken() throws Exception {
        for (; ; ) {
            final String token = parseTokenHelper();
            if (token == null) {
                return null;
            }
            if (token.startsWith(CONTEXT_TAG)) {
                inOurContext = token.substring(CONTEXT_TAG.length()).equals(context);
            } else if (token.startsWith(MODEL_TAG)) {
                // no need to parse the name, as c:geo will only support the builtin model class (also prevents class injection)
                useKinematicModel = true;
            } else if (inOurContext) {
                return token;
            }
        }
    }

    private String parseTokenHelper() throws Exception {
        final StringBuilder sb = new StringBuilder(32);
        boolean inComment = false;
        for (; ; ) {
            final int ic = readerDone ? -1 : br.read();
            if (ic < 0) {
                if (sb.length() == 0) {
                    return null;
                }
                readerDone = true;
                return sb.toString();
            }
            final char c = (char) ic;
            if (c == '\n') {
                linenr++;
            }

            if (inComment) {
                if (c == '\r' || c == '\n') {
                    inComment = false;
                }
                continue;
            }
            if (Character.isWhitespace(c)) {
                if (sb.length() > 0) {
                    return sb.toString();
                } else {
                    continue;
                }
            }
            if (c == '#' && sb.length() == 0) {
                inComment = true;
            } else {
                sb.append(c);
            }
        }
    }

    public float assign(final int variableIdx, final float value) {
        variableData[variableIdx] = value;
        return value;
    }

}


text:
#ifndef __MAC_AUTO_GENERATE_H__
#define __MAC_AUTO_GENERATE_H__

/* Automatically generated file; DO NOT EDIT. */
/* mac configure file for RT-Thread qemu */

#define AUTOMAC0  0x52
#define AUTOMAC1  0x54
#define AUTOMAC2  0x00
#define AUTOMAC3  0x78
#define AUTOMAC4  0xe7
#define AUTOMAC5  0x23

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Zend\Http\Client;

/**
 * An interface description for Zend_Http_Client_Adapter classes.
 *
 * These classes are used as connectors for Zend_Http_Client, performing the
 * tasks of connecting, writing, reading and closing connection to the server.
 *
 * @category   Zend
 * @package    Zend_Http
 * @subpackage Client_Adapter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Adapter
{
    /**
     * Set the configuration array for the adapter
     *
     * @param array $config
     */
    public function setConfig($config = array());

    /**
     * Connect to the remote server
     *
     * @param string  $host
     * @param int     $port
     * @param boolean $secure
     */
    public function connect($host, $port = 80, $secure = false);

    /**
     * Send request to the remote server
     *
     * @param string        $method
     * @param \Zend\Uri\Uri $url
     * @param string        $http_ver
     * @param array         $headers
     * @param string        $body
     * @return string Request as text
     */
    public function write($method, $url, $http_ver = '1.1', $headers = array(), $body = '');

    /**
     * Read response from server
     *
     * @return string
     */
    public function read();

    /**
     * Close the connection to the server
     *
     */
    public function close();
}


text:
namespace LeapOsvr {

	class HandSelector {

		public:

			static const int NoHandFound = -1;
			static const int MinimumWinningConfidence = 5;

			HandSelector(bool pIsLeft);

			void update(const std::vector<LEAP_HAND> &pHands);
			const int getBestHandIndex() const;

		private:

			bool mIsLeft;
			int mWinningHandId;
			int mWinningHandIndex;

            const int getCandidateIndex(const std::vector<LEAP_HAND> &pHands) const;
			const bool isNewCandidateBetterThanPrevious(
				const LEAP_HAND &pNewCandidate, const LEAP_HAND &pPrevCandidate) const;
			const bool canCandidateBecomeWinner(const LEAP_HAND &pCandidate) const;
			void setNoWinner();

	};

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Thelotrema harmandii Pit.

### Remarks
null


text:
package base

import "gophergo.org/p/talon/logging"

// 创建日志记录器。
func NewLogger() logging.Logger {
	return logging.NewSimpleLogger()
}


text:
from flexget.components.managed_lists.lists.pending_list.db import PendingListList
from flexget.manager import Session

class TestListInterface:
    config = """
        templates:
          global:
            disable: [seen]

        tasks:
          list_get:
            pending_list: test_list

          list_get_pending:
            pending_list:
              list_name: 'test_list'
              include: 'pending'

          list_get_approved:
            pending_list:
              list_name: 'test_list'
              include: 'approved'

          list_get_all:
            pending_list:
              list_name: 'test_list'
              include: 'all'

          pending_list_add:
            mock:
              - {title: 'title 1', url: "http://mock.url/file1.torrent"}
              - {title: 'title 2', url: "http://mock.url/file2.torrent"}
            accept_all: yes
            list_add:
              - pending_list: test_list

          pending_list_match:
            mock:
              - {title: 'title 1', url: "http://mock.url/file1.torrent"}
              - {title: 'title 2', url: "http://mock.url/file2.torrent"}
              - {title: 'title 3', url: "http://mock.url/file3.torrent"}
            list_match:
              from:
                - pending_list: test_list

    """

    def test_list_add(self, execute_task):
        task = execute_task('pending_list_add')
        assert len(task.entries) == 2

        task = execute_task('list_get')
        assert len(task.entries) == 0

        with Session() as session:
            list = session.query(PendingListList).first()
            assert list
            for entry in list.entries:
                entry.approved = True

        task = execute_task('list_get')
        assert len(task.entries) == 2

    def test_list_match(self, execute_task):
        task = execute_task('pending_list_add')
        assert len(task.entries) == 2

        task = execute_task('pending_list_match')
        assert len(task.accepted) == 0

        with Session() as session:
            list = session.query(PendingListList).first()
            assert list
            for entry in list.entries:
                entry.approved = True

        task = execute_task('list_get')
        assert len(task.entries) == 2

        task = execute_task('pending_list_match')
        assert len(task.accepted) == 2

        task = execute_task('list_get')
        assert len(task.entries) == 0

    def test_list_get_include(self, execute_task):
        task = execute_task('pending_list_add')
        assert len(task.entries) == 2

        with Session() as session:
            entry = session.query(PendingListList).first().entries.first()
            entry.approved = True

        task = execute_task('list_get_all')
        assert len(task.entries) == 2

        task = execute_task('list_get_pending')
        assert len(task.entries) == 1

        task = execute_task('list_get_approved')
        assert len(task.entries) == 1


text:
Структуры расположены в пространстве имён `Comindware\Tracker\API\Struct` и соответствуют некоторым
структурам, возвращаемым сервером.

### FileStruct

Описывает файл, получаемый с сервера.

## Вспомогательные типы

### File

`Comindware\Tracker\API\Util\File\File`

Интерфейс файлов, загружаемых на сервер. Этот интерфейс реализуется следующими классами.

#### LocalFile

`Comindware\Tracker\API\Util\File\LocalFile`

Позволяет загружать файлы, расположенные в локальной файловой системе клиента.

Пример:

```php
use Comindware\Tracker\API\Util\File\LocalFile;

$file = new LocalFile('/path/to/file', 'foo.jpg');
```
См. также [Вложения (Attachments)](api-attachment.ru.md).


text:
//Copyright 2006-2009 Jeroen van Menen
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

#endregion Copyright

using WatiN.Core.Constraints;

namespace WatiN.Core
{
    /// <summary>
    /// This class determines if it is possible to get an element by its Id based on the given Constraint.
    /// If so it will return an id
    /// </summary>
    /// <example>
    /// Following an example on how to use this class:
    /// <code>
    /// var idHint = IdHinter.GetIdHint(Find.ById("someId"));
    /// </code>
    /// </example>
    internal class IdHinter
    {
        private readonly Constraint _constraint;
        private string _idValue;
        private bool _hasAlreadyBeenCalled;

        private AttributeConstraint AsAttributeConstraint { get; set; }

        /// <summary>
        /// Gets the id hint. Only returns an Id if <paramref name="constraint"/> is an <see cref="AttributeConstraint"/> on an exact Id or
        /// if the <paramref name="constraint"/> is an <see cref="AndConstraint"/> with an <see cref="AttributeConstraint"/> on an exact Id
        /// and an <see cref="AnyConstraint"/>.
        /// </summary>
        /// <param name="constraint">The constraint to get the id Hint from.</param>
        /// <returns></returns>
        public static string GetIdHint(Constraint constraint)
        {
            var andConstraint = constraint as AndConstraint;
            if (andConstraint != null)
            {
                var left = new IdHinter(andConstraint.First);
                var right = new IdHinter(andConstraint.Second);

                return left.GetIdHint(right);
            }

            return new IdHinter(constraint).GetIdHint();
        }

        private IdHinter(Constraint constraint)
        {
            _constraint = constraint ?? Find.Any;
            AsAttributeConstraint = constraint as AttributeConstraint;
        }

        private string GetIdHint(IdHinter second)
        {
            if (ShouldReturnIdHint(second, this))
                return second.GetIdHint();

            return ShouldReturnIdHint(this, second) ? GetIdHint() : null;
        }

        private string GetIdHint()
        {
            if (_hasAlreadyBeenCalled) return _idValue;

            _hasAlreadyBeenCalled = true;

            if (!IsAllowedConstraint) return null;
            if (!IsIdAttributeConstraint) return null;

            var comparer = AsAttributeConstraint.Comparer as Comparers.StringComparer;
            if (comparer == null) return null;

            _idValue = comparer.ComparisonValue;

            return _idValue;
        }

        private bool IsIdAttributeConstraint
        {
            get
            {
                if (AsAttributeConstraint == null) return false;
                return Comparers.StringComparer.AreEqual(AsAttributeConstraint.AttributeName, "id", true);
            }
        }

        private bool HasId
        {
            get { return GetIdHint() != null;}
        }

        private bool IsAllowedConstraint
        {
            get { return AsAttributeConstraint != null || _constraint.Equals(AnyConstraint.Instance); }
        }

        private static bool ShouldReturnIdHint(IdHinter of, IdHinter constraint)
        {
            return of.HasId && (constraint.IsAllowedConstraint & !constraint.HasId);
        }
    }
}


text:
@implementation Student (CoreDataProperties)

@dynamic name;
@dynamic age;
@dynamic iconImageData;

@end


text:
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/smp_lock.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/personality.h>
#include <linux/compiler.h>
#include <asm/ucontext.h>
#include <asm/uaccess.h>
#include <asm/i387.h>
#include <asm/proto.h>
#include <asm/ia32_unistd.h>

/* #define DEBUG_SIG 1 */

#define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP)))

int ia32_setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
               sigset_t *set, struct pt_regs * regs);
int ia32_setup_frame(int sig, struct k_sigaction *ka,
            sigset_t *set, struct pt_regs * regs);

asmlinkage long
sys_sigaltstack(const stack_t __user *uss, stack_t __user *uoss,
		struct pt_regs *regs)
{
	return do_sigaltstack(uss, uoss, regs->rsp);
}

/*
 * Do a signal return; undo the signal stack.
 */

struct rt_sigframe
{
	char __user *pretcode;
	struct ucontext uc;
	struct siginfo info;
};

static int
restore_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc, unsigned long *prax)
{
	unsigned int err = 0;

	/* Always make any pending restarted system calls return -EINTR */
	current_thread_info()->restart_block.fn = do_no_restart_syscall;

#define COPY(x)		err |= __get_user(regs->x, &sc->x)

	COPY(rdi); COPY(rsi); COPY(rbp); COPY(rsp); COPY(rbx);
	COPY(rdx); COPY(rcx); COPY(rip);
	COPY(r8);
	COPY(r9);
	COPY(r10);
	COPY(r11);
	COPY(r12);
	COPY(r13);
	COPY(r14);
	COPY(r15);

	/* Kernel saves and restores only the CS segment register on signals,
	 * which is the bare minimum needed to allow mixed 32/64-bit code.
	 * App's signal handler can save/restore other segments if needed. */
	{
		unsigned cs;
		err |= __get_user(cs, &sc->cs);
		regs->cs = cs | 3;	/* Force into user mode */
	}

	{
		unsigned int tmpflags;
		err |= __get_user(tmpflags, &sc->eflags);
		regs->eflags = (regs->eflags & ~0x40DD5) | (tmpflags & 0x40DD5);
		regs->orig_rax = -1;		/* disable syscall checks */
	}

	{
		struct _fpstate __user * buf;
		err |= __get_user(buf, &sc->fpstate);

		if (buf) {
			if (!access_ok(VERIFY_READ, buf, sizeof(*buf)))
				goto badframe;
			err |= restore_i387(buf);
		} else {
			struct task_struct *me = current;
			if (used_math()) {
				clear_fpu(me);
				clear_used_math();
			}
		}
	}

	err |= __get_user(*prax, &sc->rax);
	return err;

badframe:
	return 1;
}

asmlinkage long sys_rt_sigreturn(struct pt_regs *regs)
{
	struct rt_sigframe __user *frame;
	sigset_t set;
	unsigned long eax;

	frame = (struct rt_sigframe __user *)(regs->rsp - 8);
	if (!access_ok(VERIFY_READ, frame, sizeof(*frame))) {
		goto badframe;
	}
	if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set))) {
		goto badframe;
	}

	sigdelsetmask(&set, ~_BLOCKABLE);
	spin_lock_irq(&current->sighand->siglock);
	current->blocked = set;
	recalc_sigpending();
	spin_unlock_irq(&current->sighand->siglock);

	if (restore_sigcontext(regs, &frame->uc.uc_mcontext, &eax))
		goto badframe;

#ifdef DEBUG_SIG
	printk("%d sigreturn rip:%lx rsp:%lx frame:%p rax:%lx\n",current->pid,regs.rip,regs.rsp,frame,eax);
#endif

	if (do_sigaltstack(&frame->uc.uc_stack, NULL, regs->rsp) == -EFAULT)
		goto badframe;

	return eax;

badframe:
	signal_fault(regs,frame,"sigreturn");
	return 0;
}

/*
 * Set up a signal frame.
 */

static inline int
setup_sigcontext(struct sigcontext __user *sc, struct pt_regs *regs, unsigned long mask, struct task_struct *me)
{
	int err = 0;

	err |= __put_user(regs->cs, &sc->cs);
	err |= __put_user(0, &sc->gs);
	err |= __put_user(0, &sc->fs);

	err |= __put_user(regs->rdi, &sc->rdi);
	err |= __put_user(regs->rsi, &sc->rsi);
	err |= __put_user(regs->rbp, &sc->rbp);
	err |= __put_user(regs->rsp, &sc->rsp);
	err |= __put_user(regs->rbx, &sc->rbx);
	err |= __put_user(regs->rdx, &sc->rdx);
	err |= __put_user(regs->rcx, &sc->rcx);
	err |= __put_user(regs->rax, &sc->rax);
	err |= __put_user(regs->r8, &sc->r8);
	err |= __put_user(regs->r9, &sc->r9);
	err |= __put_user(regs->r10, &sc->r10);
	err |= __put_user(regs->r11, &sc->r11);
	err |= __put_user(regs->r12, &sc->r12);
	err |= __put_user(regs->r13, &sc->r13);
	err |= __put_user(regs->r14, &sc->r14);
	err |= __put_user(regs->r15, &sc->r15);
	err |= __put_user(me->thread.trap_no, &sc->trapno);
	err |= __put_user(me->thread.error_code, &sc->err);
	err |= __put_user(regs->rip, &sc->rip);
	err |= __put_user(regs->eflags, &sc->eflags);
	err |= __put_user(mask, &sc->oldmask);
	err |= __put_user(me->thread.cr2, &sc->cr2);

	return err;
}

/*
 * Determine which stack to use..
 */

static void __user *
get_stack(struct k_sigaction *ka, struct pt_regs *regs, unsigned long size)
{
	unsigned long rsp;

	/* Default to using normal stack - redzone*/
	rsp = regs->rsp - 128;

	/* This is the X/Open sanctioned signal stack switching.  */
	if (ka->sa.sa_flags & SA_ONSTACK) {
		if (sas_ss_flags(rsp) == 0)
			rsp = current->sas_ss_sp + current->sas_ss_size;
	}

	return (void __user *)round_down(rsp - size, 16);
}

static int setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
			   sigset_t *set, struct pt_regs * regs)
{
	struct rt_sigframe __user *frame;
	struct _fpstate __user *fp = NULL;
	int err = 0;
	struct task_struct *me = current;

	if (used_math()) {
		fp = get_stack(ka, regs, sizeof(struct _fpstate));
		frame = (void __user *)round_down(
			(unsigned long)fp - sizeof(struct rt_sigframe), 16) - 8;

		if (!access_ok(VERIFY_WRITE, fp, sizeof(struct _fpstate)))
			goto give_sigsegv;

		if (save_i387(fp) < 0)
			err |= -1;
	} else
		frame = get_stack(ka, regs, sizeof(struct rt_sigframe)) - 8;

	if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
		goto give_sigsegv;

	if (ka->sa.sa_flags & SA_SIGINFO) {
		err |= copy_siginfo_to_user(&frame->info, info);
		if (err)
			goto give_sigsegv;
	}

	/* Create the ucontext.  */
	err |= __put_user(0, &frame->uc.uc_flags);
	err |= __put_user(0, &frame->uc.uc_link);
	err |= __put_user(me->sas_ss_sp, &frame->uc.uc_stack.ss_sp);
	err |= __put_user(sas_ss_flags(regs->rsp),
			  &frame->uc.uc_stack.ss_flags);
	err |= __put_user(me->sas_ss_size, &frame->uc.uc_stack.ss_size);
	err |= setup_sigcontext(&frame->uc.uc_mcontext, regs, set->sig[0], me);
	err |= __put_user(fp, &frame->uc.uc_mcontext.fpstate);
	if (sizeof(*set) == 16) {
		__put_user(set->sig[0], &frame->uc.uc_sigmask.sig[0]);
		__put_user(set->sig[1], &frame->uc.uc_sigmask.sig[1]);
	} else
		err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));

	/* Set up to return from userspace.  If provided, use a stub
	   already in userspace.  */
	/* x86-64 should always use SA_RESTORER. */
	if (ka->sa.sa_flags & SA_RESTORER) {
		err |= __put_user(ka->sa.sa_restorer, &frame->pretcode);
	} else {
		/* could use a vstub here */
		goto give_sigsegv;
	}

	if (err)
		goto give_sigsegv;

#ifdef DEBUG_SIG
	printk("%d old rip %lx old rsp %lx old rax %lx\n", current->pid,regs->rip,regs->rsp,regs->rax);
#endif

	/* Set up registers for signal handler */
	regs->rdi = sig;
	/* In case the signal handler was declared without prototypes */
	regs->rax = 0;

	/* This also works for non SA_SIGINFO handlers because they expect the
	   next argument after the signal number on the stack. */
	regs->rsi = (unsigned long)&frame->info;
	regs->rdx = (unsigned long)&frame->uc;
	regs->rip = (unsigned long) ka->sa.sa_handler;

	regs->rsp = (unsigned long)frame;

	/* Set up the CS register to run signal handlers in 64-bit mode,
	   even if the handler happens to be interrupting 32-bit code. */
	regs->cs = __USER_CS;

	/* This, by contrast, has nothing to do with segment registers -
	   see include/asm-x86_64/uaccess.h for details. */
	set_fs(USER_DS);

	regs->eflags &= ~TF_MASK;
	if (test_thread_flag(TIF_SINGLESTEP))
		ptrace_notify(SIGTRAP);
#ifdef DEBUG_SIG
	printk("SIG deliver (%s:%d): sp=%p pc=%p ra=%p\n",
		current->comm, current->pid, frame, regs->rip, frame->pretcode);
#endif

	return 0;

give_sigsegv:
	force_sigsegv(sig, current);
	return -EFAULT;
}

/*
 * OK, we're invoking a handler
 */

static int
handle_signal(unsigned long sig, siginfo_t *info, struct k_sigaction *ka,
		sigset_t *oldset, struct pt_regs *regs)
{
	int ret;

#ifdef DEBUG_SIG
	printk("handle_signal pid:%d sig:%lu rip:%lx rsp:%lx regs=%p\n",
		current->pid, sig,
		regs->rip, regs->rsp, regs);
#endif

	/* Are we from a system call? */
	if ((long)regs->orig_rax >= 0) {
		/* If so, check system call restarting.. */
		switch (regs->rax) {
		        case -ERESTART_RESTARTBLOCK:
			case -ERESTARTNOHAND:
				regs->rax = -EINTR;
				break;

			case -ERESTARTSYS:
				if (!(ka->sa.sa_flags & SA_RESTART)) {
					regs->rax = -EINTR;
					break;
				}
				/* fallthrough */
			case -ERESTARTNOINTR:
				regs->rax = regs->orig_rax;
				regs->rip -= 2;
				break;
		}
	}

	/*
	 * If TF is set due to a debugger (PT_DTRACE), clear the TF
	 * flag so that register information in the sigcontext is
	 * correct.
	 */
	if (unlikely(regs->eflags & TF_MASK)) {
		if (likely(current->ptrace & PT_DTRACE)) {
			current->ptrace &= ~PT_DTRACE;
			regs->eflags &= ~TF_MASK;
		}
	}

#ifdef CONFIG_IA32_EMULATION
	if (test_thread_flag(TIF_IA32)) {
		if (ka->sa.sa_flags & SA_SIGINFO)
			ret = ia32_setup_rt_frame(sig, ka, info, oldset, regs);
		else
			ret = ia32_setup_frame(sig, ka, oldset, regs);
	} else
#endif
	ret = setup_rt_frame(sig, ka, info, oldset, regs);

	if (ret == 0) {
		spin_lock_irq(&current->sighand->siglock);
		sigorsets(&current->blocked,&current->blocked,&ka->sa.sa_mask);
		if (!(ka->sa.sa_flags & SA_NODEFER))
			sigaddset(&current->blocked,sig);
		recalc_sigpending();
		spin_unlock_irq(&current->sighand->siglock);
	}

	return ret;
}

/*
 * Note that 'init' is a special process: it doesn't get signals it doesn't
 * want to handle. Thus you cannot kill init even with a SIGKILL even by
 * mistake.
 */
static void do_signal(struct pt_regs *regs)
{
	struct k_sigaction ka;
	siginfo_t info;
	int signr;
	sigset_t *oldset;

	/*
	 * We want the common case to go fast, which
	 * is why we may in certain cases get here from
	 * kernel mode. Just return without doing anything
	 * if so.
	 */
	if (!user_mode(regs))
		return;

	if (test_thread_flag(TIF_RESTORE_SIGMASK))
		oldset = &current->saved_sigmask;
	else
		oldset = &current->blocked;

	signr = get_signal_to_deliver(&info, &ka, regs, NULL);
	if (signr > 0) {
		/* Reenable any watchpoints before delivering the
		 * signal to user space. The processor register will
		 * have been cleared if the watchpoint triggered
		 * inside the kernel.
		 */
		if (current->thread.debugreg7)
			set_debugreg(current->thread.debugreg7, 7);

		/* Whee!  Actually deliver the signal.  */
		if (handle_signal(signr, &info, &ka, oldset, regs) == 0) {
			/* a signal was successfully delivered; the saved
			 * sigmask will have been stored in the signal frame,
			 * and will be restored by sigreturn, so we can simply
			 * clear the TIF_RESTORE_SIGMASK flag */
			clear_thread_flag(TIF_RESTORE_SIGMASK);
		}
		return;
	}

	/* Did we come from a system call? */
	if ((long)regs->orig_rax >= 0) {
		/* Restart the system call - no handlers present */
		long res = regs->rax;
		switch (res) {
		case -ERESTARTNOHAND:
		case -ERESTARTSYS:
		case -ERESTARTNOINTR:
			regs->rax = regs->orig_rax;
			regs->rip -= 2;
			break;
		case -ERESTART_RESTARTBLOCK:
			regs->rax = test_thread_flag(TIF_IA32) ?
					__NR_ia32_restart_syscall :
					__NR_restart_syscall;
			regs->rip -= 2;
			break;
		}
	}

	/* if there's no signal to deliver, we just put the saved sigmask
	   back. */
	if (test_thread_flag(TIF_RESTORE_SIGMASK)) {
		clear_thread_flag(TIF_RESTORE_SIGMASK);
		sigprocmask(SIG_SETMASK, &current->saved_sigmask, NULL);
	}
}

void
do_notify_resume(struct pt_regs *regs, void *unused, __u32 thread_info_flags)
{
#ifdef DEBUG_SIG
	printk("do_notify_resume flags:%x rip:%lx rsp:%lx caller:%lx pending:%lx\n",
	       thread_info_flags, regs->rip, regs->rsp, __builtin_return_address(0),signal_pending(current));
#endif

	/* Pending single-step? */
	if (thread_info_flags & _TIF_SINGLESTEP) {
		regs->eflags |= TF_MASK;
		clear_thread_flag(TIF_SINGLESTEP);
	}

	/* deal with pending signal delivery */
	if (thread_info_flags & (_TIF_SIGPENDING|_TIF_RESTORE_SIGMASK))
		do_signal(regs);
}

void signal_fault(struct pt_regs *regs, void __user *frame, char *where)
{
	struct task_struct *me = current;
	if (exception_trace)
		printk("%s[%d] bad frame in %s frame:%p rip:%lx rsp:%lx orax:%lx\n",
	       me->comm,me->pid,where,frame,regs->rip,regs->rsp,regs->orig_rax);

	force_sig(SIGSEGV, me);
}


text:
page_type: sample
languages:
- csharp
- cpp
- cppcx
products:
- windows
- windows-uwp
urlFragment: OrientationSensor
extendedZipContent:
- path: SharedContent
  target: SharedContent
- path: LICENSE
  target: LICENSE
description: "Shows how to use the Windows.Devices.Sensors.OrientationSensor API."
---

<!---
  category: DevicesSensorsAndPower
  samplefwlink: http://go.microsoft.com/fwlink/p/?LinkId=620580
--->

# Orientation sensor sample

Shows how to use the [Windows.Devices.Sensors.OrientationSensor](http://msdn.microsoft.com/library/windows/apps/br206371) API.

> **Note:** This sample is part of a large collection of UWP feature samples.
> You can download this sample as a standalone ZIP file
> [from docs.microsoft.com](https://docs.microsoft.com/samples/microsoft/windows-universal-samples/orientationsensor/),
> or you can download the entire collection as a single
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.

This sample allows the user to view the rotation matrix and Quaternion values that reflect the current device orientation.
After choosing the sensor reporting type and optimization goal,
you can choose one of these scenarios:

-   Orientation sensor data events
-   Poll orientation sensor readings
-   Sensor calibration

**Orientation sensor data events**

When you click the **Enable** button for the **Data Events** option, the app begins streaming sensor readings in real time.

**Poll orientation sensor readings**

When you click the **Enable** button for the **Polling** option, the app will retrieve the current sensor readings.

**Sensor calibration**

Allows the user to simulate sensor accuracy and demonstrates usage of the calibration bar.

## Related topics

### Reference

[Windows.Devices.Sensors namespace](http://msdn.microsoft.com/library/windows/apps/br206408)

### Related samples

* [Accelerometer sample](../Accelerometer)
* [OrientationSensor sample](/archived/OrientationSensor/) for JavaScript (archived)

## System requirements

* Windows 10 build 14393

Build the sample
----------------

1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
2. Start Microsoft Visual Studio and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio Solution (.sln) file.
4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.

Run the sample
--------------

The next steps depend on whether you just want to deploy the sample or you want to both deploy and run it.

**Deploying the sample**

1.  Select **Build** \> **Deploy Solution**.

**Deploying and running the sample**

1.  To debug the sample and then run it, press F5 or select **Debug** \> **Start Debugging**. To run the sample without debugging, press Ctrl+F5 or select**Debug** \> **Start Without Debugging**.


text:
export ARGOBALSAM_INSTALL_PATH=FIXME
export ARGOBALSAM_DATA_PATH=$ARGOBALSAM_INSTALL_PATH
export ARGOBALSAM_EXE_PATH=$ARGOBALSAM_INSTALL_PATH/exe

#####
# activate the virtualenv
################################
. $ARGOBALSAM_INSTALL_PATH/argobalsam_env/bin/activate

#####
# setup the certificate info
#######################################
. grid_setup.sh


text:
using System;
using System.Diagnostics;
using System.Threading;

namespace DevExpress.Mvvm.UI.Tests {
    public class AsyncTestFixture {
        public virtual int SecondsTimeout { get { return Debugger.IsAttached ? 180 : 25; } }
        public int MillisecondsTimeout { get { return SecondsTimeout * 1000; } }
        public TimeSpan Timeout { get { return new TimeSpan(0, 0, SecondsTimeout); } }
        public virtual int SecondsTestTimeout { get { return Debugger.IsAttached ? 240 : 120; } }
        public int MillisecondsTestTimeout { get { return SecondsTestTimeout * 1000; } }
        public TimeSpan TestTimeout { get { return new TimeSpan(0, 0, SecondsTestTimeout); } }
        public void WaitOne(WaitHandle waitHandle, int millisecondsTimeout = 0) {
            if(millisecondsTimeout == 0)
                millisecondsTimeout = MillisecondsTimeout;
            if(!waitHandle.WaitOne(millisecondsTimeout))
                throw new TimeoutException();
        }
        public void Join(Thread thread, int millisecondsTimeout = 0) {
            if(millisecondsTimeout == 0)
                millisecondsTimeout = MillisecondsTimeout;
            if(!thread.Join(millisecondsTimeout))
                throw new TimeoutException();
        }
    }
    public abstract class AsyncTestObjectBase {
        public AsyncTestObjectBase(AsyncTestFixture fixture) {
            Fixture = fixture;
        }
        protected AsyncTestFixture Fixture { get; private set; }
    }
}


text:
typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
    RowMatrixXf;

enum BorderType {
  REFLECT = 0,
  REPLICATE = 1,
  DEFAULT = REFLECT
};

// Performs separable convolution using two filters of the same size.
void SeparableConvolution2d(const RowMatrixXf& image,
                            const Eigen::RowVectorXf& kernel_x,
                            const Eigen::RowVectorXf& kernel_y,
                            const BorderType& border_type,
                            RowMatrixXf* out);

// Computes the image derivative using the Scharr filter.
void ScharrDerivative(const RowMatrixXf& image,
                      const int x_deg,
                      const int y_deg,
                      const int size,
                      const bool normalize,
                      RowMatrixXf* out);

void GaussianBlur(const RowMatrixXf& image,
                  const double sigma,
                  RowMatrixXf* out);

#endif  // CONVOLUTION_H_


text:
{% method %}
## List available local numbers
Search for available local numbers by location or pattern criteria.

For more information about Bandwidth's local phone numbers, see the FAQ

### Request URL

GET`https://api.catapult.inetwork.com/v1/availableNumbers/local?<queryParams>`

---

### Supported Parameters

| Parameter          | Description                                                                                | Mandatory |
|:-------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------|
| city               | A city name.                                                                                | No        |
| state              | A two-letter US state abbreviation ("CA" for California).                                                                                | `**`      |
| zip                | A 5-digit US ZIP code.                                                                                | `**`      |
| areaCode           | A 3-digit telephone area code.                                                                                | `**`      |
| localNumber        | The digits of a telephone number following an area code for filtering the results. Must be at least 3 digits and the areaCode field must be filled in the request.   | `***`     |
| inLocalCallingArea | Boolean value (true or false, default=false) to indicate whether to include phone numbers not in the localNumber that are in a local rate center. Only applied when localNumber is defined.                                                                                | `***`     |
| quantity           | The maximum number of numbers to return (default 10, maximum 5000).                                                                                | No        |
| pattern            | A number pattern that may include letters, digits, and the following wildcard characters:
 - `?` : matches any single digit
 - `*` : matches zero or more digits
 Don't forget to encode wildcard characters in the requested URL. | No        |

** You must choose one of state, zip, or areaCode in request.
** state, zip and areaCode are mutually exclusive, you may use only one of them per request.

*** localNumber and inLocalCallingArea only applies for searching numbers in specific areaCode.

## Properties

| Property       | Description                                                                                |
|:---------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| number         | The telephone number in E.164 format.                                                                                |
| nationalNumber | The telephone number in a friendly national format.                                                                                |
| patternMatch   | The telephone number in a friendly national format with some numbers replaced by letters if a pattern was used to search the number.                                                 |
| city           | The city of the phone number.                                                                                |
| lata           | Local access and transport area (LATA), represents an area within which a regional operating company is permitted to offer exchange telecommunications and exchange access services. |
| rateCenter     | The rate center is a term used to identify a telephone local exchange service area.                                                                                |
| state          | The state of the phone number.                                                                                |
| price          | The monthly price for the phone number.                                                                                |

{% common %}
### Example 1 of 2: Search for 3 numbers in the 910 area code

> To find up to three available local numbers in the area code 910 make the following request:

{% sample lang="bash" %}

```bash
curl -v -X GET "https://api.catapult.inetwork.com/v1/availableNumbers/local?areaCode=910&quantity=3" -u {token}:{secret}
```

{% sample lang="js" %}

```js
// Search 3 available local phone numbers with area code 910

// Promise
client.AvailableNumber.search("local", { areaCode : "910", quantity : 3 }).then(function (numbers) {});

// Callback
client.AvailableNumber.search("local", { areaCode : "910", quantity : 3 }, function (err, numbers) {});
```

{% sample lang="csharp" %}

```csharp
var results = await client.AvailableNumber.SearchLocalAsync(new LocalNumberQuery{ AreaCode = "910", Quantity = 3});
var first = results.First();
Console.WriteLine($"{first.Number} - {first.State}");
// +1234567890 - NC
```

{% sample lang="ruby" %}

```ruby
results = AvailableNumber.search_local(client, {:area_code => "910", :quantity => 3})
first_result = results.next
first_number = first_result[:number]
```

{% common %}
> The above command returns JSON structured like this:

```json
[
  {
    "number": "{number1}",
    "nationalNumber": "{national_number1}",
    "patternMatch": "          2 9 ",
    "city": "CARY",
    "lata": "426",
    "rateCenter": "CARY",
    "state": "NC",
    "price": "0.60"
  },
  {
    "number": "{number2}",
    "nationalNumber": "{national_number2}",
    "patternMatch": "          2 9 ",
    "city": "CARY",
    "lata": "426",
    "rateCenter": "CARY",
    "state": "NC",
    "price": "0.60"
  }
]
```

### Example 2 of 2: Search for City/State and Pattern

>To find up to two available local numbers in the city of Cary, North Carolina, that match the pattern "*2?9*", make the following request:

{% sample lang="bash" %}

```bash
curl -v -X GET "https://api.catapult.inetwork.com/v1/availableNumbers/local?city=Cary&state=NC&pattern=*2%3F9*&quantity=2" -u {token}:{secret} -H "Content-type: application/json"
```

{% sample lang="js" %}

```js

// Promise
client.AvailableNumber.search("local", {
  city : "Cary",
  state : "NC",
  pattern: "*2?9*",
  quantity : 2 })
.then(function (numbers) {});

// Callback
client.AvailableNumber.search("local", {
  city : "Cary",
  state : "NC",
  pattern: "*2?9*",
  quantity : 2 }
 , function (err, numbers) {});
```

{% sample lang="csharp" %}

```csharp
var results = await client.AvailableNumber.SearchLocalAsync(
  new LocalNumberQuery{
    City = "Cary",
    State = "NC",
    Pattern = "*2?9*",
    Quantity = 2
  }
);
var first = results.First();
Console.WriteLine($"{first.Number} - {first.State}");
// +1234567890 - NC
```

{% sample lang="ruby" %}

```ruby
results = AvailableNumber.search_local(client, {
  :city => "Cary",
  :state => "NC",
  :pattern => "*2?9*",
  :quantity => 2
})
first_result = results.next
first_number = first_result[:number]
```
{% common %}
> The above command returns JSON structured like this:

```json
[
    {
        "number": "{number1}",
        "nationalNumber": "{national_number1}",
        "city": "RALEIGH",
        "rateCenter": "RALEIGH",
        "state": "NC",
        "price": "0.60"
    },
    {
        "number": "{number2}",
        "nationalNumber": "{national_number2}",
        "city": "RALEIGH",
        "rateCenter": "RALEIGH",
        "state": "NC",
        "price": "0.60"
    }
]
```
{% endmethod %}


text:
<?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::get('aspirante', function () {
    return redirect('/');
});

Route::any('soap/wsPrimerIngreso', 'SoapController@wsPrimerIngreso');

//Route::any('soap/wsPrimerIngreso', 'SoapController@wsPrimerIngreso');

/*Route::get('soap/wsPrimerIngresox', function () {

//<VERIFICAR_PE>
//        <USR>usuario</USR>
//        <PWD>contraseña</PWD>//Este usuario y contraseña es para uso de ustedes, y ustedes nos dan las credenciales para consumirlo.
//        <NOV>2011026874</NOV>
//        <UA>05</UA>
//        <EXT>00</EXT>
//        <CAR>01</CAR>
//        <CICLO>2016</CICLO>
//</VERIFICAR_PE>

    $respuesta = verificar_prueba_especifica_str(
        [
            'VERIFICAR_PE' => [
            'USR' => '10006',
            'PWD' => '123123',
            'NOV' => '1000000004',
            'CUI' => '1234567789012',
            'UA' => '02',
            'EXT' => '00',
            'CAR' => '01',
            'CICLO' => '2016'
        ]
    ]);

    return view('welcome2',compact('respuesta'));
});
//*/

Route::group(['prefix' => 'aspirante'], function () {

    Route::group(['middleware' => 'admin', 'prefix' => 'admin'], function () {
        //Authentication Routes...
        $this->get('login', 'AuthAdmin\AuthController@showLoginForm')->name('admin.login');
        $this->post('login', 'AuthAdmin\AuthController@login')->name('admin.login');
        $this->get('logout', 'AuthAdmin\AuthController@logout')->name('admin.logout');

        Route::group(['middleware' => ['auth:admin']], function () {

            Route::group(['middleware' => ['adminRol:directores']], function () {
                //********** RUTAS DE DIRECTORES DE ESCUELA*************
                Route::get('escuela/primerIngreso', 'AnioController@indexPrimerIngreso')->name('admin.escuela.primerIngreso');
                Route::post('escuela/primerIngreso/guardarCupo', 'AnioController@guardarCupo')->name('admin.escuela.primerIngreso.guardarCupo');
                Route::get('escuela/primerIngreso/nuevo', 'AnioController@nuevoAnio')->name('admin.escuela.primerIngreso.nuevo');
                Route::get('escuela/primerIngreso/listado', 'AnioController@getListado')->name('admin.escuela.primerIngreso.listado');

            });

            Route::get('/', function () {
                return view('admin.index');
            })->name('admin.index');
            Route::resource('/conf', 'AdminController');

            Route::group(['middleware' => ['adminRol:jefe_bienestar']], function () {

                Route::resource('aplicacion', 'AplicacionController');
                Route::get('aplicacion/{aplicacion_id}/arte', 'AplicacionController@getArte')->name('admin.aplicacion.arte');
                Route::get('aplicacion/{aplicacion_id}/especial', 'AplicacionController@getCrearEspecial')->name('admin.aplicacion.especial');

                Route::get('aplicacion/{aplicacion_id}/actas', 'AplicacionController@getActas')->name('admin.aplicacion.actas');
                Route::get('aplicacion/{aplicacion_id}/listados', 'AplicacionController@getListados')->name('admin.aplicacion.listados');
                Route::get('aplicacion/{aplicacion_id}/listadoGeneral', 'AplicacionController@getListadoGeneral')->name('admin.aplicacion.listadoGeneral');
                Route::get('aplicacion/{aplicacion_id}/habilitar', 'AplicacionController@habilitarResultados')->name('admin.aplicacion.habilitar');
                Route::post('aplicacion/notificar','AplicacionController@notificar')->name('admin.aplicacion.notificar');

                Route::resource('aspirantes','ListaNegraController');
                Route::get('CasosEspeciales','ListaNegraController@getListaNegra')->name('admin.listaNegra');
                Route::get('CasosEspeciales/{search}','ListaNegraController@listaNegraShow')->name('admin.listaNegra.search');
                Route::resource('aplicacion/subirResultados','AspiranteAplicacionController',['only' => [
                    'edit','update'
                ]]);
                Route::post('aplicacion/subirResultados/{aplicacion_id}/percentiles','AplicacionController@actualizarPercentiles')->name('admin.aplicacion.percentiles');
                Route::get('aplicacion/plantilla/resultados','AspiranteAplicacionController@descargarPlantillaResultados')->name('admin.aplicacion.plantillaResutlados');

                //Route::resource('datos','DatosController');
                Route::post('datos/insert','DatosController@insert')->name('admin.datos.insert');
                Route::get('datos/create','DatosController@create')->name('admin.datos.create');
                Route::get('datos/insert/search','DatosController@search')->name('admin.datos.search');

                Route::get('acta/{aplicacion_id}/irregular','ActaController@getReporteIrregular')->name('admin.acta.irregular');
                Route::post('acta/{aspirante_aplicacion_id}/resultado','AspiranteAplicacionController@cambiarIrregularAprobado')->name('admin.acta.resultado');

                //recursos
                Route::get('recursos','RecursosController@index')->name('admin.recursos');
                Route::post('recursos/reglamento','RecursosController@postReglamento')->name('admin.recursos.reglamento');
                Route::post('recursos/imagenInformativa','RecursosController@postImagenInformativa')->name('admin.recursos.imagenInformativa');
                Route::post('recursos/videoBienvenida','RecursosController@postBienvenida')->name('admin.recursos.bienvenida');
                Route::post('recursos/guia-asignacion','RecursosController@postGuiaAsignacion')->name('admin.recursos.guia-asignacion');
                Route::post('recursos/video-disenio','RecursosController@postVideoDisenio')->name('admin.recursos.video-disenio');
                Route::post('recursos/video-arqui','RecursosController@postVideoArqui')->name('admin.recursos.video-arqui');
                Route::post('recursos/guia-aplicacion','RecursosController@postGuiaAplicacion')->name('admin.recursos.guia-aplicacion');
                Route::post('recursos/inicioCarousel','RecursosController@postAddToCarousel')->name('admin.recursos.postAddToCarousel');
                Route::post('recursos/inicioImgInfoDisenio','RecursosController@postImgInfoDisenio')->name('admin.recursos.postImgInfoDisenio');
                Route::post('recursos/inicioImgInfoArqui','RecursosController@postImgInfoArqui')->name('admin.recursos.postImgInfoArqui');
                Route::get('recursos/inicioCarousel/{img_pos}','RecursosController@BorImgCarrousel')->name('admin.recursos.BorImgCarrousel');
                Route::post('recursos/pensum_disenio','RecursosController@postPensumDisenio')->name('admin.recursos.pensum_disenio');
                Route::post('recursos/pensum_arqui','RecursosController@postPensumArqui')->name('admin.recursos.pensum_arqui');

                Route::get('reportes', 'reportesController@index')->name('admin.reportes.index');
                Route::get('reportes/general', 'reportesController@reporteGeneral')->name('admin.reportes.reporteGeneral');

            });

            Route::group(['middleware' => ['adminRol:secretario_decano_jefe_bienestar']], function () {
                Route::resource('acta', 'ActaController');
                Route::get('acta/search/{aplicacion_id}', 'ActaController@getQueryActas')->name('admin.acta.search');
                Route::get('acta/info/{acta_id}', 'ActaController@getInfoActa')->name('admin.acta.info');
                Route::get('acta/getAplicacionesAnio/{anio}','AplicacionController@getAplicacionesAnio')->name('admin.acta.getAplicacionesAnio');
                Route::get('acta/{acta_id}/constanciasSatisfactorias', 'ActaController@getConstanciasSatisfactorias')->name('admin.acta.constanciasSatisfactorias');
            });

            Route::group(['middleware' => ['adminRol:superadmin']], function () {
                Route::get('usuarios/adminsEliminados','GestionUsuariosController@adminsEliminados')->name('admin.usuarios.adminsEliminados');
                Route::get('usuarios/adminsEliminados/restore/{id}','GestionUsuariosController@restoreAdmin')->name('admin.usuarios.adminsEliminados.restoreAdmin');
                Route::resource('usuarios','GestionUsuariosController');

                Route::post('datos','DatosController@store')->name('admin.datos');
                Route::get('datos','DatosController@index')->name('admin.datos');
                Route::get('datos/plantilla','DatosController@descargarPlantilla')->name('admin.datos.plantilla');
                Route::get('notificar','AnioController@index')->name('admin.notificar');
                Route::get('notificar/listado','AnioController@generarListado')->name('admin.notificar.listado');
                Route::get('notificar/enviar','AnioController@enviarEscuela')->name('admin.notificar.enviar');
            });

        });
    });

});

Route::group(['middleware' => 'aspirante_web'], function () {
    Route::post('password/sendResetLink','Auth\PasswordController@sendResetLink')->name('aspirante.sendResetLink');//componer rutas
    Route::get('activation/{token}', 'Auth\AuthController@activateUser')->name('aspirante.activate');//componer correo

    /** auth routes equivalentes a Route::auth(); **/
    Route::get('login', 'Auth\AuthController@showLoginForm')->name('aspirante.login');
    Route::post('login', 'Auth\AuthController@login')->name('aspirante.login');
    Route::get('logout', 'Auth\AuthController@logout')->name('aspirante.logout');

    Route::get('register', 'Auth\AuthController@showRegistrationForm')->name('aspirante.register');
    Route::post('register', 'Auth\AuthController@register')->name('aspirante.register');

    Route::get('aspirante/password/reset/{token?}', 'Auth\PasswordController@showResetForm')->name('aspirante.password.reset');
    Route::post('password/email', 'Auth\PasswordController@sendResetLinkEmail')->name('aspirante.password.email');
    Route::post('password/reset', 'Auth\PasswordController@reset')->name('aspirante.password.reset');
    //fin auth

    Route::get('/', 'HomeController@index')->name('aspirante.home');

    //recursos del aspirante
    Route::get('recursos/imagenInformativa', 'RecursosController@viewImagenInformativa')->name('aspirante.recursos.imagenInformativa');
    Route::get('recursos/reglamento', 'RecursosController@getReglamento')->name('aspirante.recursos.reglamento');
    Route::get('recursos/pensum_disenio', 'RecursosController@getPensumDisenio')->name('aspirante.recursos.pensum_disenio');
    Route::get('recursos/pensum_arqui', 'RecursosController@getPensumArqui')->name('aspirante.recursos.pensum_arqui');
    Route::get('recursos/guia-asignacion', 'RecursosController@viewGuiaAsignacion')->name('aspirante.recursos.guia-asignacion');
    Route::get('recursos/guia-aplicacion', 'RecursosController@viewGuiaAplicacion')->name('aspirante.recursos.guia-aplicacion');

    Route::group(['middleware' => ['auth:aspirante_web']], function () {
        Route::get('configuracion', function () {
            return view('aspirante.configurarCuenta');
        })->name('aspirante.configuracion');
        Route::post('configuracion/guardar', "AspiranteController@actualizarCuenta")->name('aspirante.configuracion.guardar');
        Route::resource('datos', 'AspiranteController');
        Route::resource('formulario', 'formularioController');
        Route::get('actualizarCUI', 'formularioController@actualizarCUI');
        Route::post('actualizarCUI', 'formularioController@storeCUI');
        Route::get('aprobados', 'formularioController@getConfirmacion');
        Route::post('formulario/{formulario_id}/confirmar', 'formularioController@confirmarIntereses')->name('aspirante.formulario.confirmar');
        Route::resource('PruebaEspecifica', 'AspiranteAplicacionController', ['only' => [
            'create','store','show'
        ]]);

    });
});


text:
/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes} checked by tsc
 */
goog.module('test_files.namespaced.user');var module = module || {id: 'test_files/namespaced/user.js'};
var export_namespace_1 = goog.require('test_files.namespaced.export_namespace');
const tsickle_forward_declare_1 = goog.forwardDeclare("test_files.namespaced.export_namespace");
const /** @type {?} */ x = new export_namespace_1.valueNamespace.ValueClass();
let /** @type {?} */ y;


text:
package util

import (
	"fmt"
	"time"

	"k8s.io/apimachinery/pkg/api/errors"
	pkgruntime "k8s.io/apimachinery/pkg/runtime"
	kubeclientset "k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
)

// Type of the operation that can be executed in Federated.
type FederatedOperationType string

const (
	OperationTypeAdd    = "add"
	OperationTypeUpdate = "update"
	OperationTypeDelete = "delete"
)

// FederatedOperation definition contains type (add/update/delete) and the object itself.
type FederatedOperation struct {
	Type        FederatedOperationType
	ClusterName string
	Obj         pkgruntime.Object
}

// A helper that executes the given set of updates on federation, in parallel.
type FederatedUpdater interface {
	// Executes the given set of operations within the specified timeout.
	// Timeout is best-effort. There is no guarantee that the underlying operations are
	// stopped when it is reached. However the function will return after the timeout
	// with a non-nil error.
	Update([]FederatedOperation, time.Duration) error

	UpdateWithOnError([]FederatedOperation, time.Duration, func(FederatedOperation, error)) error
}

// A function that executes some operation using the passed client and object.
type FederatedOperationHandler func(kubeclientset.Interface, pkgruntime.Object) error

type federatedUpdaterImpl struct {
	federation FederationView

	addFunction    FederatedOperationHandler
	updateFunction FederatedOperationHandler
	deleteFunction FederatedOperationHandler
}

func NewFederatedUpdater(federation FederationView, add, update, del FederatedOperationHandler) FederatedUpdater {
	return &federatedUpdaterImpl{
		federation:     federation,
		addFunction:    add,
		updateFunction: update,
		deleteFunction: del,
	}
}

func (fu *federatedUpdaterImpl) Update(ops []FederatedOperation, timeout time.Duration) error {
	return fu.UpdateWithOnError(ops, timeout, nil)
}

func (fu *federatedUpdaterImpl) UpdateWithOnError(ops []FederatedOperation, timeout time.Duration, onError func(FederatedOperation, error)) error {
	done := make(chan error, len(ops))
	for _, op := range ops {
		go func(op FederatedOperation) {
			clusterName := op.ClusterName

			// TODO: Ensure that the clientset has reasonable timeout.
			clientset, err := fu.federation.GetClientsetForCluster(clusterName)
			if err != nil {
				done <- err
				return
			}

			switch op.Type {
			case OperationTypeAdd:
				err = fu.addFunction(clientset, op.Obj)
			case OperationTypeUpdate:
				err = fu.updateFunction(clientset, op.Obj)
			case OperationTypeDelete:
				err = fu.deleteFunction(clientset, op.Obj)
				// IsNotFound error is fine since that means the object is deleted already.
				if errors.IsNotFound(err) {
					err = nil
				}
			}
			if err != nil && onError != nil {
				onError(op, err)
			}
			done <- err
		}(op)
	}
	start := time.Now()
	for i := 0; i < len(ops); i++ {
		now := time.Now()
		if !now.Before(start.Add(timeout)) {
			return fmt.Errorf("failed to finish all operations in %v", timeout)
		}
		select {
		case err := <-done:
			if err != nil {
				return err
			}
		case <-time.After(start.Add(timeout).Sub(now)):
			return fmt.Errorf("failed to finish all operations in %v", timeout)
		}
	}
	// All operations finished in time.
	return nil
}