text:
package idemix

import (
	"io"

	amcl "github.com/IBM/idemix/bccsp/schemes/dlog/crypto/translator/amcl"
	math "github.com/IBM/mathlib"
	"github.com/pkg/errors"
)

type Translator interface {
	G1ToProto(*math.G1) *amcl.ECP
	G1FromProto(*amcl.ECP) (*math.G1, error)
	G1FromRawBytes([]byte) (*math.G1, error)
	G2ToProto(*math.G2) *amcl.ECP2
	G2FromProto(*amcl.ECP2) (*math.G2, error)
}

// Identity Mixer Credential is a list of attributes certified (signed) by the issuer
// A credential also contains a user secret key blindly signed by the issuer
// Without the secret key the credential cannot be used

// Credential issuance is an interactive protocol between a user and an issuer
// The issuer takes its secret and public keys and user attribute values as input
// The user takes the issuer public key and user secret as input
// The issuance protocol consists of the following steps:
// 1) The issuer sends a random nonce to the user
// 2) The user creates a Credential Request using the public key of the issuer, user secret, and the nonce as input
//    The request consists of a commitment to the user secret (can be seen as a public key) and a zero-knowledge proof
//     of knowledge of the user secret key
//    The user sends the credential request to the issuer
// 3) The issuer verifies the credential request by verifying the zero-knowledge proof
//    If the request is valid, the issuer issues a credential to the user by signing the commitment to the secret key
//    together with the attribute values and sends the credential back to the user
// 4) The user verifies the issuer's signature and stores the credential that consists of
//    the signature value, a randomness used to create the signature, the user secret, and the attribute values

// NewCredential issues a new credential, which is the last step of the interactive issuance protocol
// All attribute values are added by the issuer at this step and then signed together with a commitment to
// the user's secret key from a credential request
func (i *Idemix) NewCredential(key *IssuerKey, m *CredRequest, attrs []*math.Zr, rng io.Reader, t Translator) (*Credential, error) {
	return newCredential(key, m, attrs, rng, t, i.Curve)
}

func newCredential(key *IssuerKey, m *CredRequest, attrs []*math.Zr, rng io.Reader, t Translator, curve *math.Curve) (*Credential, error) {
	// check the credential request that contains
	err := m.Check(key.Ipk, curve, t)
	if err != nil {
		return nil, err
	}

	if len(attrs) != len(key.Ipk.AttributeNames) {
		return nil, errors.Errorf("incorrect number of attribute values passed")
	}

	// Place a BBS+ signature on the user key and the attribute values
	// (For BBS+, see e.g. "Constant-Size Dynamic k-TAA" by Man Ho Au, Willy Susilo, Yi Mu)
	// or http://eprint.iacr.org/2016/663.pdf, Sec. 4.3.

	// For a credential, a BBS+ signature consists of the following three elements:
	// 1. E, random value in the proper group
	// 2. S, random value in the proper group
	// 3. A as B^Exp where B=g_1 \cdot h_r^s \cdot h_sk^sk \cdot \prod_{i=1}^L h_i^{m_i} and Exp = \frac{1}{e+x}
	// Notice that:
	// h_r is h_0 in http://eprint.iacr.org/2016/663.pdf, Sec. 4.3.

	// Pick randomness E and S
	E := curve.NewRandomZr(rng)
	S := curve.NewRandomZr(rng)

	// Set B as g_1 \cdot h_r^s \cdot h_sk^sk \cdot \prod_{i=1}^L h_i^{m_i} and Exp = \frac{1}{e+x}
	B := curve.NewG1()
	B.Clone(curve.GenG1) // g_1
	Nym, err := t.G1FromProto(m.Nym)
	if err != nil {
		return nil, err
	}
	B.Add(Nym) // in this case, recall Nym=h_sk^sk
	HRand, err := t.G1FromProto(key.Ipk.HRand)
	if err != nil {
		return nil, err
	}
	B.Add(HRand.Mul(S)) // h_r^s

	HAttrs := make([]*math.G1, len(key.Ipk.HAttrs))
	for i := range key.Ipk.HAttrs {
		var err error
		HAttrs[i], err = t.G1FromProto(key.Ipk.HAttrs[i])
		if err != nil {
			return nil, err
		}
	}

	// Append attributes
	// Use Mul2 instead of Mul as much as possible for efficiency reasones
	for i := 0; i < len(attrs)/2; i++ {
		B.Add(
			// Add two attributes in one shot
			HAttrs[2*i].Mul2(
				attrs[2*i],
				HAttrs[2*i+1],
				attrs[2*i+1],
			),
		)
	}
	// Check for residue in case len(attrs)%2 is odd
	if len(attrs)%2 != 0 {
		B.Add(HAttrs[len(attrs)-1].Mul(attrs[len(attrs)-1]))
	}

	// Set Exp as \frac{1}{e+x}
	Exp := curve.ModAdd(curve.NewZrFromBytes(key.GetIsk()), E, curve.GroupOrder)
	Exp.InvModP(curve.GroupOrder)
	// Finalise A as B^Exp
	A := B.Mul(Exp)
	// The signature is now generated.

	// Notice that here we release also B, this does not harm security cause
	// it can be compute publicly from the BBS+ signature itself.
	CredAttrs := make([][]byte, len(attrs))
	for index, attribute := range attrs {
		CredAttrs[index] = attribute.Bytes()
	}

	return &Credential{
		A:     t.G1ToProto(A),
		B:     t.G1ToProto(B),
		E:     E.Bytes(),
		S:     S.Bytes(),
		Attrs: CredAttrs}, nil
}

// Ver cryptographically verifies the credential by verifying the signature
// on the attribute values and user's secret key
func (cred *Credential) Ver(sk *math.Zr, ipk *IssuerPublicKey, curve *math.Curve, t Translator) error {
	// Validate Input

	// - parse the credential
	A, err := t.G1FromProto(cred.GetA())
	if err != nil {
		return err
	}
	B, err := t.G1FromProto(cred.GetB())
	if err != nil {
		return err
	}
	E := curve.NewZrFromBytes(cred.GetE())
	S := curve.NewZrFromBytes(cred.GetS())

	// - verify that all attribute values are present
	for i := 0; i < len(cred.GetAttrs()); i++ {
		if cred.Attrs[i] == nil {
			return errors.Errorf("credential has no value for attribute %s", ipk.AttributeNames[i])
		}
	}

	HSk, err := t.G1FromProto(ipk.HSk)
	if err != nil {
		return err
	}

	HRand, err := t.G1FromProto(ipk.HRand)
	if err != nil {
		return err
	}

	HAttrs := make([]*math.G1, len(ipk.HAttrs))
	for i := range ipk.HAttrs {
		var err error
		HAttrs[i], err = t.G1FromProto(ipk.HAttrs[i])
		if err != nil {
			return err
		}
	}

	// - verify cryptographic signature on the attributes and the user secret key
	BPrime := curve.NewG1()
	BPrime.Clone(curve.GenG1)
	BPrime.Add(HSk.Mul2(sk, HRand, S))
	for i := 0; i < len(cred.Attrs)/2; i++ {
		BPrime.Add(
			HAttrs[2*i].Mul2(
				curve.NewZrFromBytes(cred.Attrs[2*i]),
				HAttrs[2*i+1],
				curve.NewZrFromBytes(cred.Attrs[2*i+1]),
			),
		)
	}
	if len(cred.Attrs)%2 != 0 {
		BPrime.Add(HAttrs[len(cred.Attrs)-1].Mul(curve.NewZrFromBytes(cred.Attrs[len(cred.Attrs)-1])))
	}
	if !B.Equals(BPrime) {
		return errors.Errorf("b-value from credential does not match the attribute values")
	}

	W, err := t.G2FromProto(ipk.W)
	if err != nil {
		return err
	}

	// Verify BBS+ signature. Namely: e(w \cdot g_2^e, A) =? e(g_2, B)
	a := curve.GenG2.Mul(E)
	a.Add(W)
	a.Affine()

	left := curve.FExp(curve.Pairing(a, A))
	right := curve.FExp(curve.Pairing(curve.GenG2, B))

	if !left.Equals(right) {
		return errors.Errorf("credential is not cryptographically valid")
	}

	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathEasy.src.LMD.Math
{
    public class Bracket : Expression
    {
        public enum TypeOfBracket
        {
            Parentheses,    // ()
            Braces,         // []
            Chevrons        // {}
        }

        public Expression Content { get; set; }
        public TypeOfBracket Type { get; set; }

        public Bracket(Expression Content, TypeOfBracket Type)
        {
            this.Content = Content;
            this.Type = Type;
        }

        public Expression evaluate()
        {
            return Content.evaluate();
        }

        public String toHTML()
        {
            if (Type == TypeOfBracket.Parentheses)
            {
                return @"\left(" + Content.toHTML() + @"\right)";
            }
            else if (Type == TypeOfBracket.Braces)
            {
                return @"\left[" + Content.toHTML() + @"\right]";
            }
            else
            {
                return @"\left\{" + Content.toHTML() + @"\right\}";
            }
        }

        public String toText()
        {
            if (Type == TypeOfBracket.Parentheses)
            {
                return @"( " + Content.toText() + @" )";
            }
            else if (Type == TypeOfBracket.Braces)
            {
                return @"[ " + Content.toText() + @" ]";
            }
            else
            {
                return @"{ " + Content.toText() + @" }";
            }
        }

        public bool canEvaluateIfSymbolsConst(Symbol[] availableSymbols)
        {
            return Content.canEvaluateIfSymbolsConst(availableSymbols);
        }

        public Expression cloneAndSubstitute(List<KeyValuePair<Symbol, Constant>> availableSymbols)
        {
            Expression cContent = Content.replaceWithValue(availableSymbols);

            if (cContent == null)
            {
                cContent = Content.cloneAndSubstitute(availableSymbols);
            }

            return new Bracket(cContent, Type);
        }

        public List<Symbol> symbolsInExpression(List<Symbol> symbols)
        {
            return Content.symbolsInExpression(symbols);
        }

        public static String ParLeftValidator(String input)
        {
            return (input[0] == '(') ? "(" : null;
        }

        public static String ParRightValidator(String input)
        {
            return (input[0] == ')') ? ")" : null;
        }

        public static String BraceLeftValidator(String input)
        {
            return (input[0] == '[') ? "[" : null;
        }

        public static String BraceRightValidator(String input)
        {
            return (input[0] == ']') ? "]" : null;
        }

        public static String ChevLeftValidator(String input)
        {
            return (input[0] == '{') ? "{" : null;
        }

        public static String ChevRightValidator(String input)
        {
            return (input[0] == '}') ? "}" : null;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import Builders from '../builders';
import Texture from '../../gl/texture';
import WorkerBroker from '../../utils/worker_broker';
import Utils from '../../utils/utils';
import {Points} from '../points/points';
import LabelBuilder from './label_builder';
import FeatureLabel from './feature_label';
import LabelOptions from './label_options';
import {StyleParser} from '../style_parser';

import log from 'loglevel';

export let TextStyle = Object.create(Points);

Object.assign(TextStyle, {
    name: 'text',
    super: Points,
    built_in: true,
    selection: false, // no feature selection for text by default

    init() {

        this.super.init.apply(this, arguments);

        // Provide a hook for this object to be called from worker threads
        this.main_thread_target = 'TextStyle-' + this.name;
        if (Utils.isMainThread) {
            WorkerBroker.addTarget(this.main_thread_target, this);
        }

        // Point style (parent class) requires texturing to be turned on
        // (labels are always drawn with textures)
        this.defines.TANGRAM_POINT_TEXTURE = true;

        // Manually un-multiply alpha, because Canvas text rasterization is pre-multiplied
        // See https://github.com/tangrams/tangram/issues/179
        this.defines.TANGRAM_UNMULTIPLY_ALPHA = true;

        // default font style
        this.default_font_style = {
            style: 'normal',
            weight: null,
            size: '12px',
            family: 'Helvetica',
            fill: 'white'
        };

        this.reset();
    },

    reset() {
        this.super.reset.call(this);
        this.texts = {}; // unique texts, keyed by tile
        this.textures = {};
        this.canvas = {};
        this.aabbs = {};
        this.features = {};
        this.feature_labels = {};
        this.feature_style_key = {};
    },

    // Called on main thread to release tile-specific resources
    freeTile (tile) {
        delete this.texts[tile];
        delete this.textures[tile];
        delete this.canvas[tile];
        delete this.aabbs[tile];
        // cleanup stored features for this tile
        for (let key in this.features) {
            let features = this.features[key];
            for (let i = 0; i < features.length; ++i) {
                if (features[i].tile_key === tile) {
                    delete features[i];
                }
            }
            if (Object.keys(features).length === 0) {
                delete this.features[key];
            }
        }
        delete this.feature_labels[tile];
        delete this.feature_style_key[tile];
    },

    // Set font style params for canvas drawing
    setFont (tile, { font_css, fill, stroke, stroke_width, px_size, px_logical_size }) {
        this.px_size = parseInt(px_size);
        this.px_logical_size = parseInt(px_logical_size);
        this.text_buffer = 8; // pixel padding around text
        let ctx = this.canvas[tile].context;

        ctx.font = font_css;
        if (stroke) {
            ctx.strokeStyle = stroke;
            ctx.lineWidth = stroke_width;
        }
        else {
            ctx.strokeStyle = null;
            ctx.lineWidth = 0;
        }
        ctx.fillStyle = fill;
        ctx.miterLimit = 2;
    },

    // Width and height of text based on current font style
    textSize (text, tile, transform) {
        let str = FeatureLabel.applyTextTransform(text, transform);
        let ctx = this.canvas[tile].context;
        let px_size = this.px_size;
        let px_logical_size = this.px_logical_size;
        let buffer = this.text_buffer * Utils.device_pixel_ratio;

        let str_width = ctx.measureText(str).width;
        let text_size = [
            str_width / Utils.device_pixel_ratio,
            this.px_size / Utils.device_pixel_ratio
        ];

        let texture_text_size = [
            Math.ceil(str_width) + buffer * 2,
            this.px_size + buffer * 2
        ];

        return { text_size, texture_text_size, px_size, px_logical_size };
    },

    // Draw text at specified location, adjusting for buffer and baseline
    drawText (text, [x, y], tile, stroke, transform) {
        let str = FeatureLabel.applyTextTransform(text, transform);
        let buffer = this.text_buffer * Utils.device_pixel_ratio;
        if (stroke) {
            this.canvas[tile].context.strokeText(str, x + buffer, y + buffer + this.px_size);
        }
        this.canvas[tile].context.fillText(str, x + buffer, y + buffer + this.px_size);
    },

    setTextureTextPositions (texts) {
        // Find widest label and sum of all label heights
        let widest = 0, height = 0;

        for (let style in texts) {
            let text_infos = texts[style];

            for (let text in text_infos) {
                let text_info = text_infos[text];
                let size = text_info.size.texture_text_size;

                text_info.position = [0, height];

                if (size[0] > widest) {
                    widest = size[0];
                }

                height += size[1];
            }
        }

        return [ widest, height ];
    },

    getTextSizes (tile, texts) {
        // create a canvas
        if(!this.canvas[tile]) {
            let canvas = document.createElement('canvas');
            this.canvas[tile] = {
                canvas: canvas,
                context: canvas.getContext('2d')
            };
        }

        for (let style in texts) {
            let text_infos = texts[style];

            for (let text in text_infos) {
                let text_style = text_infos[text].text_style;
                // update text sizes
                this.setFont(tile, text_style); // TODO: only set once above
                text_infos[text].size = this.textSize(text, tile, text_style.transform);
            }
        }

        return Promise.resolve(texts);
    },

    rasterize (tile, texts, texture_size) {
        for (let style in texts) {
            let text_infos = texts[style];

            for (let text in text_infos) {
                let info = text_infos[text];

                this.setFont(tile, info.text_style); // TODO: only set once above
                this.drawText(text, info.position, tile, info.text_style.stroke, info.text_style.transform);

                info.texcoords = Builders.getTexcoordsForSprite(
                    info.position,
                    info.size.texture_text_size,
                    texture_size
                );
            }
        }
    },

    // Called on main thread from worker, to create atlas of labels for a tile
    addTexts (tile, texts) {
        if (!this.canvas[tile]) {
            return Promise.resolve({});
        }

        let texture_size = this.setTextureTextPositions(texts);
        let context = this.canvas[tile].context;

        log.trace(`text summary for tile ${tile}: fits in ${texture_size[0]}x${texture_size[1]}px`);

        // update the canvas "context"
        this.canvas[tile].canvas.width = texture_size[0];
        this.canvas[tile].canvas.height = texture_size[1];
        context.clearRect(0, 0, texture_size[0], texture_size[1]);

        // create a texture
        let texture = 'labels-' + tile + '-' + (TextStyle.texture_id++);
        this.textures[tile] = new Texture(this.gl, texture, { filtering: 'linear' });

        // ask for rasterization for the text set
        this.rasterize(tile, texts, texture_size);

        this.textures[tile].setCanvas(this.canvas[tile].canvas);

        // we don't need tile canvas/texture once it has been copied to to GPU
        delete this.textures[tile];
        delete this.canvas[tile];

        return Promise.resolve({ texts, texture });
    },

    // Override
    startData (tile) {
        let tile_data = this.super.startData.apply(this, arguments);
        tile_data.queue = [];
        return tile_data;
    },

    createLabels (tile, texts) {
        let labels_priorities = {};

        for (let style in texts) {
            let text_infos = texts[style];

            for (let text in text_infos) {
                let text_info = text_infos[text];
                text_info.ref = 0;

                let hash = Utils.hashString(tile + style + text);

                if (!this.features[hash]) {
                    continue;
                }

                let label_features = this.features[hash];

                for (let i = 0; i < label_features.length; ++i) {
                    let label_feature = label_features[i];
                    let feature = label_feature.feature;
                    let options = new LabelOptions({
                        units_per_pixel: text_info.units_per_pixel,
                        offset: text_info.offset,
                        buffer: text_info.buffer,
                        line_exceed: text_info.line_exceed
                    });

                    let labels = LabelBuilder.buildFromGeometry(text, text_info.size, feature.geometry, options);

                    for (let i = 0; i < labels.length; ++i) {
                        let label = labels[i];
                        let area = label.area;

                        labels_priorities[text_info.priority] = labels_priorities[text_info.priority] || [];
                        labels_priorities[text_info.priority].push({ style, feature, label, area });
                    }
                }
            }
        }

        // sort by area size if defined
        for (let p = 0; p < labels_priorities.length; ++p) {
            if (!labels_priorities[p]) {
                continue;
            }

            labels_priorities[p].sort((e1, e2) => {
                if (e1.area && e2.area) {
                    return e1.area < e2.area;
                } else {
                    return false;
                }
            });
        }

        return labels_priorities;
    },

    discardLabels (tile, labels, texts) {
        this.aabbs[tile] = [];
        this.feature_labels[tile] = new Map();

        // Process labels by priority
        let priorities = Object.keys(labels).sort((a, b) => a - b);
        for (let priority of priorities) {
            if (!labels[priority]) {
                continue;
            }

            for (let i = 0; i < labels[priority].length; i++) {
                let { style, feature, label } = labels[priority][i];

                if (!label.discard(this.aabbs[tile])) {
                    if (!this.feature_labels[tile].has(feature)) {
                        this.feature_labels[tile].set(feature, []);
                    }
                    this.feature_labels[tile].get(feature).push(label);
                    texts[style][label.text].ref++;
                }
            }
        }

        for (let style in texts) {
            for (let text in texts[style]) {
                if (texts[style][text].ref < 1) {
                    delete texts[style][text];
                }
            }
        }

        for (let style in texts) {
            let text_infos = texts[style];
            // No labels for this style
            if (Object.keys(text_infos).length === 0) {
                delete texts[style];
            }
        }
    },

    // Override
    endData (tile) {
        // Count collected text
        let count;
        let tile_data = this.tile_data[tile];

        if (tile_data.queue.length > 0) {
            count = Object.keys(this.texts[tile]||{}).length;
            log.trace(`# texts for tile ${tile}: ${count}`);
        }
        if (!count) {
            return Promise.resolve();
        }

        // first call to main thread, ask for text pixel sizes
        return WorkerBroker.postMessage(this.main_thread_target, 'getTextSizes', tile, this.texts[tile]).then(texts => {
            if (!texts) {
                this.freeTile(tile);
                return this.super.endData.apply(this, arguments);
            }

            let labels = this.createLabels(tile, texts);
            if (!labels) {
                this.freeTile(tile);
                return this.super.endData.apply(this, arguments);
            }

            this.discardLabels(tile, labels, texts);

            // No labels for this tile
            if (Object.keys(texts).length === 0) {
                this.freeTile(tile);
                WorkerBroker.postMessage(this.main_thread_target, 'freeTile', tile);
                // early exit
                return;
            }

            // second call to main thread, for rasterizing the set of texts
            return WorkerBroker.postMessage(this.main_thread_target, 'addTexts', tile, texts).then(({ texts, texture }) => {
                if (texts) {
                    this.texts[tile] = texts;

                    // Attach tile-specific label atlas to mesh as a texture uniform
                    tile_data.uniforms = { u_texture: texture };
                    tile_data.textures = [texture]; // assign texture ownership to tile - TODO: implement in VBOMesh

                    // Build queued features
                    tile_data.queue.forEach(q => this.super.addFeature.apply(this, q));
                    tile_data.queue = [];
                }

                this.freeTile(tile);
                return this.super.endData.apply(this, arguments);
            });
        });
    },

    // Override to queue features instead of processing immediately
    addFeature (feature, rule, context) {
        let tile = context.tile;
        if (tile.generation !== this.generation) {
            return;
        }

        // Collect text
        let text;
        let source = rule.text_source || 'name';

        if (typeof source === 'string') {
            text = feature.properties[source];
        } else if (typeof source === 'function') {
            text = source(context);
        }

        if (text) {
            feature.text = text;

            if (!this.texts[tile.key]) {
                this.texts[tile.key] = this.texts[tile.key] || {};
            }

            // features stored by hash for later use from main thread (tile / text / style)
            let label_feature = new FeatureLabel(feature, rule, context, text, tile, this.default_font_style);
            let feature_hash = label_feature.getHash();

            if (!label_feature.style) {
                return;
            }

            let style_key = label_feature.style_key;
            this.feature_style_key[tile.key] = this.feature_style_key[tile.key] || new Map();
            this.feature_style_key[tile.key].set(feature, style_key);

            if (!this.texts[tile.key][style_key]) {
                this.texts[tile.key][style_key] = {};
            }

            // label priority (lower is higher)
            let priority = rule.priority;
            if (priority !== undefined) {
                // if priority is a number, use it as-is, otherwise, check type
                // if (typeof priority === 'string') {
                //     priority = feature.properties[priority]; // get priority from feature property
                // }
                // else if (typeof priority === 'function') {
                if (typeof priority === 'function') {
                    priority = priority(context);
                }
            }
            else {
                priority = -1 >>> 0; // default to max priority value if none set
            }

            // label offset in pixel (applied in screen space)
            let offset = rule.offset || [0, 0];
            offset[0] = parseFloat(offset[0]);
            offset[1] = parseFloat(offset[1]); // y-point down

            // label buffer in pixel
            let buffer = rule.buffer;
            if (buffer != null) {
                if (!Array.isArray(buffer)) {
                    buffer = [buffer, buffer]; // buffer can be 1D or 2D
                }

                buffer[0] = parseFloat(buffer[0]);
                buffer[1] = parseFloat(buffer[1]);
            }

            // label line exceed percentage
            let line_exceed;
            if (rule.line_exceed && rule.line_exceed.substr(-1) === '%') {
                line_exceed = rule.line_exceed.substr(0,rule.line_exceed.length-1);
            }

            if (!this.texts[tile.key][style_key][text]) {
                this.texts[tile.key][style_key][text] = {
                    text_style: label_feature.style,
                    units_per_pixel: tile.units_per_pixel,
                    priority,
                    offset,
                    buffer,
                    line_exceed,
                    ref: 0
                };
            }

            // add the label feature
            this.features = this.features || {};
            this.features[feature_hash] = this.features[feature_hash] || [];
            this.features[feature_hash].push(label_feature);

            if (!this.tile_data[tile.key]) {
                this.startData(tile.key);
            }
            this.tile_data[tile.key].queue.push([feature, rule, context]);
        }
    },

    build (style, vertex_data) {
        let vertex_template = this.makeVertexTemplate(style);

        for (let i in style.labels) {
            let label = style.labels[i];

            this.buildQuad(
                [label.position],
                label.size.texture_text_size,
                Utils.radToDeg(label.angle) || 0, vertex_data,
                vertex_template, label.options.offset
            );
        }
    },

    buildLines (lines, style, vertex_data) {
        this.build(style, vertex_data);
    },

    buildPoints (points, style, vertex_data) {
        this.build(style, vertex_data);
    },

    buildPolygons (points, style, vertex_data) {
        this.build(style, vertex_data);
    },

    _parseFeature (feature, rule_style, context) {
        let text = feature.text;

        let style = this.feature_style;
        let tile = context.tile.key;
        let style_key = this.feature_style_key[tile].get(feature);
        let text_info = this.texts[tile] && this.texts[tile][style_key] && this.texts[tile][style_key][text];

        if (!text_info || !this.feature_labels[tile].has(feature)) {
            return;
        }

        this.texcoord_scale = text_info.texcoords;
        style.text = text;
        style.labels = this.feature_labels[tile].get(feature);

        // TODO: point style (parent class) requires a color, setting it to white for now,
        // but could be made conditional in the vertex layout to save space
        style.color = TextStyle.white;

        // tell the point style (base class) that we want to render polygon labels at the polygon's centroid
        style.centroid = true;

        // points can be placed off the ground
        style.z = (rule_style.z && StyleParser.cacheDistance(rule_style.z, context)) || StyleParser.defaults.z;

        return style;
    }

});

TextStyle.texture_id = 0;
TextStyle.white = [1, 1, 1, 1];


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Cellars;

/**
 * CellarsSearch represents the model behind the search form about `app\models\Cellars`.
 */
class CellarsSearch extends Cellars
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'owner_id', 'created_at', 'default_cellar_loc_id'], 'integer'],
            [['cellar_name'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Cellars::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'owner_id' => $this->owner_id,
            'created_at' => $this->created_at,
            'default_cellar_loc_id' => $this->default_cellar_loc_id,
        ]);

        $query->andFilterWhere(['like', 'cellar_name', $this->cellar_name]);

        return $dataProvider;
    }
}


text:
using System.Linq;
using Orchard;
using Orchard.Environment.Extensions;
using Orchard.Environment.State;
using Orchard.Environment.State.Models;

namespace Lombiq.OrchardAppHost.Services.TransientHost
{
    /// <summary>
    /// An <see cref="Orchard.Environment.State.IShellStateManager"/> implementation that doesn't persist shell feature state.
    /// </summary>
    [OrchardFeature("Lombiq.OrchardAppHost.TransientHost")]
    public class TransientShellStateManager : IShellStateManager, ISingletonDependency
    {
        private const string StoreKey = "Lombiq.OrchardAppHost.TransientShellStateManager.ShellState";

        private readonly ITransientStore _transientStore;

        private ShellState ShellState
        {
            get { return _transientStore.Get<ShellState>(StoreKey); }
            set { _transientStore.Set(StoreKey, value); }
        }

        public TransientShellStateManager(ITransientStore transientStore)
        {
            _transientStore = transientStore;
        }

        public ShellState GetShellState()
        {
            return ShellState ?? new ShellState();
        }

        public void UpdateEnabledState(ShellFeatureState featureState, ShellFeatureState.State value)
        {
            GetOrAddFeatureState(featureState.Name).EnableState = value;

            featureState.EnableState = value;
        }

        public void UpdateInstalledState(ShellFeatureState featureState, ShellFeatureState.State value)
        {
            GetOrAddFeatureState(featureState.Name).InstallState = value;

            featureState.InstallState = value;
        }

        private ShellFeatureState GetOrAddFeatureState(string featureName)
        {
            var shellState = GetShellState();

            var feature = shellState.Features.SingleOrDefault(f => f.Name == featureName);
            if (feature == null)
            {
                feature = new ShellFeatureState { Name = featureName };
                shellState.Features = shellState.Features.Union(new[] { feature });
            }

            ShellState = shellState;

            return feature;
        }
    }
}


text:
module RuboCop
  module Cop
    module Style
      # This cop is designed to help you transition from mutable string literals
      # to frozen string literals.
      # It will add the `# frozen_string_literal: true` magic comment to the top
      # of files to enable frozen string literals. Frozen string literals may be
      # default in future Ruby. The comment will be added below a shebang and
      # encoding comment.
      #
      # Note that the cop will accept files where the comment exists but is set
      # to `false` instead of `true`.
      #
      # To require a blank line after this comment, please see
      # `Layout/EmptyLineAfterMagicComment` cop.
      #
      # @safety
      #  This cop's autocorrection is unsafe since any strings mutations will
      #  change from being accepted to raising `FrozenError`, as all strings
      #  will become frozen by default, and will need to be manually refactored.
      #
      # @example EnforcedStyle: always (default)
      #   # The `always` style will always add the frozen string literal comment
      #   # to a file, regardless of the Ruby version or if `freeze` or `<<` are
      #   # called on a string literal.
      #   # bad
      #   module Bar
      #     # ...
      #   end
      #
      #   # good
      #   # frozen_string_literal: true
      #
      #   module Bar
      #     # ...
      #   end
      #
      #   # good
      #   # frozen_string_literal: false
      #
      #   module Bar
      #     # ...
      #   end
      #
      # @example EnforcedStyle: never
      #   # The `never` will enforce that the frozen string literal comment does
      #   # not exist in a file.
      #   # bad
      #   # frozen_string_literal: true
      #
      #   module Baz
      #     # ...
      #   end
      #
      #   # good
      #   module Baz
      #     # ...
      #   end
      #
      # @example EnforcedStyle: always_true
      #   # The `always_true` style enforces that the frozen string literal
      #   # comment is set to `true`. This is a stricter option than `always`
      #   # and forces projects to use frozen string literals.
      #   # bad
      #   # frozen_string_literal: false
      #
      #   module Baz
      #     # ...
      #   end
      #
      #   # bad
      #   module Baz
      #     # ...
      #   end
      #
      #   # good
      #   # frozen_string_literal: true
      #
      #   module Bar
      #     # ...
      #   end
      class FrozenStringLiteralComment < Base
        include ConfigurableEnforcedStyle
        include FrozenStringLiteral
        include RangeHelp
        extend AutoCorrector

        MSG_MISSING_TRUE = 'Missing magic comment `# frozen_string_literal: true`.'
        MSG_MISSING = 'Missing frozen string literal comment.'
        MSG_UNNECESSARY = 'Unnecessary frozen string literal comment.'
        MSG_DISABLED = 'Frozen string literal comment must be set to `true`.'
        SHEBANG = '#!'

        def on_new_investigation
          return if processed_source.tokens.empty?

          case style
          when :never
            ensure_no_comment(processed_source)
          when :always_true
            ensure_enabled_comment(processed_source)
          else
            ensure_comment(processed_source)
          end
        end

        private

        def ensure_no_comment(processed_source)
          return unless frozen_string_literal_comment_exists?

          unnecessary_comment_offense(processed_source)
        end

        def ensure_comment(processed_source)
          return if frozen_string_literal_comment_exists?

          missing_offense(processed_source)
        end

        def ensure_enabled_comment(processed_source)
          if frozen_string_literal_specified?
            return if frozen_string_literals_enabled?

            # The comment exists, but is not enabled.
            disabled_offense(processed_source)
          else # The comment doesn't exist at all.
            missing_true_offense(processed_source)
          end
        end

        def last_special_comment(processed_source)
          token_number = 0
          if processed_source.tokens[token_number].text.start_with?(SHEBANG)
            token = processed_source.tokens[token_number]
            token_number += 1
          end

          next_token = processed_source.tokens[token_number]
          token = next_token if Encoding::ENCODING_PATTERN.match?(next_token&.text)

          token
        end

        def frozen_string_literal_comment(processed_source)
          processed_source.find_token do |token|
            token.text.start_with?(FROZEN_STRING_LITERAL)
          end
        end

        def missing_offense(processed_source)
          range = source_range(processed_source.buffer, 0, 0)

          add_offense(range, message: MSG_MISSING) { |corrector| insert_comment(corrector) }
        end

        def missing_true_offense(processed_source)
          range = source_range(processed_source.buffer, 0, 0)

          add_offense(range, message: MSG_MISSING_TRUE) { |corrector| insert_comment(corrector) }
        end

        def unnecessary_comment_offense(processed_source)
          frozen_string_literal_comment = frozen_string_literal_comment(processed_source)

          add_offense(frozen_string_literal_comment.pos, message: MSG_UNNECESSARY) do |corrector|
            remove_comment(corrector, frozen_string_literal_comment)
          end
        end

        def disabled_offense(processed_source)
          frozen_string_literal_comment = frozen_string_literal_comment(processed_source)

          add_offense(frozen_string_literal_comment.pos, message: MSG_DISABLED) do |corrector|
            enable_comment(corrector)
          end
        end

        def remove_comment(corrector, node)
          corrector.remove(range_with_surrounding_space(range: node.pos, side: :right))
        end

        def enable_comment(corrector)
          comment = frozen_string_literal_comment(processed_source)

          corrector.replace(line_range(comment.line), FROZEN_STRING_LITERAL_ENABLED)
        end

        def insert_comment(corrector)
          comment = last_special_comment(processed_source)

          if comment
            corrector.insert_after(line_range(comment.line), following_comment)
          else
            corrector.insert_before(processed_source.buffer.source_range, preceding_comment)
          end
        end

        def line_range(line)
          processed_source.buffer.line_range(line)
        end

        def preceding_comment
          "#{FROZEN_STRING_LITERAL_ENABLED}\n"
        end

        def following_comment
          "\n#{FROZEN_STRING_LITERAL_ENABLED}"
        end
      end
    end
  end
end


text:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    debug: true,
    devtool: 'inline-source-map',
    noInfo: false,
    entry: [
        path.resolve(__dirname, 'src/index')
    ],
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'src'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    plugins: [
        // Create HTML file that includes reference to bundled js
        new HtmlWebpackPlugin({
            template: 'src/index.html',
            inject: true
        })
    ],
    module: {
        loaders: [
            {test: /\.js$/, exclude: /node_modules/, loaders: ['babel']},
            {test: /\.css$/, loaders: ['style','css']}
        ]
    }
}


text:
import React from 'react'
import {branch} from 'baobab-react/higher-order'
import Actions from '../actions'

import {
  Row, Col,
  Table, Icon, Button,
  Form, Input, InputNumber
} from 'antd'
const FormItem = Form.Item;

const styles = {
  container: {
    padding: '24px'
  },
  table: {
    marginTop: '8px'
  }
}

class Accounts extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault()
    Actions.addAccount(this.props.form.getFieldsValue())
  }

  render = () => {
    const {
      items,
      form
    } = this.props

    const { getFieldProps } = this.props.form;
    const columns = [{
      title: 'Username',
      dataIndex: 'username',
      key: 'username'
    }, {
      title: 'Provider',
      dataIndex: 'provider',
      key: 'provider'
    }, {
      title: 'Actions',
      key: 'actions',
      render: (text, record) =>

          <Button type='primary'
            style={{marginRight: 8}}
            onClick={()=>Actions.login(record)}
          >login</Button>
          <Button onClick={()=>Actions.removeAccount(record)}>
            remove
          </Button>

    }]

    return <Row>
      <Col span={16} style={styles.container}>

Account management

      </Col>
      <Col span={8} style={styles.container}>

Add account

        <Form onSubmit={this.handleSubmit}>
          <FormItem label='username'>
            <Input
              {...getFieldProps('username')}/>
          </FormItem>
          <FormItem label='password'>
            <Input type='password'
              {...getFieldProps('password')}/>
          </FormItem>
          <FormItem label='provider (google or ptc)'>
            <Input
              {...getFieldProps('provider')}/>
          </FormItem>
          <FormItem type='number' label='lat'>
            <Input {...getFieldProps('lat')}/>
          </FormItem>
          <FormItem type='number' label='lng'>
            <Input {...getFieldProps('lng')}/>
          </FormItem>
          <Button type='primary' htmlType='submit'>add</Button>
        </Form>
      </Col>
    </Row>
  }
}

Accounts = Form.create()(Accounts)

export default branch({
  items: ['accounts']
}, Accounts)


text:
#ifndef MACARONI_MODEL_CPP_CLASSLUA_CPP
#define MACARONI_MODEL_CPP_CLASSLUA_CPP

#include "ClassLua.h"
#include <Macaroni/Model/Cpp/AccessLuaMetaData.h>
#include <Macaroni/Model/Cpp/ClassParentListLuaMetaData.h>
#include "../ElementLua.h"
#include <Macaroni/Model/Import.h>
#include <Macaroni/Model/ImportList.h>
#include "../NodeLua.h"
#include "../NodeListLua.h"
#include <Macaroni/Model/ReasonLuaMetaData.h>
 #include <Macaroni/Model/Project/Target.h>
 #include <Macaroni/Model/Project/TargetPtr.h>
#include <Macaroni/Model/Project/TargetLuaMetaData.h>
#include "TypeInfoLua.h"
#include "VariableLua.h"

#include <Macaroni/Lua.h>

struct lua_State;

#define LUAGLUE_STARTNAMESPACE BEGIN_NAMESPACE(Macaroni, Model, Cpp)
#define LUAGLUE_ENDNAMESPACE	END_NAMESPACE
#define LUAGLUE_CLASSNAME Class
#define LUAGLUE_CLASSREFNAME ClassPtr
#define LUAGLUE_CLASSFULLLUANAME "Macaroni.Model.Cpp.Class"
#define LUAGLUE_CLASSFULLCPPNAME Macaroni::Model::Cpp::Class
#define LUAGLUE_REGISTRATIONCLASSNAME ClassLuaMetaData
#define LUAGLUE_HELPERCLASS ClassLuaFunctions
#define LUAGLUE_OPENOTHERMODULES // Macaroni::Model::NodeLuaMetaData::OpenInLua(L);
#define LUAGLUE_CREATEMETATABLE

BEGIN_NAMESPACE(Macaroni, Model, Cpp)

int FunctionArgumentsOpenInLua(lua_State * L);

int FunctionReturnTypeInfoOpenInLua(lua_State * L);

END_NAMESPACE

#include "../../LuaGlue.hpp"

	static int Create(lua_State * L)
	{
		using Macaroni::Model::Element;
		using Macaroni::Model::ElementLuaMetaData;
		using Macaroni::Model::Node;
		using Macaroni::Model::NodeLuaMetaData;
		using Macaroni::Model::NodePtr;
		using Macaroni::Model::NodeList;
		using Macaroni::Model::NodeListLuaMetaData;
		using Macaroni::Model::NodeListPtr;
		using Macaroni::Model::Reason;
		using Macaroni::Model::ReasonLuaMetaData;
		using Macaroni::Model::ReasonPtr;
		using Macaroni::Model::Project::TargetPtr;
		using Macaroni::Model::Project::TargetLuaMetaData;

		TargetPtr target;
		if (TargetLuaMetaData::IsType(L, 1))
		{
			target = TargetLuaMetaData::GetInstance(L, 1);
		}
		else
		{
			luaL_error(L, "Expected Target for argument 1.");
		}

		if (!NodeLuaMetaData::IsType(L, 2))
		{
			luaL_error(L, "Expected Node for argument 2.");
		}
		NodePtr node = NodeLuaMetaData::GetInstance(L, 2);

		if (!AccessLuaMetaData::IsType(L, 3))
		{
			luaL_error(L, "Expected Access for argument 3.");
		}
		AccessPtr access = AccessLuaMetaData::GetInstance(L, 3);

		if (!NodeListLuaMetaData::IsType(L, 4))
		{
			luaL_error(L, "Expected NodeList for argument 4.");
		}
		NodeListPtr imports = NodeListLuaMetaData::GetInstance(L, 4);

		if (!ReasonLuaMetaData::IsType(L, 5))
		{
			luaL_error(L, "Expected Reason for argument 5.");
		}
		ReasonPtr reason = ReasonLuaMetaData::GetInstance(L, 5);

		::Macaroni::Model::ImportList importList;
		for(auto ptr : *imports)
		{
			importList.emplace_back(
				*ptr, ::Macaroni::Model::ImportType::Normal);
		}

		ClassPtr newInstance = Class::Create(target, node, false, access,
			                                 importList, reason);

		ElementPtr memberPtr = boost::dynamic_pointer_cast<Element>(newInstance);
		ElementLuaMetaData::PutInstanceOnStack(L, memberPtr);
		return 1;
	}

	static int __index(lua_State * L, const LUAGLUE_CLASSREFNAME & ptr,
									  const std::string & index)
	{
		if (index == "Inline")
		{
			lua_pushboolean(L, ptr->IsInline() ? 1 : 0);
		}
		else if (index == "IsStruct")
		{
			lua_pushboolean(L, ptr->IsStruct() ? 1 : 0);
		}
		else if (index == "FriendNodes")
		{
			NodeListPtr list = ptr->GetFriendNodes();
			NodeListLuaMetaData::PutInstanceOnStack(L, list);
		}
		else if (index == "GlobalNodes")
		{
			NodeListPtr list = ptr->GetGlobalNodes();
			NodeListLuaMetaData::PutInstanceOnStack(L, list);
		}
		else if (index == "GetImportedNodes")
		{
			const ImportList & imports = ptr->GetImportedNodes();
			lua_createtable(L, imports.size(), 0);
			for (unsigned int i = 0; i < imports.size(); ++ i)
			{
				lua_pushinteger(L, i + 1);
				lua_createtable(L, 0, 2);
					lua_pushstring(L, "Node");
					NodePtr ref(&(imports[i].GetNode()));  // glad this is intrusive
					NodeLuaMetaData::PutInstanceOnStack(L, ref);
					lua_settable(L, -3);

					lua_pushstring(L, "Type");
					lua_pushstring(L,
						((imports[i].GetType() == ImportType::Normal)
							? "Normal" : "H"));
					lua_settable(L, -3);

				lua_settable(L, -3);
			}
			return 1;
		}
		else if (index == "Parents")
		{
			ClassParentListPtr list = ptr->GetParents();
			ClassParentListLuaMetaData::PutInstanceOnStack(L, list);
		}
		else if (index == "TemplateParameterList")
		{
			NodePtr tpl = ptr->GetTemplateParameterList();
			NodeLuaMetaData::PutInstanceOnStack(L, tpl);
			return 1;
		}
		else
		{
			lua_pushnil(L);
		}
		return 1;
	}

	static int __tostring(lua_State * L)
	{
		lua_pushstring(L, "Class");
		return 1;
	}

	#define LUAGLUE_ADDITIONALMETATABLEMETHODS \
		/*{"__tostring", LUAGLUE_HELPERCLASS::__tostring}, */

	#define LUAGLUE_ADDITIONALTABLEMETHODS \
		{"Create", LUAGLUE_HELPERCLASS::Create},

#include "../../LuaGlue2.hpp"

#endif


text:
require 'generators/devise/views_generator'

module DeviseInvitable
  module Generators
    class InvitationViewsGenerator < Rails::Generators::Base
      include ::Devise::Generators::ViewPathTemplates

      def copy_views
        view_directory :invitations
      end
    end

    class SimpleFormForGenerator < InvitationViewsGenerator
      source_root File.expand_path('../templates/simple_form_for', __FILE__)
    end

    class FormForGenerator < InvitationViewsGenerator
      source_root File.expand_path('../../../../app/views/devise', __FILE__)
    end

    class MailerViewsGenerator < Rails::Generators::Base
      include ::Devise::Generators::ViewPathTemplates
      source_root File.expand_path('../../../../app/views/devise', __FILE__)
      desc 'Copies Devise mail erb views to your application.'
      hide!

      def copy_views
        view_directory :mailer
      end
    end

    class ViewsGenerator < Rails::Generators::Base
      desc 'Copies all DeviseInvitable views to your application.'
      argument :scope, required: false, default: nil, desc: 'The scope to copy views to'

      invoke MailerViewsGenerator

      hook_for :form_builder, aliases: '-b', desc: 'Form builder to be used', default: defined?(SimpleForm) ? 'simple_form_for' : 'form_for'
    end
  end
end


text:
"""Utilities"""

from urlparse import urlparse

def format_url(ip, port):
    port = "" if port in (80, 443) else ":{0:d}".format(port)
    scheme = "https" if port == 443 else "http"
    url = "{0:s}://{1:s}{2:s}".format(scheme, ip, port)
    return url

def parse_redis_url(url):
    parsed = urlparse(url)

    netloc = parsed.netloc
    if "@" in netloc:
        creds, host = netloc.split("@")
        _, password = creds.split(":")
    else:
        host = netloc
        password = None

    host, port = host.split(":")

    if parsed.path:
        database = int(parsed.path.replace("/", ""))
    else:
        database = 0

    return host, port, password, database


text:
* Make sure you have a [GitHub account](https://github.com/signup/free)
* Submit a ticket for your issue, assuming one does not already exist.
  * Clearly describe the issue including steps to reproduce when it is a bug.
  * Make sure you fill in the earliest version that you know has the issue.
* Fork the repository on GitHub

## Making Changes

* Create a topic branch from where you want to base your work.
  * This is usually the master branch.
  * Only target release branches if you are certain your fix must be on that
    branch.
  * To quickly create a topic branch based on master; `git branch
    fix/master/my_contribution master` then checkout the new branch with `git
    checkout fix/master/my_contribution`.  Please avoid working directly on the
    `master` branch.
* Make commits of logical units.
* Check for unnecessary whitespace with `git diff --check` before committing.

## Submitting Changes

* Push your changes to a topic branch in your fork of the repository.
* Submit a pull request to the repository.

## Coding Style

### Code
* Indentation: 4 spaces, no tabs
* Maximum line width for code and comments: 100
* Opening braces *do* go on their own line

### XML
* XML Maximum line width 999
* XML: Split multiple attributes each on a new line (Eclipse: Properties -> XML -> XML Files -> Editor)
* XML: Indent using spaces with Indention size 4 (Eclipse: Properties -> XML -> XML Files -> Editor)

See http://www.androidpolice.com/2009/11/04/auto-formatting-android-xml-files-with-eclipse/

## Additional Resources

* [General GitHub documentation](http://help.github.com/)
* [GitHub pull request documentation](http://help.github.com/send-pull-requests/)


text:
require 'action_controller/railtie'
require 'action_mailer/railtie'

Bundler.require(*Rails.groups)

STREAM = StringIO.new unless defined?(STREAM)

class Dummy < Rails::Application
  config.eager_load = true
  config.filter_parameters += [:password]
  config.secret_key_base = '2624599ca9ab3cf3823626240138a128118a87683bf03ab8f155844c33b3cd8cbbfa3ef5e29db6f5bd182f8bd4776209d9577cfb46ac51bfd232b00ab0136b24'
  config.session_store :cookie_store, key: '_rails70_session'

  config.log_tags = [:uuid, 'TEST_TAG']
  config.loga = {
    device: STREAM,
    host: 'bird.example.com',
    service_name: 'hello_world_app',
    service_version: '1.0',
  }
  config.action_mailer.delivery_method = :test
end

class ApplicationController < ActionController::Base
  include Rails.application.routes.url_helpers
  protect_from_forgery with: :null_session

  def ok
    render plain: 'Hello Rails'
  end

  def error
    nil.name
  end

  def show
    render json: params
  end

  def create
    render json: params
  end

  def new
    redirect_to :ok
  end

  def update
    @id = params[:id]
    render '/user'
  end
end

class FakeMailer < ActionMailer::Base
  default from: 'notifications@example.com'

  def self.send_email
    basic_mail.deliver_now
  end

  def basic_mail
    mail(
      to: 'user@example.com',
      subject: 'Welcome to My Awesome Site',
      body: 'Banana muffin',
      content_type: 'text/html',
    )
  end
end

Dummy.routes.append do
  get 'ok'        => 'application#ok'
  get 'error'     => 'application#error'
  get 'show'      => 'application#show'
  post 'users'    => 'application#create'
  get 'new'       => 'application#new'
  put 'users/:id' => 'application#update'
end

Dummy.initialize!


text:
package org.springframework.social.twitter.api.impl.advertising;

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

import org.springframework.social.twitter.api.advertising.StatisticsOfPromotedAccountQuery;
import org.springframework.social.twitter.api.advertising.StatisticsSnapshot;
import org.springframework.util.MultiValueMap;

/**
 * Facilitates the creation of the query that will be
 * used to filter results from the {@link StatisticsSnapshot} endpoint.
 *
 * @author Hudson Mendes
 */
public class StatisticsOfPromotedAccountQueryBuilder extends AbstractTwitterQueryForStatsBuilder<StatisticsOfPromotedAccountQuery> implements
        StatisticsOfPromotedAccountQuery {
    private List<String> promotedAccountIds;

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.social.twitter.api.impl.advertising.TwitterQueryForStatsOfPromotedAccount#withPromotedAccounts(java.lang.String)
     */
    @Override
    public StatisticsOfPromotedAccountQueryBuilder withPromotedAccounts(String... promotedAccountIds) {
        this.promotedAccountIds = new ArrayList<String>();
        for (int i = 0; i < promotedAccountIds.length; i++)
            this.promotedAccountIds.add(promotedAccountIds[i]);
        return this;
    }

    @Override
    protected void makeParameters(MultiValueMap<String, String> map) {
        appendParameter(map, "promoted_account_ids", this.promotedAccountIds);
    }

}


text:
/*
	Burst mine
	Distributed graphical plotter and miner for Burst.
	Author: Cryo
	Bitcoin: 138gMBhCrNkbaiTCmUhP9HLU9xwn5QKZgD
	Burst: BURST-YA29-QCEW-QXC3-BKXDL
*/

#ifndef CRYO_BURST_MINE_PLUGINS_NATIVE_JS_JS_PLOTS_WRITER_STAGGERED_FILE_H
#define CRYO_BURST_MINE_PLUGINS_NATIVE_JS_JS_PLOTS_WRITER_STAGGERED_FILE_H

#include <memory>
#include <functional>
#include <node.h>
#include <burstMine/js/impl/AsyncData.h>

#include "../PlotsWriterStaggeredFile.h"

namespace cryo {
namespace burstMine {
namespace plugins {
namespace native {
namespace js {

class JsPlotsWriterStaggeredFile {
	private:
		static v8::Persistent<v8::Function> s_constructor;

	public:
		static void init(v8::Isolate* p_isolate);

		static v8::Handle<v8::Value> New(v8::Isolate* p_isolate, std::unique_ptr<cryo::burstMine::plugins::native::PlotsWriterStaggeredFile>& p_plotsWriter);

	private:
		static void unwrap(const v8::FunctionCallbackInfo<v8::Value>& p_info, std::function<void(cryo::burstMine::plugins::native::PlotsWriterStaggeredFile*)> p_functor);
		static void unwrap(const v8::PropertyCallbackInfo<v8::Value>& p_info, std::function<void(cryo::burstMine::plugins::native::PlotsWriterStaggeredFile*)> p_functor);

		static void getStaggerSize(v8::Local<v8::String> p_property, const v8::PropertyCallbackInfo<v8::Value>& p_info);
		static void getPath(v8::Local<v8::String> p_property, const v8::PropertyCallbackInfo<v8::Value>& p_info);

		static void writePlots(const v8::FunctionCallbackInfo<v8::Value>& p_info);
		static void isClosed(const v8::FunctionCallbackInfo<v8::Value>& p_info);
		static void close(const v8::FunctionCallbackInfo<v8::Value>& p_info);
};

namespace impl {

class AsyncDataWritePlots : public cryo::burstMine::js::impl::AsyncData {
	public:
		cryo::burstMine::ScoopsBuffer* buffer;
		std::size_t size;
		cryo::burstMine::plugins::native::PlotsWriterStaggeredFile* plotsWriter;
};

class AsyncDataClose : public cryo::burstMine::js::impl::AsyncData {
	public:
		v8::Persistent<v8::Object> self;
		cryo::burstMine::plugins::native::PlotsWriterStaggeredFile* plotsWriter;
};

}

}}}}}

#endif


text:
<!doctype html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Publish default database — Google Earth Enterprise 5.3.7 documentation</title>
    <link rel="stylesheet" href="../../static/bizstyle.css" type="text/css" />
    <link rel="stylesheet" href="../../static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Make Web Map Service (WMS) requests" href="makeWMSRequests.html" />
    <link rel="prev" title="Manage virtual hosts" href="manageVirtualHosts.html" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.7 documentation »

GEE Server administration »

Previous topic

Manage virtual hosts

Next topic

Make Web Map Service (WMS) requests

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Publish default database¶

Google Earth Enterprise (GEE) Server allows users to publish one 3D
database as the default database. This is the database that will be
served when Earth Client signs into the base URL without including
a database name.

Publishing as Default

To make a 3D database the default database, simply select "On" for "Default
Database" when publishing the database.

This can also be done from the command line by including the --setecdefault
option with the geserveradmin --publishdb command.

e.g., geserveradmin --publishdb SFDb_3d --targetpath SFDb_3d --setecdefault

Note that only one database can be the default at any given time. If you
publish a database as the default, the previous default will be cleared.

Viewing the Default Database

To view the default database in Earth Client, simply sign into the base
URL of the GEE Server. (e.g., http://my-opengee-server.com)

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.7 documentation »

GEE Server administration »

        © Copyright 2020, Open GEE Contributors.
      Created using Sphinx 1.7.5.


text:
#include "graphd/graphd-ast-debug.h"

#include <stdio.h>

/** The name of the file to be used for logging */
#define DEBUG_FILE_NAME "graphd-debug.log"

static char const *get_greq_id(graphd_request const *const greq) {
  graphd_request_parameter const *grp;

  for (grp = greq->greq_parameter_head; grp; grp = grp->grp_next) {
    if (grp->grp_format == graphd_format_request_id) {
      graphd_request_parameter_id const *id =
          (graphd_request_parameter_id const *)grp;
      return id->id_s;
    }
  }

  return "unknown";
}

static FILE *get_debug_file(void) {
  static FILE *f = NULL;   // debug file handle
  static time_t last = 0;  // the last time the handle was used

  if (f == NULL) {
    const unsigned long long pid = getpid();
    char path[128];
    sprintf(path, "%s.%llu", DEBUG_FILE_NAME, pid);
    if ((f = fopen(path, "w")))
      setvbuf(f, NULL, _IOLBF, 0);  // line buffered
    else
      f = stderr;
  }

  /* print current time if more than 1 second has elapsed since the last
   * time we wrote to the file */
  const time_t now = time(NULL);
  if ((now - last) >= 1) {
    char buf[64];
    struct tm tm;
    localtime_r(&now, &tm);
    strftime(buf, sizeof(buf), "%F %T", &tm);
    fprintf(f, "============== Time: %s ==============\n", buf);
    last = now;
  }

  return f;
}

void graphd_ast_debug_reading(graphd_request const *greq) {
  /* current row and column number (in graphd-micro.c) */
  extern unsigned int gdp_micro_row, gdp_micro_col;
  /* the numerical identifier of the request */
  const unsigned long long reqno = greq->greq_req.req_id;

  FILE *f = get_debug_file();

  fprintf(f, "[R%llu] @L%u,C%u\n", reqno, gdp_micro_row, gdp_micro_col);
}

void graphd_ast_debug_received(graphd_request const *greq, bool eof) {
  /* a potentially malformed request? */
  const bool malformed = greq->greq_micro.micro_malformed;
  /* the numerical identifier of the request */
  const unsigned long long reqno = greq->greq_req.req_id;
  /* request size */
  const size_t reqsz = greq->greq_request_size;

  FILE *f = get_debug_file();

  fprintf(f, "[R%llu] Microparsed (%zu B)\n", reqno, reqsz);

  if (malformed) fprintf(f, "[R%llu] Possibly malformed\n", reqno);
  if (eof) fprintf(f, "[R%llu] EOF\n", reqno);
}

void graphd_ast_debug_parsed(graphd_request const *greq, bool has_errors) {
  const unsigned long long reqno = greq->greq_req.req_id;

  FILE *f = get_debug_file();

  if (has_errors)
    fprintf(f, "[R%llu] Has errors\n", reqno);
  else
    fprintf(f, "[R%llu] Ok\n", reqno);

  fprintf(f, "[R%llu] Id: %s\n", reqno, get_greq_id(greq));
}

void graphd_ast_debug_serving(graphd_request const *greq) {
  FILE *f = get_debug_file();

  fprintf(f, "[R%llu] Serving\n", greq->greq_req.req_id);
}

void graphd_ast_debug_finished(graphd_request const *greq) {
  FILE *f = get_debug_file();

  fprintf(f, "[R%llu] Finished\n", greq->greq_req.req_id);
}


text:
using NUnit.Framework;

namespace FluentNHibernate.Testing
{
    [TestFixture]
    public class Debugging
    {
        [Test]
        public void Break()
        {
            //Assert.Fail("Make it break");
        }
    }
}


text:
using System;
using System.Linq.Expressions;
using AutoMapper;
using KendoGridBinderEx.Examples.Business.Entities;
using KendoGridBinderEx.Examples.Business.Repository;

namespace KendoGridBinderEx.Examples.Business.AutoMapper
{
    //public class NullSafeResolver<TEntity, TViewModel, TResult> : IValueResolver<TEntity, TViewModel, TResult>, IKendoGridExValueResolver<TEntity>
    //{
    //    private readonly Expression<Func<TEntity, TResult>> _expression;

    //    public NullSafeResolver(Expression<Func<TEntity, TResult>> expression)
    //    {
    //        _expression = expression;
    //    }

    //    public Expression<Func<TEntity, object>> Expression => _expression.ToTypedExpression<TEntity>();

    //    public string DestinationProperty => _expression.Body.ToString().Replace(_expression.Parameters[0] + ".", string.Empty);

    //    public TResult Resolve(TEntity source, TViewModel destination, TResult destMember, ResolutionContext context)
    //    {
    //        return source.NullSafeGetValue(_expression);
    //    }
    //}

    //ValueResolver<long, TEntity> where TEntity : class, IEntity, new()
    public class EntityResolver<TResultEntity> : IValueResolver<IEntity, object, TResultEntity> where TResultEntity : class, IEntity, new()
    {
        readonly IRepository<TResultEntity> _service;

        public EntityResolver(IRepository<TResultEntity> service)
        {
            _service = service;
        }

        public TResultEntity Resolve(IEntity source, object destination, TResultEntity destMember, ResolutionContext context)
        {
            return source.Id > 0 ? _service.FirstOrDefault(x => x.Id == source.Id) : null;
        }
    }
}


text:
//module imports
var fs = require('fs'); //file system access
var http = require('http'); //http socket
var https = require('https'); //https socket
var FileDeliverer = require('./FileDeliverer.js'); //filesender class
var ServerConfigReader = new (require('./ServerConfigReader.js'))();

//creating http server
if (ServerConfigReader.httpEnabled) {
	var server = http.createServer((new FileDeliverer).deliver); //set reaction function
	server.listen(ServerConfigReader.httpPort, ServerConfigReader.serverHost); //bind server
}

//creating https server
if (ServerConfigReader.httpsEnabled) {
	var certificateOptions = {
	  key: fs.readFileSync(ServerConfigReader.httpsPrivateKeyPath),
	  cert: fs.readFileSync(ServerConfigReader.httpsCertificatePath)
	};

	var HTTPSServer = https.createServer(certificateOptions, (new FileDeliverer).deliver); //set reaction function
	HTTPSServer.listen(ServerConfigReader.httpsPort, ServerConfigReader.serverHost); //bind server
}


text:
package daemon // import "github.com/docker/docker/daemon"

import (
	apitypes "github.com/docker/docker/api/types"
	lncluster "github.com/docker/libnetwork/cluster"
)

// Cluster is the interface for github.com/docker/docker/daemon/cluster.(*Cluster).
type Cluster interface {
	ClusterStatus
	NetworkManager
	SendClusterEvent(event lncluster.ConfigEventType)
}

// ClusterStatus interface provides information about the Swarm status of the Cluster
type ClusterStatus interface {
	IsAgent() bool
	IsManager() bool
}

// NetworkManager provides methods to manage networks
type NetworkManager interface {
	GetNetwork(input string) (apitypes.NetworkResource, error)
	GetNetworks() ([]apitypes.NetworkResource, error)
	RemoveNetwork(input string) error
}


text:
<?php

$skipped = true;

if (!static::tableExists('relationships')) {
    printf("Skipping migration because table `relationships` does not exist yet\n");
    return static::STATUS_SKIPPED;
}

// migration
if (!static::columnExists('relationships', 'Slot')) {
    print("Adding field `Slot` to table `relationships`'\n");
    DB::nonQuery("ALTER TABLE `relationships` ADD COLUMN `Slot` varchar(255) NULL default NULL");
    DB::nonQuery("ALTER TABLE `history_relationships` ADD COLUMN `Slot` varchar(255) NULL default NULL");
    DB::nonQuery("ALTER TABLE `relationships` ADD UNIQUE KEY `PersonSlot` (`PersonID`,`Slot`)");
    $skipped = false;
}

// done
return $skipped ? static::STATUS_SKIPPED : static::STATUS_EXECUTED;


text:
package io.undertow.conduits;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;

import org.xnio.IoUtils;
import org.xnio.channels.StreamSourceChannel;
import org.xnio.conduits.AbstractStreamSinkConduit;
import org.xnio.conduits.ConduitWritableByteChannel;
import org.xnio.conduits.Conduits;
import org.xnio.conduits.StreamSinkConduit;

import static org.xnio.Bits.allAreClear;
import static org.xnio.Bits.anyAreSet;

/**
 * A conduit that discards all data written to it. This allows head requests to 'just work', as all data written
 * will be discarded.
 *
 * @author Stuart Douglas
 */
public final class HeadStreamSinkConduit extends AbstractStreamSinkConduit<StreamSinkConduit> {

    private final ConduitListener<? super HeadStreamSinkConduit> finishListener;

    private int state;
    private final boolean shutdownDelegate;

    private static final int FLAG_CLOSE_REQUESTED = 1;
    private static final int FLAG_CLOSE_COMPLETE = 1 << 1;
    private static final int FLAG_FINISHED_CALLED = 1 << 2;

    /**
     * Construct a new instance.
     *
     * @param next           the next channel
     * @param finishListener the listener to call when the channel is closed or the length is reached
     */
    public HeadStreamSinkConduit(final StreamSinkConduit next, final ConduitListener<? super HeadStreamSinkConduit> finishListener) {
        this(next, finishListener, false);
    }

    /**
     * Construct a new instance.
     *
     * @param next           the next channel
     * @param finishListener the listener to call when the channel is closed or the length is reached
     */
    public HeadStreamSinkConduit(final StreamSinkConduit next, final ConduitListener<? super HeadStreamSinkConduit> finishListener, boolean shutdownDelegate) {
        super(next);
        this.finishListener = finishListener;
        this.shutdownDelegate = shutdownDelegate;
    }

    public int write(final ByteBuffer src) throws IOException {
        if (anyAreSet(state, FLAG_CLOSE_COMPLETE)) {
            throw new ClosedChannelException();
        }
        int remaining = src.remaining();
        src.position(src.position() + remaining);
        return remaining;
    }

    public long write(final ByteBuffer[] srcs, final int offset, final int length) throws IOException {
        if (anyAreSet(state, FLAG_CLOSE_COMPLETE)) {
            throw new ClosedChannelException();
        }
        long total = 0;
        for (int i = offset; i < offset + length; ++i) {
            ByteBuffer src = srcs[i];
            int remaining = src.remaining();
            total += remaining;
            src.position(src.position() + remaining);
        }
        return total;
    }

    @Override
    public int writeFinal(ByteBuffer src) throws IOException {
        return Conduits.writeFinalBasic(this, src);
    }

    @Override
    public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException {
        return Conduits.writeFinalBasic(this, srcs, offset, length);
    }

    @Override
    public long transferFrom(final FileChannel src, final long position, final long count) throws IOException {
        if (anyAreSet(state, FLAG_CLOSE_COMPLETE)) {
            throw new ClosedChannelException();
        }
        return src.transferTo(position, count, new ConduitWritableByteChannel(this));
    }

    @Override
    public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
        if (anyAreSet(state, FLAG_CLOSE_COMPLETE)) {
            throw new ClosedChannelException();
        }
        return IoUtils.transfer(source, count, throughBuffer, new ConduitWritableByteChannel(this));
    }

    public boolean flush() throws IOException {
        int val = state;
        if (anyAreSet(val, FLAG_CLOSE_COMPLETE)) {
            return true;
        }
        boolean flushed = false;
        try {
            return flushed = next.flush();
        } finally {
            exitFlush(val, flushed);
        }
    }

    public void suspendWrites() {
        long val = state;
        if (anyAreSet(val, FLAG_CLOSE_COMPLETE)) {
            return;
        }
        next.suspendWrites();
    }

    public void resumeWrites() {
        long val = state;
        if (anyAreSet(val, FLAG_CLOSE_COMPLETE)) {
            return;
        }
        next.resumeWrites();
    }

    public boolean isWriteResumed() {
        // not perfect but not provably wrong either...
        return allAreClear(state, FLAG_CLOSE_COMPLETE) && next.isWriteResumed();
    }

    public void wakeupWrites() {
        long val = state;
        if (anyAreSet(val, FLAG_CLOSE_COMPLETE)) {
            return;
        }
        next.wakeupWrites();
    }

    public void terminateWrites() throws IOException {
        int oldVal, newVal;
        oldVal = state;
        if (anyAreSet(oldVal, FLAG_CLOSE_REQUESTED | FLAG_CLOSE_COMPLETE)) {
            // no action necessary
            return;
        }
        newVal = oldVal | FLAG_CLOSE_REQUESTED;
        state = newVal;
        if(shutdownDelegate) {
            next.terminateWrites();
        }
    }

    private void exitFlush(int oldVal, boolean flushed) {
        int newVal = oldVal;
        boolean callFinish = false;
        if (anyAreSet(oldVal, FLAG_CLOSE_REQUESTED) && flushed) {
            newVal |= FLAG_CLOSE_COMPLETE;
            if (!anyAreSet(oldVal, FLAG_FINISHED_CALLED)) {
                newVal |= FLAG_FINISHED_CALLED;
                callFinish = true;
            }
            state = newVal;
            if (callFinish) {
                if (finishListener != null) {
                    finishListener.handleEvent(this);
                }
            }
        }
    }

}


text:
if ENV['WORKER_LIB'] == 'shoryuken'

require 'shoryuken'
require 'system_information'

module ShoryukenWorker

  def self.included(base)
    base.send :include, Shoryuken::Worker
    base.send :extend, ClassMethods
  end

  def perform(sqs_msg, body)
    @message = sqs_msg
    process(body)
  end

  def logger
    Shoryuken.logger
  end

  module ClassMethods
    def worker_options(*args)
      shoryuken_options(*args)
    end

    def publish(queue, message, options={})
      options[:message_attributes] ||= {}
      options[:message_attributes]['shoryuken_class'] = {
        string_value: self.to_s,
        data_type: 'String'
      }
      options[:message_body] = message.to_json

      sqs_queue = Shoryuken::Client.queues(env_prefix_queue(queue))
      sqs_queue.send_message(options)
    end

    def env_prefix_queue(queue)
      "#{SystemInformation.env}_#{queue}"
    end
  end
end

end # if ENV['WORKER_LIB'] == 'shoryuken'


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

title: Geolocation
---

Geolocation
===========

> `geolocation` オブジェクトはデバイスの GPS センサーへのアクセスを提供します。

Geolocation は緯度や経度といったデバイスの位置情報を提供します。主に Global Positioning System (GPS) から位置情報を取得しますが、 IP アドレスや RFID, WiFi, Bluetooh, MAC アドレス, 基地局 ID などのソースからも現在位置を推測します。ただしこの API がデバイスの正確な位置を特定する保証はありません。

この API は [W3C Geo location API Specification](http://dev.w3.org/geo/api/spec-source.html) をベースとしています。いくつかのデバイス (Android, BlackBerry, Bada, Windows Phone 7, webOS, Tizen) ではすでにこの機能の実装を提供しています。 これらについては、 Cordova の実装ではなくビルトインのサポートが実行されます。位置情報のサポートがされてないデバイスについては、Cordovaの実装によってW3Cの仕様に沿った機能が提供されます。

メソッド
-------

- [geolocation.getCurrentPosition](geolocation.getCurrentPosition.html)
- [geolocation.watchPosition](geolocation.watchPosition.html)
- [geolocation.clearWatch](geolocation.clearWatch.html)

引数
---------

- [geolocationSuccess](parameters/geolocationSuccess.html)
- [geolocationError](parameters/geolocationError.html)
- [geolocationOptions](parameters/geolocation.options.html)

オブジェクト (読み取り専用)
-------------------

- [Position](Position/position.html)
- [PositionError](PositionError/positionError.html)
- [Coordinates](Coordinates/coordinates.html)

パーミッション
-----------

### Android

#### app/res/xml/plugins.xml

    <plugin name="Geolocation" value="org.apache.cordova.GeoBroker" />

#### app/AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />

### Bada

    パーミッションの設定は必要ありません。

### BlackBerry WebWorks

#### www/plugins.xml

    <plugin name="Geolocation" value="org.apache.cordova.geolocation.Geolocation" />

#### www/config.xml

    <rim:permissions>
        <rim:permit>read_geolocation</rim:permit>
    </rim:permissions>

### iOS

#### App/Supporting Files/Cordova.plist

    <key>Plugins</key>
    <dict>
        <key>Geolocation</key>
        <string>CDVLocation</string>
    </dict>

### webOS

    パーミッションの設定は必要ありません。

### Windows Phone

#### Properties/WPAppManifest.xml

    <Capabilities>
        <Capability Name="ID_CAP_LOCATION" />
    </Capabilities>

参照: [Application Manifest for Windows Phone](http://msdn.microsoft.com/en-us/library/ff769509%28v=vs.92%29.aspx)

### Tizen

    パーミッションの設定は必要ありません。