text:
package es.gob.afirma.keystores.filters;

import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import es.gob.afirma.core.keystores.KeyStoreManager;

/** Filtro para certificados. Debe autocontener toda la lógica que indique si un
 * certificado cumple o no las condiciones del filtro.
 * El establecimiento de los datos encesarios para las condiciones de filtrado queda fuera
 * del interfaz y debe ser específico para cada implementación.
 * @author Tomás García-Merás */
public abstract class CertificateFilter {

    /** Comprueba si un certificado se adecúa al filtro
     * @param cert Certificado a comprobar
     * @return true si el certificado se adecúa al filtro, false en caso contrario
     */
    public abstract boolean matches(final X509Certificate cert);

    /** Obtiene los alias de certificados de un listado que cumplen con un determinado criterio. Por defecto,
     * el establecido en el método {@link #matches(X509Certificate)}.
     * @param aliases Listado de alias de certificados.
     * @param ksm AOKeyStoreManager que contiene los certificados cuyos
     *            alias se indican.
     * @return Alias de certificados que cumplen el criterio. */
    public String[] matches(final String[] aliases, final KeyStoreManager ksm) {
        final List<String> filteredAliases = new ArrayList<String>();
        for (final String alias : aliases) {
            if(matches(ksm.getCertificate(alias))) {
                filteredAliases.add(alias);
            }
        }
        return filteredAliases.toArray(new String[filteredAliases.size()]);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace neurosim
{
	public class CountDownChart : NetworkChart
	{
		protected Color[] countDownColor = new Color[]
		{
			Color.FromArgb(0, 0, 0),		  // 0
			Color.FromArgb(64, 0, 0),    // 1
			Color.FromArgb(128, 0, 0),    // 2
			Color.FromArgb(192, 0, 0),    // 3
			Color.FromArgb(255, 64, 0),    // 4
			Color.FromArgb(255, 128, 0),    // 5
			Color.FromArgb(255, 192, 0),	  // 6
			Color.FromArgb(255, 255, 64),	  // 7
			Color.FromArgb(255, 255, 128),    // 8
			Color.FromArgb(255, 255, 192),    // 9
			Color.FromArgb(255, 255, 255),	  // 10
		};

		public override bool Draw(FastPixel fp, Graphics gr, List<NeuronPlot> plots)
		{
			fp.Clear(Color.Black);

			foreach (NeuronPlot np in plots)
			{
				ShowNeuronBasedOnFiredCountDown(fp, np);
			}

			return true;
		}

		protected void ShowNeuronBasedOnFiredCountDown(FastPixel fp, NeuronPlot np)
		{
			if (np.Neuron.ActionState == Neuron.State.Firing)
			{
				np.FiredCountDown = 11;
			}

			if (np.FiredCountDown > 0)
			{
				--np.FiredCountDown;
				Color color = countDownColor[np.FiredCountDown];
				Plot(fp, np.Location, color);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2017 Google Inc.
//
// 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.

import {CircuitShaders} from "src/circuit/CircuitShaders.js"
import {Config} from "src/Config.js"
import {Controls} from "src/circuit/Controls.js"
import {CustomGateSet} from "src/circuit/CustomGateSet.js"
import {DetailedError} from "src/base/DetailedError.js"
import {equate_Maps} from "src/base/Equate.js";
import {Gate} from "src/circuit/Gate.js"
import {GateColumn} from "src/circuit/GateColumn.js"
import {GateShaders} from "src/circuit/GateShaders.js"
import {Gates, INITIAL_STATES_TO_GATES} from "src/gates/AllGates.js"
import {Point} from "src/math/Point.js"
import {seq, Seq} from "src/base/Seq.js"
import {Util} from "src/base/Util.js"

/**
 * Defines a circuit layout, with wires and columns and gates.
 * Also exposes utility methods for querying useful facts about the layout (e.g. disabled gates).
 *
 * Doesn't compute any amplitudes or probabilities or other possibly-time-dependent stuff. See CircuitStats for that.
 */
class CircuitDefinition {
    /**
     * @param {!int} numWires
     * @param {!Array.<!GateColumn>} columns
     * @param {undefined|!int=} outerRowOffset
     * @param {undefined|!Map.<!string, *>=} outerContext
     * @param {!CustomGateSet} customGateSet
     * @param {!boolean} isNested
     * @param {!Map.<!int, !string>} customInitialValues
     */
    constructor(numWires,
                columns,
                outerRowOffset=0,
                outerContext=new Map(),
                customGateSet=new CustomGateSet(),
                isNested=false,
                customInitialValues=new Map()) {
        if (numWires < 0) {
            throw new DetailedError("Bad numWires", {numWires})
        }
        if (!Array.isArray(columns)) {
            throw new DetailedError("Bad columns", {numWires, columns})
        }
        if (!columns.every(e => e instanceof GateColumn)) {
            throw new DetailedError("Not a GateColumn", {columns})
        }
        if (!columns.every(e => e.gates.length === numWires)) {
            throw new DetailedError("Wrong gate count in a column", {numWires, columns})
        }

        /** @type {!int} */
        this.numWires = numWires;
        /** @type {!Array.<!GateColumn>} */
        this.columns = columns;
        /** @type {!CustomGateSet} */
        this.customGateSet = customGateSet;

        this.outerRowOffset = outerRowOffset;
        this.outerContext = outerContext;
        this.isNested = isNested;
        /** @type {!Map.<!int, !string>} */
        this.customInitialValues = new Map();
        for (let [k, v] of customInitialValues.entries()) {
            if (!Number.isInteger(k) || k < 0) {
                throw new DetailedError('Initial state key out of range.', {customInitialValues, numWires});
            }
            if (k >= this.numWires) {
                continue;
            }
            this.customInitialValues.set(k, v);
        }

        /**
         * @type {!Array.<!Array.<undefined|!string>>}
         * @private
         */
        this._colRowDisabledReason = [];
        /**
         * @type {!Array.<undefined|!int>}
         * @private
         */
        this._measureMasks = [0];
        let mask = 0;
        let prevStickyCtx = new Map();
        for (let col of columns) {
            let {allReasons: rowReasons, stickyCtx} = col.perRowDisabledReasons(
                mask,
                outerRowOffset,
                outerContext,
                prevStickyCtx,
                isNested);
            mask = col.nextMeasureMask(mask, rowReasons);
            this._colRowDisabledReason.push(rowReasons);
            this._measureMasks.push(mask);
            prevStickyCtx = stickyCtx;
        }

        /**
         * @type {!Map.<!string, !{col: !int, row: !int, gate: !Gate}>}
         * @private
         */
        this._gateSlotCoverMap = this._computeGateSlotCoverMap();

        /**
         * @type {!Map.<!string, !Array.<!Map.<!string, *>>>}
         * @private
         */
        this._cachedColumnContexts = new Map();
    }

    /**
     * @returns {!int}
     */
    gateWeight() {
        return seq(this.columns).
            flatMap(e => e.gates).
            filter(e => e !== undefined).
            map(e => e.knownCircuit === undefined ? 1 : e.knownCircuit.gateWeight()).
            sum();
    }

    /**
     * @returns {!boolean}
     */
    hasControls() {
        return !this.columns.every(e => !e.hasControl(-1));
    }

    /**
     * @param {!int} wire
     * @returns {!CircuitDefinition}
     */
    withSwitchedInitialStateOn(wire) {
        let m = new Map([...this.customInitialValues.entries()]);
        let v = m.get(wire);
        let cycle = [...INITIAL_STATES_TO_GATES.keys()];
        let newVal = cycle[(cycle.indexOf(v) + 1) % cycle.length];
        if (newVal === undefined) {
            m.delete(wire);
        } else {
            m.set(wire, newVal);
        }
        return this.withInitialStates(m);
    }

    /**
     * @param {!Map.<!int, *>} map
     * @returns {!CircuitDefinition}
     */
    withInitialStates(map) {
        return new CircuitDefinition(
            this.numWires,
            this.columns,
            this.outerRowOffset,
            this.outerContext,
            this.customGateSet,
            this.isNested,
            map);
    }

    /**
     * @returns {!boolean}
     */
    hasOnlyUnitaryGates() {
        return this.columns.every(e => e.indexOfNonUnitaryGate() === undefined);
    }

    /**
     * @returns {!boolean}
     */
    hasNonControlGates() {
        let colHasNonControl = col => !col.gates.every(e => e === undefined || e.isControl());
        return !this.columns.every(e => !colHasNonControl(e));
    }

    /**
     * @param {!int} max
     * @returns {!int}
     */
    countGatesUpTo(max) {
        let n = 0;
        for (let c of this.columns) {
            for (let g of c.gates) {
                if (g !== undefined) {
                    n++;
                    if (n >= max) {
                        return n;
                    }
                }
            }
        }
        return n;
    }

    /**
     * @returns {!Set.<!String>}
     */
    getUnmetContextKeys() {
        let result = new Set();
        for (let c = 0; c < this.columns.length; c++) {
            let col = this.columns[c];
            let ctx = this.colCustomContextFromGates(c, 0);
            for (let gate of col.gates) {
                for (let key of gate === undefined ? [] : gate.getUnmetContextKeys()) {
                    let altKey = key.
                        replace('Input Range ', 'Input Default ').
                        replace('Input NO_DEFAULT Range ', 'Input Range ');
                    if (!ctx.has(key) && !ctx.has(altKey)) {
                        result.add(key);
                    }
                }
            }
        }
        return result;
    }

    /**
     * @param {!int} outerRowOffset
     * @param {!Map.<!string, *>} outerContext
     * @returns {!CircuitDefinition}
     */
    withDisabledReasonsForEmbeddedContext(outerRowOffset, outerContext) {
        return new CircuitDefinition(
            this.numWires,
            this.columns,
            outerRowOffset,
            outerContext,
            this.customGateSet,
            true,
            this.customInitialValues);
    }

    /**
     * @returns {!Map.<!string, !{col: !int, row: !int, gate: !Gate}>}
     * @private
     */
    _computeGateSlotCoverMap() {
        let result = new Map();
        for (let col = 0; col < this.columns.length; col++) {
            for (let row = 0; row < this.numWires; row++) {
                let gate = this.columns[col].gates[row];
                if (gate !== undefined) {
                    for (let i = 0; i < gate.width; i++) {
                        for (let j = 0; j < gate.height; j++) {
                            result.set((col+i)+":"+(row+j), {col, row, gate});
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * @returns {!boolean}
     */
    isEmpty() {
        return this.columns.length === 0;
    }

    /**
     * @param {*} other
     * @returns {!boolean}
     */
    isEqualTo(other) {
        if (this === other) {
            return true;
        }
        return other instanceof CircuitDefinition &&
            this.numWires === other.numWires &&
            seq(this.columns).isEqualTo(seq(other.columns), Util.CUSTOM_IS_EQUAL_TO_EQUALITY) &&
            equate_Maps(this.customInitialValues, other.customInitialValues);
    }

    /**
     * @returns {!string}
     */
    toString() {
        let wire = n => "─".repeat(n);
        let wireAround = (n, s) =>
            wire(Math.floor(n - s.length)/2) +
            s +
            wire(Math.ceil(n - s.length)/2);
        let colWidths = Seq.range(this.columns.length).
            map(c => seq(this.columns[c].gates).map(e => e === undefined ? 0 : e.serializedId.length).max()).
            toArray();
        return `CircuitDefinition (${this.numWires} wires, ${this.columns.length} cols):\n\t` +
            Seq.range(this.numWires).
                map(r => wire(1) + Seq.range(this.columns.length).
                    map(c => {
                        let g = this.columns[c].gates[r];
                        let label = g === undefined ? "" : g.serializedId;
                        return wireAround(colWidths[c], label);
                    }).
                    join(wire(1)) + wire(1)).
                join('\n\t');
    }

    /**
     * This mainly exists for writing tests that are understandable.
     * @param {!string} diagram
     * @param {!Map.<!string, !Gate|!{ofSize: !function(!int) : !Gate}>} gateMap
     * @returns {!CircuitDefinition}
     */
    static fromTextDiagram(gateMap, diagram) {
        let lines = seq(diagram.split('\n')).map(e => e.trim()).filter(e => e !== '').toArray();
        if (seq(lines.map(e => e.length)).distinct().count() > 1) {
            throw new DetailedError("Uneven diagram", {diagram});
        }

        let rowCount = lines.length;
        let colCount = lines.length > 0 ? lines[0].length : 0;

        let spanAt = (col, row) => {
            for (let d = 1; row + d < lines.length; d++) {
                if (gateMap.get(lines[row + d][col]) !== null) {
                    return d;
                }
            }
            return lines.length - row;
        };

        return new CircuitDefinition(
            rowCount,
            Seq.range(colCount).
                map(col => new GateColumn(seq(lines).mapWithIndex((line, row) => {
                    let char = line[col];
                    if (!gateMap.has(char)) {
                        throw new DetailedError("Unspecified gate", {char});
                    }
                    let gateOrFamily = gateMap.get(char);
                    if (gateOrFamily === null || gateOrFamily === undefined) {
                        return undefined;
                    }
                    if (gateOrFamily.hasOwnProperty('ofSize')) {
                        return gateOrFamily.ofSize(spanAt(col, row));
                    }
                    if (gateOrFamily instanceof Gate) {
                        return gateOrFamily;
                    }

                    throw new DetailedError("Not a gate", gateOrFamily);
                }).toArray())).
                toArray());
    }

    /**
     * @returns {Infinity|!number}
     */
    stableDuration() {
        return seq(this.columns).
            flatMap(c => c.gates).
            filter(g => g !== undefined).
            map(g => g.stableDuration()).
            min(Infinity);
    }

    /**
     * Returns a munged compact text representation of the circuit.
     *
     * The text isn't intended to be particularly understandable, but it should vaguely reflect or at least
     * distinguish the circuit from others when skimming a list of hashes (e.g. links in browser history).
     *
     * @returns {!string}
     */
    readableHash() {
        let allGates = seq(this.columns)
            .flatMap(e => e.gates)
            .filter(e => e !== undefined)
            .map(e => e.symbol)
            .toArray();
        if (allGates.length === 0) {
            return Config.EMPTY_CIRCUIT_TITLE;
        }
        let allGatesString = `${this.numWires} wires, ${allGates.length} ops, ${allGates.join("").split("^").join("")}`;
        if (allGatesString.length <= 40) {
            return allGatesString;
        }
        return allGatesString.substring(0, 40) + `…`;
    }

    /**
     * @param {!Array.<!GateColumn>} cols
     * @returns {!CircuitDefinition}
     */
    withColumns(cols) {
        return new CircuitDefinition(
            this.numWires,
            cols,
            this.outerRowOffset,
            this.outerContext,
            this.customGateSet,
            false,
            this.customInitialValues);
    }

    /**
     * @returns {!Set.<!int>}
     * @private
     */
    _usedColumns() {
        let usedCols = new Set();
        for (let col = 0; col < this.columns.length; col++) {
            for (let i = 0; i < this.columns[col].maximumGateWidth(); i++) {
                usedCols.add(col+i);
            }
        }
        return usedCols;
    }

    /**
     * @param {!int} col
     * @param {!int} row
     * @param {!int} width
     * @param {!int} height
     * @returns {undefined|!{col: !int, row: !int}}
     * @private
     */
    _findWidthWiseOverlapInRect(col, row, width, height) {
        for (let i = 1; i < width && col + i < this.columns.length; i++) {
            for (let j = 0; j < height; j++) {
                let otherGate = this.findGateCoveringSlot(col+i, row+j);
                if (otherGate === undefined || otherGate.col === col) {
                    continue;
                }
                return {col: otherGate.col, row: otherGate.row};
            }
        }
        return undefined;
    }

    /**
     * @returns {!CircuitDefinition}
     */
    withWidthOverlapsFixed() {
        let newCols = [];
        for (let col = 0; col < this.columns.length; col++) {
            let paddingRequired = Seq.range(this.numWires).map(row => {
                let gate = this.columns[col].gates[row];
                if (gate === undefined) {
                    return 0;
                }
                let f = this._findWidthWiseOverlapInRect(col, row, gate.width, gate.height);
                if (f === undefined) {
                    return 0;
                }
                return gate.width - (f.col - col);
            }).max(0);

            newCols.push(this.columns[col]);
            for (let i = 0; i < paddingRequired; i++) {
                newCols.push(GateColumn.empty(this.numWires));
            }
        }

        return this.withColumns(newCols);
    }

    /**
     * @param {!int} col
     * @returns {!Set.<!int>}
     * @private
     */
    _findHeightWiseOverlapsInCol(col) {
        let pushedGates = new Set();
        let h = 0;
        for (let row = 0; row < this.numWires; row++) {
            h -= 1;
            let gate = this.gateInSlot(col, row);
            if (gate !== undefined) {
                if (h > 0) {
                    pushedGates.add(row);
                }
                h = Math.max(h, gate.height);
            }
        }
        return pushedGates;
    }

    /**
     * @param {!int} recurseLimit If a bug causes an infinite height-overlap-fixing loop, this will save us.
     * @returns {!CircuitDefinition}
     */
    withHeightOverlapsFixed(recurseLimit=5) {
        let newCols = [];
        for (let col = 0; col < this.columns.length; col++) {
            let pushedGateIndexes = this._findHeightWiseOverlapsInCol(col);
            if (pushedGateIndexes.size === 0) {
                newCols.push(this.columns[col]);
                continue;
            }

            let keptGates = seq(this.columns[col].gates).
                mapWithIndex((g, row) => pushedGateIndexes.has(row) ? undefined : g).
                toArray();
            let pushedGates = seq(this.columns[col].gates).
                mapWithIndex((g, row) => g !== undefined && (g.isControl() || pushedGateIndexes.has(row)) ?
                    g :
                    undefined).
                toArray();

            newCols.push(new GateColumn(keptGates));
            newCols.push(new GateColumn(pushedGates));
        }

        let result = this.withColumns(newCols);
        if (newCols.length > this.columns.length && recurseLimit > 0) {
            // The pushed gates may still contain more height overlaps.
            result = result.withHeightOverlapsFixed(recurseLimit-1);
        }
        return result;
    }

    /**
     * @param {!int=0} extra
     * @returns {!CircuitDefinition}
     */
    withTrailingSpacersIncluded(extra=0) {
        return this.withColumns([
            ...this.columns,
            ...new Array(Math.max(0, this.minimumRequiredColCount() + extra - this.columns.length)).
                fill(GateColumn.empty(this.numWires))
        ]);
    }

    /**
     * @returns {!CircuitDefinition}
     */
    trimEmptyColumnsAtEndIgnoringGateWidths() {
        for (let n = this.columns.length; ; n--) {
            if (n === 0 || !this.columns[n-1].isEmpty()) {
                return this.withColumns(this.columns.slice(0, n));
            }
        }
    }

    /**
     * @returns {!CircuitDefinition}
     */
    withUncoveredColumnsRemoved() {
        let used = this._usedColumns();
        return new CircuitDefinition(
            this.numWires,
            seq(this.columns).filterWithIndex((e, i) => used.has(i)).toArray(),
            this.outerRowOffset,
            this.outerContext,
            this.customGateSet,
            false,
            this.customInitialValues);
    }

    /**
     * @param {!int} {newWireCount}
     * @returns {!CircuitDefinition}
     */
    withWireCount(newWireCount) {
        if (newWireCount === this.numWires) {
            return this;
        }
        return new CircuitDefinition(
            newWireCount,
            this.columns.map(c => new GateColumn([
                ...c.gates.slice(0, newWireCount),
                ...new Array(Math.max(0, newWireCount - c.gates.length)).fill(undefined)
            ])),
            this.outerRowOffset,
            this.outerContext,
            this.customGateSet,
            false,
            this.customInitialValues);
    }

    /**
     * @returns {!int} The minimum number of wires needed to hold the gates in the circuit, accounting for their height
     * and assuming the gate positions are fixed (i.e. wires can only be added or removed from the bottom).
     */
    minimumRequiredWireCount() {
        let best = 1;
        for (let c of this.columns) {
            best = Math.max(best, c.minimumRequiredWireCount());
        }
        for (let usedWire of this.customInitialValues.keys()) {
            best = Math.max(best, usedWire + 1);
        }
        return best;
    }

    /**
     * @returns {!CircuitDefinition}
     */
    withMinimumWireCount() {
        return this.withWireCount(this.minimumRequiredWireCount());
    }

    /**
     * @returns {!int} The minimum number of columns needed to hold the gates in the circuit, accounting for their width
     * and assuming the gate positions are fixed (i.e. columns can only be added or removed from the right).
     */
    minimumRequiredColCount() {
        let best = 0;
        for (let col = 0; col < this.columns.length; col++) {
            best = Math.max(best, this.columns[col].maximumGateWidth() + col);
        }
        return best;
    }

    /**
     * @param {!int} col
     * @returns {!int}
     */
    colIsMeasuredMask(col) {
        if (col < 0) {
            return 0;
        }
        return this._measureMasks[Math.min(col, this.columns.length)];
    }

    /**
     * @param {!int} col
     * @returns {!int}
     */
    colDesiredSingleQubitStatsMask(col) {
        if (col < 0 || col >= this.columns.length) {
            return 0;
        }
        let c = this.columns[col];
        let total = 0;
        for (let row = 0; row < c.gates.length; row++) {
            if (c.gates[row] !== undefined &&
                    c.gates[row].isSingleQubitDisplay &&
                    this.gateAtLocIsDisabledReason(col, row) === undefined) {
                total |= 1 << row;
            }
        }

        return total;
    }

    /**
     * @param {!int} col
     * @param {!int} outerRowOffset
     * @returns {!Map.<!string, *>}
     */
    colCustomContextFromGates(col, outerRowOffset) {
        if (col < 0 || col >= this.columns.length) {
            return new Map();
        }
        let key = "" + outerRowOffset;
        let result = this._cachedColumnContexts.get(key);
        if (result === undefined) {
            result = this._uncached_customContextFromGates(outerRowOffset);
            this._cachedColumnContexts.set(key, result);
        }
        return result[col];
    }

    /**
     * @param {!int} outerRowOffset
     * @returns {!Array.<!Map.<!string, *>>}
     */
    _uncached_customContextFromGates(outerRowOffset) {
        let results = [];
        let stickyCtx = new Map();
        for (let col = 0; col < this.columns.length; col++) {
            let ctx = new Map(stickyCtx);
            let c = this.columns[col];
            for (let row = 0; row < c.gates.length; row++) {
                let g = c.gates[row];
                if (g === undefined || this.gateAtLocIsDisabledReason(col, row) !== undefined) {
                    continue;
                }

                for (let {key, val} of g.customColumnContextProvider(outerRowOffset + row, g)) {
                    //noinspection JSUnusedAssignment
                    ctx.set(key, val);
                    if (!g.isContextTemporary) {
                        stickyCtx.set(key, val);
                    }
                }
            }
            results.push(ctx);
        }
        return results;
    }

    /**
     * @param {!Point} pt
     * @returns {boolean}
     */
    locIsMeasured(pt) {
        let row = pt.y;
        if (row < 0 || row >= this.numWires) {
            return false;
        }
        return (this.colIsMeasuredMask(pt.x) & (1 << row)) !== 0;
    }

    /**
     * @param {!Point} pt
     * @returns {undefined|boolean}
     */
    locClassifyMeasuredIncludingGateExtension(pt) {
        let row = pt.y;
        if (row < 0 || row >= this.numWires) {
            return false;
        }
        let gate = this.columns[pt.x].gates[row];
        let h = gate === undefined ? 1 : gate.height;
        let r = (this.colIsMeasuredMask(pt.x) >> row) & ((1 << h) - 1);
        return r === 0 ? false : r === (1 << h) - 1 ? true : undefined;
    }

    /**
     * A gate is only "in" the slot at its top left.
     * It "covers" any other slots underneath it.
     * @param {!int} col
     * @param {!int} row
     * @returns {undefined|!Gate}
     */
    gateInSlot(col, row) {
        if (col < 0 || col >= this.columns.length || row < 0 || row >= this.numWires) {
            return undefined;
        }
        let gate = this.columns[col].gates[row];
        return gate === undefined ? undefined : gate;
    }

    /**
     * A slot is covered when a gate is in it or extends over it.
     * @param {!int} col
     * @param {!int} row
     * @returns {undefined|!{col: !int, row: !int, gate: !Gate}}
     */
    findGateCoveringSlot(col, row) {
        let key = col+":"+row;
        if (!this._gateSlotCoverMap.has(key)) {
            return undefined;
        }
        return this._gateSlotCoverMap.get(key);
    }

    /**
     * @param {!Point} pt
     * @returns {!boolean}
     */
    locIsControlWireStarter(pt) {
        let gate = this.gateInSlot(pt.x, pt.y);
        return gate !== undefined && gate.isControlWireSource;
    }

    /**
     * @param {!Point} pt
     * @returns {boolean}
     */
    locStartsSingleControlWire(pt) {
        return this.locIsControlWireStarter(pt) &&
            this.locClassifyMeasuredIncludingGateExtension(pt) !== true &&
            this.gateAtLocIsDisabledReason(pt.x, pt.y) === undefined;
    }

    /**
     * @param {!Point} pt
     * @returns {boolean}
     */
    locStartsDoubleControlWire(pt) {
        return this.locIsControlWireStarter(pt) &&
            this.locClassifyMeasuredIncludingGateExtension(pt) !== false &&
            this.gateAtLocIsDisabledReason(pt.x, pt.y) === undefined;
    }

    /**
     * @param {int} col
     * @returns {undefined|![!int, !int]}
     */
    colGetEnabledSwapGate(col) {
        if (col < 0 || col >= this.columns.length) {
            return undefined;
        }
        let locs = [];
        for (let row = 0; row < this.numWires; row++) {
            if (this.gateInSlot(col, row) === Gates.Special.SwapHalf) {
                if (this.gateAtLocIsDisabledReason(col, row) !== undefined) {
                    return undefined;
                }
                locs.push(row);
            }
        }
        if (locs.length !== 2) {
            return undefined;
        }
        return locs;
    }

    /**
     * @param {!Point} pt
     * @param {!string} key
     * @returns {!boolean}
     */
    locProvidesStat(pt, key) {
        let g = this.gateInSlot(pt.x, pt.y);
        return g !== undefined && !g.customColumnContextProvider(0, g).every(e => e.key !== key);
    }

    /**
     * @param {!Point} pt
     * @param {!string} key
     * @returns {!boolean}
     */
    locNeedsStat(pt, key) {
        let g = this.gateInSlot(pt.x, pt.y);
        return g !== undefined && g.getUnmetContextKeys().has(key);
    }

    /**
     * @param {!Point} pt
     * @returns {!boolean}
     */
    locHasControllableGate(pt) {
        let g = this.gateInSlot(pt.x, pt.y);
        return g !== undefined && g.interestedInControls;
    }

    /**
     * @param {!int} col
     * @returns {!boolean}
     */
    colHasControls(col) {
        if (col < 0 || col >= this.columns.length) {
            return false;
        }
        return this.columns[col].hasControl();
    }

    /**
     * @param {!int} col
     * @returns {boolean}
     */
    colHasSingleWireControl(col) {
        if (col < 0 || col >= this.columns.length) {
            return false;
        }
        return this.columns[col].hasCoherentControl(this._measureMasks[col]);
    }

    /**
     * @param {!int} col
     * @returns {boolean}
     */
    colHasDoubleWireControl(col) {
        if (col < 0 || col >= this.columns.length) {
            return false;
        }
        return this.columns[col].hasMeasuredControl(this._measureMasks[col]);
    }

    /**
     * @params {!int} col
     * @returns {!Controls}
     */
    colControls(col) {
        if (col < 0 || col >= this.columns.length) {
            return Controls.NONE;
        }
        let result = Controls.NONE;
        let column = this.columns[col];
        for (let i = 0; i < column.gates.length; i++) {
            let gate = column.gates[i];
            if (gate !== undefined && this.gateAtLocIsDisabledReason(col, i) === undefined) {
                let bit = gate.controlBit();
                if (bit !== undefined) {
                    result = result.and(Controls.bit(i, bit));
                }
            }
        }
        return result;
    }

    /**
     * @param {!int} col
     * @param {!int} row
     * @returns {undefined|!string}
     */
    gateAtLocIsDisabledReason(col, row) {
        if (col < 0 || row < 0 || col >= this._colRowDisabledReason.length || row >= this.numWires) {
            return undefined;
        }
        return this._colRowDisabledReason[col][row];
    }

    /**
     * @param {!CircuitEvalContext} ctx
     * @return {void}
     */
    applyInitialStateOperations(ctx) {
        for (let wire = 0; wire < this.numWires; wire++) {
            let state = this.customInitialValues.get(wire);
            if (!INITIAL_STATES_TO_GATES.has(state)) {
                throw new DetailedError('Unrecognized initial state.', {state});
            }
            for (let gate of INITIAL_STATES_TO_GATES.get(state)) {
                GateShaders.applyMatrixOperation(ctx.withRow(ctx.row + wire), gate.knownMatrixAt(ctx.time))
            }
        }
    }

    /**
     * @param {!int} colIndex
     * @param {!CircuitEvalContext} ctx
     * @return {void}
     */
    applyMainOperationsInCol(colIndex, ctx) {
        if (colIndex < 0 || colIndex >= this.columns.length) {
            return;
        }

        this._applyOpsInCol(colIndex, ctx, gate => {
            if (gate.definitelyHasNoEffect() || gate === Gates.Special.SwapHalf) {
                return undefined;
            }

            if (gate.customOperation !== undefined) {
                return gate.customOperation;
            }

            return ctx => GateShaders.applyMatrixOperation(ctx, gate.knownMatrixAt(ctx.time));
        });

        let swapRows = this.colGetEnabledSwapGate(colIndex);
        if (swapRows !== undefined) {
            let [i, j] = swapRows;
            ctx.applyOperation(CircuitShaders.swap(ctx.withRow(i + ctx.row), j + ctx.row));
        }
    }

    /**
     * @param {!int} colIndex
     * @param {!CircuitEvalContext} ctx
     * @return {void}
     */
    applyBeforeOperationsInCol(colIndex, ctx) {
        this._applyOpsInCol(colIndex, ctx, g => g.customBeforeOperation);
    }

    /**
     * @param {!int} colIndex
     * @param {!CircuitEvalContext} ctx
     * @return {void}
     */
    applyAfterOperationsInCol(colIndex, ctx) {
        this._applyOpsInCol(colIndex, ctx, g => g.customAfterOperation);
    }

    /**
     * @param {!int} colIndex
     * @param {!CircuitEvalContext} ctx
     * @param {!function(!Gate) : !function(!CircuitEvalContext)} opGetter
     * @private
     */
    _applyOpsInCol(colIndex, ctx, opGetter) {
        if (colIndex < 0 || colIndex >= this.columns.length) {
            return;
        }
        let col = this.columns[colIndex];

        for (let row = 0; row < this.numWires; row++) {
            let gate = col.gates[row];
            if (gate === undefined || this.gateAtLocIsDisabledReason(colIndex, row) !== undefined) {
                continue;
            }

            let op = opGetter(gate);
            if (op !== undefined) {
                op(ctx.withRow(ctx.row + row));
            }
        }
    }

    /**
     * @param {!int} colIndex
     * @returns {!Array.<!int>}
     */
    customStatRowsInCol(colIndex) {
        if (colIndex < 0 || colIndex >= this.columns.length) {
            return [];
        }

        let col = this.columns[colIndex];
        let result = [];
        for (let row = 0; row < col.gates.length; row++) {
            if (col.gates[row] !== undefined &&
                    col.gates[row].customStatTexturesMaker !== undefined &&
                    this.gateAtLocIsDisabledReason(colIndex, row) === undefined) {
                result.push(row);
            }
        }
        return result;
    }

    /**
     * @param {!int} col
     * @param {!int} row
     * @param {!int} height
     * @returns {!boolean}
     */
    isSlotRectCoveredByGateInSameColumn(col, row, height) {
        for (let j = 0; j < height; j++) {
            let f = this.findGateCoveringSlot(col, row+j);
            if (f !== undefined && f.col === col) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param {!Gate} gate
     * @returns {!CircuitDefinition}
     */
    withCustomGate(gate) {
        return new CircuitDefinition(
            this.numWires,
            this.columns,
            this.outerRowOffset,
            this.outerContext,
            this.customGateSet.withGate(gate),
            false,
            this.customInitialValues);
    }

    /**
     * @param {!int} columnIndex
     * @returns {!Array.<!{first: !int, last: !int, measured: !boolean}>}
     */
    controlLinesRanges(columnIndex) {
        let col = this.columns[columnIndex];
        let n = col.gates.length;

        let swapRows = this.colGetEnabledSwapGate(columnIndex);

        let pt = i => new Point(columnIndex, i);
        let hasControllable = i => this.locHasControllableGate(pt(i));
        let hasCoherentControl = i => this.locStartsSingleControlWire(pt(i));
        let hasMeasuredControl = i => this.locStartsDoubleControlWire(pt(i));
        let hasSwap = i => swapRows !== undefined && swapRows.indexOf(i) !== -1;
        let coversCoherentWire = i => this.locClassifyMeasuredIncludingGateExtension(pt(i)) !== true;
        let coversMeasuredWire = i => this.locClassifyMeasuredIncludingGateExtension(pt(i)) !== false;

        // Control connections.
        let result = [
            srcDstMatchInRange(n, hasSwap, hasSwap, false),
            srcDstMatchInRange(n, hasControllable, hasCoherentControl, false),
            srcDstMatchInRange(n, hasControllable, hasMeasuredControl, true),
        ];

        // Input->Output gate connections.
        for (let letter of Gates.InputGates.Letters) {
            let key = `Input Range ${letter}`;
            let altInKey = `Input Default ${letter}`;
            let altOutKey = `Input NO_DEFAULT Range ${letter}`;
            let isInput = i => this.locProvidesStat(pt(i), key) || this.locProvidesStat(pt(i), altInKey);
            let isOutput = i => this.locNeedsStat(pt(i), key) || this.locNeedsStat(pt(i), altOutKey);
            result.push(
                srcDstMatchInRange(n, i => isInput(i) && coversCoherentWire(i), isOutput, false),
                srcDstMatchInRange(n, i => isInput(i) && coversMeasuredWire(i), isOutput, true)
            );
        }

        return result.filter(e => e !== undefined);
    }
}

/**
 * @param {!int} rangeLen
 * @param {!function(!int) : !boolean} srcPredicate
 * @param {!function(!int) : !boolean} dstPredicate
 * @param {!boolean} measured
 * @returns {undefined|!{first:!int, last:!int, measured:!boolean}}
 * @private
 */
function srcDstMatchInRange(rangeLen, srcPredicate, dstPredicate, measured) {
    let [src1, src2] = firstLastMatchInRange(rangeLen, srcPredicate);
    let [dst1, dst2] = firstLastMatchInRange(rangeLen, dstPredicate);
    if (dst1 === undefined || src1 === undefined) {
        return undefined;
    }
    return {
        first: Math.min(src1, dst1),
        last: Math.max(src2, dst2),
        measured: measured
    };
}

/**
 * @param {!int} rangeLen
 * @param {!function(!int): !boolean} predicate
 * @returns {!Array.<undefined|!int>}
 */
function firstLastMatchInRange(rangeLen, predicate){
    let first = undefined;
    let last = undefined;
    for (let i = 0; i < rangeLen; i++) {
        if (predicate(i)) {
            if (first === undefined) {
                first = i;
            }
            last = i;
        }
    }
    return [first, last];
}

CircuitDefinition.EMPTY = new CircuitDefinition(0, []);

export {CircuitDefinition}


text:
HOW TO USE
==========

First you should provide a config file for messaging driver. Sample config
for kombu driver could be found in oslo_msg_check.conf.sample in git repo.

Check applications
------------------

The check pair of applications allows you to run two processes and
then periodically check "RPC connectivity" between them.

To run them execute:

::

    oslo_msg_check_client --config-file oslo_msg_check.conf
    oslo_msg_check_server --config-file oslo_msg_check.conf

Now whenever you send GET request to port 5000, oslo_msg_check_client
will return 200 OK only it was able to send RPC request to
oslo_msg_check_server and received reply from it.

Load applications
-----------------

The load pair of applications allows to load messages into rabbitmq
and consume them. It uses oslo.messaging notification mechanism.

To put messages into RabbitMQ run

::

    oslo_msg_load_generator --config-file oslo_msg_check.conf --messages-to-send 1000

To read them, run

::

    oslo_msg_load_consumer --config-file oslo_msg_check.conf

HOW TO INSTALL
==============

Built your deb or take one from the git repository. But, in later case it
is up to you to make sure that it was built from the latest sources!

Install the deb like a regular deb package

::

    sudo apt-get update
    sudo dpkg -i oslo.messaging-check-tool_1.0-1~u14.04+mos1_all.deb

If the command above fails, run

::

    sudo apt-get -f install

HOW TO BUILD
============

Get an Ubuntu 14.04 machine and clone the project to it:

::

    git clone https://github.com/dmitrymex/oslo.messaging-check-tool.git
    cd oslo.messaging-check-tool

Add Fuel mirrors, for 8.0 do

::

    sudo tar -xzf aptsources.tgz -C /etc/apt/

Install the dependencies and build tools

::

    sudo apt-get update
    sudo apt-get install git dpkg-dev debhelper dh-systemd openstack-pkg-tools po-debconf python-all python-pbr python-setuptools python-sphinx python-babel python-eventlet python-flask python-oslo.config python-oslo.log python-oslo.messaging python-oslosphinx

Build the package

::

    DEB_BUILD_OPTIONS=nocheck dpkg-buildpackage -rfakeroot -us -uc

The built package could be found in the parent directory, like

::

    ../oslo.messaging-check-tool_1.0-1~u14.04+mos1_all.deb


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Santiago Doyle | Leonardo A. Saravia</title>
    <link>https://lsaravia.github.io/authors/santiago-doyle/</link>
      <atom:link href="https://lsaravia.github.io/authors/santiago-doyle/index.xml" rel="self" type="application/rss+xml" />
    <description>Santiago Doyle</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><copyright>Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional.</copyright><lastBuildDate>Fri, 05 Jan 2018 00:00:00 +0000</lastBuildDate>
    <image>
      <url>https://lsaravia.github.io/img/bio-photo.jpg</url>
      <title>Santiago Doyle</title>
      <link>https://lsaravia.github.io/authors/santiago-doyle/</link>
    </image>

    <item>
      <title>The Food Web of Potter Cove (Antarctica): Complexity, Structure and Function</title>
      <link>https://lsaravia.github.io/publication/marina-2018/</link>
      <pubDate>Fri, 05 Jan 2018 00:00:00 +0000</pubDate>
      <guid>https://lsaravia.github.io/publication/marina-2018/</guid>
      <description></description>
    </item>

    <item>
      <title>Power Laws and Critical Fragmentation in Global Forests</title>
      <link>https://lsaravia.github.io/publication/saravia-2018-a/</link>
      <pubDate>Mon, 01 Jan 2018 00:00:00 +0000</pubDate>
      <guid>https://lsaravia.github.io/publication/saravia-2018-a/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
import { Type } from '@ephox/katamari';

import Editor from 'tinymce/core/api/Editor';
import Delay from 'tinymce/core/api/util/Delay';
import LocalStorage from 'tinymce/core/api/util/LocalStorage';
import Tools from 'tinymce/core/api/util/Tools';

import * as Events from '../api/Events';
import * as Options from '../api/Options';

const isEmpty = (editor: Editor, html?: string): boolean => {
  if (Type.isUndefined(html)) {
    return editor.dom.isEmpty(editor.getBody());
  } else {
    const trimmedHtml = Tools.trim(html);

    if (trimmedHtml === '') {
      return true;
    } else {
      const fragment = new DOMParser().parseFromString(trimmedHtml, 'text/html');
      return editor.dom.isEmpty(fragment);
    }
  }
};

const hasDraft = (editor: Editor): boolean => {
  const time = parseInt(LocalStorage.getItem(Options.getAutoSavePrefix(editor) + 'time') ?? '0', 10) || 0;

  if (new Date().getTime() - time > Options.getAutoSaveRetention(editor)) {
    removeDraft(editor, false);
    return false;
  }

  return true;
};

const removeDraft = (editor: Editor, fire?: boolean): void => {
  const prefix = Options.getAutoSavePrefix(editor);

  LocalStorage.removeItem(prefix + 'draft');
  LocalStorage.removeItem(prefix + 'time');

  if (fire !== false) {
    Events.fireRemoveDraft(editor);
  }
};

const storeDraft = (editor: Editor): void => {
  const prefix = Options.getAutoSavePrefix(editor);

  if (!isEmpty(editor) && editor.isDirty()) {
    LocalStorage.setItem(prefix + 'draft', editor.getContent({ format: 'raw', no_events: true }));
    LocalStorage.setItem(prefix + 'time', new Date().getTime().toString());
    Events.fireStoreDraft(editor);
  }
};

const restoreDraft = (editor: Editor): void => {
  const prefix = Options.getAutoSavePrefix(editor);

  if (hasDraft(editor)) {
    editor.setContent(LocalStorage.getItem(prefix + 'draft') ?? '', { format: 'raw' });
    Events.fireRestoreDraft(editor);
  }
};

const startStoreDraft = (editor: Editor): void => {
  const interval = Options.getAutoSaveInterval(editor);
  Delay.setEditorInterval(editor, () => {
    storeDraft(editor);
  }, interval);
};

const restoreLastDraft = (editor: Editor): void => {
  editor.undoManager.transact(() => {
    restoreDraft(editor);
    removeDraft(editor);
  });

  editor.focus();
};

export {
  isEmpty,
  hasDraft,
  removeDraft,
  storeDraft,
  restoreDraft,
  startStoreDraft,
  restoreLastDraft
};


text:
class ActiveRecord::Base
  def self.per_page
    class_name = name.underscore.to_sym
    Settings[class_name] && Settings[class_name][:per_page] ? Settings[class_name][:per_page] : 20
  end
end


text:
package com.asakusafw.bridge.directio.api;

import java.io.IOException;
import java.text.MessageFormat;

import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;

import com.asakusafw.bridge.broker.ResourceBroker;
import com.asakusafw.runtime.core.ResourceConfiguration;
import com.asakusafw.runtime.directio.DataFormat;
import com.asakusafw.runtime.directio.api.DirectIoDelegate;
import com.asakusafw.runtime.io.ModelInput;

/**
 * A framework API for accessing Direct I/O.
 *

 * Clients can use this class only in operator methods.
 *

 *
 *
 requirements

 *

 * This API requires that either {@link Configuration a Hadoop configuration} object or
 * {@link ResourceConfiguration Asakusa configuration} object has been registered to {@link ResourceBroker}.
 *

 * @deprecated this API is not for application developers,
 *      please use {@link com.asakusafw.runtime.directio.api.DirectIo} instead
 */
@Deprecated
public final class DirectIo {

    private DirectIo() {
        return;
    }

    /**
     * Returns data model objects from Direct I/O data sources.
     *

     * Clients can obtain each data model object:
     *

try (ModelInput<Hoge> input = DirectIo.open(...)) {
    Hoge object = new Hoge();
    while (input.readTo(object)) {
        // process object
        System.out.println(object);
    }
}

     * , or can build a list of data model objects:

List<Hoge> list = new ArrayList<>();
try (ModelInput<Hoge> input = DirectIo.open(...)) {
    while (true) {
        // create a new object in each iteration
        Hoge object = new Hoge();
        if (!input.readTo(object)) {
            break;
        }
        list.add(object);
    }
}

     * @param <T> the data model object type
     * @param formatClass the Direct I/O data format class
     * @param basePath the base path (must not contain variables)
     * @param resourcePattern the resource pattern (must not contain variables)
     * @return the data model objects
     * @throws IOException if failed to open data model objects on the data source
     */
    public static <T> ModelInput<T> open(
            Class<? extends DataFormat<T>> formatClass,
            String basePath,
            String resourcePattern) throws IOException {
        DirectIoDelegate delegate = getDelegate();
        return delegate.open(formatClass, basePath, resourcePattern);
    }

    private static DirectIoDelegate getDelegate() {
        Configuration conf = getHadoopConfiguration();
        assert conf != null;
        return new DirectIoDelegate(conf);
    }

    private static Configuration getHadoopConfiguration() {
        ResourceConfiguration asakusa = ResourceBroker.find(ResourceConfiguration.class);
        if (asakusa instanceof Configurable) {
            Configuration conf = ((Configurable) asakusa).getConf();
            if (conf != null) {
                return conf;
            }
        }
        Configuration hadoop = ResourceBroker.find(Configuration.class);
        if (hadoop != null) {
            return hadoop;
        }
        throw new IllegalStateException(MessageFormat.format(
                "required resource has not been prepared yet: {0}",
                Configuration.class));
    }
}


text:
cd /tmp;

# Retrieve the latest version from bitbucket.
echo -e "\n\033[01;34mRetreiving changes from BitBucket.org\033[00m"
hg clone https://kalekold@bitbucket.org/kalekold/vim-linux;

# Install the files.
echo -e "\n\033[01;30mInstalling files\033[00m"
rm -rf ~/.vim;
rm -f ~/.vimrc;
cp -rf /tmp/vim-linux/.vim/ ~/.vim/;
cp -f /tmp/vim-linux/.vimrc ~/.vimrc;
sudo cp -f /tmp/vim-linux/icons/vim.png /usr/share/pixmaps/vim.png

# Update vimrc for the current environment.
echo -e "\033[01;30mUpdating vimrc for current environment\033[00m"
# sed -i 's/CtrlP \/media\/Data\/Projects\//CtrlP \/home\/gary\/codebase\/gen2\/switch\//g' ~/.vimrc
# sed '/set cursorline/d' ~/.vimrc

# Remove any temporary files.
echo -e "\033[01;30mRemoving temporary files\033[00m"
rm -rf /tmp/vim-linux/;

# Change the directory to home.
cd ~;

echo -e "\033[01;34mDone\033[00m"
notify-send --icon=/usr/share/pixmaps/vim.png "Update complete" "All Vim settings have been updated to the latest version."


text:
package com.crazycabo.views.pages.templates;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import ru.yandex.qatools.allure.annotations.Parameter;
import com.crazycabo.views.BasePage;

import static junit.framework.TestCase.assertTrue;

/**
 * Created By: Brian Smith on 4/28/15.
 * Package: java.com.crazycabo.views.pages
 * Description: This child page class details an example where one page recursively loads another.
 */

public class _ChildPageTemplate extends BasePage
{
    /* This is a stripped-down example intended to show you how child page classes can attempt to load() pages and
     * interact with them in order to display this page. Think of an authentication page as the parent and home page
     * as a child since authentication is required in order to display it.
     *
     * View the _PageTemplate class for general page class details.
     */

    @Parameter("Add parameter name")
    private String s;

    @Parameter("Add parameter name")
    private String s2;

    @FindBy(xpath = "")
    public WebElement e1;

    @FindBy(xpath = "")
    public WebElement e2;

    // Input the values necessary for use within the load() method.
    public _ChildPageTemplate(WebDriver driver, String s, String s2)
    {
        super(driver);
        this.s = s;
        this.s2 = s2;
    }

    /* The load() method of a child page class attempts to load its' parent before loading itself. This kind of logic
     * can be chained together several times so that a call to load one page can recursively load several other pages
     * in a sequence. This leads to greater reuse and less headache when dealing with a complicated connected page
     * structure.
     */
    @Override
    public void load()
    {
        // Create an object of the parent page and attempt to load it.
        _PageTemplate parentPage = new _PageTemplate(localDriver);
        parentPage.get();

        // Execute action on the parent page to display this page and wait until an element on this page displays.
        parentPage.userAction(this.s, this.s2);
        waitUntilClickable(e1, 30);
    }

    /* This method is used to check if the page is available, or loaded.
     * If an error is thrown the first time, the load() method above executes and then this will execute a second time.
     * If a second error is thrown, the test will be in error.
     */
    @Override
    public void isLoaded() throws Error
    {
        /* This method requires a simple assertion to determine if the page successfully loads. You can use any of the
         * available jUnit assertions. Generally, you will assert against an element
         */
        assertTrue("Page is not displayed.", elementDisplays(e1));
    }
}


text:
function [ isGameOver ] = checkIfGameOver(gameOverMask,mask)
    TOLERANCE = 1000;
    and = mask.*gameOverMask;
    diff = abs(sum(and(:))-sum(gameOverMask(:)));
    isGameOver = diff <= TOLERANCE;
end


text:
<ng-container *ngIf="showMetric$ | async">
    <pp-notice-container></pp-notice-container>

        <pp-side-navigation-bar *ngIf="sideNavigationUI"></pp-side-navigation-bar>

            <pp-header-logo></pp-header-logo>

                <pp-host-group-list-container></pp-host-group-list-container>
                <pp-period-selector-container></pp-period-selector-container>

            <button class="fas fa-question-circle" (click)="onShowHelp($event)"></button>
            <pp-configuration-icon-container></pp-configuration-icon-container>

                <pp-host-group-list-container></pp-host-group-list-container>
                <pp-period-selector-container></pp-period-selector-container>

                    <pp-host-group-and-host-list-container></pp-host-group-and-host-list-container>

                <router-outlet></router-outlet>

</ng-container>


text:
package de.rfelgent.tus.web;

import de.rfelgent.tus.TusHeaders;
import de.rfelgent.tus.domain.Asset;
import de.rfelgent.tus.domain.AssetNotFoundException;
import de.rfelgent.tus.domain.AssetStatus;
import de.rfelgent.tus.domain.LockException;
import de.rfelgent.tus.domain.StorageException;
import de.rfelgent.tus.service.AssetStorage;
import de.rfelgent.tus.service.AssetLocker;
import de.rfelgent.tus.service.ExpirationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @author rfelgentraeger
 */
@RestController
@RequestMapping("/files")
public class UploadController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private AssetStorage assetStorage;
    @Autowired
    private AssetLocker assetLocker;
    @Autowired
    private ExpirationService expirationService;

    @RequestMapping(value = {"/{id}", "/{id}/"}, method = {RequestMethod.PATCH})
    public ResponseEntity<Void> upload(@RequestHeader(value = "Content-Type", required = false) String contentType,
                                       @RequestHeader(value = TusHeaders.UPLOAD_OFFSET, required = false) Long offset,
                                       @RequestHeader(value = TusHeaders.UPLOAD_LENGTH, required = false) Long uploadLength,
                                       @RequestHeader(value = TusHeaders.UPLOAD_META, required = false) String uploadMeta,
                                       @PathVariable(value = "id") String id,
                                       HttpServletRequest request) throws IOException, StorageException, LockException {
        if (contentType == null || offset == null
                || !"application/offset+octet-stream".equalsIgnoreCase(contentType)) {
            throw new IllegalArgumentException("Invalid request");
        }

        Asset asset = assetStorage.find(id);
        if (asset == null) {
            throw new AssetNotFoundException();
        }
        if (asset.getExpirationDate() != null &&
                asset.getExpirationDate().before(new Date())) {
            LOGGER.warn("The asset {} is not updatable due to expiration date", asset.getReferenceId());
            throw new AssetNotFoundException();
        }
        if (asset.getTotalSize() == null
                && uploadLength != null && uploadLength > 0) {
            asset.setTotalSize(uploadLength);
            //TODO: explicitly "save" changed entity
        }

        if (uploadMeta != null) {
            LOGGER.warn("Updating meta data during upload is not supported by this implementation! Not handling: {}", uploadMeta);
        }

        try {
            assetLocker.lock(asset.getReferenceId());

            AssetStatus assetStatus = assetStorage.status(asset.getReferenceId());
            if (assetStatus.getUploadedSize() != offset) {
                return ResponseEntity.status(HttpStatus.CONFLICT).build();
            }

            assetStorage.write(asset.getReferenceId(), request.getInputStream());

            //update the status after previous write attempt
            assetStatus = assetStorage.status(asset.getReferenceId());

            HttpHeaders headers = new HttpHeaders();
            headers.set(TusHeaders.UPLOAD_OFFSET, Long.toString(assetStatus.getUploadedSize()));
            if (asset.getExpirationDate() != null) {
                headers.set(TusHeaders.UPLOAD_EXPIRES, expirationService.toRFC7231Format(asset.getExpirationDate()));
            }
            return ResponseEntity.noContent().headers(headers).build();
        } finally {
            assetLocker.release(asset.getReferenceId());
        }
    }
}


text: a { one color: black }


text:
/* crt0.o should come from the linker script, but for compatibility,
   we mention it here for -msim.  */
#undef  STARTFILE_SPEC
#define STARTFILE_SPEC "%{msim:crt0%O%s} crti%O%s crtbegin%O%s"

#undef  ENDFILE_SPEC
#define ENDFILE_SPEC	"crtend%O%s crtn%O%s"

#undef  LIB_SPEC
#define LIB_SPEC "%{msim:--start-group -lc -lsim --end-group;" \
	":-lc}"

#undef LINK_SPEC
#define LINK_SPEC ENDIAN_LINK_SPEC


text:
+++
title = "HA"
weight = 3
+++

## Configuration Item Explanation

```properties
spring.shardingsphere.datasource.names= # Omit the data source configuration, please refer to the usage

spring.shardingsphere.rules.database-discovery.data-sources.<database-discovery-data-source-name>.data-source-names= # Data source names, multiple data source names separated with comma. Such as: ds_0, ds_1
spring.shardingsphere.rules.database-discovery.data-sources.<database-discovery-data-source-name>.discovery-heartbeat-name= # Detect heartbeat name
spring.shardingsphere.rules.database-discovery.data-sources.<database-discovery-data-source-name>.discovery-type-name= # Database discovery type name

spring.shardingsphere.rules.database-discovery.discovery-heartbeats.<discovery-heartbeat-name>.props.keep-alive-cron= # This is cron expression, such as:'0/5 * * * * ?'

spring.shardingsphere.rules.database-discovery.discovery-types.<discovery-type-name>.type= # Database discovery type, such as: MGR、openGauss
spring.shardingsphere.rules.database-discovery.discovery-types.<discovery-type-name>.props.group-name= # Required parameters for database discovery types, such as MGR's group-name

```


text:
#ifndef MASTERMIND_HEURISTIC_STRATEGY_HPP
#define MASTERMIND_HEURISTIC_STRATEGY_HPP

#include "Strategy.hpp"
#include "util/call_counter.hpp"

/**
 * Define FAVOR_POSSIBILITY to 1 to make a heuristic strategy favor
 * a guess that is among the remaining possibilities when multiple
 * guesses have the same heuristic score.
 *
 * Normally, this flag should be set to 0 because we expect the
 * heuristic score to fully capture the available information from
 * the partition. However, setting this to 1 does improve the result
 * marginally in certain cases, e.g. "-r bc -s entropy". Also it
 * may help in compatilibity with legacy implementations that favor
 * a remaining possibility as guess in case of a tie.
 *
 * @ingroup Heuristic
 */
#define FAVOR_POSSIBILITY 0

namespace Mastermind {

///
/// Type of a function object that takes as input the partitioning of
/// remaining possibilities and returns as output a heuristic score.
///
template <class Heuristic>
///
/// Implements a class of strategies that make a guess according to the
/// score it produces given a heuristic function.
///
/// <remarks>
/// A heuristic strategy makes a guess by computing a score for each of the
/// candidate guesses using a heuristic function. The heuristic
/// function takes as input the partitioning of the set of remaining
/// possibilities using the guess, and outputs a scalar score. The guess
/// that produces the optimal (lowest) score is chosen. If multiple guesses
/// produce the same score, the guess that is in the possibility set is
/// chosen. If multiple choices still exist, the first one is chosen.
///
/// The heuristic function used by the strategy is specified by the
/// template parameter Heuristic. It takes as input the
/// frequency table of the partition, and returns a heuristic score.
/// The partition is defined as below.
///
/// Suppose there are N remaining possibilities. Given
/// a guess, these possibilities can be partitioned into m
/// cells, where the possibilities in each cell have the same feedback
/// when compared to the guess. That is, given that guess, there is
/// no way to distinguish one possibility from another in the same
/// cell.
///
/// Note that when computing the heuristic score, we always assume that
/// each codeword in the possibility set is equally-likely to be the
/// secret.
/// </remarks>
class HeuristicStrategy : public Strategy
{
	const Engine *e;
	Heuristic h;

	struct choice_t
	{
		typedef typename Heuristic::score_t score_t;

		int i; // index to the choice, -1 = undefined
		typename Heuristic::score_t score; // score of the choice
#if FAVOR_POSSIBILITY
		bool ispos; // whether the choice is a remaining possibility
		choice_t() : i(-1), score(), ispos(false) { }
		choice_t(int _i, const score_t _score, bool _ispos)
			: i(_i), score(_score), ispos(_ispos) { }
#else
		choice_t() : i(-1), score() { }
		choice_t(int _i, const score_t &_score)
			: i(_i), score(_score) { }
#endif

		bool operator < (const choice_t &other) const
		{
			if (i < 0)
				return false;
			if (other.i < 0)
				return true;
			if (score < other.score)
				return true;
			if (other.score < score)
				return false;
#if FAVOR_POSSIBILITY
			if (!ispos && other.ispos)
				return true;
			if (ispos && !other.ispos)
				return false;
#endif
			return i < other.i;
		}
	};

public:

	typedef typename Heuristic::score_t score_type;

	///
    /// Creates a heuristic strategy using the supplied heuristic function.
    ///
    /// <param name="engine">Context.</param>
    /// <param name="heuristic">Heuristic function object.</param>
	HeuristicStrategy(const Engine *engine, const Heuristic &heuristic = Heuristic())
		: e(engine), h(heuristic) { }

	Heuristic& heuristic() { return h; }

	/// Returns the name of the strategy.
	virtual std::string name() const
	{
		 return h.name();
	}

#if 1
	/// Evaluates an array of candidates, and stores the heuristic score
	/// of each candidate.
	void evaluate(
		CodewordConstRange possibilities,
		CodewordConstRange candidates,
		score_type *scores) const
	{
		UPDATE_CALL_COUNTER("EvaluateHeuristic_Possibilities", (unsigned int)possibilities.size());
		UPDATE_CALL_COUNTER("EvaluateHeuristic_Candidates", (unsigned int)candidates.size());

		assert(scores != NULL);

		int n = (int)candidates.size();

#if _OPENMP
		// OpenMP index variable (i) must have signed integer type.
		#pragma omp parallel for schedule(static)
#endif
		for (int i = 0; i < n; ++i)
		{
			// Partition the remaining possibilities.
			Codeword guess = candidates[i];
			FeedbackFrequencyTable freq = e->compare(guess, possibilities);

			// Compute a score of the partition.
			score_type score = h.compute(freq);

			// Store the score.
			scores[i] = score;
		}
	}
#endif

	/// Makes the guess that produces the lowest heuristic score.
	virtual Codeword make_guess(
		CodewordConstRange possibilities,
		CodewordConstRange candidates) const
	{
		UPDATE_CALL_COUNTER("EvaluateHeuristic_Possibilities", (unsigned int)possibilities.size());
		UPDATE_CALL_COUNTER("EvaluateHeuristic_Candidates", (unsigned int)candidates.size());

		if (candidates.empty())
			return Codeword();

#if 0
		static int debug_i = 0;
		extern int estimate_obvious_lowerbound(
			const Rules &rules,
			CodewordConstRange possibilities);

		// Pure debug output: when there are a few possibilities left,
		// what are the typical structure of these remaining possibilities?
		if (possibilities.size() < 14 && rand() % 750 == 0)
		{
			std::cout << '[' << (++debug_i) << "] ";
			for (size_t j = 0; j < possibilities.size(); ++j)
			{
				std::cout << possibilities[j] << ' ';
			}

			// Find the best possibility.
			score_type best = score_type();
			for (size_t i = 0; i < possibilities.size(); ++i)
			{
				Codeword guess = possibilities[i];
				FeedbackFrequencyTable freq = e.frequencies(guess, possibilities);
				score_type score = h.compute(freq);
				if (i == 0 || score < best)
				{
					best = score;
				}
			}
			std::cout << "(" << best << " v ";

			// Find the best in all.
			for (size_t i = 0; i < candidates.size(); ++i)
			{
				Codeword guess = candidates[i];
				FeedbackFrequencyTable freq = e.frequencies(guess, possibilities);
				score_type score = h.compute(freq);
				if (i == 0 || score < best)
				{
					best = score;
				}
			}
			std::cout << best;
			std::cout << " : " << estimate_obvious_lowerbound(e.rules(), possibilities);
			std::cout << ")";
			std::cout << std::endl;
		}
#endif

#if _OPENMP
		choice_t global_choice;
#else
		choice_t choice;
#endif

#if FAVOR_POSSIBILITY
		size_t target = Feedback::perfectValue(e.rules()).value();
#endif

		// Evaluate each candidate guess and find the one that
		// produces the lowest score.
		int n = (int)candidates.size();

		// OpenMP index variable (i) must have signed integer type.
#if _OPENMP
		#pragma omp parallel if (0)
		{
			choice_t choice;

			#pragma omp for schedule(static)
#endif
			for (int i = 0; i < n; ++i)
			{
				Codeword guess = candidates[i];
				FeedbackFrequencyTable freq = e->compare(guess, possibilities);

				// Compute a score of the partition.
				score_type score = h.compute(freq);

				// Keep track of the guess that produces the lowest score.
#if FAVOR_POSSIBILITY
				choice_t current(i, score, freq[target] > 0);
#else
				choice_t current(i, score);
#endif
				choice = std::min(choice, current);
			}
#if _OPENMP
			#pragma omp critical
			{
				global_choice = std::min(global_choice, choice);
			}
		}
		return candidates[global_choice.i];
#else
		return candidates[choice.i];
#endif
	}
};

} // namespace Mastermind

#endif // MASTERMIND_HEURISTIC_STRATEGY_HPP


text:
using namespace v8;
using namespace GenApi_3_0_Basler_pylon_v5_0;

class U3VEventMessageWrap : public node::ObjectWrap
{
public:
    static NAN_MODULE_INIT(Initialize);
    static Nan::Persistent<v8::FunctionTemplate> prototype;

    U3V_EVENT_MESSAGE* GetWrapped() const
    {
        return m_U3VEventMessage;
    };

    void SetWrapped(U3V_EVENT_MESSAGE* u3VEventMessage)
    {
        m_U3VEventMessage = u3VEventMessage;
    };

    static v8::Handle<v8::Value> NewInstance(U3V_EVENT_MESSAGE* u3VEventMessage);

private:
    static Nan::Persistent<v8::Function> constructor;
    U3VEventMessageWrap(Nan::NAN_METHOD_ARGS_TYPE info);
    ~U3VEventMessageWrap();
    static NAN_METHOD(New);

    // Wrapped object
    U3V_EVENT_MESSAGE* m_U3VEventMessage;
};


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hym. à Gast. Imp. Ross. Obs. (Petropoli) 12 (1836)

#### Original name
Agaricus putidus Weinm., 1836

### Remarks
null


text:
""" A non-interactive command-line interface to the StorPool API. """

from __future__ import print_function

import argparse
import json
import os
import re
import sys

import six.moves

from storpool import spapi, spconfig

def deep_to_json(data):
    """ Convert an API reply to serializable data. """
    if getattr(data, 'to_json', None) is not None:
        return deep_to_json(data.to_json())
    if isinstance(data, list):
        return [deep_to_json(obj) for obj in data]
    if isinstance(data, dict):
        # Bah, we cannot use dict comprehension on CentOS 6, can we...
        return {name: deep_to_json(value) for name, value in data.items()}
    return data

def from_config_with_overrides(**kwargs):
    """ Create an API object with access credentials taken from the StorPool
    configuration files and overridden by environment variables. """
    cfg = spconfig.SPConfig()
    data = {}
    for name in ('SP_API_HTTP_HOST', 'SP_API_HTTP_PORT', 'SP_AUTH_TOKEN'):
        value = os.environ.get(name, None)
        if value is None:
            value = cfg[name]
        data[name] = value

    return spapi.Api(host=data['SP_API_HTTP_HOST'],
                     port=int(data['SP_API_HTTP_PORT']),
                     auth=data['SP_AUTH_TOKEN'],
                     **kwargs)

def err_exit(name, descr, **args):
    """ Output an error in JSON form to the standard error stream and exit. """
    err = {
        'error': {
            'transient': False,
            'name': name,
            'descr': descr,
        },
    }
    err['error'].update(args)
    sys.exit(json.dumps(err, indent=2))

def parse_args():
    """ Parse the command-line arguments, going through some weird contortions
    to not allow the ArgumentParser to output anything to the standard error
    stream, since we want to report all errors in JSON form. """
    parser = argparse.ArgumentParser(
        prog='pycli',
        description='StorPool non-interactive CLI and stuff',
    )
    parser.add_argument('-N', '--noop', action='store_true',
                        help='No-operation mode')
    parser.add_argument('--json', type=str,
                        help='JSON arguments to send to the API')
    parser.add_argument('-C', '--clustername', type=str,
                        help='Name of a remote cluster to send the command to')
    parser.add_argument('-M', '--multicluster', action='store_true',
                        help='Enable multicluster mode')
    parser.add_argument('-P', '--post', action='store_true',
                        help='Use a POST query instead of a GET one')
    parser.add_argument('query', type=str,
                        help='The HTTP query to send')
    parser.add_argument('args', type=str, nargs='*',
                        help='Arguments to pass to the API')

    # OK, so this is a bit weird...
    errbuf = six.moves.StringIO()
    orig_stderr = sys.stderr
    sys.stderr = errbuf
    try:
        args = parser.parse_args()
    except SystemExit as ex_err:
        sys.stderr = orig_stderr
        if ex_err.code == 0:
            sys.exit(0)
        err_exit('cliParseArgs',
                 'Could not parse the command-line arguments',
                 parser_errors=errbuf.getvalue())
    except BaseException as err:  # pylint: disable=broad-except
        sys.stderr = orig_stderr
        err_exit('cliParseArgs', str(err),
                 parser_errors=errbuf.getvalue())

    sys.stderr = orig_stderr
    return args

def get_api_method(args):
    """ Find the API method with the specified name and HTTP method.

    Validate the number of arguments passed. """
    http_method = 'POST' if args.post else 'GET'

    try:
        api = from_config_with_overrides(multiCluster=args.multicluster)
    except KeyError as k_err:
        err_exit('cliMissingConfigVariable',
                 'Missing CLI configuration variable',
                 missing=k_err.args[0])
    except BaseException as err:  # pylint: disable=broad-except
        err_exit('cliInitAPI', str(err))

    for name in dir(api):
        method = getattr(api, name, None)
        if method is None:
            continue
        doc = getattr(method, 'spDoc', None)
        if doc is None:
            continue
        query = getattr(doc, 'query', None)
        if query == args.query and doc.method == http_method:
            break
    else:
        err_exit('cliUnknownQuery', 'Unknown API query',
                 method=http_method, query=args.query)

    args_req = getattr(method.spDoc, 'args', {}).keys()
    if len(args_req) != len(args.args):
        re_arg = re.compile('[{] (?P<name> [^}]+) [}]', re.X)
        arg_names = re_arg.findall(method.spDoc.path)
        err_exit('cliInvalidNumberOfArguments',
                 'Invalid number of arguments supplied',
                 supplied_count=len(args.args),
                 required_count=len(args_req),
                 required_names=arg_names)

    json_req = getattr(method.spDoc, 'json', None) is not None
    if json_req and args.json is None:
        err_exit('cliJSONRequired',
                 'This method requires JSON data')
    elif args.json is not None and not json_req:
        err_exit('cliNoJSONRequired',
                 'This method does not require any JSON data')

    return method

def main():
    """ Main function: parse the arguments, make the call, report. """
    args = parse_args()
    method = get_api_method(args)
    method_args = args.args
    if args.json is not None:
        method_args.append(json.loads(args.json))
    method_kwargs = {"clusterName": args.clustername}

    if args.noop:
        print('About to invoke {method} with {args}, {kwargs}'
              .format(method=repr(method), args=repr(method_args),
                      kwargs=repr(method_kwargs)))
        return

    try:
        res = method(*method_args, **method_kwargs)
        print(json.dumps(deep_to_json(res), indent=2))
    except spapi.ApiError as err:
        print(json.dumps(err.json, indent=2), file=sys.stderr)
        sys.exit(3 if err.name == 'objectDoesNotExist' else 2)

if __name__ == '__main__':
    main()


text:
using System.Collections.Generic;
using Xunit;

namespace System.Linq.Expressions.Tests
{
    public static class BinaryGreaterThanOrEqualTests
    {
        public static IEnumerable<object[]> TestData()
        {
            foreach (bool useInterpreter in new bool[] { true, false })
            {
                yield return new object[] { new byte[] { 0, 1, byte.MaxValue }, useInterpreter };
                yield return new object[] { new char[] { '\0', '\b', 'A', '\uffff' }, useInterpreter };
                yield return new object[] { new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, useInterpreter };
                yield return new object[] { new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, useInterpreter };
                yield return new object[] { new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, useInterpreter };
                yield return new object[] { new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, useInterpreter };
                yield return new object[] { new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, useInterpreter };
                yield return new object[] { new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, useInterpreter };
                yield return new object[] { new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, useInterpreter };
                yield return new object[] { new uint[] { 0, 1, uint.MaxValue }, useInterpreter };
                yield return new object[] { new ulong[] { 0, 1, ulong.MaxValue }, useInterpreter };
                yield return new object[] { new ushort[] { 0, 1, ushort.MaxValue }, useInterpreter };

                yield return new object[] { new byte?[] { null, 0, 1, byte.MaxValue }, useInterpreter };
                yield return new object[] { new char?[] { null, '\0', '\b', 'A', '\uffff' }, useInterpreter };
                yield return new object[] { new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, useInterpreter };
                yield return new object[] { new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, useInterpreter };
                yield return new object[] { new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, useInterpreter };
                yield return new object[] { new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }, useInterpreter };
                yield return new object[] { new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }, useInterpreter };
                yield return new object[] { new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, useInterpreter };
                yield return new object[] { new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }, useInterpreter };
                yield return new object[] { new uint?[] { null, 0, 1, uint.MaxValue }, useInterpreter };
                yield return new object[] { new ulong?[] { null, 0, 1, ulong.MaxValue }, useInterpreter };
                yield return new object[] { new ushort?[] { null, 0, 1, ushort.MaxValue }, useInterpreter };
            }
        }

        [Theory]
        [MemberData(nameof(TestData))]
        public static void GreaterThanOrEqual(Array array, bool useInterpreter)
        {
            Type type = array.GetType().GetElementType();
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array.Length; j++)
                {
                    object a = array.GetValue(i);
                    object b = array.GetValue(j);
                    BinaryExpression equal = Expression.GreaterThanOrEqual(Expression.Constant(a, type), Expression.Constant(b, type));
                    GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomGreaterThanOrEqual(a, b));
                }
            }
        }

        [Theory]
        [MemberData(nameof(TestData))]
        public static void GreaterThan(Array array, bool useInterpreter)
        {
            Type type = array.GetType().GetElementType();
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array.Length; j++)
                {
                    object a = array.GetValue(i);
                    object b = array.GetValue(j);
                    BinaryExpression equal = Expression.GreaterThan(Expression.Constant(a, type), Expression.Constant(b, type));
                    GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomGreaterThan(a, b));
                }
            }
        }

        [Theory]
        [MemberData(nameof(TestData))]
        public static void LessThanOrEqual(Array array, bool useInterpreter)
        {
            Type type = array.GetType().GetElementType();
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array.Length; j++)
                {
                    object a = array.GetValue(i);
                    object b = array.GetValue(j);
                    BinaryExpression equal = Expression.LessThanOrEqual(Expression.Constant(a, type), Expression.Constant(b, type));
                    GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomLessThanOrEqual(a, b));
                }
            }
        }

        [Theory]
        [MemberData(nameof(TestData))]
        public static void LessThan(Array array, bool useInterpreter)
        {
            Type type = array.GetType().GetElementType();
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array.Length; j++)
                {
                    object a = array.GetValue(i);
                    object b = array.GetValue(j);
                    BinaryExpression equal = Expression.LessThan(Expression.Constant(a, type), Expression.Constant(b, type));
                    GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomLessThan(a, b));
                }
            }
        }

        [Fact]
        public static void GreaterThanOrEqual_CannotReduce()
        {
            Expression exp = Expression.GreaterThanOrEqual(Expression.Constant(0), Expression.Constant(0));
            Assert.False(exp.CanReduce);
            Assert.Same(exp, exp.Reduce());
            Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
        }

        [Fact]
        public static void GreaterThan_CannotReduce()
        {
            Expression exp = Expression.GreaterThan(Expression.Constant(0), Expression.Constant(0));
            Assert.False(exp.CanReduce);
            Assert.Same(exp, exp.Reduce());
            Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
        }

        [Fact]
        public static void LessThanOrEqual_CannotReduce()
        {
            Expression exp = Expression.LessThanOrEqual(Expression.Constant(0), Expression.Constant(0));
            Assert.False(exp.CanReduce);
            Assert.Same(exp, exp.Reduce());
            Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
        }

        [Fact]
        public static void LessThan_CannotReduce()
        {
            Expression exp = Expression.LessThan(Expression.Constant(0), Expression.Constant(0));
            Assert.False(exp.CanReduce);
            Assert.Same(exp, exp.Reduce());
            Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
        }

        [Fact]
        public static void ThrowsOnLeftNull()
        {
            Assert.Throws<ArgumentNullException>("left", () => Expression.GreaterThanOrEqual(null, Expression.Constant(0)));
            Assert.Throws<ArgumentNullException>("left", () => Expression.GreaterThan(null, Expression.Constant(0)));
            Assert.Throws<ArgumentNullException>("left", () => Expression.LessThanOrEqual(null, Expression.Constant(0)));
            Assert.Throws<ArgumentNullException>("left", () => Expression.LessThanOrEqual(null, Expression.Constant(0)));
        }

        [Fact]
        public static void ThrowsOnRightNull()
        {
            Assert.Throws<ArgumentNullException>("right", () => Expression.GreaterThanOrEqual(Expression.Constant(0), null));
            Assert.Throws<ArgumentNullException>("right", () => Expression.GreaterThan(Expression.Constant(0), null));
            Assert.Throws<ArgumentNullException>("right", () => Expression.LessThanOrEqual(Expression.Constant(0), null));
            Assert.Throws<ArgumentNullException>("right", () => Expression.LessThan(Expression.Constant(0), null));
        }

        private static class Unreadable<T>
        {
            public static T WriteOnly
            {
                set { }
            }
        }

        [Fact]
        public static void ThrowsOnLeftUnreadable()
        {
            Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
            Assert.Throws<ArgumentException>("left", () => Expression.GreaterThanOrEqual(value, Expression.Constant(1)));
            Assert.Throws<ArgumentException>("left", () => Expression.GreaterThan(value, Expression.Constant(1)));
            Assert.Throws<ArgumentException>("left", () => Expression.LessThanOrEqual(value, Expression.Constant(1)));
            Assert.Throws<ArgumentException>("left", () => Expression.LessThan(value, Expression.Constant(1)));
        }

        [Fact]
        public static void ThrowsOnRightUnreadable()
        {
            Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
            Assert.Throws<ArgumentException>("right", () => Expression.GreaterThanOrEqual(Expression.Constant(1), value));
            Assert.Throws<ArgumentException>("right", () => Expression.GreaterThan(Expression.Constant(1), value));
            Assert.Throws<ArgumentException>("right", () => Expression.LessThanOrEqual(Expression.Constant(1), value));
            Assert.Throws<ArgumentException>("right", () => Expression.LessThan(Expression.Constant(1), value));
        }

        [Fact]
        public static void GreaterThanOrEqual_ToString()
        {
            BinaryExpression e = Expression.GreaterThanOrEqual(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
            Assert.Equal("(a >= b)", e.ToString());
        }

        [Fact]
        public static void GreaterThan_ToString()
        {
            BinaryExpression e = Expression.GreaterThan(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
            Assert.Equal("(a > b)", e.ToString());
        }

        [Fact]
        public static void LessThanOrEqual_ToString()
        {
            BinaryExpression e = Expression.LessThanOrEqual(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
            Assert.Equal("(a <= b)", e.ToString());
        }

        [Fact]
        public static void LessThan_ToString()
        {
            BinaryExpression e = Expression.LessThan(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
            Assert.Equal("(a < b)", e.ToString());
        }
    }
}


text:
/**

\file CommandBuilder.h
\brief Contains declaration of CommandBuilder class.

*//*******************************************************************/

#ifndef __COMMANDBUILDER__
#define __COMMANDBUILDER__

class Command;
class wxString;

// CommandBuilder has the task of validating and interpreting a command string.
// If the string represents a valid command, it builds the command object.

class CommandBuilder
{
   private:
      bool mValid;
      Command *mCommand;
      wxString mError;

      void Failure(const wxString &msg = wxEmptyString);
      void Success(Command *cmd);
      void BuildCommand(const wxString &cmdName, wxString cmdParams);
      void BuildCommand(wxString cmdString);
   public:
      CommandBuilder(const wxString &cmdString);
      CommandBuilder(const wxString &cmdName,
                     const wxString &cmdParams);
      ~CommandBuilder();
      bool WasValid();
      Command *GetCommand();
      void Cleanup();
      const wxString &GetErrorMessage();
};
#endif /* End of include guard: __COMMANDBUILDER__ */


text:
'''
Created on 08 dec. 2015

@author: arxit
'''

from qgis.gui import QgsEditorWidgetWrapper, QgsEditorConfigWidget, QgsEditorWidgetFactory, QgsEditorWidgetRegistry, QgsFilterLineEdit
from qgis.core import NULL
from PyQt4.QtGui import QWidget, QPalette, QPushButton, QGridLayout, QLineEdit, QFileDialog, QLabel, QHBoxLayout
from PyQt4.QtCore import QCoreApplication, QFileInfo, QSettings

import os.path

class SimpleFilenameWidgetWrapper(QgsEditorWidgetWrapper):
    def value(self):
        if self.mLineEdit is not None:
            if self.mLineEdit.text() == str(QSettings().value('qgis/nullValue', 'NULL' )) or self.mLineEdit.text() == '':
                value = NULL
            else:
                value = self.mLineEdit.text()

        if self.mLabel is not None:
            value = self.mLabel.text();

        return value

    def setValue(self, value):
        if self.mLineEdit is not None:
            if value == NULL or value is None:
                self.mLineEdit.setText(str(QSettings().value('qgis/nullValue', 'NULL')))
            else:
                self.mLineEdit.setText(value)

        if self.mLabel is not None:
            self.mLabel.setText(value)

    def createWidget(self, parent):
        '''
        #Create a new empty widget
        '''

        container = QWidget(parent)
        container.setBackgroundRole(QPalette.Window)
        container.setAutoFillBackground(True)

        le = QgsFilterLineEdit(container)
        pbn = QPushButton('...', container)
        layout = QGridLayout()

        layout.setMargin(0)
        layout.addWidget(le, 0, 0);
        layout.addWidget(pbn, 0, 1);

        container.setLayout(layout);

        return container

    def initWidget(self, editor):
        self.mLineEdit = editor if type(editor) is QLineEdit else editor.findChild(QLineEdit)

        self.mPushButton = editor.findChild(QPushButton)

        if self.mPushButton is not None:
            self.mPushButton.clicked.connect(self.selectFileName)

        self.mLabel = editor if type(editor) is QLabel else None

        if self.mLineEdit is not None:
            fle = editor
            if type(fle) is QgsFilterLineEdit:
                fle.setNullValue(str(QSettings().value('qgis/nullValue', 'NULL')))

            self.mLineEdit.textChanged.connect(self.onTextChanged)

    def onTextChanged(self, newText):
        self.valueChanged.emit(newText)

    def valid(self):
        return self.mLineEdit is not None or self.mLabel is not None

    def selectFileName(self):
        if self.mLineEdit is not None:
            text = self.mLineEdit.text()

        if self.mLabel is not None:
            text = self.mLabel.text()

        fileName = QFileDialog.getOpenFileName(self.mLineEdit,
                                               QCoreApplication.translate('SimpleFilenameWidgetWrapper','Select a file'),
                                               QFileInfo(text).absolutePath())

        if fileName.strip() == u'':
            return

        fileName = os.path.splitext(os.path.basename(fileName.strip()))[0]

        if self.mLineEdit is not None:
            self.mLineEdit.setText(fileName)

        if self.mLabel is not None:
            self.mLineEdit.setText(fileName)

class SimpleFilenameWidgetWrapperConfig(QgsEditorConfigWidget):
    def __init__(self, layer, idx, parent):
        QgsEditorConfigWidget.__init__(self, layer, idx, parent)

        self.setLayout(QHBoxLayout())
        self.ruleEdit = QLabel(self)
        self.ruleEdit.setText(QCoreApplication.translate('SimpleFilenameWidgetWrapperConfig','A filename without extension editor widget.'))
        self.layout().addWidget(self.ruleEdit)

    def config(self):
        return {}

    def setConfig(self, config):
        pass

class SimpleFilenameWidgetWrapperFactory(QgsEditorWidgetFactory):
    def __init__(self):
        QgsEditorWidgetFactory.__init__(self, QCoreApplication.translate('SimpleFilenameWidgetWrapperFactory','Simple Filename'))

    def create(self, layer, fieldIdx, editor, parent):
        return SimpleFilenameWidgetWrapper(layer, fieldIdx, editor, parent)

    def configWidget(self, layer, idx, parent):
        return SimpleFilenameWidgetWrapperConfig(layer, idx, parent)

myFactory = SimpleFilenameWidgetWrapperFactory()
QgsEditorWidgetRegistry.instance().registerWidget('SimpleFilename', myFactory)


text:
from typing import List

import datahub.emitter.mce_builder as builder
from datahub.emitter.mcp import MetadataChangeProposalWrapper
from datahub.emitter.rest_emitter import DatahubRestEmitter
from datahub.metadata.com.linkedin.pegasus2avro.dataset import (
    DatasetLineageTypeClass,
    UpstreamClass,
    UpstreamLineage,
)
from datahub.metadata.schema_classes import ChangeTypeClass

# Construct upstream tables.
upstream_tables: List[UpstreamClass] = []
upstream_table_1 = UpstreamClass(
    dataset=builder.make_dataset_urn("bigquery", "upstream_table_1", "PROD"),
    type=DatasetLineageTypeClass.TRANSFORMED,
)
upstream_tables.append(upstream_table_1)
upstream_table_2 = UpstreamClass(
    dataset=builder.make_dataset_urn("bigquery", "upstream_table_2", "PROD"),
    type=DatasetLineageTypeClass.TRANSFORMED,
)
upstream_tables.append(upstream_table_2)

# Construct a lineage object.
upstream_lineage = UpstreamLineage(upstreams=upstream_tables)

# Construct a MetadataChangeProposalWrapper object.
lineage_mcp = MetadataChangeProposalWrapper(
    entityType="dataset",
    changeType=ChangeTypeClass.UPSERT,
    entityUrn=builder.make_dataset_urn("bigquery", "downstream"),
    aspectName="upstreamLineage",
    aspect=upstream_lineage,
)

# Create an emitter to the GMS REST API.
emitter = DatahubRestEmitter("http://localhost:8080")

# Emit metadata!
emitter.emit_mcp(lineage_mcp)


text:
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Unit Test -- message</title>
  </head>
  <body>
    <script src="bower_components/testjs/test.js"></script>
    <script src="message.js"></script>
    <script src="message_test.js"></script>
  </body>
</html>