text:
> REST API abstraction layer to easily consume data. Based on [artesaos/restinga](https://github.com/artesaos/restinga).

[![Build Status](https://travis-ci.org/jay-ess/restinga-node.svg?branch=master)](https://travis-ci.org/jay-ess/restinga-node)
[![Coverage Status](https://coveralls.io/repos/github/jay-ess/restinga-node/badge.svg?branch=master)](https://coveralls.io/github/jay-ess/restinga-node?branch=master)
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)

## Contents

* [Usage](#usage)
* [Overview](#overview)
* [Debug](#debug)
* [Docs](#docs)
  * [Resource Methods](#resource-methods)
  * [Make Your Auth System](#make-your-auth-system)
  * [Make Your Format](#make-your-format)

## Usage

```sh
npm install -S restinga
```

## Overview

###### digital-ocean-descriptor.js

```js
import {Descriptor} from 'restinga';
import {Bearer} from 'restinga/lib/auth';

export default class DigitalOceanDescriptor extends Descriptor {
  constructor() {
    super({
      service: 'digital-ocean',
      prefix: 'https://api.digitalocean.com/v2',

      // Optional User-Agent for requests:
      agent: 'restinga-node/1.0.0 (https://github.com/jay-ess/restinga-node)'
    });
  }

  // Optional auth setup
  get authorization() {
    return new Bearer('YourToken');
  }
}
```

###### container.js

```js
import {Container} from 'restinga';
import DigitalOceanDescriptor from './digital-ocean-descriptor';

Container.register(new DigitalOceanDescriptor());
```

###### droplet.js

```js
import {Resource} from 'restinga';
import {receiveJson, sendJson} from 'restinga/lib/format';

export default class Droplet extends receiveJson(sendJson(Resource)) {
  setup() {
    super.setup({
      service: 'digital-ocean', // match a descriptor service name
      name: 'droplets',
      identifier: 'id',
      collectionRoot: 'droplets',
      itemRoot: 'droplet'
    });
  }
}
```

###### usage.js

```js
import Droplet from './droplet';

const droplet = new Droplet({
  name: 'server.restinga.dev',
  region: 'nyc3',
  size: '512mb',
  image: 'ubuntu-14-04-x64'
});

// Resources methods return Promises

droplet.save()
  .then(droplet => console.log(droplet.get('id'))) // Returns itself
  .catch(err => console.log(err));

// Wanna some async-await?

try {
  await droplet.save();
  console.log(droplet.get('id'));
} catch (err) {
  console.log(err);
}
```

See a working example: [test/resource.test.js](test/resource.test.js).

## Debug

Wanna know what's happening behind the scenes? This module uses [visionmedia/debug](https://github.com/visionmedia/debug), so you can just run `DEBUG=restinga:* node your-file.js` and get a pretty output of how restinga is working.

## Docs

### Resource methods

Method | Return Type | Description
--- | --- | ---
hasParentResource() | `Boolean` | True if you're using a nested resource
childResource(resource) | `Resource` | Make a resource your child
getIdentifier() | `?string` | Return the identifier value
get(key) | `*` | Return `key` from attributes
set(key, value) | `self` | Change a key from attributes
set(obj) | `self` | Change multiple attributes
unset(key) | `self` | Delete `key` from attributes
`static` all(query) | `Promise` => `Resource[]` | Static search resources
getAll(query) | `Promise` => `Resource[]` | Search resources
`static` find(identifier) | `Promise` => `Resource` | Static search for an resource with identifier = `identifier`
doFind(identifier) | `Promise` => `Resource` | Search for an resource with identifier = `identifier`
save() | `Promise` => `Resource` | Save this resource
update() | `Promise` => `Resource` | Update this resource
destroy() | `Promise` | Delete this resource

### Make Your Auth System

For you to make your own authorization class, just make a class with a `setupAuth()` method that takes no params and returns an object like this:

```js
class MyAuthSystem {
  setupRequest() {
    return {
      opts: {},
      headers: {}
    };
  }
}
```

`opts` follow [http.request](https://nodejs.org/api/http.html#http_http_request_options_callback) since we use [got](https://github.com/sindresorhus/got) for requests. And `headers` are plain HTTP headers.

### Make Your Format

Formats are High Order Classes that work as mixins and take care of understand what comes from your REST API responses.

To make a format, you must build `receiveSomething()` and `sendSomething()` mixins. See [src/format/](src/format/) for examples.

##### Receiver Methods:

Method | Return Type | Description
--- | --- | ---
getAcceptHeader() | `string` | Value to the `Accept` HTTP header
factory(rawResponse) | `Resource` | Parse a resource and return it's instance
factoryCollection(rawResponse) | `Resource[]` | Parse multiple resources and returns an array of instances

##### Sender Methods:

Method | Return Type | Description
--- | --- | ---
getContentTypeHeader() | `string` | Value to the `Content-Type` HTTP header
encode() | `*` | Do whatever you need with `this.attributes` before sendind it

## License

[MIT](LICENSE.md)


text:
#include "GrCCCoverageProcessor.h"

#include "GrMesh.h"
#include "glsl/GrGLSLVertexGeoBuilder.h"

using InputType = GrGLSLGeometryBuilder::InputType;
using OutputType = GrGLSLGeometryBuilder::OutputType;

/**
 * This class and its subclasses implement the coverage processor with geometry shaders.
 */
class GrCCCoverageProcessor::GSImpl : public GrGLSLGeometryProcessor {
protected:
    GSImpl(std::unique_ptr<Shader> shader) : fShader(std::move(shader)) {}

    virtual bool hasCoverage() const { return false; }

    void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor&,
                 FPCoordTransformIter&& transformIter) final {
        this->setTransformDataHelper(SkMatrix::I(), pdman, &transformIter);
    }

    void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final {
        const GrCCCoverageProcessor& proc = args.fGP.cast<GrCCCoverageProcessor>();

        // The vertex shader simply forwards transposed x or y values to the geometry shader.
        SkASSERT(1 == proc.numVertexAttributes());
        gpArgs->fPositionVar = proc.fVertexAttribute.asShaderVar();

        // Geometry shader.
        GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
        this->emitGeometryShader(proc, varyingHandler, args.fGeomBuilder, args.fRTAdjustName);
        varyingHandler->emitAttributes(proc);
        varyingHandler->setNoPerspective();
        SkASSERT(!args.fFPCoordTransformHandler->nextCoordTransform());

        // Fragment shader.
        fShader->emitFragmentCode(proc, args.fFragBuilder, args.fOutputColor, args.fOutputCoverage);
    }

    void emitGeometryShader(const GrCCCoverageProcessor& proc,
                            GrGLSLVaryingHandler* varyingHandler, GrGLSLGeometryBuilder* g,
                            const char* rtAdjust) const {
        int numInputPoints = proc.numInputPoints();
        SkASSERT(3 == numInputPoints || 4 == numInputPoints);

        int inputWidth = (4 == numInputPoints || proc.hasInputWeight()) ? 4 : 3;
        const char* posValues = (4 == inputWidth) ? "sk_Position" : "sk_Position.xyz";
        g->codeAppendf("float%ix2 pts = transpose(float2x%i(sk_in[0].%s, sk_in[1].%s));",
                       inputWidth, inputWidth, posValues, posValues);

        GrShaderVar wind("wind", kHalf_GrSLType);
        g->declareGlobal(wind);
        Shader::CalcWind(proc, g, "pts", wind.c_str());
        if (PrimitiveType::kWeightedTriangles == proc.fPrimitiveType) {
            SkASSERT(3 == numInputPoints);
            SkASSERT(kFloat4_GrVertexAttribType == proc.fVertexAttribute.cpuType());
            g->codeAppendf("%s *= half(sk_in[0].sk_Position.w);", wind.c_str());
        }

        SkString emitVertexFn;
        SkSTArray<2, GrShaderVar> emitArgs;
        const char* corner = emitArgs.emplace_back("corner", kFloat2_GrSLType).c_str();
        const char* bloatdir = emitArgs.emplace_back("bloatdir", kFloat2_GrSLType).c_str();
        const char* coverage = nullptr;
        if (this->hasCoverage()) {
            coverage = emitArgs.emplace_back("coverage", kHalf_GrSLType).c_str();
        }
        const char* cornerCoverage = nullptr;
        if (GSSubpass::kCorners == proc.fGSSubpass) {
            cornerCoverage = emitArgs.emplace_back("corner_coverage", kHalf2_GrSLType).c_str();
        }
        g->emitFunction(kVoid_GrSLType, "emitVertex", emitArgs.count(), emitArgs.begin(), [&]() {
            SkString fnBody;
            if (coverage) {
                fnBody.appendf("%s *= %s;", coverage, wind.c_str());
            }
            if (cornerCoverage) {
                fnBody.appendf("%s.x *= %s;", cornerCoverage, wind.c_str());
            }
            fnBody.appendf("float2 vertexpos = fma(%s, float2(bloat), %s);", bloatdir, corner);
            fShader->emitVaryings(varyingHandler, GrGLSLVarying::Scope::kGeoToFrag, &fnBody,
                                  "vertexpos", coverage ? coverage : wind.c_str(), cornerCoverage);
            g->emitVertex(&fnBody, "vertexpos", rtAdjust);
            return fnBody;
        }().c_str(), &emitVertexFn);

        float bloat = kAABloatRadius;
#ifdef SK_DEBUG
        if (proc.debugBloatEnabled()) {
            bloat *= proc.debugBloat();
        }
#endif
        g->defineConstant("bloat", bloat);

        this->onEmitGeometryShader(proc, g, wind, emitVertexFn.c_str());
    }

    virtual void onEmitGeometryShader(const GrCCCoverageProcessor&, GrGLSLGeometryBuilder*,
                                      const GrShaderVar& wind, const char* emitVertexFn) const = 0;

    virtual ~GSImpl() {}

    const std::unique_ptr<Shader> fShader;

    typedef GrGLSLGeometryProcessor INHERITED;
};

/**
 * Generates conservative rasters around a triangle and its edges, and calculates coverage ramps.
 *
 * Triangle rough outlines are drawn in two steps: (1) draw a conservative raster of the entire
 * triangle, with a coverage of +1, and (2) draw conservative rasters around each edge, with a
 * coverage ramp from -1 to 0. These edge coverage values convert jagged conservative raster edges
 * into smooth, antialiased ones.
 *
 * The final corners get touched up in a later step by GSTriangleCornerImpl.
 */
class GrCCCoverageProcessor::GSTriangleHullImpl : public GrCCCoverageProcessor::GSImpl {
public:
    GSTriangleHullImpl(std::unique_ptr<Shader> shader) : GSImpl(std::move(shader)) {}

    bool hasCoverage() const override { return true; }

    void onEmitGeometryShader(const GrCCCoverageProcessor&, GrGLSLGeometryBuilder* g,
                              const GrShaderVar& wind, const char* emitVertexFn) const override {
        fShader->emitSetupCode(g, "pts", wind.c_str());

        // Visualize the input triangle as upright and equilateral, with a flat base. Paying special
        // attention to wind, we can identify the points as top, bottom-left, and bottom-right.
        //
        // NOTE: We generate the rasters in 5 independent invocations, so each invocation designates
        // the corner it will begin with as the top.
        g->codeAppendf("int i = (%s > 0 ? sk_InvocationID : 4 - sk_InvocationID) %% 3;",
                       wind.c_str());
        g->codeAppend ("float2 top = pts[i];");
        g->codeAppendf("float2 right = pts[(i + (%s > 0 ? 1 : 2)) %% 3];", wind.c_str());
        g->codeAppendf("float2 left = pts[(i + (%s > 0 ? 2 : 1)) %% 3];", wind.c_str());

        // Determine which direction to outset the conservative raster from each of the three edges.
        g->codeAppend ("float2 leftbloat = sign(top - left);");
        g->codeAppend ("leftbloat = float2(0 != leftbloat.y ? leftbloat.y : leftbloat.x, "
                                          "0 != leftbloat.x ? -leftbloat.x : -leftbloat.y);");

        g->codeAppend ("float2 rightbloat = sign(right - top);");
        g->codeAppend ("rightbloat = float2(0 != rightbloat.y ? rightbloat.y : rightbloat.x, "
                                           "0 != rightbloat.x ? -rightbloat.x : -rightbloat.y);");

        g->codeAppend ("float2 downbloat = sign(left - right);");
        g->codeAppend ("downbloat = float2(0 != downbloat.y ? downbloat.y : downbloat.x, "
                                           "0 != downbloat.x ? -downbloat.x : -downbloat.y);");

        // The triangle's conservative raster has a coverage of +1 all around.
        g->codeAppend ("half4 coverages = half4(+1);");

        // Edges have coverage ramps.
        g->codeAppend ("if (sk_InvocationID >= 2) {"); // Are we an edge?
        Shader::CalcEdgeCoverageAtBloatVertex(g, "top", "right",
                                              "float2(+rightbloat.y, -rightbloat.x)",
                                              "coverages[0]");
        g->codeAppend (    "coverages.yzw = half3(-1, 0, -1 - coverages[0]);");
        // Reassign bloats to characterize a conservative raster around a single edge, rather than
        // the entire triangle.
        g->codeAppend (    "leftbloat = downbloat = -rightbloat;");
        g->codeAppend ("}");

        // Here we generate the conservative raster geometry. The triangle's conservative raster is
        // the convex hull of 3 pixel-size boxes centered on the input points. This translates to a
        // convex polygon with either one, two, or three vertices at each input point (depending on
        // how sharp the corner is) that we split between two invocations. Edge conservative rasters
        // are convex hulls of 2 pixel-size boxes, one at each endpoint. For more details on
        // conservative raster, see:
        // https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter42.html
        g->codeAppendf("bool2 left_right_notequal = notEqual(leftbloat, rightbloat);");
        g->codeAppend ("if (all(left_right_notequal)) {");
                           // The top corner will have three conservative raster vertices. Emit the
                           // middle one first to the triangle strip.
        g->codeAppendf(    "%s(top, float2(-leftbloat.y, +leftbloat.x), coverages[0]);",
                           emitVertexFn);
        g->codeAppend ("}");
        g->codeAppend ("if (any(left_right_notequal)) {");
                           // Second conservative raster vertex for the top corner.
        g->codeAppendf(    "%s(top, rightbloat, coverages[1]);", emitVertexFn);
        g->codeAppend ("}");

        // Main interior body.
        g->codeAppendf("%s(top, leftbloat, coverages[2]);", emitVertexFn);
        g->codeAppendf("%s(right, rightbloat, coverages[1]);", emitVertexFn);

        // Here the invocations diverge slightly. We can't symmetrically divide three triangle
        // points between two invocations, so each does the following:
        //
        // sk_InvocationID=0: Finishes the main interior body of the triangle hull.
        // sk_InvocationID=1: Remaining two conservative raster vertices for the third hull corner.
        // sk_InvocationID=2..4: Finish the opposite endpoint of their corresponding edge.
        g->codeAppendf("bool2 right_down_notequal = notEqual(rightbloat, downbloat);");
        g->codeAppend ("if (any(right_down_notequal) || 0 == sk_InvocationID) {");
        g->codeAppendf(    "%s((0 == sk_InvocationID) ? left : right, "
                              "(0 == sk_InvocationID) ? leftbloat : downbloat, "
                              "coverages[2]);", emitVertexFn);
        g->codeAppend ("}");
        g->codeAppend ("if (all(right_down_notequal) && 0 != sk_InvocationID) {");
        g->codeAppendf(    "%s(right, float2(-rightbloat.y, +rightbloat.x), coverages[3]);",
                           emitVertexFn);
        g->codeAppend ("}");

        // 5 invocations: 2 triangle hull invocations and 3 edges.
        g->configure(InputType::kLines, OutputType::kTriangleStrip, 6, 5);
    }
};

/**
 * Generates a conservative raster around a convex quadrilateral that encloses a cubic or quadratic.
 */
class GrCCCoverageProcessor::GSCurveHullImpl : public GrCCCoverageProcessor::GSImpl {
public:
    GSCurveHullImpl(std::unique_ptr<Shader> shader) : GSImpl(std::move(shader)) {}

    void onEmitGeometryShader(const GrCCCoverageProcessor&, GrGLSLGeometryBuilder* g,
                              const GrShaderVar& wind, const char* emitVertexFn) const override {
        const char* hullPts = "pts";
        fShader->emitSetupCode(g, "pts", wind.c_str(), &hullPts);

        // Visualize the input (convex) quadrilateral as a square. Paying special attention to wind,
        // we can identify the points by their corresponding corner.
        //
        // NOTE: We split the square down the diagonal from top-right to bottom-left, and generate
        // the hull in two independent invocations. Each invocation designates the corner it will
        // begin with as top-left.
        g->codeAppend ("int i = sk_InvocationID * 2;");
        g->codeAppendf("float2 topleft = %s[i];", hullPts);
        g->codeAppendf("float2 topright = %s[%s > 0 ? i + 1 : 3 - i];", hullPts, wind.c_str());
        g->codeAppendf("float2 bottomleft = %s[%s > 0 ? 3 - i : i + 1];", hullPts, wind.c_str());
        g->codeAppendf("float2 bottomright = %s[2 - i];", hullPts);

        // Determine how much to outset the conservative raster hull from the relevant edges.
        g->codeAppend ("float2 leftbloat = float2(topleft.y > bottomleft.y ? +1 : -1, "
                                                 "topleft.x > bottomleft.x ? -1 : +1);");
        g->codeAppend ("float2 upbloat = float2(topright.y > topleft.y ? +1 : -1, "
                                               "topright.x > topleft.x ? -1 : +1);");
        g->codeAppend ("float2 rightbloat = float2(bottomright.y > topright.y ? +1 : -1, "
                                                  "bottomright.x > topright.x ? -1 : +1);");

        // Here we generate the conservative raster geometry. It is the convex hull of 4 pixel-size
        // boxes centered on the input points, split evenly between two invocations. This translates
        // to a polygon with either one, two, or three vertices at each input point, depending on
        // how sharp the corner is. For more details on conservative raster, see:
        // https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter42.html
        g->codeAppendf("bool2 left_up_notequal = notEqual(leftbloat, upbloat);");
        g->codeAppend ("if (all(left_up_notequal)) {");
                           // The top-left corner will have three conservative raster vertices.
                           // Emit the middle one first to the triangle strip.
        g->codeAppendf(    "%s(topleft, float2(-leftbloat.y, leftbloat.x));", emitVertexFn);
        g->codeAppend ("}");
        g->codeAppend ("if (any(left_up_notequal)) {");
                           // Second conservative raster vertex for the top-left corner.
        g->codeAppendf(    "%s(topleft, leftbloat);", emitVertexFn);
        g->codeAppend ("}");

        // Main interior body of this invocation's half of the hull.
        g->codeAppendf("%s(topleft, upbloat);", emitVertexFn);
        g->codeAppendf("%s(bottomleft, leftbloat);", emitVertexFn);
        g->codeAppendf("%s(topright, upbloat);", emitVertexFn);

        // Remaining two conservative raster vertices for the top-right corner.
        g->codeAppendf("bool2 up_right_notequal = notEqual(upbloat, rightbloat);");
        g->codeAppend ("if (any(up_right_notequal)) {");
        g->codeAppendf(    "%s(topright, rightbloat);", emitVertexFn);
        g->codeAppend ("}");
        g->codeAppend ("if (all(up_right_notequal)) {");
        g->codeAppendf(    "%s(topright, float2(-upbloat.y, upbloat.x));", emitVertexFn);
        g->codeAppend ("}");

        g->configure(InputType::kLines, OutputType::kTriangleStrip, 7, 2);
    }
};

/**
 * Generates conservative rasters around corners (aka pixel-size boxes) and calculates
 * coverage and attenuation ramps to fix up the coverage values written by the hulls.
 */
class GrCCCoverageProcessor::GSCornerImpl : public GrCCCoverageProcessor::GSImpl {
public:
    GSCornerImpl(std::unique_ptr<Shader> shader) : GSImpl(std::move(shader)) {}

    bool hasCoverage() const override { return true; }

    void onEmitGeometryShader(const GrCCCoverageProcessor& proc, GrGLSLGeometryBuilder* g,
                              const GrShaderVar& wind, const char* emitVertexFn) const override {
        fShader->emitSetupCode(g, "pts", wind.c_str());

        g->codeAppendf("int corneridx = sk_InvocationID;");
        if (!proc.isTriangles()) {
            g->codeAppendf("corneridx *= %i;", proc.numInputPoints() - 1);
        }

        g->codeAppendf("float2 corner = pts[corneridx];");
        g->codeAppendf("float2 left = pts[(corneridx + (%s > 0 ? %i : 1)) %% %i];",
                       wind.c_str(), proc.numInputPoints() - 1, proc.numInputPoints());
        g->codeAppendf("float2 right = pts[(corneridx + (%s > 0 ? 1 : %i)) %% %i];",
                       wind.c_str(), proc.numInputPoints() - 1, proc.numInputPoints());

        g->codeAppend ("float2 leftdir = corner - left;");
        g->codeAppend ("leftdir = (float2(0) != leftdir) ? normalize(leftdir) : float2(1, 0);");

        g->codeAppend ("float2 rightdir = right - corner;");
        g->codeAppend ("rightdir = (float2(0) != rightdir) ? normalize(rightdir) : float2(1, 0);");

        // Find "outbloat" and "crossbloat" at our corner. The outbloat points diagonally out of the
        // triangle, in the direction that should ramp to zero coverage with attenuation. The
        // crossbloat runs perpindicular to outbloat.
        g->codeAppend ("float2 outbloat = float2(leftdir.x > rightdir.x ? +1 : -1, "
                                                "leftdir.y > rightdir.y ? +1 : -1);");
        g->codeAppend ("float2 crossbloat = float2(-outbloat.y, +outbloat.x);");

        g->codeAppend ("half attenuation; {");
        Shader::CalcCornerAttenuation(g, "leftdir", "rightdir", "attenuation");
        g->codeAppend ("}");

        if (proc.isTriangles()) {
            g->codeAppend ("half2 left_coverages; {");
            Shader::CalcEdgeCoveragesAtBloatVertices(g, "left", "corner", "-outbloat",
                                                     "-crossbloat", "left_coverages");
            g->codeAppend ("}");

            g->codeAppend ("half2 right_coverages; {");
            Shader::CalcEdgeCoveragesAtBloatVertices(g, "corner", "right", "-outbloat",
                                                     "crossbloat", "right_coverages");
            g->codeAppend ("}");

            // Emit a corner box. The first coverage argument erases the values that were written
            // previously by the hull and edge geometry. The second pair are multiplied together by
            // the fragment shader. They ramp to 0 with attenuation in the direction of outbloat,
            // and linearly from left-edge coverage to right-edge coverage in the direction of
            // crossbloat.
            //
            // NOTE: Since this is not a linear mapping, it is important that the box's diagonal
            // shared edge points in the direction of outbloat.
            g->codeAppendf("%s(corner, -crossbloat, right_coverages[1] - left_coverages[1],"
                              "half2(1 + left_coverages[1], 1));",
                           emitVertexFn);

            g->codeAppendf("%s(corner, outbloat, 1 + left_coverages[0] + right_coverages[0], "
                              "half2(0, attenuation));",
                           emitVertexFn);

            g->codeAppendf("%s(corner, -outbloat, -1 - left_coverages[0] - right_coverages[0], "
                              "half2(1 + left_coverages[0] + right_coverages[0], 1));",
                           emitVertexFn);

            g->codeAppendf("%s(corner, crossbloat, left_coverages[1] - right_coverages[1],"
                              "half2(1 + right_coverages[1], 1));",
                           emitVertexFn);
        } else {
            // Curves are simpler. The first coverage value of -1 means "wind = -wind", and causes
            // the Shader to erase what it had written previously for the hull. Then, at each vertex
            // of the corner box, the Shader will calculate the curve's local coverage value,
            // interpolate it alongside our attenuation parameter, and multiply the two together for
            // a final coverage value.
            g->codeAppendf("%s(corner, -crossbloat, -1, half2(1));", emitVertexFn);
            g->codeAppendf("%s(corner, outbloat, -1, half2(0, attenuation));",
                           emitVertexFn);
            g->codeAppendf("%s(corner, -outbloat, -1, half2(1));", emitVertexFn);
            g->codeAppendf("%s(corner, crossbloat, -1, half2(1));", emitVertexFn);
        }

        g->configure(InputType::kLines, OutputType::kTriangleStrip, 4, proc.isTriangles() ? 3 : 2);
    }
};

void GrCCCoverageProcessor::initGS() {
    SkASSERT(Impl::kGeometryShader == fImpl);
    if (4 == this->numInputPoints() || this->hasInputWeight()) {
        fVertexAttribute =
                {"x_or_y_values", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
        GR_STATIC_ASSERT(sizeof(QuadPointInstance) ==
                         2 * GrVertexAttribTypeSize(kFloat4_GrVertexAttribType));
        GR_STATIC_ASSERT(offsetof(QuadPointInstance, fY) ==
                         GrVertexAttribTypeSize(kFloat4_GrVertexAttribType));
    } else {
        fVertexAttribute =
                {"x_or_y_values", kFloat3_GrVertexAttribType, kFloat3_GrSLType};
        GR_STATIC_ASSERT(sizeof(TriPointInstance) ==
                         2 * GrVertexAttribTypeSize(kFloat3_GrVertexAttribType));
        GR_STATIC_ASSERT(offsetof(TriPointInstance, fY) ==
                         GrVertexAttribTypeSize(kFloat3_GrVertexAttribType));
    }
    this->setVertexAttributes(&fVertexAttribute, 1);
    this->setWillUseGeoShader();
}

void GrCCCoverageProcessor::appendGSMesh(sk_sp<const GrGpuBuffer> instanceBuffer, int instanceCount,
                                         int baseInstance, SkTArray<GrMesh>* out) const {
    // GSImpl doesn't actually make instanced draw calls. Instead, we feed transposed x,y point
    // values to the GPU in a regular vertex array and draw kLines (see initGS). Then, each vertex
    // invocation receives either the shape's x or y values as inputs, which it forwards to the
    // geometry shader.
    SkASSERT(Impl::kGeometryShader == fImpl);
    GrMesh& mesh = out->emplace_back(GrPrimitiveType::kLines);
    mesh.setNonIndexedNonInstanced(instanceCount * 2);
    mesh.setVertexData(std::move(instanceBuffer), baseInstance * 2);
}

GrGLSLPrimitiveProcessor* GrCCCoverageProcessor::createGSImpl(std::unique_ptr<Shader> shadr) const {
    if (GSSubpass::kHulls == fGSSubpass) {
        return this->isTriangles()
                   ? (GSImpl*) new GSTriangleHullImpl(std::move(shadr))
                   : (GSImpl*) new GSCurveHullImpl(std::move(shadr));
    }
    SkASSERT(GSSubpass::kCorners == fGSSubpass);
    return new GSCornerImpl(std::move(shadr));
}

redpajama_set_name: RedPajamaGithub


text:
NS_LONG_BEGIN

void TaskDataParam::pushString(std::string key, std::string value)
{
    m_strings[key] = value;
}

void TaskDataParam::pushNumber(std::string key, double value)
{
    m_numbers[key] = value;
}

std::string TaskDataParam::getStringValue(std::string key)
{
	if (m_numbers.empty())
	{
		return "";
	}
    for (auto &iter: m_strings)
    {
        if (iter.first == key)
        {
            return iter.second;
        }
    }
    return "";
}

double TaskDataParam::getNumberValue(std::string key)
{
	if (m_numbers.empty())
	{
		return 0;
	}
    for (auto &iter: m_numbers)
    {
        if (iter.first == key)
        {
            return iter.second;
        }
    }
    return 0;
}

std::string TaskData::getID()
{
    return m_id;
};

std::function<void()> TaskData::getTaskFunction()
{
    return m_taskFunction;
};

void TaskData::execute()
{
    if (m_taskFunction)
    {
        m_taskFunction();
    }
};

std::function<void(TaskDataParam *)> TaskDataCommon::getTaskFunction()
{
    return m_taskFunction;
};

void TaskDataCommon::execute()
{
    if (m_taskFunction)
    {
        m_taskFunction(m_TaskDataParam);
    }
};

LTask::LTask():
	m_pTaskData(nullptr)
{
}

    LTask::LTask(TaskData *taskData):
            m_pTaskData(taskData)
    {

    }

    LTask::LTask(std::function<void()> taskFunc)
    {
        m_pTaskData = new TaskData("normal", taskFunc);
    }

    LTask::LTask(std::function<void(TaskDataParam *)> taskFunction, TaskDataParam *dataParam)
    {
        m_pTaskData = new TaskDataCommon("common", taskFunction, dataParam);
    }

LTask::~LTask()
{

}

LTask * LTask::create(TaskData * taskData)
{
	auto task = new LTask(taskData);
	return task;
}

    LTask* LTask::create(std::function<void()> taskFunc)
    {
        auto task = new LTask(taskFunc);
        return task;
    }

    LTask* LTask::create(std::function<void(TaskDataParam *)> taskFunction, TaskDataParam *dataParam)
    {
        auto task = new LTask(taskFunction, dataParam);
        return task;
    }

TaskData * LTask::getTaskData()
{
	return m_pTaskData;
}

std::string LTask::getID()
{
	if (m_pTaskData)
	{
		return m_pTaskData->getID();
	}
	return "";
}

std::function<void()> LTask::getTaskFunction()
{
	if (m_pTaskData)
	{
		return m_pTaskData->getTaskFunction();
	}
	return nullptr;
}

void LTask::execute()
{
    if (m_pTaskData)
    {
        return m_pTaskData->execute();
    }
}

    void LTask::commit(bool addNewThread)
    {
        auto pool = LThreadPool::getInstance();
        pool->pushTask(this);

        if (addNewThread)
        {
            pool->addThread();
        }
    }

NS_LONG_END


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
StringInputStream (Apache Ant API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.tools.ant.filters.StringInputStream class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.tools.ant.filters

Class StringInputStream

java.lang.Object
  java.io.InputStream
      org.apache.tools.ant.util.ReaderInputStream
          org.apache.tools.ant.filters.StringInputStream

All Implemented Interfaces:
java.io.Closeable

public class StringInputStream
extends ReaderInputStream

Wraps a String as an InputStream.

Constructor Summary

StringInputStream(java.lang.String source)

          Composes a stream from a String

StringInputStream(java.lang.String source,
                  java.lang.String encoding)

          Composes a stream from a String with the specified encoding

Method Summary

Methods inherited from class org.apache.tools.ant.util.ReaderInputStream

available, close, mark, markSupported, read, read, reset

Methods inherited from class java.io.InputStream

read, skip

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StringInputStream

public StringInputStream(java.lang.String source)

Composes a stream from a String

Parameters:
source - The string to read from. Must not be null.

StringInputStream

public StringInputStream(java.lang.String source,
                         java.lang.String encoding)

Composes a stream from a String with the specified encoding

Parameters:
source - The string to read from. Must not be null.
encoding - The encoding scheme.  Also must not be null.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
**References:**
- https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces

## Namespace

A namespace is a mapping from names to objects. Most namespaces are currently
implemented as Python dictionaries, but that's normally not noticeable in any
way (except for performance), and it may change in the future.

**Examples of namespaces are:**
- the set of built-in names (containing functions such as abs(), and built-in exception names)
- the global names in a module
- and the local names in a function invocation
- and in a sense the set of attributes of an object also form a namespace.

The important thing to know about namespaces is that there is absolutely no
relation between names in different namespaces.
For instance, two different modules may both define a function `maximize` without
confusion — users of the modules must prefix it with the module name.

### Attributes

By the way, I use the word attribute for any name following a dot — for
example, in the expression `z.real`, `real` is an attribute of the object `z`.
Strictly speaking, references to names in modules are attribute references: in
the expression modname.funcname, modname is a module object and funcname is an
attribute of it. In this case there happens to be a straightforward mapping
between the module's attributes and the global names defined in the module:
they share the same namespace!

Attributes may be read-only or writable. In the latter case, assignment to
attributes is possible. Module attributes are writable: you can write
`modname.the_answer = 42	. Writable attributes may also be deleted with the
`del` statement. For example, `del modname.the_answer` will remove the
attribute `the_answer` from the object named by `modname`.

## Life-time

Namespaces are created at different moments and have different lifetimes.

### Built-in namespace

The namespace containing the built-in names is created when the Python
interpreter
starts up, and is never deleted.

### GLobal namespace

The global namespace for a module is created when the module definition is read
in; normally, module namespaces also last
until the interpreter quits.

### Module namespace

The statements executed by the top-level invocation of the interpreter, either
read from a script file or interactively, are considered part of a module
called `__main__`, so they have their own global namespace. (The built-in names
actually also live in a module; this is called builtins.)

### Local Namespace

The local namespace for a function is created when the function is called, and
deleted when the function returns or raises an exception that is not handled
within the function. (Actually, forgetting would be a better way to describe
what actually happens.) Of course, recursive invocations each have their own
local namespace.

## Scope

A scope is a textual region of a Python program where a namespace is directly
accessible. ''Directly accessible'' here means that an unqualified reference to a
name attempts to find the name in the namespace.

Although scopes are determined statically, they are used dynamically. At any
time during execution, there are at least three nested scopes whose namespaces
are directly accessible:

- the innermost scope, which is searched first, contains the local names
- the scopes of any enclosing functions, which are searched starting with the nearest
enclosing scope, contains non-local, but also non-global names
- the next-to-last scope contains the current module's global names
- the outermost scope (searched last) is the namespace containing built-in names

If a name is declared global, then all references and assignments go directly
to the middle scope containing the module's global names.

### local and `nonlocal`

To rebind variables found outside of the innermost scope, the `nonlocal`
statement can be used; if not declared `nonlocal`, those variables are
read-only (an attempt to write to such a variable will simply create a new
local variable in the innermost scope, leaving the identically named outer
variable unchanged).

Usually, the local scope references the local names of the (textually) current
function. Outside functions, the local scope references the same namespace as
the global scope: the module's namespace. Class definitions place yet another
namespace in the local scope.

It is important to realize that scopes are determined textually: the global
scope of a function defined in a module is that module's namespace, no matter
from where or by what alias the function is called. On the other hand, the
actual search for names is done dynamically, at run time — however, the
language definition is evolving towards static name resolution, at "compile"
time, so don't rely on dynamic name resolution! (In fact, local variables are
already determined statically.)

### Assignment always go into the innermost scope!

A special quirk of Python is that – if no global statement is in effect –
assignments to names always go into the innermost scope. Assignments do not
copy data — they just bind names to objects. The same is true for deletions:
the statement del x removes the binding of x from the namespace referenced by
the local scope. In fact, all operations that introduce new names use the local
scope: in particular, import statements and function definitions bind the
module or function name in the local scope.

### `global` statement

The `global` statement can be used to indicate that particular variables live in
the global scope and should be rebound there; the `nonlocal` statement indicates
that particular variables live in an enclosing scope and should be rebound
there.


text:
import BLOG from "./Blog.constants";

export const requestStart = () => {
  return {
    type: BLOG.REQUEST_START,
    loading: true
  };
};

export const requestSuccess = (post) => {
  return {
    type: BLOG.REQUEST_SUCCESS,
    post,
    loading: false
  };
};

export const requestError = (errors) => {
  return {
    type: BLOG.REQUEST_ERROR,
    errors,
    loading: false
  };
};

export const addCommentStart = () => {
  return {
    type: BLOG.ADD_COMMENT_START,
    addCommentLoading: true,
  }
};

export const addCommentSuccess = (comment) => {
  return {
    type: BLOG.ADD_COMMENT_SUCCESS,
    comment,
    addCommentLoading: false,
  }
};


text:
import getPlatform from './platform';

const ALT_REGEX = /^alt$/i;
const SHIFT_REGEX = /^shift$/i;
const CTRL_REGEX = /^ctrl$/i;
const META_REGEX = /^meta$/i;
const CMD_REGEX = /^cmd$/i;

export default class KeyboardListener {
  type; // keydown, keyup, keypress
  altKey = false;
  ctrlKey = false;
  shiftKey = false;
  metaKey = false;
  keyOrCode;
  platform;

  constructor(platform = getPlatform()) {
    this.platform = platform;
  }

  static parse(s, platform = getPlatform()) {
    let keyboardListener = new KeyboardListener(platform);
    let [eventType, keyCombo] = s.split(':');
    keyboardListener.type = eventType;

    if (keyCombo === '+') {
      keyboardListener.keyOrCode = keyCombo;
      return keyboardListener;
    }

    keyCombo.split('+').forEach((part) => {
      if (ALT_REGEX.test(part)) {
        keyboardListener.altKey = true;
      } else if (CTRL_REGEX.test(part)) {
        keyboardListener.ctrlKey = true;
      } else if (META_REGEX.test(part)) {
        keyboardListener.metaKey = true;
      } else if (SHIFT_REGEX.test(part)) {
        keyboardListener.shiftKey = true;
      } else if (CMD_REGEX.test(part)) {
        if (platform.indexOf('Mac') > -1) {
          keyboardListener.metaKey = true;
        } else {
          keyboardListener.ctrlKey = true;
        }
      } else {
        keyboardListener.keyOrCode = part;
      }
    });
    return keyboardListener;
  }

  createMatchingKeyboardEvent(opts = {}) {
    return new KeyboardEvent(
      this.type,
      Object.assign(
        {
          // one of these next two will be incorrect. For test usage, if usually
          // doesn't matter, but you can pass in correct values via opts if needed.
          key: this.keyOrCode,
          code: this.keyOrCode,

          altKey: this.altKey,
          ctrlKey: this.ctrlKey,
          metaKey: this.metaKey,
          shiftKey: this.shiftKey,
        },
        opts
      )
    );
  }
}


text:
import logging
import logging.handlers

from config import Config

log_file = '/var/log/twitch-browser/twitch-browser.log'
log_format = '%(asctime)s %(levelname)-8s [%(module)s] %(msg)s'
file_handler = logging.handlers.TimedRotatingFileHandler(
    log_file,
    when='midnight',
    interval=1,
    backupCount=28)
file_handler.setFormatter(logging.Formatter(log_format))

config = Config(
    host='0.0.0.0',
    port=5000,
    debug=True,
    use_reloader=False,
    use_evalex=False,
    processes=16,
    log_handlers=[
        file_handler,
    ],
)

try:
    from twitch_browser.settings import local
    config.update(local.config)
except ImportError:
    pass


text:
  <form class="well form-vertical" autocomplete="off" action="{{ url_for('update_game') }}" method=POST>
  Delete Game

Edit Game

    <input type="hidden" name="lead_id" class="span3" value="{{ lead.id }}">
    <input type="hidden" name="game_id" class="span3" value="{{ game.id }}">

    <input type="text" name="name" class="span3" value="{{ game.name }}">Name

    <select name="statuses" data-placeholder="Select Some Statuses" class="chzn-select">
      {% for status in attributes.get('statuses') %}
      <option value="{{ status.name }}" {% if game.statuses %}{% if status in game.statuses %}selected='selected'{% endif %}{% endif %}>{{ status.name }}</option>
      {% endfor %}
    </select>Status

    <input type="text" name="ratings" class="span3" value="{{ game.ratings }}">Ratings

    <select name="ages" data-placeholder="Select Some Ages" multiple="multiple" class="chzn-select">
      {% for age in attributes.get('ages') %}
      <option value="{{ age.name }}" {% if game.ages %}{% if age in game.ages %}selected='selected'{% endif %}{% endif %}>{{ age.name }}</option>
      {% endfor %}
    </select>Age

    <select name="genders" data-placeholder="Select Some Genders" multiple="multiple" class="chzn-select">
      {% for gender in attributes.get('genders') %}
      <option value="{{ gender.name }}" {% if game.genders %}{% if gender in game.genders %}selected='selected'{% endif %}{% endif %}>{{ gender.name }}</option>
      {% endfor %}
    </select>Gender

    <select data-placeholder="Select a Platform..." name="platform" class="chzn-select">
        {% for opt in ["iOS", "Android", "Web"] %}
        <option value="{{ opt }}" {% if game.platform == opt %}selected='selected'{% endif %}>{{ opt }}</option>
        {% endfor %}
    </select>What platform are they on?

    <input type="text" name="int_date" value="{{ game.int_date }}">Integration Date

    <select name="tags" data-placeholders="Select Relevent Tags" multiple="multiple" class="chzn-select">
        {% for tag in attributes.get('tags') %}
        <option value="{{ tag.name }}" {% if game.tags %} {% if tag in game.tags %} selected='selected' {%endif%}
        {%endif%}>{{ tag.name }}</option>
        {% endfor %}
    </select>Tags

    <button type="submit" class="btn btn-primary">Send Changes</button>
    Cancel
</form>


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
      xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
      xml:base="http://buildserver.labs.intellij.net/httpAuth/app/nuget/v1/FeedService.svc/">
  <title type="text">Packages</title>
  <id>http://buildserver.labs.intellij.net/httpAuth/app/nuget/v1/FeedService.svc/Packages()</id>
  <updated>2019-11-28T13:09:17Z</updated>
  <link rel="self" title="Packages" href="Packages"/>
  <entry>
    <id>http://buildserver.labs.intellij.net/httpAuth/app/nuget/v1/FeedService.svc/Packages(Id='EasyHttp',Version='1.7.0')</id>
    <category term="NuGetGallery.V2FeedPackage" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
    <link rel="edit" title="V2FeedPackage"
          href="Packages(Id='EasyHttp',Version='1.7.0')"/>
    <content type="application/zip"
             src="http://buildserver.labs.intellij.net/httpAuth/repository/download/dm-fc-b/1439179:id/easyhttp.1.7.0.nupkg"/>
    <title type="text">EasyHttp</title>
    <updated>2017-01-15T00:11:07Z</updated>
    <author>
      <name>Hadi Hariri and Contributors</name>
    </author>
    <m:properties>
      <d:Id>EasyHttp</d:Id>
      <d:Version>1.7.0</d:Version>
      <d:NormalizedVersion>1.7.0</d:NormalizedVersion>
      <d:Authors>Hadi Hariri and Contributors</d:Authors>
      <d:Copyright>Copyright 2012 Hadi Hariri and Contributors</d:Copyright>
      <d:Created m:type="Edm.DateTime">2017-01-15T00:11:07.297+00:00</d:Created>
      <d:Dependencies>JsonFX:[2.0.1209.2802, ):</d:Dependencies>
      <d:Description>An HTTP Client for .NET</d:Description>
      <d:DownloadCount m:type="Edm.Int32">302155</d:DownloadCount>
      <d:GalleryDetailsUrl>https://www.nuget.org/packages/EasyHttp/1.7.0</d:GalleryDetailsUrl>
      <d:IconUrl>https://api.nuget.org/v3-flatcontainer/easyhttp/1.7.0/icon</d:IconUrl>
      <d:IsLatestVersion m:type="Edm.Boolean">true</d:IsLatestVersion>
      <d:IsAbsoluteLatestVersion m:type="Edm.Boolean">true</d:IsAbsoluteLatestVersion>
      <d:IsPrerelease m:type="Edm.Boolean">false</d:IsPrerelease>
      <d:Language m:null="true"/>
      <d:LastUpdated m:type="Edm.DateTime">2017-01-15T00:11:07.297+00:00</d:LastUpdated>
      <d:Published m:type="Edm.DateTime">2017-01-15T00:11:07.297+00:00</d:Published>
      <d:PackageHash>rdPAirDUajd7naq6qF/jTBzkruxNRLI069bLpSteQ/raPWgou7o5rZJiglYIwatsMEgk5wdbL6qp7MmcJt8Aug==</d:PackageHash>
      <d:PackageHashAlgorithm>SHA512</d:PackageHashAlgorithm>
      <d:PackageSize m:type="Edm.Int64">86365</d:PackageSize>
      <d:ProjectUrl>http://github.com/easyhttp/EasyHttp</d:ProjectUrl>
      <d:ReportAbuseUrl>https://www.nuget.org/packages/EasyHttp/1.7.0/ReportAbuse</d:ReportAbuseUrl>
      <d:ReleaseNotes>This release adds support for mocking and stubbing HttpClient (by virtualizing public members) and introduces a new method of intercepting requests and
        injecting explicit responses. See http://github.com/easyhttp/EasyHttp for more detail.
      </d:ReleaseNotes>
      <d:RequireLicenseAcceptance m:type="Edm.Boolean">false</d:RequireLicenseAcceptance>
      <d:Summary></d:Summary>
      <d:Tags>HTTP REST</d:Tags>
      <d:Title>EasyHttp</d:Title>
      <d:VersionDownloadCount m:type="Edm.Int32">47412</d:VersionDownloadCount>
      <d:MinClientVersion m:null="true"/>
      <d:LastEdited m:type="Edm.DateTime">2018-11-03T21:27:01.84+00:00</d:LastEdited>
      <d:LicenseUrl>https://raw.github.com/hhariri/EasyHttp/master/LICENSE.TXT</d:LicenseUrl>
      <d:LicenseNames m:null="true"/>
      <d:LicenseReportUrl m:null="true"/>
    </m:properties>
  </entry>
</feed>


text:
using SuccincT.Options;

namespace SuccincT.Parsers
{
    /// <summary>
    /// Defines a set of string extension methods for parsing float, double and decimal
    /// values in an elegant fashion (avoiding exception throwing and out parameters).
    /// </summary>
    public static class FloatParsers
    {
        /// <summary>
        /// Parses the current string for a 32 bit float value and returns an Option{float} with None or the value.
        /// </summary>
        public static Option<float> TryParseFloat(this string source) =>
            float.TryParse(source, out var result) ? Option<float>.Some(result) : Option<float>.None();

        /// <summary>
        /// Parses the current string for a 64 bit float value and returns an Option{double} with None or the value.
        /// </summary>
        public static Option<double> TryParseDouble(this string source) =>
            double.TryParse(source, out var result) ? Option<double>.Some(result) : Option<double>.None();

        /// <summary>
        /// Parses the current string for a 128 bit float value and returns an Option{decimal} with None or the value.
        /// </summary>
        public static Option<decimal> TryParseDecimal(this string source) =>
            decimal.TryParse(source, out var result) ? Option<decimal>.Some(result) : Option<decimal>.None();
    }
}


text:
/*jslint devel: true,  undef: true, newcap: true, strict: true, maxerr: 50 */

/*global YUI*/

/**
 * The support object that organizes access to the login dialog.
 *
 * @module login-processor
 */
YUI.add('login-processor', function(Y) {
    "use strict";

    // handy constants and shortcuts used in the module
    var Lang = Y.Lang,
    NAME = 'loginProcessor';

    /**
     * The login-processing component
     *
     * @class LoginProcessor
     * @extends Y.Model
     * @uses xxxxx
     * @constructor
     * @cfg {object} configuration attributes
     */
    Y.LoginProcessor = Y.Base.create(
        NAME,
        Y.Model,
        [],
        {
            initializer: function() {
            },

            /**
             * Called by GatewayModels when they want to try to log in, to serialize
             * contention for the login dialog (or any other login resources.)
             * Models are pushed onto a queue if this is called when some other
             * gatewayModel has the lock.
             */
            requestLoginLock: function(gatewayModel, callback, canChangeUrl) {
                var $this = this;

                var lockQueueEntry = this.get('loginLock');

                if (lockQueueEntry) {
                    // Don't allow the same gateway model to be on the queue more than once.
                    if (lockQueueEntry.gatewayModel !== gatewayModel) {
                        var loginLockQueue = this.get('loginLockQueue');
                        for (var i = 0; i < loginLockQueue.length; i++) {
                            if (loginLockQueue[i].gatewayModel === gatewayModel) {
                                // already queued, just ignore it.
                                return;
                            }
                        }

                        // we're not in the queue, push a new entry
                        loginLockQueue.push({gatewayModel: gatewayModel,
                                             callback: callback,
                                             canChangeUrl: canChangeUrl});
                    }
                } else {
                    this.set('loginLock', {gatewayModel: gatewayModel,
                                           callback: callback,
                                           canChangeUrl: canChangeUrl});

                    // XXX Should this really be invokeLater()? Or does that
                    // cause potential issues because the guy getting the lock
                    // hasn't actually had a chance to process yet?
                    invokeLater(function() {$this.processLogin(false, null, null);}, 0);
                }
            },

            hasLoginLock: function(gatewayModel) {
                var lockQueueEntry = this.get('loginLock');
                return (lockQueueEntry !== null && lockQueueEntry.gatewayModel === gatewayModel);
            },

            /**
             * If a given model has the lock or is in the lock queue, remove it.
             * It is NOT an error if the model is in neither.
             */
            clearLoginLock: function(gatewayModel) {
                var loginLockQueue = this.get('loginLockQueue');

                if (this.hasLoginLock(gatewayModel)) {
                    if (loginLockQueue.length == 0) {
                        this.set('loginLock', null);
                    } else {
                        var nextEntry = loginLockQueue.shift();
                        this.set('loginLock', nextEntry);

                        // XXX Should this really be invokeLater()? Or does that
                        // cause potential issues because the guy getting the lock
                        // hasn't actually had a chance to process yet?
                        invokeLater(function() {$this.processLogin(false, null, null);}, 0);
                    }
                } else {
                    for (var i = 0; i < loginLockQueue.length; i++) {
                        if (loginLockQueue[i].gatewayModel === gatewayModel) {
                            loginLockQueue.splice(index, 1);
                        }
                    }
                }
            },

            /**
             * Emergency function to bail on all loginresource requests
             */
            clearAllLoginLockRequests: function() {
                this.set('loginLockQueue', []);
                this.set('loginLock', null);
            },

            /**
             * Process the login request that currently has the login lock. Cycle until
             * we either get a set of credentials to return or the user bails.
             */
            processLogin: function(showError, username, password) {
                var $this = this;

                var lockRequest = this.get('loginLock');
                var connectionUrl = lockRequest.gatewayModel.get('connectionUrl');

                this.get('loginPanel').display(connectionUrl,
                                               lockRequest.canChangeUrl,
                                               showError,
                                               username,
                                               password,
                                               function(connectionUrl, username, password, cancelling) {
                                                   $this.gatherCredentialsCallback(connectionUrl,
                                                                                username,
                                                                                password,
                                                                                cancelling);
                                               });
            },

            /**
             * Process the response from the loginPanel. The loginLock still contains
             * the original parameters of the login before any user changes.
             */
            gatherCredentialsCallback: function(connectionUrl, username, password, cancelling) {
                var $this = this;

                var lockQueueEntry = this.get('loginLock');

                if (cancelling || isEmpty(!username) || isEmpty(connectionUrl)) {
                    // user has bailed. Clear the entry from the lock queue and continue.
                    invokeLater(function() {$this.clearLoginLock(lockQueueEntry.gatewayModel);}, 0);
                    return;
                }

                lockQueueEntry.callback(connectionUrl, username, password);
            },
        },
        {
            ATTRS: {

                app: {
                    value: null     // the CommandCenter
                },

                loginPanel: {
                    value: null
                },

                // The GatewayModel that has the login lock.
                loginLock: {
                    value: null
                },

                // The GatewayModels that are waiting for the login lock
                loginLockQueue: {
                    value: []
                }
            }
        }
    );
}, '0.99', {
    requires: ['model', 'cluster-model', 'gateway-model']
});


text:
require 'rails_helper'

RSpec.describe MarioLevel, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"
end


text: Python bindings for FFTW


text:
package com.ultraflynn.sygrl.authentication;

import org.junit.Test;

import java.time.LocalDateTime;

import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertTrue;

public class AccessTokenTest {
    @Test
    public void shouldKnowWhenNotExpired() {
        AccessToken accessToken = new AccessToken(LocalDateTime.now(), 1200, "access_token", "refresh token");
        assertFalse(accessToken.hasExpired());
    }

    @Test
    public void shouldKnowWhenOnExpiryCutover() {
        AccessToken accessToken = new AccessToken(LocalDateTime.now().minusSeconds(1200), 1200, "access_token", "refresh token");
        assertTrue(accessToken.hasExpired());
    }

    @Test
    public void shouldKnowWhenWellOverExpiry() {
        AccessToken accessToken = new AccessToken(LocalDateTime.now().minusSeconds(1500), 1200, "access_token", "refresh token");
        assertTrue(accessToken.hasExpired());
    }

    @Test
    public void shouldKnowWhenCloseToExpiry() {
        AccessToken accessToken = new AccessToken(LocalDateTime.now().minusSeconds(1080), 1200, "access_token", "refresh token");
        assertTrue(accessToken.hasExpired());
    }

    @Test
    public void shouldKnowWhenCloseToExpiryButStillValid() {
        AccessToken accessToken = new AccessToken(LocalDateTime.now().minusSeconds(1079), 1200, "access_token", "refresh token");
        assertFalse(accessToken.hasExpired());
    }
}


text:
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}

INSTALLED_APPS = [
    'django',
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.sessions',
    'openstack_auth',
    'openstack_auth.tests'
]

MIDDLEWARE_CLASSES = [
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware'
]

AUTHENTICATION_BACKENDS = ['openstack_auth.backend.KeystoneBackend']

OPENSTACK_KEYSTONE_URL = "http://localhost:5000/v2.0"

ROOT_URLCONF = 'openstack_auth.tests.urls'

LOGIN_REDIRECT_URL = '/'

SECRET_KEY = 'badcafe'

OPENSTACK_API_VERSIONS = {
    "identity": 2.0
}

USE_TZ = True

OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT = False

OPENSTACK_KEYSTONE_DEFAULT_DOMAIN = 'domain'


text:
local utils = require 'utils'

validArgs = validArgs or utils.invert({
 'help',
 'temperature',
 'category',
 'token',
 'flag',
 'all',
 'dur',
 'unit',
 'age',
 'size',
 'fixed',
 'set',
 'percent',
 'mode',
 'amount',
 'announcement',
})
local args = utils.processArgs({...}, validArgs)

if args.help then -- Help declaration
 print([[body-change.lua
  Change the body parts of a unit (currently only supports changing temperature, size, or setting on fire)
  arguments:
   -help
     print this help message
   -unit id
     REQUIRED
     id of the target unit
   -category TYPE                           \
     change body parts of specific category |
     examples:                              |
      TENTACLE                              |
      HOOF_REAR                             |
      HEAD                                  |
   -token TYPE                              |
     change body parts by specific token    | Must at least one of these arguments if changing temperature
     examples:                              |
      UB                                    |
      LB                                    |
      REYE                                  |
   -flag FLAG                               |
     change body parts by specific flag     |
     examples:                              |
      SIGHT                                 |
      LIMB                                  |
      SMALL                                 /
   -temperature
     temperature to set body parts to
     special token:
      Fire - sets the body part on fire
   -size
     Valid Types:
      All
      Size
      Length
      Area
   -age (Not currently supported)
   -mode (Mode Type)
     Valid Types:
      Fixed
      Percent
      Set
   -amount #
   -dur #
     length of time, in in-game ticks, for the change to last
     0 means the change is permanent
     DEFAULT: 0
  examples:
   unit/body-change -unit \\UNIT_ID -flag GRASP -temperature fire -dur 1000
   unit/body-change -unit \\UNIT_ID -category LEG_LOWER -temperature 8000
 ]])
 return
end

if args.unit and tonumber(args.unit) then
 unit = df.unit.find(tonumber(args.unit))
else
 print('No unit selected')
 return
end

dur = tonumber(args.dur) or 0
if dur < 0 then return end
value = args.amount

if args.temperature then
 changeType = 'Temperature'
 parts = {}
 if args.category == 'ALL' or args.token == 'ALL' or args.flag == 'ALL' then
  body = unit.body.body_plan.body_parts
  for k,v in ipairs(body) do
   parts[k] = k
  end
 elseif args.category then
  parts = dfhack.script_environment('functions/unit').checkBodyCategory(unit,args.category)
 elseif args.token then
  parts = dfhack.script_environment('functions/unit').checkBodyToken(unit,args.token)
 elseif args.flag then
  parts = dfhack.script_environment('functions/unit').checkBodyFlag(unit,args.flag)
 else
  print('No body parts declared for temperature change')
  return
 end

 for _,part in ipairs(parts) do
  if args.temperature == 'Fire' or args.temperature == 'fire' then
   dfhack.script_environment('functions/unit').changeBody(unit,part,changeType,'Fire',dur)
  else
   current = unit.status2.body_part_temperature[part].whole
   if args.mode == 'Fixed' or args.mode == 'fixed' then
    change = tonumber(value)
   elseif args.mode == 'Percent' or args.mode == 'percent' then
    local percent = (100+tonumber(value))/100
    change = current*percent - current
   elseif args.mode == 'Set' or args.mode == 'set' then
    change = tonumber(value) - current
   else
    print('No method for change defined')
    return
   end
   dfhack.script_environment('functions/unit').changeBody(unit,part,changeType,change,dur)
  end
 end
elseif args.age then
 changeType = 'age'
elseif args.size then
 if args.size == 'Size' or args.size == 'All' then
  current = unit.body.size_info.size_cur
  change = dfhack.script_environment('functions/misc').getChange(current,value,args.mode)
  dfhack.script_environment('functions/unit').changeBody(unit,nil,'Size',change,dur)
 end
 if args.size == 'Area' or args.size == 'All' then
  current = unit.body.size_info.area_cur
  if args.mode == 'Fixed' or args.mode == 'fixed' then
   change = tonumber(value)
  elseif args.mode == 'Percent' or args.mode == 'percent' then
   local percent = (100+tonumber(value))/100
   change = current*percent - current
  elseif args.mode == 'Set' or args.mode == 'set' then
   change = tonumber(value) - current
  else
   print('No method for change defined')
   return
  end
  dfhack.script_environment('functions/unit').changeBody(unit,nil,'Area',change,dur)
 end
 if args.size == 'Length' or args.size == 'All' then
  current = unit.body.size_info.length_cur
  if args.mode == 'Fixed' or args.mode == 'fixed' then
   change = tonumber(value)
  elseif args.mode == 'Percent' or args.mode == 'percent' then
   local percent = (100+tonumber(value))/100
   change = current*percent - current
  elseif args.mode == 'Set' or args.mode == 'set' then
   change = tonumber(value) - current
  else
   print('No method for change defined')
   return
  end
  dfhack.script_environment('functions/unit').changeBody(unit,nil,'Length',change,dur)
 end
else
 print('Nothing to change declared, choose -age, -size, or -temperature')
 return
end


text:
module Azure::Postgresql::Mgmt::V2017_12_01
  module Models
    #
    # Represents a server to be created.
    #
    class ServerForCreate

      include MsRestAzure

      # @return [Sku] The SKU (pricing tier) of the server.
      attr_accessor :sku

      # @return [ServerPropertiesForCreate] Properties of the server.
      attr_accessor :properties

      # @return [String] The location the resource resides in.
      attr_accessor :location

      # @return [Hash{String => String}] Application-specific metadata in the
      # form of key-value pairs.
      attr_accessor :tags

      #
      # Mapper for ServerForCreate class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ServerForCreate',
          type: {
            name: 'Composite',
            class_name: 'ServerForCreate',
            model_properties: {
              sku: {
                client_side_validation: true,
                required: false,
                serialized_name: 'sku',
                type: {
                  name: 'Composite',
                  class_name: 'Sku'
                }
              },
              properties: {
                client_side_validation: true,
                required: true,
                serialized_name: 'properties',
                type: {
                  name: 'Composite',
                  polymorphic_discriminator: 'createMode',
                  uber_parent: 'ServerPropertiesForCreate',
                  class_name: 'ServerPropertiesForCreate'
                }
              },
              location: {
                client_side_validation: true,
                required: true,
                serialized_name: 'location',
                type: {
                  name: 'String'
                }
              },
              tags: {
                client_side_validation: true,
                required: false,
                serialized_name: 'tags',
                type: {
                  name: 'Dictionary',
                  value: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package com.arturmkrtchyan.kafka;

public class KafkaPluginException extends RuntimeException {

    private static final long serialVersionUID = -2715142907876721085L;

    public KafkaPluginException() {
        super();
    }

    public KafkaPluginException(final String message) {
        super(message);
    }

    public KafkaPluginException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public KafkaPluginException(final Throwable cause) {
        super(cause);
    }

}


text:
#region License

#endregion

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects;
using Spring.Transaction;

namespace Spring.Testing.Microsoft
{
	/// <summary>
	/// Summary description for AbstractDependencyInjectionSpringContextTestsTests.
	/// </summary>
	[TestClass]
	public class AbstractDependencyInjectionSpringContextTestsTests
	{
        //Force loading of this assembly since MsTest runner doesn't run in the 'working' directory and find
        //dynamically loaded assemblies... (you have *got* to be kidding!!!)
        //Investigate use of [DeploymentItem(...)]
	    private Type t = typeof (CallCountingTransactionManager);
	    private Type t2 = typeof (TestObject);

        private class TestAbstractDependencyInjectionSpringContextTests : AbstractDependencyInjectionSpringContextTests
        {
            public static readonly string[] CONFIGLOCATIONS = new string[] {"assembly://Spring.Testing.Microsoft.Tests/Spring.Testing.Microsoft/TestApplicationContext.xml"};

            public TestAbstractDependencyInjectionSpringContextTests()
            {}

            public TestAbstractDependencyInjectionSpringContextTests(bool registerWithContextRegistry)
            {
                base.RegisterContextWithContextRegistry = registerWithContextRegistry;
            }

            public IConfigurableApplicationContext ApplicationContext
            {
                get { return base.applicationContext; }
            }

            protected override string[] ConfigLocations
            {
                get { return CONFIGLOCATIONS; }
            }

            public new bool HasCachedContext(object key)
            {
                return base.HasCachedContext(key);
            }
        }

        private TestAbstractDependencyInjectionSpringContextTests fixtureInstance ;

        [TestCleanup]
        public void TearDown()
        {
            AbstractSpringContextTests.ClearContextCache();
        }

	    [TestMethod]
        public void RegistersWithContextRegistryByDefault()
	    {
	        fixtureInstance = new TestAbstractDependencyInjectionSpringContextTests();
            Assert.IsTrue(fixtureInstance.RegisterContextWithContextRegistry);
            Assert.AreEqual(typeof(CallCountingTransactionManager), t);
            Assert.AreEqual(typeof(TestObject), t2);

	    }

	    [TestMethod]
        public void UnregistersFromContextRegistryWhenDirty()
	    {
	        fixtureInstance = new TestAbstractDependencyInjectionSpringContextTests();
            Assert.IsTrue(fixtureInstance.RegisterContextWithContextRegistry);
            fixtureInstance.TestInitialize();
            Assert.IsTrue( ContextRegistry.IsContextRegistered(fixtureInstance.ApplicationContext.Name) );
            fixtureInstance.TestCleanup();
            Assert.IsTrue(ContextRegistry.IsContextRegistered(fixtureInstance.ApplicationContext.Name));
            fixtureInstance.TestInitialize();
            Assert.IsTrue(ContextRegistry.IsContextRegistered(fixtureInstance.ApplicationContext.Name));
            fixtureInstance.SetDirty();
            fixtureInstance.TestCleanup();
            Assert.IsFalse(ContextRegistry.IsContextRegistered(fixtureInstance.ApplicationContext.Name));
	    }

	    [TestMethod]
        public void DoesNotRegisterContextWithContextRegistry()
	    {
	        fixtureInstance = new TestAbstractDependencyInjectionSpringContextTests();
            Assert.IsTrue(fixtureInstance.RegisterContextWithContextRegistry);
            fixtureInstance.RegisterContextWithContextRegistry = false;
            fixtureInstance.TestInitialize();
            Assert.IsFalse( ContextRegistry.IsContextRegistered(fixtureInstance.ApplicationContext.Name) );
            fixtureInstance.TestCleanup();
            Assert.IsFalse( ContextRegistry.IsContextRegistered(fixtureInstance.ApplicationContext.Name) );
	    }

        [TestMethod]
        public void CachesApplicationContexts()
        {
	        fixtureInstance = new TestAbstractDependencyInjectionSpringContextTests(false);
            fixtureInstance.TestInitialize();
            Assert.IsNotNull(fixtureInstance.ApplicationContext);
            Assert.AreEqual(1, fixtureInstance.LoadCount); // context has been loaded
            Assert.IsTrue(fixtureInstance.HasCachedContext(TestAbstractDependencyInjectionSpringContextTests.CONFIGLOCATIONS));
            fixtureInstance.TestCleanup();

            TestAbstractDependencyInjectionSpringContextTests otherFixtureInstance = new TestAbstractDependencyInjectionSpringContextTests(false);
            otherFixtureInstance.TestInitialize();
            Assert.IsNotNull(otherFixtureInstance.ApplicationContext);
            Assert.AreEqual(0, otherFixtureInstance.LoadCount); // context was obtained from cache
            Assert.AreSame(fixtureInstance.ApplicationContext, otherFixtureInstance.ApplicationContext);
            otherFixtureInstance.SetDirty(); // purge cache and dispose cached instances
            Assert.IsFalse(fixtureInstance.HasCachedContext(TestAbstractDependencyInjectionSpringContextTests.CONFIGLOCATIONS));
            otherFixtureInstance.TestCleanup();
            otherFixtureInstance = new TestAbstractDependencyInjectionSpringContextTests(false);
            otherFixtureInstance.TestInitialize();
            Assert.IsNotNull(otherFixtureInstance.ApplicationContext);
            Assert.AreEqual(1, otherFixtureInstance.LoadCount); // context was reloaded because of SetDirty() above
            Assert.AreNotSame(fixtureInstance.ApplicationContext, otherFixtureInstance.ApplicationContext);
            otherFixtureInstance.TestCleanup();
        }
	}
}


text:
NACL_SDK_VERSION := 34

THIS_MAKEFILE := $(abspath $(lastword $(MAKEFILE_LIST)))
CURRENT_DIR := $(patsubst %/,%,$(dir $(THIS_MAKEFILE)))
NACL_SDK_ROOT := $(CURRENT_DIR)/nacl_sdk/pepper_$(NACL_SDK_VERSION)

WARNINGS := -W -Wall
CXXFLAGS := $(WARNINGS)

GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
OSHELPERS = python $(NACL_SDK_ROOT)/tools/oshelpers.py
OSNAME := $(shell $(GETOS))

PNACL_TC_PATH := $(abspath $(NACL_SDK_ROOT)/toolchain/$(OSNAME)_pnacl)
PNACL_CXX := $(PNACL_TC_PATH)/bin/pnacl-clang++
PNACL_FINALIZE := $(PNACL_TC_PATH)/bin/pnacl-finalize
CXXFLAGS += -I$(NACL_SDK_ROOT)/include -Ideps/openssl/include
LDFLAGS := -L$(NACL_SDK_ROOT)/lib/pnacl/Release -lppapi_cpp -lppapi -Ldeps/openssl/lib -lcrypto

all: nacl_android_rsa.pexe

.cc.o:
	$(PNACL_CXX) -c -o $@ $< -O2 $(CXXFLAGS)

nacl_android_rsa.bc: module.o instance.o android_rsa.o modp_b64.o endian.o
	$(PNACL_CXX) -o $@ $^ $(LDFLAGS)

nacl_android_rsa.pexe: deps/openssl.deps nacl_android_rsa.bc
	$(PNACL_FINALIZE) -o $@ $<

deps/openssl.deps: deps/openssl.zip
	cd deps ; unzip openssl.zip && touch openssl.deps

distclean: clean
	rm -rf nacl_sdk
	rm -f nacl_sdk.zip

clean:
	rm -rf nacl_android_rsa.pexe nacl_android_rsa.bc *.o deps/openssl.deps deps/openssl


text:
<!DOCTYPE html>

	<title>Spring Events</title>

			<form th:object="${event}" action="" method="post">

				<fieldset th:if="${#fields.hasErrors('all')}" class="error">
					<legend>Errors in Form</legend>

							The field name
							The error message

				</fieldset>

				<fieldset class="eventForm">

					<legend>New Event</legend>

							Date:

								<input type="date" th:field="*{eventDate}" maxlength="30" />

error

							Name:

								<input type="text" th:field="*{name}" maxlength="30" />

error

							Location:

								<input type="text" th:field="*{location}" maxlength="30" />

error

				</fieldset>

							<input type="submit" class="btnsmall" name="submit" id="submit" value="  Submit »" />

			</form>


text:
#include "tigl_config.h"

#include <qnamespace.h>
#include "TIGLViewerContext.h"
#include "TIGLViewerInternal.h"
#include "TIGLViewerSettings.h"
#include "tiglcommonfunctions.h"

#include "ISession_Point.h"
#include "ISession_Text.h"
#include "ISession_Direction.h"

#include <OpenGl_GraphicDriver.hxx>

TIGLViewerContext::TIGLViewerContext()
{
    // Create the OCC Viewers
    TCollection_ExtendedString a3DName("Visual3D");
    myViewer = createViewer( a3DName.ToExtString(), "", 1000.0 );
    myViewer->SetDefaultLights();
    myViewer->SetZBufferManagment(Standard_False);
    myViewer->SetDefaultViewProj( V3d_Zpos );    // Top view
    myContext = new AIS_InteractiveContext( myViewer );

    myGridType       = Aspect_GT_Rectangular;
    myGridMode       = Aspect_GDM_Lines;
    myGridColor      = Quantity_NOC_RED4;
    myGridTenthColor = Quantity_NOC_GRAY90;

    myContext->SetHilightColor(Quantity_NOC_WHITE);
    myContext->SetIsoNumber(0);

    setGridOffset (0.0);
    gridXY();
    gridOn();
}

TIGLViewerContext::~TIGLViewerContext()
{

}

Handle_V3d_Viewer& TIGLViewerContext::getViewer()
{
    return myViewer;
}

Handle_AIS_InteractiveContext& TIGLViewerContext::getContext()
{
    return myContext;
}

Handle_V3d_Viewer TIGLViewerContext::createViewer( const Standard_ExtString aName,
                                                   const Standard_CString aDomain,
                                                   const Standard_Real ViewSize )
{
    static Handle(OpenGl_GraphicDriver) deviceHandle;

    if (deviceHandle.IsNull()) {
      Handle(Aspect_DisplayConnection) aDisplayConnection;
#if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
      aDisplayConnection = new Aspect_DisplayConnection (qgetenv ("DISPLAY").constData());
#endif
      deviceHandle = new OpenGl_GraphicDriver (aDisplayConnection);
    }

    return new V3d_Viewer(  deviceHandle,
                            aName,
                            aDomain,
                            ViewSize,
                            V3d_XposYnegZpos,
                            Quantity_NOC_BLACK,
                            V3d_ZBUFFER,
                            V3d_GOURAUD,
                            V3d_WAIT );
}
/*!
\brief    Deletes all objects.

        This function deletes all dispayed objects from the AIS context.
        No parameters.
*/
void TIGLViewerContext::deleteAllObjects()
{
    AIS_ListOfInteractive aList;
    myContext->DisplayedObjects( aList );
    AIS_ListIteratorOfListOfInteractive aListIterator;
    for ( aListIterator.Initialize( aList ); aListIterator.More(); aListIterator.Next() ) {
        myContext->Remove( aListIterator.Value(), Standard_False);
    }
    myContext->UpdateCurrentViewer();
}
/*!
\brief    Sets the privileged plane to the XY Axis.
*/
void TIGLViewerContext::gridXY  ( void )
{
    myGridColor      = Quantity_NOC_RED4;
    myViewer->Grid()->SetColors( myGridColor, myGridTenthColor );
    gp_Ax3 aPlane(gp_Pnt( 0., 0., 0. ),gp_Dir(0., 0., 1.));
    myViewer->SetPrivilegedPlane( aPlane );
}
/*!
\brief    Sets the privileged plane to the XZ Axis.

          Note the negative direction of the Y axis.
          This is corrrect for a right-handed co-ordinate set.
*/
void TIGLViewerContext::gridXZ  ( void )
{
    myGridColor      = Quantity_NOC_BLUE4;
    myViewer->Grid()->SetColors( myGridColor, myGridTenthColor );
    gp_Ax3 aPlane( gp_Pnt(0., 0., 0.),gp_Dir(0., -1., 0.) );
    myViewer->SetPrivilegedPlane( aPlane );
}
/*!
\brief    Sets the privileged plane to the XY Axis.
 */
void TIGLViewerContext::gridYZ  ( void )
{
    myGridColor      = Quantity_NOC_GREEN4;
    myViewer->Grid()->SetColors( myGridColor, myGridTenthColor );
    gp_Ax3 aPlane( gp_Pnt( 0., 0., 0.), gp_Dir( 1., 0., 0. ) );
    myViewer->SetPrivilegedPlane( aPlane );
}

/*!
 * \brief Toggles the grid on and off
 */
void TIGLViewerContext::toggleGrid(bool gridIsOn)
{
    if (gridIsOn) {
        gridOn();
    }
    else {
        gridOff();
    }
}

/*!
\brief    Turn the grid on.
 */
void TIGLViewerContext::gridOn  ( void )
{
    myViewer->ActivateGrid( myGridType , myGridMode );
    myViewer->SetGridEcho ( Standard_True );
}

/*!
\brief    Turn the grid off.
*/
void TIGLViewerContext::gridOff ( void )
{
    myViewer->DeactivateGrid();
    myViewer->SetGridEcho( Standard_False );
}

/*!
\brief    Select a rectangular grid
*/
void TIGLViewerContext::gridRect ( void )
{
    myGridType = Aspect_GT_Rectangular;
    myViewer->ActivateGrid( myGridType , myGridMode );
    myViewer->Grid()->SetColors( myGridColor, myGridTenthColor );
}
/*!
\brief    Select a circular grid.
*/
void TIGLViewerContext::gridCirc ( void )
{
    myGridType = Aspect_GT_Circular;
    myViewer->ActivateGrid( myGridType , myGridMode );
    myViewer->Grid()->SetColors( myGridColor, myGridTenthColor );
}

/*!
 * \brief Toggles wireframe view.
 * \param wireframe True, if wireframes should be printed
 */
void TIGLViewerContext::wireFrame(bool wireframe)
{
    if (!myContext.IsNull()){
        if (wireframe) {
            myContext->SetDisplayMode(AIS_WireFrame);
        }
        else {
            myContext->SetDisplayMode(AIS_Shaded);
        }
    }
}

void TIGLViewerContext::setGridOffset (Quantity_Length offset)
{
    Quantity_Length radius;
    Quantity_Length xSize, ySize;
    Quantity_Length oldOffset;

    myViewer->CircularGridGraphicValues( radius, oldOffset );
    myViewer->SetCircularGridGraphicValues( radius, offset);

    myViewer->RectangularGridGraphicValues(xSize, ySize, oldOffset);
    myViewer->SetRectangularGridGraphicValues(xSize, ySize, offset);
}

// a small helper when we just want to display a shape
void TIGLViewerContext::displayShape(const TopoDS_Shape& loft, Quantity_Color color)
{
    TIGLViewerSettings& settings = TIGLViewerSettings::Instance();
    Handle(AIS_Shape) shape = new AIS_Shape(loft);
    shape->SetMaterial(Graphic3d_NOM_METALIZED);
    shape->SetColor(color);
    shape->SetOwnDeviationCoefficient(settings.tesselationAccuracy());
    myContext->Display(shape, Standard_True);

    if (settings.enumerateFaces()) {
        TopTools_IndexedMapOfShape shapeMap;
        TopExp::MapShapes(loft, TopAbs_FACE, shapeMap);
        for (int i = 1; i <= shapeMap.Extent(); ++i) {
            const TopoDS_Face& face = TopoDS::Face(shapeMap(i));
            gp_Pnt p = GetCentralFacePoint(face);
            QString s = QString("%1").arg(i);
            displayPoint(p, s.toStdString().c_str(), false, 0., 0., 0., 10.);
        }
    }
}

// Displays a point on the screen
void TIGLViewerContext::displayPoint(const gp_Pnt& aPoint,
                                     const char* aText,
                                     Standard_Boolean UpdateViewer,
                                     Standard_Real anXoffset,
                                     Standard_Real anYoffset,
                                     Standard_Real aZoffset,
                                     Standard_Real TextScale)
{
    Handle(ISession_Point) aGraphicPoint = new ISession_Point(aPoint.X(), aPoint.Y(), aPoint.Z());
    myContext->Display(aGraphicPoint,UpdateViewer);
    Handle(ISession_Text) aGraphicText = new ISession_Text(aText, aPoint.X() + anXoffset,
                                                 aPoint.Y() + anYoffset,
                                                 aPoint.Z() + aZoffset);
    aGraphicText->SetScale(TextScale);
    myContext->Display(aGraphicText,UpdateViewer);
}

// convenience wrapper
void TIGLViewerContext::drawPoint(double x, double y, double z)
{
    displayPoint(gp_Pnt(x,y,z), "", Standard_True, 0,0,0, 1.0);
}

// Displays a vector on the screen
void TIGLViewerContext::displayVector(const gp_Pnt& aPoint,
                                      const gp_Vec& aVec,
                                      const char* aText,
                                      Standard_Boolean UpdateViewer,
                                      Standard_Real anXoffset,
                                      Standard_Real anYoffset,
                                      Standard_Real aZoffset,
                                      Standard_Real TextScale)
{
    Handle(ISession_Direction) aGraphicDirection = new ISession_Direction(aPoint, aVec);
    myContext->Display(aGraphicDirection,UpdateViewer);
    Handle(ISession_Text) aGraphicText = new ISession_Text(aText, aPoint.X() + anXoffset,
                                                 aPoint.Y() + anYoffset,
                                                 aPoint.Z() + aZoffset);
    aGraphicText->SetScale(TextScale);
    myContext->Display(aGraphicText,UpdateViewer);
}

// convenience wrapper
void TIGLViewerContext::drawVector(double x, double y, double z, double dirx, double diry, double dirz)
{
    displayVector(gp_Pnt(x,y,z), gp_Vec(dirx, diry, dirz), "", Standard_True, 0,0,0, 1.0);
}


text:
class ExtendedAttribute(object):
    """NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually."""

    def __init__(self):
        """
        Attributes:
          swaggerTypes (dict): The key is attribute name and the value is attribute type.
          attributeMap (dict): The key is attribute name and the value is json key in definition.
        """
        self.swaggerTypes = {
            'FieldId': 'str',
            'Value': 'str',
            'ValueGuid': 'str',
            'DurationFormat': 'TimeUnitType'

        }

        self.attributeMap = {
            'FieldId': 'FieldId','Value': 'Value','ValueGuid': 'ValueGuid','DurationFormat': 'DurationFormat'}

        self.FieldId = None # str
        self.Value = None # str
        self.ValueGuid = None # str
        self.DurationFormat = None # TimeUnitType


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ELEMENT_RARE_DATA_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ELEMENT_RARE_DATA_H_

#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/platform/heap/collection_support/heap_hash_set.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"

namespace blink {

class ElementSMILAnimations;
class SVGElementResourceClient;

class SVGElementRareData final : public GarbageCollected<SVGElementRareData> {
 public:
  SVGElementRareData()
      : corresponding_element_(nullptr),
        instances_updates_blocked_(false),
        needs_override_computed_style_update_(false),
        web_animated_attributes_dirty_(false) {}
  SVGElementRareData(const SVGElementRareData&) = delete;
  SVGElementRareData& operator=(const SVGElementRareData&) = delete;

  SVGElementSet& OutgoingReferences() { return outgoing_references_; }
  const SVGElementSet& OutgoingReferences() const {
    return outgoing_references_;
  }
  SVGElementSet& IncomingReferences() { return incoming_references_; }
  const SVGElementSet& IncomingReferences() const {
    return incoming_references_;
  }

  HeapHashSet<WeakMember<SVGElement>>& ElementInstances() {
    return element_instances_;
  }
  const HeapHashSet<WeakMember<SVGElement>>& ElementInstances() const {
    return element_instances_;
  }

  bool InstanceUpdatesBlocked() const { return instances_updates_blocked_; }
  void SetInstanceUpdatesBlocked(bool value) {
    instances_updates_blocked_ = value;
  }

  SVGElement* CorrespondingElement() const {
    return corresponding_element_.Get();
  }
  void SetCorrespondingElement(SVGElement* corresponding_element) {
    corresponding_element_ = corresponding_element;
  }

  void SetWebAnimatedAttributesDirty(bool dirty) {
    web_animated_attributes_dirty_ = dirty;
  }
  bool WebAnimatedAttributesDirty() const {
    return web_animated_attributes_dirty_;
  }

  HashSet<QualifiedName>& WebAnimatedAttributes() {
    return web_animated_attributes_;
  }

  ElementSMILAnimations* GetSMILAnimations() { return smil_animations_; }
  ElementSMILAnimations& EnsureSMILAnimations();

  MutableCSSPropertyValueSet* AnimatedSMILStyleProperties() const {
    return animated_smil_style_properties_.Get();
  }
  MutableCSSPropertyValueSet* EnsureAnimatedSMILStyleProperties();

  const ComputedStyle* OverrideComputedStyle(Element*, const ComputedStyle*);
  void ClearOverriddenComputedStyle();

  void SetNeedsOverrideComputedStyleUpdate() {
    needs_override_computed_style_update_ = true;
  }

  SVGElementResourceClient* GetSVGResourceClient() { return resource_client_; }
  SVGElementResourceClient& EnsureSVGResourceClient(SVGElement*);

  AffineTransform* AnimateMotionTransform();

  void Trace(Visitor*) const;

 private:
  SVGElementSet outgoing_references_;
  SVGElementSet incoming_references_;
  HeapHashSet<WeakMember<SVGElement>> element_instances_;
  Member<SVGElement> corresponding_element_;
  Member<SVGElementResourceClient> resource_client_;
  Member<ElementSMILAnimations> smil_animations_;
  bool instances_updates_blocked_ : 1;
  bool needs_override_computed_style_update_ : 1;
  bool web_animated_attributes_dirty_ : 1;
  HashSet<QualifiedName> web_animated_attributes_;
  Member<MutableCSSPropertyValueSet> animated_smil_style_properties_;
  scoped_refptr<ComputedStyle> override_computed_style_;
  // Used by <animateMotion>
  AffineTransform animate_motion_transform_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_ELEMENT_RARE_DATA_H_


text:
from __future__ import absolute_import

import six

from sentry.api.serializers import Serializer, register
from sentry.models import Environment, Rule

def _generate_rule_label(project, rule, data):
    from sentry.rules import rules

    rule_cls = rules.get(data['id'])
    if rule_cls is None:
        return

    rule_inst = rule_cls(project, data=data, rule=rule)
    return rule_inst.render_label()

@register(Rule)
class RuleSerializer(Serializer):
    def get_attrs(self, item_list, user, *args, **kwargs):
        environments = Environment.objects.in_bulk(
            filter(None, [i.environment_id for i in item_list]),
        )
        return {
            i: {
                'environment': environments.get(i.environment_id)
            } for i in item_list
        }

    def serialize(self, obj, attrs, user):
        environment = attrs['environment']
        d = {
            # XXX(dcramer): we currently serialize unsaved rule objects
            # as part of the rule editor
            'id':
            six.text_type(obj.id) if obj.id else None,
            'conditions': [
                dict(o.items() + [('name', _generate_rule_label(obj.project, obj, o))]) for o in obj.data.get('conditions', [])
            ],
            'actions': [
                dict(o.items() + [('name', _generate_rule_label(obj.project, obj, o))]) for o in obj.data.get('actions', [])
            ],
            'actionMatch':
            obj.data.get('action_match') or Rule.DEFAULT_ACTION_MATCH,
            'frequency':
            obj.data.get('frequency') or Rule.DEFAULT_FREQUENCY,
            'name':
            obj.label,
            'dateCreated':
            obj.date_added,
            'environment': environment.name if environment is not None else None,
        }
        return d


text:
using UnityEngine;

namespace Firebase.TestLab {
  /// <summary>
  /// Interface for Firebase Test Lab's Game Loops.
  /// </summary>
  public abstract class TestLabManager {

    public const int NO_SCENARIO_PRESENT = -1;

    public bool IsTestingScenario {
      get { return ScenarioNumber > NO_SCENARIO_PRESENT; }
    }

    public abstract int ScenarioNumber { get; }

    private bool isFinished = false;

    /// <summary>
    /// Use when the scenario is finished and the app can be closed. Safe to call multiple times.
    /// </summary>
    public void NotifyHarnessTestIsComplete() {
      // This function wraps the platform-specific logic to ensure it only gets called once.
      if (!isFinished) {
        OnFinishTest();
      }
      isFinished = true;
    }

    /// <summary>
    /// Informs the Game Loop runner that the test is finished, and that the testapp should be
    /// closed.
    /// </summary>
    protected abstract void OnFinishTest();

    public abstract void LogToResults(string s);

    /// <summary>
    /// Creates an appropriate implementation based on the environment. Will determine if FTL
    /// is being used and is supported by the current platform. If so, will return a
    /// platform-specific implementation. Otherwise, will return a dummy that can safely absorb
    /// API calls.
    /// </summary>
    public static TestLabManager Instantiate() {
      if (Application.platform == RuntimePlatform.Android) {
        return AndroidTestLabManager.Create();
      } else if (Application.platform == RuntimePlatform.IPhonePlayer) {
        return IOSTestLabManager.Create();
      } else if (IsDesktopPlatform(Application.platform)) {
        return DesktopTestLabManager.Create();
      } else {
        return new DummyTestLabManager();
      }
    }

    static bool IsDesktopPlatform(RuntimePlatform platform) {
      return platform == RuntimePlatform.OSXPlayer
        || platform == RuntimePlatform.WindowsPlayer
        || platform == RuntimePlatform.LinuxPlayer;
    }
  }
}


text:
using System;

namespace QuickGraph.Representations.Petri
{
	using QuickGraph.Concepts.Petri;

	public class AllwaysTrueConditionExpression : IConditionExpression
	{
		#region IConditionExpression Members

		public bool IsEnabled(QuickGraph.Concepts.Petri.Collections.ITokenCollection tokens)
		{
			return true;
		}

		#endregion
	}
}


text:
<?php

namespace Continuous\DeployAgent\Resource;

use League\Flysystem\Filesystem;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerAwareTrait;

/**
 * AbstractResource
 *
 * @package    Continuous\DeployAgent
 * @subpackage Resource
 * @license    http://opensource.org/licenses/Apache-2.0 Apache License, Version 2.0
 */
abstract class AbstractResource implements ResourceInterface, EventManagerAwareInterface
{
    use EventManagerAwareTrait;

    /**
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * @return Filesystem
     */
    public function getFilesystem()
    {
        return $this->filesystem;
    }

    /**
     * @param Filesystem $filesystem
     * @return AbstractResource
     */
    public function setFilesystem($filesystem)
    {
        $this->filesystem = $filesystem;
        return $this;
    }
}


text:
extern crate failure;
#[macro_use]
extern crate failure_derive;

mod parser;
mod tokenizer;

pub mod ast;
pub mod atoms;
pub mod traits;

pub use tokenizer::Tokenizer;
pub use parser::parse;


text:
<?php

abstract class AbstractController
{
    use Filter;
    use Http;
    use Messages;
    use Translation;
    use SecurityToken;

    /** @var View */
    protected $View;
    /** @var db */
    protected $db;

    public function __construct()
    {
        $this->View = View::getSingleton();
        $this->db = db::getSingleton();
    }

    protected function validate(FormValidation $FV) :bool
    {
        return $FV->validate();
    }

    protected function deleteIsAllowed()
    {
        return Config::configByPath(DbData::ALLOW_DELETE_KEY) === Config::CONFIG_VALUE_YES;
    }

    protected function hrefWebsite($data)
    {
        return href_website($data);
    }

    protected function hrefAdmin($data)
    {
        return href_admin($data);
    }

    protected function setCookie($name, $value, $expire, $path)
    {
        setCookie($name, $value, $expire, $path);
    }

    protected function isLoggedIn()
    {
        return User::isLoggedIn();
    }
}