text:
/* A D3 library to plot 2D charts that can be zoomed/panned.
 * This is a modified version based on
 * https://gist.github.com/stepheneb/1182434
 */
SimpleGraph = function(properties, obj) {
  this.obj = obj;
  this.chart = document.getElementById(properties.selector.slice(1));
  var cx = this.chart.clientWidth;
  var cy = properties.aspect_ratio ?
    this.chart.clientWidth / properties.aspect_ratio
    : this.chart.clientHeight;

  var xLimits = properties.x_attrs.domain ?
    properties.x_attrs.domain : [0.0, 30.0];
  this.invertX = properties.x_attrs.invert ?
    properties.x_attrs.invert : false;
  this.numXTicks = properties.x_attrs.num_ticks ?
    properties.x_attrs.num_ticks : 10;

  var yLimits = properties.y_attrs.domain ?
    properties.y_attrs.domain : [0.0, 10.0];
  this.invertY = properties.y_attrs.invert ?
    properties.y_attrs.invert : false;
  this.numYTicks = properties.y_attrs.num_ticks ?
    properties.y_attrs.num_ticks : 10;

  this.interactive = properties.interactive ? properties.interactive : false;

  var padding_scale_x = cx / 1000 + 1;
  var padding_scale_y = cy / 1000 + 1;
  var padding = {
    "top":    (properties.title  ? 30 : 5) * padding_scale_y,
    "right":  15 * padding_scale_x,
    "bottom": (properties.x_attrs.label ? 60 : 20) * padding_scale_y,
    "left":   (properties.y_attrs.label ? 54 : 36) * padding_scale_x
  };

  this.size = {
    "width":  cx - padding.left - padding.right,
    "height": cy - padding.top  - padding.bottom
  };

  // x-scale
  this.x = d3.scale.linear()
      .range([0, this.size.width])
      .nice();
  this.setXDomain(xLimits).nice();

  // drag x-axis logic
  this.downx = Math.NaN;

  // y-scale
  this.y = d3.scale.linear()
      .range([0, this.size.height])
      .nice();
  this.setYDomain(yLimits).nice();

  // drag y-axis logic
  this.downy = Math.NaN;

  this.dragged = this.selected = null;

  this.canvas = d3.select(this.chart).append("svg")
      .attr("width",  cx)
      .attr("height", cy)
      .append("g")
      .attr("transform", "translate(" + padding.left + "," + padding.top + ")");

  this.plot = this.canvas.append("rect")
      .attr("width", this.size.width)
      .attr("height", this.size.height)
      .style("fill", "#EEEEEE")
      .attr("pointer-events", "all");

  this.updateScale();

  this.grid = this.canvas.append("g")
      .attr("id", "grid")

  this.svg = this.canvas.append("svg")
      .attr("top", 0)
      .attr("left", 0)
      .attr("width", this.size.width)
      .attr("height", this.size.height)
      .attr("viewBox", "0 0 "+this.size.width+" "+this.size.height);
      // .attr("class", "line");

  // add Chart Title
  if (properties.title) {
    this.canvas.append("text")
        .attr("class", "axis")
        .text(properties.title)
        .attr("x", this.size.width/2)
        .attr("dy","-0.8em")
        .style("text-anchor","middle");
  }

  // Add the x-axis label
  if (properties.x_attrs.label) {
    this.canvas.append("text")
        .attr("class", "axis")
        .text(properties.x_attrs.label)
        .attr("x", this.size.width/2)
        .attr("y", this.size.height)
        .attr("dy","2.4em")
        .style("text-anchor","middle");
  }

  // add y-axis label
  if (properties.y_attrs.label) {
    this.canvas.append("g").append("text")
        .attr("class", "axis")
        .text(properties.y_attrs.label)
        .style("text-anchor","middle")
        // Place the ylabel right against the left border of the padding.
        .attr("transform","translate(" + (-padding.left + 20) + ", " +
              this.size.height/2+") rotate(-90)");
  }

  if (this.interactive) {
    var self = this;
    d3.select(this.chart)
        .on("mousemove.drag", self.mousemove())
        .on("touchmove.drag", self.mousemove())
        .on("mouseup.drag",   self.mouseup())
        .on("touchend.drag",  self.mouseup());
  }

  this.redraw()();
};

//
// SimpleGraph methods
//

SimpleGraph.prototype.setXDomain = function(limits) {
  return this.x.domain(this.invertX ? [limits[1], limits[0]] : limits);
}

SimpleGraph.prototype.setYDomain = function(limits) {
  // Our notion of "inverted" corresponds to d3's default ordering of the
  // bounds.
  return this.y.domain(this.invertY ? limits : [limits[1], limits[0]]);
}

SimpleGraph.prototype.getXLimits = function() {
  var domain = this.x.domain();
  return this.invertX ? [domain[1], domain[0]] : domain
}

SimpleGraph.prototype.getYLimits = function() {
  var domain = this.y.domain();
  return this.invertY ? domain : [domain[1], domain[0]]
}

SimpleGraph.prototype.updateScale = function() {
  if (this.interactive) {
    // Change the zooming scale accordingly.
    this.plot.call(d3.behavior.zoom().x(this.x).y(this.y)
                     .on("zoom", this.redraw()));
  }
};

SimpleGraph.prototype.update = function() {
  if (this.obj.refresh) {
    this.obj.refresh();
  }

  if (d3.event && d3.event.keyCode) {
    d3.event.preventDefault();
    d3.event.stopPropagation();
  }
}

SimpleGraph.prototype.mousemove = function() {
  var self = this;
  return function() {
    // p is where the mouse is in the canvas's coordinate.
    // Note p[1] is 0 at the top of the canvas and largest at the bottom.
    var p = d3.mouse(self.canvas[0][0]),
        t = d3.event.changedTouches;
    if (self.dragged) {
      self.dragged.y = self.y.invert(Math.max(0, Math.min(self.size.height, p[1])));
      self.update();
    };
    // downx is the position of the mousedown event along the X axis.
    if (!isNaN(self.downx)) {
      d3.select(self.chart).style("cursor", "ew-resize");
      // rupx is the position of the mouse in the X axis coordination.
      var rupx = self.x.invert(p[0]),
          x_limits = self.getXLimits(),
          xaxis1 = x_limits[0],
          xaxis2 = x_limits[1],
          xextent = xaxis2 - xaxis1;
      if (rupx != 0) {
        var changex, new_limits;
        changex = (self.downx - xaxis1) / (rupx - xaxis1);
        new_limits = [xaxis1, xaxis1 + (xextent * changex)];
        self.setXDomain(new_limits)
        self.redraw()();
        self.updateScale();
      }
      d3.event.preventDefault();
      d3.event.stopPropagation();
    };
    // downy is the position of the mousedown event along the Y axis.
    if (!isNaN(self.downy)) {
      d3.select(self.chart).style("cursor", "ns-resize");
      // rupy is the position of the mouse in the Y axis coordination.
      var rupy = self.y.invert(p[1]),
          y_limits = self.getYLimits(),
          yaxis1 = y_limits[0],
          yaxis2 = y_limits[1],
          yextent = yaxis2 - yaxis1;
      if (rupy != 0) {
        var changey, new_limits;
        changey = (self.downy - yaxis1) / (rupy - yaxis1);
        new_limits = [yaxis1, yaxis1 + (yextent * changey)];
        self.setYDomain(new_limits);
        self.redraw()();
        self.updateScale();
      }
      d3.event.preventDefault();
      d3.event.stopPropagation();
    }
  }
};

SimpleGraph.prototype.mouseup = function() {
  var self = this;
  return function() {
    document.onselectstart = function() { return true; };
    d3.select(self.chart).style("cursor", "auto");
    d3.select(self.chart).style("cursor", "auto");
    if (!isNaN(self.downx)) {
      self.redraw()();
      self.downx = Math.NaN;
      d3.event.preventDefault();
      d3.event.stopPropagation();
    };
    if (!isNaN(self.downy)) {
      self.redraw()();
      self.downy = Math.NaN;
      d3.event.preventDefault();
      d3.event.stopPropagation();
    }
    if (self.dragged) {
      self.dragged = null
    }
  }
}

SimpleGraph.prototype.redraw = function() {
  var self = this;
  return function() {
    var tx = function(d) {
      return "translate(" + self.x(d) + ",0)";
    },
    ty = function(d) {
      return "translate(0," + self.y(d) + ")";
    },
    stroke = function(d) {
      return d ? "#ccc" : "#666";
    },
    fx = self.x.tickFormat(self.numXTicks),
    fy = self.y.tickFormat(self.numYTicks);

    // Regenerate x-ticks…
    var gx = self.grid.selectAll("g.x")
        .data(self.x.ticks(self.numXTicks), String)
        .attr("transform", tx);

    gx.select("text")
        .text(fx);

    var gxe = gx.enter().insert("g", "a")
        .attr("class", "x")
        .attr("transform", tx);

    gxe.append("line")
        .attr("stroke", stroke)
        .attr("y1", 0)
        .attr("y2", self.size.height);

    var x_text = gxe.append("text")
        .attr("class", "axis")
        .attr("y", self.size.height)
        .attr("dy", "1em")
        .attr("text-anchor", "middle")
        .text(fx)
        .style("cursor", "ew-resize");

    if (self.interactive) {
      x_text
        .on("mouseover", function(d) { d3.select(this).style("font-weight", "bold");})
        .on("mouseout",  function(d) { d3.select(this).style("font-weight", "normal");})
        .on("mousedown.drag",  self.xaxis_drag())
        .on("touchstart.drag", self.xaxis_drag());
    }

    gx.exit().remove();

    // Regenerate y-ticks…
    var gy = self.grid.selectAll("g.y")
        .data(self.y.ticks(self.numYTicks), String)
        .attr("transform", ty);

    gy.select("text")
        .text(fy);

    var gye = gy.enter().insert("g", "a")
        .attr("class", "y")
        .attr("transform", ty)
        .attr("background-fill", "#FFEEB6");

    gye.append("line")
        .attr("stroke", stroke)
        .attr("x1", 0)
        .attr("x2", self.size.width);

    var y_text = gye.append("text")
        .attr("class", "axis")
        .attr("x", -3)
        .attr("dy", ".35em")
        .attr("text-anchor", "end")
        .text(fy)
        .style("cursor", "ns-resize");

    if (self.interactive) {
      y_text
        .on("mouseover", function(d) { d3.select(this).style("font-weight", "bold");})
        .on("mouseout",  function(d) { d3.select(this).style("font-weight", "normal");})
        .on("mousedown.drag",  self.yaxis_drag())
        .on("touchstart.drag", self.yaxis_drag());
    }

    gy.exit().remove();
    self.updateScale();
    self.update();
  }
}

SimpleGraph.prototype.xaxis_drag = function() {
  var self = this;
  return function(d) {
    document.onselectstart = function() { return false; };
    var p = d3.mouse(self.canvas[0][0]);
    self.downx = self.x.invert(p[0]);
  }
};

SimpleGraph.prototype.yaxis_drag = function(d) {
  var self = this;
  return function(d) {
    document.onselectstart = function() { return false; };
    var p = d3.mouse(self.canvas[0][0]);
    self.downy = self.y.invert(p[1]);
  }
};

function getAxisScale(scale, range) {
  if (scale == 'time') {
    return d3.time.scale().range(range);
  } else if (scale == 'linear') {
    return d3.scale.linear().nice().range(range).nice();
  } else if (scale == 'log') {
    return d3.scale.log().range(range);
  }
}


text:
package com.guye.orm.impl;

import java.lang.reflect.Type;

import com.guye.orm.LinkField;

public abstract class TemplateLinkField<T,S> implements LinkField{

    public String name;
    public Class<?> clazz;
    public int type;
    public RecordAdapter<?> ra;
    public Class<?> targetType;

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Type getType() {
        return getTypeClass();
    }

    @Override
    public Class<?> getTypeClass() {
        return clazz;
    }

    @Override
    public int getLinkType() {
        return type;
    }

    @Override
    public RecordAdapter<?> getLinkedEntity() {
        return ra;
    }

    @Override
    public Class<?> getTargetType() {
        return targetType;
    }

}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from wtforms import Form
from wtforms import TextField
from wtforms import HiddenField

from ez2pay.i18n import LocalizerFactory

get_localizer = LocalizerFactory()

class FormFactory(object):

    def __init__(self, localizer):
        self.localizer = localizer
        _ = self.localizer
        self.required_msg = _(u'This field is required.')

    def make_payment_form(self):
        _ = self.localizer

        class PaymentForm(Form):
            first_name = TextField(_('First name'), [
            ])
            last_name = TextField(_('Last name'), [
            ])
            card_number = TextField(_('Card number'), [
            ])
            expire_year = TextField(_('Expire Year (e.g. 2013)'), [
            ])
            expire_month = TextField(_('Expire month (e.g. 10)'), [
            ])
            security_code = TextField(_('Security code'), [
            ])
            payment_uri = HiddenField(_(''), [
            ])
        return PaymentForm


text:
<?php

namespace Google\Service\Contentwarehouse;

class SecurityCredentialsYoutubeUserProto extends \Google\Model
{
  /**
   * @var string
   */
  public $youtubeUserId;

  /**
   * @param string
   */
  public function setYoutubeUserId($youtubeUserId)
  {
    $this->youtubeUserId = $youtubeUserId;
  }
  /**
   * @return string
   */
  public function getYoutubeUserId()
  {
    return $this->youtubeUserId;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SecurityCredentialsYoutubeUserProto::class, 'Google_Service_Contentwarehouse_SecurityCredentialsYoutubeUserProto');


text:
package cucumber.eclipse.editor.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import cucumber.eclipse.editor.nature.CucumberProjectNature;

public class AddNatureHandler extends AbstractHandler {

	public Object execute(ExecutionEvent event) throws ExecutionException {
	    Object selection = ((IStructuredSelection)
	            HandlerUtil.getCurrentSelection(event)).getFirstElement();

	    IProject project = (IProject) ((selection instanceof IAdaptable)
	            ? ((IAdaptable) selection).getAdapter(IProject.class) : null);

	    try {
	    	CucumberProjectNature cucumberProjectNature = new CucumberProjectNature();
	    	cucumberProjectNature.setProject(project);
	    	cucumberProjectNature.configure();

        } catch (CoreException e) {
            throw new ExecutionException("Error adding nature", e);
        }

		return null;
	}

}


text:
import { Architect } from '@angular-devkit/architect';
import { logging } from '@angular-devkit/core';
import { createArchitect, host } from '../utils';

describe('Browser Builder bundle budgets', () => {
  const targetSpec = { project: 'app', target: 'build' };
  let architect: Architect;

  beforeEach(async () => {
    await host.initialize().toPromise();
    architect = (await createArchitect(host.root())).architect;
  });
  afterEach(async () => host.restore().toPromise());

  it('accepts valid bundles', async () => {
    const overrides = {
      optimization: true,
      budgets: [{ type: 'allScript', maximumError: '100mb' }],
    };
    const logger = new logging.Logger('');
    const logs: string[] = [];
    logger.subscribe(e => logs.push(e.message));

    const run = await architect.scheduleTarget(targetSpec, overrides, { logger });
    const output = await run.result;
    expect(output.success).toBe(true);
    expect(logs.join()).not.toContain('WARNING');
    await run.stop();
  });

  it('shows errors', async () => {
    const overrides = {
      optimization: true,
      budgets: [{ type: 'all', maximumError: '100b' }],
    };

    const run = await architect.scheduleTarget(targetSpec, overrides);
    const output = await run.result;
    expect(output.success).toBe(false);
    await run.stop();
  });

  it('shows warnings', async () => {
    const overrides = {
      optimization: true,
      budgets: [{ type: 'all', minimumWarning: '100mb' }],
    };
    const logger = new logging.Logger('');
    const logs: string[] = [];
    logger.subscribe(e => logs.push(e.message));

    const run = await architect.scheduleTarget(targetSpec, overrides, { logger });
    const output = await run.result;
    expect(output.success).toBe(true);
    expect(logs.join()).toContain('WARNING');
    await run.stop();
  });

  it(`shows warnings for large component css when using 'anyComponentStyle' when AOT`, async () => {
    const overrides = {
      aot: true,
      optimization: true,
      budgets: [{ type: 'anyComponentStyle', maximumWarning: '1b' }],
    };

    const cssContent = `
      .foo { color: white; padding: 1px; }
      .buz { color: white; padding: 2px; }
      .bar { color: white; padding: 3px; }
    `;

    host.writeMultipleFiles({
      'src/app/app.component.css': cssContent,
      'src/assets/foo.css': cssContent,
      'src/styles.css': cssContent,
    });

    const logger = new logging.Logger('');
    const logs: string[] = [];
    logger.subscribe(e => logs.push(e.message));

    const run = await architect.scheduleTarget(targetSpec, overrides, { logger });
    const output = await run.result;
    expect(output.success).toBe(true);
    expect(logs.length).toBe(2);
    expect(logs.join()).toMatch(/WARNING.+app\.component\.css/);
    await run.stop();
  });

  it(`shows error for large component css when using 'anyComponentStyle' when AOT`, async () => {
    const overrides = {
      aot: true,
      optimization: true,
      budgets: [{ type: 'anyComponentStyle', maximumError: '1b' }],
    };

    const cssContent = `
      .foo { color: white; padding: 1px; }
      .buz { color: white; padding: 2px; }
      .bar { color: white; padding: 3px; }
    `;

    host.writeMultipleFiles({
      'src/app/app.component.css': cssContent,
      'src/assets/foo.css': cssContent,
      'src/styles.css': cssContent,
    });

    const logger = new logging.Logger('');
    const logs: string[] = [];
    logger.subscribe(e => logs.push(e.message));

    const run = await architect.scheduleTarget(targetSpec, overrides, { logger });
    const output = await run.result;
    expect(output.success).toBe(false);
    expect(logs.length).toBe(2);
    expect(logs.join()).toMatch(/ERROR.+app\.component\.css/);
    await run.stop();
  });

  describe(`should ignore '.map' files`, () => {
    it(`when 'bundle' budget`, async () => {
      const overrides = {
        optimization: true,
        extractLicenses: true,
        budgets: [{ type: 'bundle', name: 'main', maximumError: '3Kb' }],
      };

      const run = await architect.scheduleTarget(targetSpec, overrides);
      const output = await run.result;
      expect(output.success).toBe(true);
      await run.stop();
    });

    it(`when 'intial' budget`, async () => {
      const overrides = {
        optimization: true,
        budgets: [{ type: 'initial', maximumError: '1mb' }],
      };

      const run = await architect.scheduleTarget(targetSpec, overrides);
      const output = await run.result;
      expect(output.success).toBe(true);
      await run.stop();
    });

    it(`when 'all' budget`, async () => {
      const overrides = {
        optimization: true,
        budgets: [{ type: 'all', maximumError: '1mb' }],
      };

      const run = await architect.scheduleTarget(targetSpec, overrides);
      const output = await run.result;
      expect(output.success).toBe(true);
      await run.stop();
    });

    it(`when 'any' budget`, async () => {
      const overrides = {
        optimization: true,
        budgets: [{ type: 'any', maximumError: '1mb' }],
      };

      const run = await architect.scheduleTarget(targetSpec, overrides);
      const output = await run.result;
      expect(output.success).toBe(true);
      await run.stop();
    });
  });
});


text:
ALTER TABLE test_table_1 RENAME TO _test_table_1_old;

CREATE TABLE test_table_1 (
    id TEXT NOT NULL PRIMARY KEY,
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);

INSERT INTO test_table_1 (id, updated_at, created_at)
    SELECT org_id, updated_at, created_at
    FROM _test_table_1_old;

DROP TABLE _test_table_1_old;


text:
from .dataset import *
# from .coco import *
from .balloon import *
# from .voc import *


text:
<!DOCTYPE html>

	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<title>jQuery Waypoints Sticky Shortcut</title>
	<meta name="description" content="A jQuery Waypoints shortcut extension for easier sticky elements">
	<meta name="viewport" content="width=480">

	<link href='http://fonts.googleapis.com/css?family=Ubuntu+Mono|Lato:400,700|PT+Serif:700' rel='stylesheet' type='text/css'>

jQuery Waypoints

Sticky Elements

First include the shortcut script.

<script src="/path/to/waypoints-sticky.min.js"></script>

The Sticky Elements shortcut is used to make elements "stick" to the top of the page when the user scrolls past. It packages a few best practices around this pattern into one simple function extension of jQuery Waypoints. The most basic usage looks like this:

$('.my-sticky-element').waypoint('sticky');

What This Shortcut Does

Creates a wrapper around the element. This wrapper is what actually becomes the waypoint. It remains statically positioned in your document, acting as a placeholder while the sticky element is free to gain and lose fixed positioning.

Sets that wrapper’s height. When your sticky element gains fixed positioning it will no longer have an effect on the document flow. By giving the static wrapper the same height as the sticky element, we avoid any sudden "jumps" that come with shifting content.

Adds a class to the sticky element when the user reaches it. By default, when the element reaches the top of the viewport it gains the stuck class.

What This Shortcut Does Not

Give stuck elements fixed positioning. It is left to you, the author, to give the stuck elements fixed positioning in CSS. With so many design possibilities, the script cannot make any assumptions about how the sticky element should look. The shortcut only goes as far as to add the class to give you a hook for this styling.

Adjust for the wrapper. Besides height, other CSS properties on your sticky element may effect the layout of surrounding content. Margins are one example. You should move any of these styles off of your sticky element and onto the wrapper so that they will persist during the "stuck" state.

The "sticky" waypoint method may also be passed an options object. This options object can be used to override the class name of the "stuck" state and the HTML of the wrapper element. Here are the defaults:

$('.my-sticky-element').waypoint('sticky', {
  wrapper: '<div class="sticky-wrapper" />',
  stuckClass: 'stuck'
});

This options object is just an extension of the regular Waypoints options object, so you can pass along any traditional options you may want. A common one is the offset option.

$('.my-sticky-element').waypoint('sticky', {
  offset: 30 // Apply "stuck" when element 30px from top
});


text:
package com.badlogic.gdx.physics.box2d.joints;

import com.badlogic.gdx.math.*;
import com.badlogic.gdx.physics.box2d.*;

public class RevoluteJointDef extends JointDef
{
    public boolean enableLimit;
    public boolean enableMotor;
    public final Vector2 localAnchorA;
    public final Vector2 localAnchorB;
    public float lowerAngle;
    public float maxMotorTorque;
    public float motorSpeed;
    public float referenceAngle;
    public float upperAngle;

    public RevoluteJointDef() {
        super();
        this.localAnchorA = new Vector2();
        this.localAnchorB = new Vector2();
        this.referenceAngle = 0.0f;
        this.enableLimit = false;
        this.lowerAngle = 0.0f;
        this.upperAngle = 0.0f;
        this.enableMotor = false;
        this.motorSpeed = 0.0f;
        this.maxMotorTorque = 0.0f;
        this.type = JointType.RevoluteJoint;
    }

    public void initialize(final Body bodyA, final Body bodyB, final Vector2 vector2) {
        this.bodyA = bodyA;
        this.bodyB = bodyB;
        this.localAnchorA.set(bodyA.getLocalPoint(vector2));
        this.localAnchorB.set(bodyB.getLocalPoint(vector2));
        this.referenceAngle = bodyB.getAngle() - bodyA.getAngle();
    }
}


text:
namespace v8 {
namespace internal {
namespace interpreter {

// List of supported intrisics, with upper case name, lower case name and
// expected number of arguments (-1 denoting argument count is variable).
#define INTRINSICS_LIST(V)                                           \
  V(AsyncFunctionAwaitCaught, async_function_await_caught, 2)        \
  V(AsyncFunctionAwaitUncaught, async_function_await_uncaught, 2)    \
  V(AsyncFunctionEnter, async_function_enter, 2)                     \
  V(AsyncFunctionReject, async_function_reject, 3)                   \
  V(AsyncFunctionResolve, async_function_resolve, 3)                 \
  V(AsyncGeneratorAwaitCaught, async_generator_await_caught, 2)      \
  V(AsyncGeneratorAwaitUncaught, async_generator_await_uncaught, 2)  \
  V(AsyncGeneratorReject, async_generator_reject, 2)                 \
  V(AsyncGeneratorResolve, async_generator_resolve, 3)               \
  V(AsyncGeneratorYield, async_generator_yield, 3)                   \
  V(CreateJSGeneratorObject, create_js_generator_object, 2)          \
  V(GeneratorGetResumeMode, generator_get_resume_mode, 1)            \
  V(GeneratorClose, generator_close, 1)                              \
  V(GetImportMetaObject, get_import_meta_object, 0)                  \
  V(Call, call, -1)                                                  \
  V(CopyDataProperties, copy_data_properties, 2)                     \
  V(CreateIterResultObject, create_iter_result_object, 2)            \
  V(CreateAsyncFromSyncIterator, create_async_from_sync_iterator, 1) \
  V(HasProperty, has_property, 2)                                    \
  V(IsArray, is_array, 1)                                            \
  V(IsJSReceiver, is_js_receiver, 1)                                 \
  V(IsSmi, is_smi, 1)                                                \
  V(ToStringRT, to_string, 1)                                        \
  V(ToLength, to_length, 1)                                          \
  V(ToObject, to_object, 1)

class IntrinsicsHelper {
 public:
  enum class IntrinsicId {
#define DECLARE_INTRINSIC_ID(name, lower_case, count) k##name,
    INTRINSICS_LIST(DECLARE_INTRINSIC_ID)
#undef DECLARE_INTRINSIC_ID
        kIdCount
  };
  STATIC_ASSERT(static_cast<uint32_t>(IntrinsicId::kIdCount) <= kMaxUInt8);

  V8_EXPORT_PRIVATE static bool IsSupported(Runtime::FunctionId function_id);
  static IntrinsicId FromRuntimeId(Runtime::FunctionId function_id);
  static Runtime::FunctionId ToRuntimeId(IntrinsicId intrinsic_id);

 private:
  DISALLOW_IMPLICIT_CONSTRUCTORS(IntrinsicsHelper);
};

}  // namespace interpreter
}  // namespace internal
}  // namespace v8

#endif  // V8_INTERPRETER_INTERPRETER_INTRINSICS_H_


text:
package nifi.apex.examples.logs.data;

import com.datatorrent.contrib.nifi.NiFiDataPacket;
import com.datatorrent.contrib.nifi.NiFiDataPacketBuilder;
import com.datatorrent.contrib.nifi.StandardNiFiDataPacket;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Produces a dictionary file for NiFi containing the log levels that should be
 * collected based on the rate of error and warn messages coming in.
 */
public class DictionaryBuilder implements NiFiDataPacketBuilder<LogLevels> {

    public static final String ERROR = "ERROR";
    public static final String WARN = "WARN";
    public static final String INFO = "INFO";
    public static final String DEBUG = "DEBUG";

    public static final String ERROR_WARN_TOTAL_ATTR = "error.warn.total";
    public static final String ERROR_WARN_RATE_ATTR = "error.warn.rate";
    public static final String WINDOW_MILLIS_ATTR = "window.size.millis";

    private final int windowSizeMillis;
    private final double minRatePerSecond;

    private DictionaryBuilder() {
        this.windowSizeMillis = 0;
        this.minRatePerSecond = 0;
    }

    /**
     * @param windowSizeMillis the windowSize in milliseconds that the LogLevels were computed over
     *
     * @param minRatePerSecond the rate of error and warn messages over the window that indicates not to
     *                              collect other levels, if the actual rate is less we can collect more
     */
    public DictionaryBuilder(final int windowSizeMillis, final double minRatePerSecond) {
        this.windowSizeMillis = windowSizeMillis;
        this.minRatePerSecond = minRatePerSecond;
    }

    @Override
    public NiFiDataPacket createNiFiDataPacket(LogLevels logLevels) {
        // get the total number of error and warn messages
        int totalWarnError = 0;
        totalWarnError += logLevels.get(ERROR);
        totalWarnError += logLevels.get(WARN);

        // calculate the number of ERROR/WARN messages per second
        double windowSizeSeconds = windowSizeMillis / 1000;
        double actualRate = ((double)totalWarnError) / windowSizeSeconds;

        // always collect ERROR/WARN messages
        StringBuilder builder = new StringBuilder();
        builder.append(ERROR).append("\n");
        builder.append(WARN).append("\n");

        // only collect INFO and DEBUG if ERROR/WARN is less than minimum rate
        if (actualRate < minRatePerSecond) {
            builder.append(INFO).append("\n");
            builder.append(DEBUG).append("\n");
        }

        // pass the rate, total, and window size as attributes
        Map<String,String> attrs = new HashMap<>();
        attrs.put(ERROR_WARN_RATE_ATTR, String.valueOf(actualRate));
        attrs.put(ERROR_WARN_TOTAL_ATTR, String.valueOf(totalWarnError));
        attrs.put(WINDOW_MILLIS_ATTR, String.valueOf(windowSizeMillis));

        byte[] content = builder.toString().getBytes(StandardCharsets.UTF_8);
        return new StandardNiFiDataPacket(content, attrs);
    }

}


text:
'use strict';

import React from 'react';
import ReactNative, { StyleSheet, Dimensions } from 'react-native';
import RGFColors from './RGFColors';

export function Text({ style, ...props }: Object): ReactElement {
  return <ReactNative.Text style={[styles.font, style]} {...props} />;
}

export function NumText({ style, ...props }: Object): ReactElement {
  return <ReactNative.Text style={[styles.numFont, style]} {...props} />;
}

export function Heading1({ style, ...props }: Object): ReactElement {
  return (
    <ReactNative.Text style={[styles.font, styles.h1, style]} {...props} />
  );
}

export function Paragraph({ style, ...props }: Object): ReactElement {
  return <ReactNative.Text style={[styles.font, styles.p, style]} {...props} />;
}

export function numberWithCommas(str) {
  if (str === undefined || str === '') {
    return '';
  }
  // TODO: Experiment
  // for (var i = 0; i < 10; i++) {
  //   x = x.replace(convertToPersian[i], i);
  // }
  let parts = str.toString().split('.');
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return parts.join('.');
}

export function parseNumberWithCommas(str) {
  str = str.replace(/,/g, '');
  let pattern = /^\d+$/;
  if (!pattern.test(str)) {
    console.error('Error: parseNumberWithCommas', str);
    return '';
  }

  str = parseInt(str, 10);
  return str;
}

const scale = Dimensions.get('window').width / 375;

function normalize(size: number): number {
  return Math.round(scale * size);
}

const styles = StyleSheet.create({
  font: {
    // fontFamily: require('../env').textFont,
  },
  numFont: {
    // fontFamily: require('../env').digitFont,
  },
  h1: {
    fontSize: normalize(24),
    lineHeight: normalize(27),
    color: RGFColors.darkText,
    fontWeight: 'bold',
    letterSpacing: -1,
  },
  p: {
    fontSize: normalize(15),
    lineHeight: normalize(23),
    color: RGFColors.lightText,
  },
});


text:
<?php

namespace Drupal\slick_ui\Form;

use Drupal\Core\Url;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Builds the form to delete a Slick optionset.
 */
class SlickDeleteForm extends EntityConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to delete the Slick optionset %label?', ['%label' => $this->entity->label()]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('entity.slick.collection');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this->t('Delete');
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->entity->delete();

    drupal_set_message($this->t('The Slick optionset %label has been deleted.', ['%label' => $this->entity->label()]));
    $this->logger('user')->notice('Deleted optionset %oid (%label)', ['%oid' => $this->entity->id(), '%label' => $this->entity->label()]);

    $form_state->setRedirectUrl($this->getCancelUrl());
  }

}


text:
<?xml version="1.0"?>
<GetLowestPricedOffersForASINResponse
    xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
    <GetLowestPricedOffersForASINResult MarketplaceID="ATVPDKIKX0DER" ItemCondition="New"
        ASIN="B000EVPGSQ" status="NoBuyableOffers">
        <Identifier>
            <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
            <ASIN>B000EVPGSQ</ASIN>
            <ItemCondition>New</ItemCondition>
        </Identifier>
        <Summary>
            <TotalOfferCount>0</TotalOfferCount>
        </Summary>
        <Offers/>
    </GetLowestPricedOffersForASINResult>
    <ResponseMetadata>
        <RequestId>2bb867cd-8fa3-406c-adba-eb84c1796d21</RequestId>
    </ResponseMetadata>
</GetLowestPricedOffersForASINResponse>


text:
package fromjava.nosei_rpclit_apt.server;

public class Fault2 extends Exception {

    int age;

    public Fault2 (String message, int age) {
	  super(message);
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}


text:
This repository comes as a solution to the missing Sitefinity fuctionality to control the revision history of pages

## Revision History Sample

Users want to be able to apply revision history settings and set a number of revisions that should be stored.
This sample configures the revision history of pages with two options:

- by number of versions to keep
- by time (not older than X days)

### License information

This project has been released under the Apache License, version 2.0, the text of which is included in the repository.

### Requirements

* Sitefinity license
* .NET Framework 4
* Visual Studio 2012
* Microsoft SQL Server 2008R2 or later versions

### Video demo:

[![Revision history settings for pages in Sitefinity](http://content.screencast.com/users/Veronica_Mil/folders/Jing/media/c4aac438-3df3-4061-a1d7-0931289d08cf/2015-02-27_1618.png)](http://screencast.com/t/J0fcNJuAsUiL)

### Additional resources:

For more detailed explanation on the code see:
[My personal blog - Sitefinity tips and tricks](http://www.sitefinitytipsandtricks.net/2015/02/27/revision-history-settings/)


text:
require "rails_helper"

describe Types::EveBlueprintInventionMaterialType do
end


text:
{% extends layout_template_name %}
{% block styles_head %}
	{{ parent() }}
	<link href="//cdn.datatables.net/plug-ins/3cfcc339e89/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
	<link href="/{{ core_type }}/lib/javascripts/DataTables-extended/css/bootstrap_datatables.css" rel="stylesheet" type="text/css" />
	<link href="//cdnjs.cloudflare.com/ajax/libs/sweetalert/0.3.2/sweet-alert.min.css" rel="stylesheet" type="text/css">
{% endblock %}
{% block content %}
  {% if flash.message %}

{{ flash.message }}

  {% endif %}

      Manage
      Name
      Group
      Active

{% endblock %}
{% block js_bottom %}
	{{ parent() }}

{% endblock %}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('checkout', '0003_auto_20170906_0556'),
    ]

    replaces = [
        ('cart', '0004_auto_20171129_1004'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='cart',
            options={'ordering': ('-last_status_change',)},
        ),
        migrations.AlterModelOptions(
            name='cartline',
            options={},
        ),
    ]


text:
    #pragma hdrstop
#endif

#ifndef  WX_PRECOMP
  #include "wx/wx.h"
#endif //precompiled headers

#include "wx/log.h"
#include "wx/config.h"

#ifndef wxHAS_IMAGES_IN_RESOURCES
    #include "../sample.xpm"
#endif

// ----------------------------------------------------------------------------
// classes
// ----------------------------------------------------------------------------

class MyApp: public wxApp
{
public:
  // implement base class virtuals
  virtual bool OnInit() wxOVERRIDE;
  virtual int OnExit() wxOVERRIDE;
};

class MyFrame: public wxFrame
{
public:
    MyFrame();
    virtual ~MyFrame();

    // callbacks
    void OnQuit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
    void OnDelete(wxCommandEvent& event);

private:
    wxTextCtrl *m_text;
    wxCheckBox *m_check;

    wxDECLARE_EVENT_TABLE();
};

// ----------------------------------------------------------------------------
// event tables
// ----------------------------------------------------------------------------

wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
  EVT_MENU(wxID_EXIT, MyFrame::OnQuit)
  EVT_MENU(wxID_ABOUT, MyFrame::OnAbout)
  EVT_MENU(wxID_DELETE, MyFrame::OnDelete)
wxEND_EVENT_TABLE()

// ============================================================================
// implementation
// ============================================================================

// ----------------------------------------------------------------------------
// application
// ----------------------------------------------------------------------------

wxIMPLEMENT_APP(MyApp);

// `Main program' equivalent, creating windows and returning main app frame
bool MyApp::OnInit()
{
    if ( !wxApp::OnInit() )
        return false;

    // we're using wxConfig's "create-on-demand" feature: it will create the
    // config object when it's used for the first time. It has a number of
    // advantages compared with explicitly creating our wxConfig:
    //  1) we don't pay for it if we don't use it
    //  2) there is no danger to create it twice

    // application and vendor name are used by wxConfig to construct the name
    // of the config file/registry key and must be set before the first call
    // to Get() if you want to override the default values (the application
    // name is the name of the executable and the vendor name is the same)
    SetVendorName(wxT("wxWidgets"));
    SetAppName(wxT("conftest")); // not needed, it's the default value

    wxConfigBase *pConfig = wxConfigBase::Get();

    // uncomment this to force writing back of the defaults for all values
    // if they're not present in the config - this can give the user an idea
    // of all possible settings for this program
    pConfig->SetRecordDefaults();

    // or you could also write something like this:
    //  wxFileConfig *pConfig = new wxFileConfig("conftest");
    //  wxConfigBase::Set(pConfig);
    // where you can also specify the file names explicitly if you wish.
    // Of course, calling Set() is optional and you only must do it if
    // you want to later retrieve this pointer with Get().

    // create the main program window
    MyFrame *frame = new MyFrame;
    frame->Show(true);

    // use our config object...
    if ( pConfig->Read(wxT("/Controls/Check"), 1l) != 0 ) {
        wxMessageBox(wxT("You can disable this message box by unchecking\n")
                    wxT("the checkbox in the main window (of course, a real\n")
                    wxT("program would have a checkbox right here but we\n")
                    wxT("keep it simple)"), wxT("Welcome to wxConfig demo"),
                    wxICON_INFORMATION | wxOK);
    }

    return true;
}

int MyApp::OnExit()
{
    // clean up: Set() returns the active config object as Get() does, but unlike
    // Get() it doesn't try to create one if there is none (definitely not what
    // we want here!)
    delete wxConfigBase::Set((wxConfigBase *) NULL);

    return 0;
}

// ----------------------------------------------------------------------------
// frame
// ----------------------------------------------------------------------------

// main frame ctor
MyFrame::MyFrame()
       : wxFrame((wxFrame *) NULL, wxID_ANY, wxT("wxConfig Demo"))
{
    SetIcon(wxICON(sample));

    // menu
    wxMenu *file_menu = new wxMenu;

    file_menu->Append(wxID_DELETE, wxT("&Delete"), wxT("Delete config file"));
    file_menu->AppendSeparator();
    file_menu->Append(wxID_ABOUT, wxT("&About\tF1"), wxT("About this sample"));
    file_menu->AppendSeparator();
    file_menu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Exit the program"));
    wxMenuBar *menu_bar = new wxMenuBar;
    menu_bar->Append(file_menu, wxT("&File"));
    SetMenuBar(menu_bar);

#if wxUSE_STATUSBAR
    CreateStatusBar();
#endif // wxUSE_STATUSBAR

    // child controls
    wxPanel *panel = new wxPanel(this);
    wxStaticText* st = new wxStaticText(panel, wxID_ANY, wxT("These controls remember their values!"));
    m_text = new wxTextCtrl(panel, wxID_ANY);
    m_check = new wxCheckBox(panel, wxID_ANY, wxT("show welcome message box at startup"));

    // put everything in a sizer
    wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
    sizer->Add(st, wxSizerFlags().Border(wxLEFT|wxBOTTOM|wxTOP, 10));
    sizer->Add(m_text, wxSizerFlags().Border(wxLEFT|wxBOTTOM|wxRIGHT, 10).Expand());
    sizer->Add(m_check, wxSizerFlags().Border(wxLEFT, 10));
    panel->SetSizer(sizer);

    // restore the control's values from the config

    // NB: in this program, the config object is already created at this moment
    // because we had called Get() from MyApp::OnInit(). However, if you later
    // change the code and don't create it before this line, it won't break
    // anything - unlike if you manually create wxConfig object with Create()
    // or in any other way (then you must be sure to create it before using it!).
    wxConfigBase *pConfig = wxConfigBase::Get();

    // we could write Read("/Controls/Text") as well, it's just to show SetPath()
    pConfig->SetPath(wxT("/Controls"));

    m_text->SetValue(pConfig->Read(wxT("Text"), wxT("")));
    m_check->SetValue(pConfig->Read(wxT("Check"), 1l) != 0);

    // SetPath() understands ".."
    pConfig->SetPath(wxT("../MainFrame"));

    // restore frame position and size
    int x = pConfig->Read(wxT("x"), 50),
        y = pConfig->Read(wxT("y"), 50),
        w = pConfig->Read(wxT("w"), 350),
        h = pConfig->Read(wxT("h"), 200);
    Move(x, y);
    SetClientSize(w, h);

    pConfig->SetPath(wxT("/"));
    wxString s;
    if ( pConfig->Read(wxT("TestValue"), &s) )
    {
        wxLogStatus(this, wxT("TestValue from config is '%s'"), s.c_str());
    }
    else
    {
        wxLogStatus(this, wxT("TestValue not found in the config"));
    }
}

void MyFrame::OnQuit(wxCommandEvent&)
{
    Close(true);
}

void MyFrame::OnAbout(wxCommandEvent&)
{
    wxMessageBox(wxT("wxConfig demo\n(c) 1998-2001 Vadim Zeitlin"), wxT("About"),
                 wxICON_INFORMATION | wxOK);
}

void MyFrame::OnDelete(wxCommandEvent&)
{
    wxConfigBase *pConfig = wxConfigBase::Get();
    if ( pConfig == NULL )
    {
        wxLogError(wxT("No config to delete!"));
        return;
    }

    if ( pConfig->DeleteAll() )
    {
        wxLogMessage(wxT("Config file/registry key successfully deleted."));

        delete wxConfigBase::Set(NULL);
        wxConfigBase::DontCreateOnDemand();
    }
    else
    {
        wxLogError(wxT("Deleting config file/registry key failed."));
    }
}

MyFrame::~MyFrame()
{
    wxConfigBase *pConfig = wxConfigBase::Get();
    if ( pConfig == NULL )
        return;

    // save the control's values to the config
    pConfig->Write(wxT("/Controls/Text"), m_text->GetValue());
    pConfig->Write(wxT("/Controls/Check"), m_check->GetValue());

    // save the frame position
    int x, y, w, h;
    GetClientSize(&w, &h);
    GetPosition(&x, &y);
    pConfig->Write(wxT("/MainFrame/x"), (long) x);
    pConfig->Write(wxT("/MainFrame/y"), (long) y);
    pConfig->Write(wxT("/MainFrame/w"), (long) w);
    pConfig->Write(wxT("/MainFrame/h"), (long) h);

    pConfig->Write(wxT("/TestValue"), wxT("A test value"));
}


text:
<?php

namespace NilPortugues\SchemaOrg\Properties;

use NilPortugues\SchemaOrg\SchemaProperty;

/**
 * The International Standard of Industrial Classification of All Economic Activities (ISIC), Revision 4 code for a particular organization, business person, or place.
 */
class IsicV4Property extends SchemaProperty
{
    const SCHEMA_URL = 'http://schema.org/isicV4';
    const PROPERTY_NAME = 'isicV4';

    /**
     * A list of schemas allowed to use this property.
     *
     * @var array
     */
    protected static $allowedSchemas = [
        'http://schema.org/Organization',
        'http://schema.org/Place',
        'http://schema.org/Person',
    ];
}


text:
namespace specter {

Menu::Menu(ViewResources& res, View& parentView, IMenuNode* rootNode) : View(res, parentView) {
  commitResources(res, [&](boo::IGraphicsDataFactory::Context& ctx) -> bool {
    buildResources(ctx, res);
    m_vertsBinding.init(ctx, res, 8, m_viewVertBlockBuf);
    return true;
  });
  m_headText = std::make_unique<TextView>(res, *this, res.m_mainFont);
  m_scroll.m_view = std::make_unique<ScrollView>(res, *this, ScrollView::Style::ThinIndicator);
  m_content = std::make_unique<ContentView>(res, *this);
  m_scroll.m_view->setContentView(m_content.get());
  reset(rootNode);
}

Menu::~Menu() = default;

void Menu::reset(IMenuNode* rootNode) {
  m_rootNode = rootNode;
  m_thisNode = rootNode;
  ViewResources& res = rootView().viewRes();

  for (int i = 0; i < 8; ++i)
    m_verts[i].m_color = res.themeData().tooltipBackground();
  m_vertsBinding.load<decltype(m_verts)>(m_verts);

  m_subMenu.reset();

  const std::string* headText = rootNode->text();
  m_headText->typesetGlyphs(headText ? *headText : "", rootView().themeData().uiAltText());

  float pf = rootView().viewRes().pixelFactor();
  int itemAdv = (ROW_HEIGHT + ITEM_MARGIN * 2) * pf;
  m_cWidth = m_headText->nominalWidth() + 10 * pf;
  m_cHeight = headText ? itemAdv : 0;
  m_cTop = m_cHeight;

  size_t subCount = rootNode->subNodeCount();
  m_items.clear();
  if (subCount) {
    m_items.reserve(subCount);
    for (size_t i = 0; i < subCount; ++i) {
      IMenuNode* node = rootNode->subNode(i);
      const std::string* nodeText = node->text();
      ViewChild<std::unique_ptr<ItemView>>& item = m_items.emplace_back();

      if (nodeText != nullptr) {
        item.m_view = std::make_unique<ItemView>(res, *this, *nodeText, i, node);
        m_cWidth = std::max(m_cWidth, int(item.m_view->m_textView->nominalWidth() + 10 * pf));
      }

      m_cHeight += itemAdv;
    }
  }
}

Menu::Menu(ViewResources& res, View& parentView, IMenuNode* rootNode, IMenuNode* thisNode)
: View(res, parentView), m_rootNode(rootNode), m_thisNode(thisNode) {
  commitResources(res, [&](boo::IGraphicsDataFactory::Context& ctx) -> bool {
    buildResources(ctx, res);
    m_vertsBinding.init(ctx, res, 8, m_viewVertBlockBuf);
    return true;
  });
  m_headText = std::make_unique<TextView>(res, *this, res.m_mainFont);
  m_scroll.m_view = std::make_unique<ScrollView>(res, *this, ScrollView::Style::ThinIndicator);
  m_content = std::make_unique<ContentView>(res, *this);
  m_scroll.m_view->setContentView(m_content.get());
}

Menu::ContentView::ContentView(ViewResources& res, Menu& menu) : View(res, menu), m_menu(menu) {
  commitResources(res, [&](boo::IGraphicsDataFactory::Context& ctx) -> bool {
    buildResources(ctx, res);
    m_hlVertsBinding.init(ctx, res, 4, m_viewVertBlockBuf);
    return true;
  });

  m_hlVerts[0].m_color = res.themeData().button1Hover();
  m_hlVerts[1].m_color = res.themeData().button2Hover();
  m_hlVerts[2].m_color = res.themeData().button1Hover();
  m_hlVerts[3].m_color = res.themeData().button2Hover();
}

Menu::ItemView::ItemView(ViewResources& res, Menu& menu, std::string_view text, size_t idx, IMenuNode* node)
: View(res, menu), m_menu(menu), m_idx(idx), m_node(node) {
  commitResources(res, [&](boo::IGraphicsDataFactory::Context& ctx) -> bool {
    buildResources(ctx, res);
    return true;
  });
  m_textView = std::make_unique<TextView>(res, *this, res.m_mainFont);
  m_textView->typesetGlyphs(text, res.themeData().uiText());
}

void Menu::setVerts(int width, int height, float pf) {
  m_verts[0].m_pos.assign(0, height - m_cTop - pf, 0);
  m_verts[1].m_pos.assign(0, 0, 0);
  m_verts[2].m_pos.assign(width, height - m_cTop - pf, 0);
  m_verts[3].m_pos.assign(width, 0, 0);

  m_verts[4].m_pos.assign(0, height, 0);
  m_verts[5].m_pos.assign(0, height - m_cTop + pf, 0);
  m_verts[6].m_pos.assign(width, height, 0);
  m_verts[7].m_pos.assign(width, height - m_cTop + pf, 0);

  m_vertsBinding.load<decltype(m_verts)>(m_verts);
}

void Menu::ContentView::setHighlightedItem(size_t idx) {
  if (idx == SIZE_MAX) {
    m_highlightedItem = SIZE_MAX;
    return;
  }
  ViewChild<std::unique_ptr<ItemView>>& vc = m_menu.m_items[idx];

  if (!vc.m_view) {
    m_highlightedItem = SIZE_MAX;
    return;
  }

  m_highlightedItem = idx;
  const boo::SWindowRect& bgRect = subRect();
  const boo::SWindowRect& itemRect = vc.m_view->subRect();
  int y = itemRect.location[1] - bgRect.location[1];

  m_hlVerts[0].m_pos.assign(0, y + itemRect.size[1], 0);
  m_hlVerts[1].m_pos.assign(0, y, 0);
  m_hlVerts[2].m_pos.assign(itemRect.size[0], y + itemRect.size[1], 0);
  m_hlVerts[3].m_pos.assign(itemRect.size[0], y, 0);

  m_hlVertsBinding.load<decltype(m_hlVerts)>(m_hlVerts);
}

void Menu::mouseDown(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) {
  m_scroll.mouseDown(coord, button, mod);
}

void Menu::ContentView::mouseDown(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) {
  for (ViewChild<std::unique_ptr<ItemView>>& v : m_menu.m_items)
    v.mouseDown(coord, button, mod);
}

void Menu::ItemView::mouseDown(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) {}

void Menu::mouseUp(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) {
  m_scroll.mouseUp(coord, button, mod);
  if (m_deferredActivation) {
    IMenuNode* node = m_deferredActivation;
    m_deferredActivation = nullptr;
    node->activated(coord);
  }
}

void Menu::ContentView::mouseUp(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) {
  for (ViewChild<std::unique_ptr<ItemView>>& v : m_menu.m_items)
    v.mouseUp(coord, button, mod);
}

void Menu::ItemView::mouseUp(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) {
  if (m_menu.m_content->m_highlightedItem == m_idx)
    m_menu.m_deferredActivation = m_node;
}

void Menu::mouseMove(const boo::SWindowCoord& coord) { m_scroll.mouseMove(coord); }

void Menu::ContentView::mouseMove(const boo::SWindowCoord& coord) {
  for (ViewChild<std::unique_ptr<ItemView>>& v : m_menu.m_items)
    v.mouseMove(coord);
}

void Menu::ItemView::mouseEnter(const boo::SWindowCoord& coord) { m_menu.m_content->setHighlightedItem(m_idx); }

void Menu::mouseLeave(const boo::SWindowCoord& coord) { m_scroll.mouseLeave(coord); }

void Menu::ContentView::mouseLeave(const boo::SWindowCoord& coord) {
  for (ViewChild<std::unique_ptr<ItemView>>& v : m_menu.m_items)
    v.mouseLeave(coord);
}

void Menu::ItemView::mouseLeave(const boo::SWindowCoord& coord) { m_menu.m_content->unsetHighlightedItem(m_idx); }

void Menu::scroll(const boo::SWindowCoord& coord, const boo::SScrollDelta& scroll) { m_scroll.scroll(coord, scroll); }

void Menu::think() { m_scroll.m_view->think(); }

void Menu::resized(const boo::SWindowRect& root, const boo::SWindowRect& sub) {
  float pf = rootView().viewRes().pixelFactor();
  boo::SWindowRect rect = sub;
  rect.size[0] = m_cWidth;
  if (rect.location[1] - m_cHeight < 0) {
    rect.location[1] += ROW_HEIGHT * pf;
    rect.size[1] = std::min(root.size[1] - rect.location[1], m_cHeight);
  } else {
    rect.location[1] -= m_cHeight;
    rect.size[1] = m_cHeight;
  }

  View::resized(root, rect);
  m_scroll.m_view->resized(root, rect);
  setVerts(rect.size[0], rect.size[1], pf);

  rect.location[0] += 5 * pf;
  rect.location[1] += rect.size[1] - (ROW_HEIGHT + ITEM_MARGIN - 5) * pf;
  rect.size[0] = m_headText->nominalWidth();
  rect.size[1] = m_headText->nominalHeight();
  m_headText->resized(root, rect);
}

void Menu::ContentView::resized(const boo::SWindowRect& root, const boo::SWindowRect& sub,
                                const boo::SWindowRect& scissor) {
  View::resized(root, sub);
  float pf = rootView().viewRes().pixelFactor();
  m_scissorRect = scissor;
  boo::SWindowRect itemRect = sub;
  itemRect.size[0] = m_menu.m_cWidth;
  itemRect.size[1] = ROW_HEIGHT * pf;
  itemRect.location[1] += sub.size[1] - m_menu.m_cTop + ITEM_MARGIN * pf;
  int itemAdv = (ROW_HEIGHT + ITEM_MARGIN * 2) * pf;
  for (ViewChild<std::unique_ptr<ItemView>>& c : m_menu.m_items) {
    itemRect.location[1] -= itemAdv;
    if (c.m_view)
      c.m_view->resized(root, itemRect);
  }
}

void Menu::ItemView::resized(const boo::SWindowRect& root, const boo::SWindowRect& sub) {
  View::resized(root, sub);
  float pf = rootView().viewRes().pixelFactor();
  boo::SWindowRect textRect = sub;
  textRect.location[0] += 5 * pf;
  textRect.location[1] += 5 * pf;
  m_textView->resized(root, textRect);
}

void Menu::draw(boo::IGraphicsCommandQueue* gfxQ) {
  View::draw(gfxQ);
  gfxQ->setShaderDataBinding(m_vertsBinding);
  gfxQ->draw(0, 4);
  m_scroll.m_view->draw(gfxQ);
  gfxQ->setShaderDataBinding(m_vertsBinding);
  gfxQ->draw(4, 4);
  m_headText->draw(gfxQ);
}

void Menu::ContentView::draw(boo::IGraphicsCommandQueue* gfxQ) {
  View::draw(gfxQ);
  gfxQ->setScissor(m_scissorRect);
  if (m_highlightedItem != SIZE_MAX) {
    gfxQ->setShaderDataBinding(m_hlVertsBinding);
    gfxQ->draw(0, 4);
  }
  for (ViewChild<std::unique_ptr<ItemView>>& c : m_menu.m_items)
    if (c.m_view)
      c.m_view->draw(gfxQ);
  gfxQ->setScissor(rootView().subRect());
}

void Menu::ItemView::draw(boo::IGraphicsCommandQueue* gfxQ) {
  View::draw(gfxQ);
  m_textView->draw(gfxQ);
}

} // namespace specter


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Model_noticia extends CI_Model {

  function __construct() {
    parent::__construct();
    $this->load->database();
    $this->load->helper('date');
  }

  function insertNoticia($titulo, $texto, $imagen){

    $text = stripslashes(nl2br($texto));

    if($this->session->userdata('usuario')){
      $data = array(
        'titulo' => $titulo,
        'texto' => $text,
        'fecha' => standard_date('DATE_W3C', now()),
        'autor' => $this->session->userdata('usuario'),
        'imagen' => $imagen
      );
      return $this->db->insert('noticia', $data);
    }else{
      $data = array(
        'titulo' => $titulo,
        'texto' => $texto,
        'fecha' => standard_date('DATE_W3C', now()),
        'autor' => 'Anonimo',
        'imagen' => $imagen
      );
      return $this->db->insert('noticia', $data);
    }

  }

  public function borrarPost($id){
    $this->db->where('id', $id);
    return $this->db->delete('noticia');
  }

  /*FUNCION QUE DEVUELVE LOS POSTS*/
  public function getNoticias() {

    $this->db->order_by("id", "desc");
    $this->db->limit(10);
    $query = $this->db->get('noticia');
    return $query->result_array();

  }

  public function getAllNoticias() {

    $this->db->order_by("id", "desc");
    $query = $this->db->get('noticia');
    return $query->result_array();

  }

  public function getNoticia($id){
    $this->db->where("id", $id);
    $query = $this->db->get('noticia');
    return $query->result_array();
  }

  public function getComentarios($id){
    $this->db->order_by("id", "desc");
    $this->db->where("noticia", $id);
    $query = $this->db->get('comentario');
    return $query->result_array();
  }

  function insertComentario($comentario, $autor, $noticia){

    $texto = stripslashes(nl2br($comentario));

    if($this->session->userdata('usuario')){
      $data = array(
        'autor' => $autor,
        'fecha' => standard_date('DATE_W3C', now()),
        'contenido' => $texto,
        'noticia' => $noticia
      );
    }else{
      $data = array(
        'autor' => 'Anonimo',
        'fecha' => standard_date('DATE_W3C', now()),
        'contenido' => $texto,
        'noticia' => $noticia
      );
    }

    return $this->db->insert('comentario', $data);

  }

  /*FUNCION QUE DEVUELVE TODOS LOS COMENTARIOS*/
  public function get_allComents() {
    $query = $this->db->get('comentario');
    return $query->result_array();
  }

  /*FUNCION PARA LOS LIKES*/
  public function likeUp($id, $likes){
    $data = array(
      'likes' => $likes + 1
    );
    $this->db->where('id', $id);
    return $this->db->update('comentario', $data);
  }

  public function record_count() {
    return $this->db->count_all("noticia");
  }

  public function fetch_posts($limit, $start) {
    $this->db->order_by("id", "desc");
    $this->db->limit($limit, $start);
    $query = $this->db->get("noticia");

    if ($query->num_rows() > 0) {
      foreach ($query->result() as $row) {
        $data[] = $row;
      }
      return $data;
    }
    return false;
  }

}


text:
<?php

namespace Finite\Event;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * This class is here to provide a compatibility layer between symfony
 * versions from 2.8 to ^5.0
 */
class StateMachineDispatcher
{
    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    public function __construct(EventDispatcherInterface $eventDispatcher = null)
    {
        $this->eventDispatcher = $eventDispatcher ?: new EventDispatcher;
    }

    public function dispatch($eventName, StateMachineEvent $event)
    {
        if (self::isUnder43()) {
            return $this->eventDispatcher->dispatch($eventName, $event);
        }

        return $this->eventDispatcher->dispatch($event, $eventName);
    }

    public function addListener($eventName, $listener, $priority = 0)
    {
        return $this->eventDispatcher->addListener($eventName, $listener, $priority);
    }

    private static function isUnder43()
    {
        static $result = null;

        if (null === $result) {
            $reflectionMethod     = new \ReflectionMethod(EventDispatcherInterface::class, 'dispatch');
            $reflectionParameters = $reflectionMethod->getParameters();
            $result               = count($reflectionParameters) >= 2 && 'event' === $reflectionParameters[1]->getName();
        }

        return $result;
    }
}


text:
/* This stuff will eventually be replaced by calls to the
   storage manager in the new GHC/Hugs RTS.   -- sof
*/

#if defined(__CYGWIN32__) || defined(__MINGW32__) || defined(__CYGWIN__)
#define __BASTARDIZED_WIN32__ 1
#endif

/*-----------------------------------------------------------
-- (c) 1998,  Daan Leijen, leijen@@fwi.uva.nl
-----------------------------------------------------------*/
/* #define DEBUG */

/* if you don't use COM, comment this out */
/* (pass the setting for this via command line instead.) */
/* #define COM */

/* define the DLL export macro */
#if defined(_BASTARDIZED_WIN32__)
#define DLLEXPORT(res)  __declspec(dllexport) res
#else
/* redef this default for your system */
#define DLLEXPORT(res)  extern res
#endif

#ifdef COM
#define COBJMACROS
#define CINTERFACE
#endif

#include <stdio.h>

#if !defined(__BASTARDIZED_WIN32__) && defined(COM)
#include <windows.h>
#else
# if defined(__BASTARDIZED_WIN32__)
  #include <windows.h>
# if defined(__BASTARDIZED_WIN32__) && defined(COM)
  #include "comPrim.h"
# endif
# endif
#include <stdlib.h>
#endif

#ifdef DEBUG
static int nallocs = 0;
static int nallocs_ = 0;
#endif

void primPointerCheck(void)
{
#ifdef DEBUG
    if (nallocs - nallocs_ != 0)
      printf( "pointer errors: allocs - frees = %i\n", nallocs - nallocs_ );
    nallocs_ = nallocs;
#endif
}

/*-----------------------------------------------------------
-- Free routines for foreign objects
-----------------------------------------------------------*/

DLLEXPORT(void) primFreeBSTR( void* p )
{
#ifdef COM
   if (p) SysFreeString( (BSTR)p );
#endif
}

DLLEXPORT(void) primNoFree( void* p )
{
#if 0
 char    msg[200];
 WCHAR* wmsg;
 HRESULT hr;

 sprintf(msg, "freeing: %p", p);
 MessageBox(NULL, msg, "primNoFree", MB_OK );

 hr = primGUIDToString(p, &wmsg);
 if (SUCCEEDED(hr)) {
    MessageBoxW(NULL, wmsg, L"primNoFree-clsid", MB_OK);
 }
#endif
}

void primFinalise (void* f, void* a)
{ ((void (*)(void *))f)(a); }

/*-----------------------------------------------------------
-- Memory allocation
-----------------------------------------------------------*/

DLLEXPORT(void*) primAllocMemory( int size )
{
#ifdef COM

#ifdef DEBUG
    void* p;
    p = CoTaskMemAlloc( size );
    printf("alloc: %p, size = %i\n", p, size );
    if (p) nallocs++;
    return p;
#else
    return CoTaskMemAlloc(size);
#endif

#else
    return malloc(size);
#endif
}

/* COM version of freeing */
#ifdef COM
DLLEXPORT(void) primFreeMemory( void* p )
{
 #ifdef DEBUG
   if (!p) printf( "freeing null pointer\n" );
 #endif
   if (!p) return;
 #ifdef DEBUG
   if (p) nallocs--;
   printf( "free: %p\n", p);
 #endif
   CoTaskMemFree( p );
}
#endif

#ifndef COM
DLLEXPORT(void) primFreeMemory( void* p )
{
 #ifdef DEBUG
   if (!p) printf( "free null pointer\n" );
 #endif

   if (!p) return;

   free(p);
}
#endif /* !COM */

/* Strictly speaking, converting a function pointer to a void*
   is not guaranteed to be information preserving in ANSI C.
*/
void* finalFreeMemory() { return (void*)&primFreeMemory; }
void* finalNoFree()     { return (void*)&primNoFree;   }
void* finalFreeBSTR()   { return (void*)&primFreeBSTR; }


text:
set -o errexit
set -o nounset
set -o pipefail

SCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..
CODEGEN_PKG=${CODEGEN_PKG:-$(cd ${SCRIPT_ROOT}; ls -d -1 vendor/k8s.io/code-generator 2>/dev/null || echo ${GOPATH}/src/k8s.io/code-generator)}

vendor/k8s.io/code-generator/generate-groups.sh all \
  github.com/nerdalize/nerd/crd/pkg/client github.com/nerdalize/nerd/crd/pkg/apis \
  stable.nerdalize.com:v1 \
  --go-header-file ${SCRIPT_ROOT}/hack/custom-boilerplate.go.txt


text:
namespace tests {
class QuantityDefinitionsSiTest
{
public:
    QuantityDefinitionsSiTest();
};
}


text:
package org.antlr.gunit;

public abstract class AbstractTest implements ITestCase {
	// store essential individual test result for string template
	protected String header;
	protected String actual;

	protected boolean hasErrorMsg;

	private String testedRuleName;
	private int testCaseIndex;

	// TODO: remove these. They're only used as part of a refactor to keep the
	//       code cleaner. It is a mock-instanceOf() replacement.
	public abstract int getType();
	public abstract String getText();

	public abstract String getExpected();
	// return an escaped string of the expected result
	public String getExpectedResult() {
		String expected = getExpected();
		if ( expected!=null ) expected = JUnitCodeGen.escapeForJava(expected);
		return expected;
	}
	public abstract String getResult(gUnitTestResult testResult);
	public String getHeader() { return this.header; }
	public String getActual() { return this.actual; }
	// return an escaped string of the actual result
	public String getActualResult() {
		String actual = getActual();
		// there is no need to escape the error message from ANTLR
		if ( actual!=null && !hasErrorMsg ) actual = JUnitCodeGen.escapeForJava(actual);
		return actual;
	}

	public String getTestedRuleName() { return this.testedRuleName; }
	public int getTestCaseIndex() { return this.testCaseIndex; }

	public void setHeader(String rule, String lexicalRule, String treeRule, int numOfTest, int line, String input) {
		StringBuffer buf = new StringBuffer();
		buf.append("test" + numOfTest + " (");
		if ( treeRule!=null ) {
			buf.append(treeRule+" walks ");
		}
		if ( lexicalRule!=null ) {
			buf.append(lexicalRule + ", line"+line+")" + " - ");
		}
		else buf.append(rule + ", line"+line+")" + " - ");
		buf.append( "\"" );
		buf.append( input );
		buf.append( "\"" );
		this.header = buf.toString();
	}
	public void setActual(String actual) { this.actual = actual; }

	public void setTestedRuleName(String testedRuleName) { this.testedRuleName = testedRuleName; }
	public void setTestCaseIndex(int testCaseIndex) { this.testCaseIndex = testCaseIndex; }

}


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

namespace EighteenSeventeen.Core.DataTypes
{
    public class Train
    {
        public TrainType Type { get; }

        private readonly static ImmutableDictionary<TrainType, int> Costs = new Dictionary<TrainType, int>
        {
            [TrainType.Two] = 100,
            [TrainType.TwoPlus] = 100,
            [TrainType.Three] = 250,
        }.ToImmutableDictionary();

        public Train(TrainType type)
        {
            Type = type;
        }

        public int Cost => Costs[Type];
    }

    public enum TrainType
    {
        Two,
        TwoPlus,
        Three,
        Four,
        Five,
        Six,
        Seven,
        Eight
    }
}


text:
import logging
import os
import sys

def init_logging():
    log_level = os.environ.get('EXECUTOR_LOG_LEVEL', 'INFO')
    logging.basicConfig(level = log_level,
                        stream = sys.stderr,
                        format='%(asctime)s %(levelname)s %(message)s')


text:
using UnityEngine;
using System.Collections;

public class DroneMovement : MonoBehaviour {

	private Transform player;
	private DroneShooting droneShooting;
	private DroneHealth droneHealth;
	private const float HEALTH_TAKE_DURATION = 4f;
	private float dist;
	private float healthTakeStart;

	void Awake() {
		player = GameObject.FindGameObjectWithTag(Tags.player).transform;
		droneShooting = GetComponent<DroneShooting>();
		droneHealth = GetComponent<DroneHealth>();
	}

	void Update ()
	{
		//if (!droneShooting.getShootingStatus ()) {
		this.dist = Vector3.Distance (player.position, transform.position);
		if(droneHealth.health >= 100) {
			if (dist > 2.5) {
				if (!droneShooting.getShootingStatus ())
					transform.LookAt (player);
				transform.position += transform.forward * 3 * Time.deltaTime;
				Vector3 newpos = transform.position;
				newpos.y = 2.7f;
				transform.position = newpos;
			}
		} else {
			if (dist < 6) {
				transform.position += -transform.forward * 3 * Time.deltaTime;
				Vector3 newpos = transform.position;
				newpos.y = 2.7f;
				transform.position = newpos;
				healthTakeStart = Time.time;
			} else if(Time.time - healthTakeStart > HEALTH_TAKE_DURATION){
				droneHealth.AddHealth(50);
			}
		}
		//}
	}

}


text:
package ubic.gemma.model.analysis.expression.diff;

import java.io.Serializable;

/**
 * @author frances
 */
@SuppressWarnings({ "unused", "WeakerAccess" }) // Used in frontend
public class IncludedResultSetInfoValueObject implements Serializable {

    /**
     * The serial version UID of this class. Needed for serialization.
     */
    private static final long serialVersionUID = -4660741839991839187L;

    private Long experimentId;
    private Long analysisId;
    private Long resultSetId;

    public Long getAnalysisId() {
        return this.analysisId;
    }

    public void setAnalysisId( Long analysisId ) {
        this.analysisId = analysisId;
    }

    public Long getExperimentId() {
        return this.experimentId;
    }

    public void setExperimentId( Long experimentId ) {
        this.experimentId = experimentId;
    }

    public Long getResultSetId() {
        return this.resultSetId;
    }

    public void setResultSetId( Long resultSetId ) {
        this.resultSetId = resultSetId;
    }
}


text:
const {expect} = require('chai');
const pug = require('pug');
var Languages = require('../src/languages')

describe('Test Language', function() {

  before(done => {
      Languages = Languages.instance();
      Languages.init(['en_EN', 'fr_FR'], `${__dirname}/../langs/`, done);
  })

  it('Hello', () => {
    expect('hello'.t()).to.equal('Hello');
  })

  it('Value is null', () => {
    const val = Languages.translate(null)
    expect(val).to.equal('');
  })

  it('Value is undefined', () => {
    const val = Languages.translate(undefined)
    expect(val).to.equal('');
  })

  it('Connect', () => {
    expect('connect'.t()).to.equal('To connect');
    expect('connect help'.t()).to.equal('Connect help');
  })

  it('Local Language', () => {
    expect('hello'.t('fr_FR')).to.equal('Bonjour');
  })

  it('With in group', () => {
    expect('email'.t()).to.equal('Email');
  })

  it('Singular', () => {
    expect('new'.t(1)).to.equal('New');
  })

  it('Plurial - s', () => {
    expect('new'.t(2)).to.equal('News');
    expect('new'.t(3)).to.equal('News');
  })

  it('Other plurial - ies', () => {
    expect('directory'.t(2)).to.equal('Directories');
    expect('directory'.t(3)).to.equal('Directories');
  })

  it('With variable', () => {
    expect('welcome'.t('website')).to.equal('Welcome on website');
  })

  it('With two variable', () => {
    expect('step'.t(1, 3)).to.equal('Step 1 / 3');
  })

  it('Combination with {}', () => {
    expect('save as'.t()).to.equal('Save as');
  })

  it('Combination with group', () => {
    expect('all confirm'.t()).to.equal('All confirm');
  })

  it('Combination with parameter', () => {
    expect('you have nb message'.t(2)).to.equal('You have 2 messages');
  })

  it('Boolean', () => {
    expect('connection | logout'.t(true)).to.equal('Login');
    expect('connection | logout'.t(false)).to.equal('Logout');
  })

  it('Combination with parameter and boolean', () => {
    let nbMsg = 0;
    expect('you have nb message | you have no message'.t(nbMsg>0, nbMsg)).to.equal('You have no message');
    nbMsg = 3;
    expect('you have nb message | you have no message'.t(nbMsg>0, nbMsg)).to.equal(`You have ${nbMsg} messages`);
  });

  it('Combination with parameter and boolean in ()', () => {
    let nbMsg = 0;
    expect('you have (nb message | no message)'.t(nbMsg>0, nbMsg)).to.equal('You have no message');
  });

  it('Two IDs', () => {
    expect('you have + message'.t(2)).to.equal('You have messages');
  })

  it('Id not exists', () => {
    expect('foo'.t()).to.equal('');
  })

  describe('Compile template and Pug', function() {

    const customPattern =  {
      patternStart: '[',
      patternEnd: ']',
      pipe: '-',
      fnStart: '(',
      fnEnd: ')',
      paramsSeparator: ','
    }

    it('Simple render', () => {
      const render = Languages.render('{{hello | t}}')
      expect(render).to.equal('Hello');
    })

    it('Simple render with markups', () => {
      const render = Languages.render('
{{hello | t}}

{{hello | t}}
')
      expect(render).to.equal('
Hello

Hello
');
    })

    it('Simple render with quotation mark', () => {
      let render = Languages.render('{{"hello" | t}}')
      expect(render).to.equal('Hello');
      render = Languages.render('{{\'hello\' | t}}')
      expect(render).to.equal('Hello');
    })

    it('Render with 1 parameter', () => {
      const render = Languages.render('{{new | t:2}}')
      expect(render).to.equal('News');
    })

    it('Render with 2 parameters', () => {
      const render = Languages.render('{{step | t:1:3}}')
      expect(render).to.equal('Step 1 / 3');
    })

    it('Render with 2 parameters with markups', () => {
      const render = Languages.render('
{{step | t:1:3}}

{{hello | t}}
')
      expect(render).to.equal('
Step 1 / 3

Hello
');
    })

    it('Render with boolean', () => {
      const render = Languages.render('{{connection | logout | t:true}}')
      expect(render).to.equal('Login');
    })

    it('Render with custom pattern', () => {
      const render = Languages.render('[hello - t]', customPattern)
      expect(render).to.equal('Hello');
    })

    it('Render with custom pattern and 2 parameters', () => {
      const render = Languages.render('[step - t(1,3)]', customPattern)
      expect(render).to.equal('Step 1 / 3');
    })

    const pugRender = `p
      :translate() {{"hello" | t}} Sam`

    it('Render with Pug', () => {
      let render = pug.render(pugRender, {
        filters: {
          translate: function (text) {
            return Languages.render(text);
          }
        }
      });
      expect(render).to.equal('
Hello Sam
');
    })

    it('Render with Pug method', () => {
      let render = pug.render(pugRender, {filters: Languages.load.Pug() });
      expect(render).to.equal('
Hello Sam
');
    })

    it('Render with Pug method and other filters', () => {
      let render = pug.render(pugRender, {filters: Languages.load.Pug({
        otherFilter: {}
      })});
      expect(render).to.equal('
Hello Sam
');
    })

  })

  describe('With namespace', function() {

    before(done => {
      Languages.add(["en_EN"], `${__dirname}/plugin/`, "plugin_name", done)
    })

    it('Hello', () => {
      expect('plugin_name.hello'.t()).to.equal('Hello world');
    })

  });

})


text:
This document describes the governance model for the AMP open source project, and in particular the [AMP HTML GitHub project](https://github.com/ampproject/amphtml).

Our governance model is as follows:

* There is a single [Tech Lead](#list-of-core-committers), who will have the final say on all decisions regarding technical direction.
* The Tech Lead directs the [Core Committers](#list-of-core-committers), whose members include the Tech Lead and those who have been appointed by the Tech Lead as Core Committers.
* In the event the Tech Lead is unable to perform their duty, or abdicates, the Core Committers can select a new Tech Lead from amongst themselves.
* In the unlikely event that there are no more Core Committers, Google Inc. will appoint a new Tech Lead.
* Significant feature development and changes to AMP require following the ["Intent to implement"](./CONTRIBUTING.md#contributing-features) process including approval from the Tech Lead and one Core Committer.
* Before contributions can be merged into the AMP Project, approval must be given by an [Owner and a Core Committer](./contributing/owners-and-committers.md)

### List of Core Committers:

* **Tech Lead: Malte Ubl (@cramforce)**
* Ali Ghassemi (@aghassemi)
* Avi Mehta (@avimehta). Specialty: Analytics
* Barb Paduch (@bpaduch). Specialty: Docs
* Sriram Krishnan (@camelburrito)
* Chen Shay (@chenshay)
* William Chou (@choumx)
* Dima Voytenko (@dvoytenko)
* Erwin Mombay (@erwinmombay)
* Greg Grothaus (@Gregable). Specialty: Validator
* David Sedano (@honeybadgerdontcare). Specialty: Validator
* Justin Ridgewell (@jridgewell)
* Hongfei Ding (@lannka)
* Yuxi Chen (@muxin)
* Johannes Henkel (@powdercloud). Specialty: Validator
* Wassim Gharbi (@wassgha)
* Yuxuan Zhou (@zhouyx)


text:
/*
 * rt_round_snf.h
 *
 * Real-Time Workshop code generation for Simulink model "CSE1_CV3_1Straight.mdl".
 *
 * Model Version              : 1.296
 * Real-Time Workshop version : 7.3  (R2009a)  15-Jan-2009
 * C source code generated on : Fri Feb 14 09:46:51 2014
 *
 * Target selection: nidll_vxworks.tlc
 *   Note: GRT includes extra infrastructure and instrumentation for prototyping
 * Embedded hardware selection: 32-bit Generic
 * Code generation objectives: Unspecified
 * Validation result: Not run
 */

#ifndef RTW_HEADER_rt_round_snf_h_
#define RTW_HEADER_rt_round_snf_h_
#include "rtwtypes.h"

extern real_T rt_round_snf(const real_T xr);

#endif                                 /* RTW_HEADER_rt_round_snf_h_ */


text:
from __future__ import absolute_import

from .cms_apps import *  # NOQA


text:
package dump

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
	"sort"
	"strings"
	"testing"

	"github.com/hyperledger/burrow/bcm"
	"github.com/hyperledger/burrow/execution/state"
	"github.com/stretchr/testify/require"
	"github.com/syndtr/goleveldb/leveldb/opt"
	dbm "github.com/tendermint/tm-db"
)

// The tests in this package are quite a good starting point for investigating the inadequacies of IAVL...
func TestMain(m *testing.M) {
	// For pprof
	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()
	code := m.Run()
	os.Exit(code)
}

func BenchmarkDump(b *testing.B) {
	b.StopTimer()
	st := testLoad(b, NewMockSource(1000, 1000, 100, 10000))
	dumper := NewDumper(st, &bcm.Blockchain{})
	b.StartTimer()
	for n := 0; n < b.N; n++ {
		err := dumper.Transmit(NullSink{}, 0, 0, All)
		require.NoError(b, err)
	}
}

func TestDump(t *testing.T) {
	mockSource := NewMockSource(50, 50, 100, 100)
	st := testLoad(t, mockSource)
	dumper := NewDumper(st, mockSource)
	sink := CollectSink{
		Rows: make([]string, 0),
	}
	err := dumper.Transmit(&sink, 0, 0, All)
	require.NoError(t, err)

	sort.Strings(sink.Rows)

	m := NewMockSource(50, 50, 100, 100)
	data := make([]string, 0)

	for {
		row, err := m.Recv()
		if err == io.EOF {
			break
		}
		bs, _ := json.Marshal(row)
		data = append(data, string(bs))
	}

	sort.Strings(data)

	require.Equal(t, sink.Rows, data)
}

// Test util

func normaliseDump(dump string) string {
	rows := strings.Split(dump, "\n")
	sort.Stable(sort.StringSlice(rows))
	return strings.Join(rows, "\n")
}

func dumpToJSONString(t *testing.T, st *state.State, blockchain Blockchain) string {
	buf := new(bytes.Buffer)
	receiver := NewDumper(st, blockchain).Source(0, 0, All)
	err := Write(buf, receiver, false, All)
	require.NoError(t, err)
	return string(buf.Bytes())
}

func loadDumpFromJSONString(t *testing.T, st *state.State, jsonDump string) {
	reader, err := NewJSONReader(bytes.NewBufferString(jsonDump))
	require.NoError(t, err)
	err = Load(reader, st)
	require.NoError(t, err)
}

func testDB(t testing.TB) dbm.DB {
	testDir, err := ioutil.TempDir("", "TestDump")
	require.NoError(t, err)
	var options *opt.Options
	db, err := dbm.NewGoLevelDBWithOpts("TestDumpDB", testDir, options)
	require.NoError(t, err)
	return db
}


text:
#include <google/protobuf/message.h>
#include <memory>
#include <string>

#include "Core/Buffer.h"

/**
 * \file
 * Utilities for dealing with protocol buffers.
 */

#ifndef LOGCABIN_CORE_PROTOBUF_H
#define LOGCABIN_CORE_PROTOBUF_H

namespace google {
namespace protobuf {

/**
 * Equality for protocol buffers so that they can be used in EXPECT_EQ.
 * This is useful for testing.
 */
bool operator==(const Message& a, const Message& b);

/**
 * Inequality for protocol buffers so that they can be used in EXPECT_NE.
 * This is useful for testing.
 */
bool operator!=(const Message& a, const Message& b);

// Equality and inequality between protocol buffers and their text format
// representations. These are useful for testing.
bool operator==(const Message& a, const std::string& b);
bool operator==(const std::string& a, const Message& b);
bool operator!=(const Message& a, const std::string& b);
bool operator!=(const std::string& a, const Message& b);

} // namespace google::protobuf
} // namespace google

namespace LogCabin {
namespace Core {
namespace ProtoBuf {

namespace Internal {

/// Helper for fromString template.
void fromString(const std::string& str, google::protobuf::Message& protoBuf);

} // namespace LogCabin::ProtoBuf::Internal

/**
 * Create a protocol buffer message form a text format.
 * This is useful for testing.
 * \tparam ProtoBuf
 *      A derived class of ProtoBuf::Message.
 * \param str
 *      The string representation of the protocol buffer message.
 *      Fields that are missing will not throw an error, but the resulting
 *      protocol buffer may be less useful.
 * \return
 *      The parsed protocol buffer.
 */
template<typename ProtoBuf>
ProtoBuf
fromString(const std::string& str)
{
    ProtoBuf protoBuf;
    Internal::fromString(str, protoBuf);
    return protoBuf;
}

/**
 * Dumps a protocol buffer message.
 * This is useful for debugging and for testing.
 *
 * \param protoBuf
 *      The protocol buffer message to dump out. It is safe to call this even
 *      if you haven't filled in all required fields, but the generated string
 *      will not be directly parse-able.
 * \param forCopyingIntoTest
 *      If set to true, this will return a string in a format most useful for
 *      writing unit tests. You can basically copy and paste this from your
 *      terminal into your test file without manual processing. If set to false
 *      (default), the output will be nicer to read but harder to copy into a
 *      test file.
 * \return
 *      Textual representation. This will be printable ASCII; binary will be
 *      escaped.
 */
std::string
dumpString(const google::protobuf::Message& protoBuf,
           bool forCopyingIntoTest = false);

/**
 * Copy the contents of a protocol buffer into a new one.
 */
std::unique_ptr<google::protobuf::Message>
copy(const google::protobuf::Message& protoBuf);

/**
 * Parse a protocol buffer message out of a Core::Buffer.
 * \param from
 *      The Core::Buffer from which to extract a protocol buffer.
 * \param[out] to
 *      The empty protocol buffer to fill in with the contents of the
 *      Core::Buffer.
 * \param skipBytes
 *      The number of bytes to skip at the beginning of 'from' (defaults to 0).
 * \return
 *      True if the protocol buffer was parsed successfully; false otherwise
 *      (for example, if a required field is missing).
 */
bool
parse(const Core::Buffer& from,
      google::protobuf::Message& to,
      uint32_t skipBytes = 0);

/**
 * Serialize a protocol buffer message into a Core::Buffer.
 * \param from
 *      The protocol buffer containing the contents to serialize into the
 *      Core::Buffer. All required fields must be set or this will PANIC.
 * \param[out] to
 *      The Core::Buffer to fill in with the contents of the protocol buffer.
 * \param skipBytes
 *      The number of bytes to allocate at the beginning of 'to' but leave
 *      uninitialized for someone else to fill in (defaults to 0).
 */
void
serialize(const google::protobuf::Message& from,
          Core::Buffer& to,
          uint32_t skipBytes = 0);

/**
 * An abstract stream from which ProtoBufs may be read.
 */
struct InputStream {
    /**
     * Destructor.
     */
    virtual ~InputStream() {}
    /**
     * Return the number of bytes read so far.
     */
    virtual uint64_t getBytesRead() const = 0;
    /**
     * Read a ProtoBuf message from the stream.
     * \return
     *      Empty string if successful, otherwise an error message if an error
     *      occurred. The stream is probably no longer usable after an error.
     */
    virtual std::string readMessage(google::protobuf::Message& message) = 0;
    /**
     * Read some raw bytes from the stream.
     * \return
     *      The number of bytes read before the end of the stream was reached,
     *      up to 'length'.
     */
    virtual uint64_t readRaw(void* data, uint64_t length) = 0;
};

/**
 * An abstract stream to which ProtoBufs may be written.
 */
struct OutputStream {
    /**
     * Destructor.
     */
    virtual ~OutputStream() {}
    /**
     * Return the number of bytes written so far.
     */
    virtual uint64_t getBytesWritten() const = 0;
    /**
     * Write the given ProtoBuf message to the stream.
     */
    virtual void writeMessage(const google::protobuf::Message& message) = 0;
    /**
     * Write some raw bytes to the stream.
     */
    virtual void writeRaw(const void* data, uint64_t length) = 0;
};

} // namespace LogCabin::Core::ProtoBuf
} // namespace LogCabin::Core
} // namespace LogCabin

#endif /* LOGCABIN_CORE_PROTOBUF_H */


text:
<?php

namespace Ding\Mvc\Http;

use Ding\Mvc\IViewRender;
use Ding\Mvc\IMapper;
use Ding\Mvc\Exception\MvcException;
use Ding\Mvc\ModelAndView;
use Ding\Mvc\RedirectModelAndView;
use Ding\Mvc\ForwardModelAndView;
use Ding\Container\Impl\ContainerImpl;

/**
 * Http front controller.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Mvc
 * @subpackage Http
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class HttpFrontController
{
    /**
     * Log4PHP Logger or own dummy implementation.
     * @var Logger
     */
    private static $_logger;

    public static function dispatch(
        HttpDispatcher $dispatcher,
        HttpViewResolver $viewResolver,
        HttpAction $action,
        IMapper $mapper,
        IViewRender $render
    ) {
        $dispatchInfo = $mapper->map($action);
        if ($dispatchInfo === false) {
            throw new MvcException(
            	'No suitable controller for: ' . $action->getId()
            );
        }
        $controller = $dispatchInfo->handler;
        $actionHandler = $dispatchInfo->method;

        self::$_logger->debug(
        	'Found mapped controller: ' . get_class($controller)
            . ' with action: ' . $actionHandler
        );
        $modelAndView = $dispatcher->dispatch($dispatchInfo);
        if ($modelAndView instanceof ForwardModelAndView) {
            self::$_logger->debug(
              	'Forwarding ModelAndView: ' . $modelAndView->getName()
            );
            $newAction = new HttpAction($modelAndView->getName(), $modelAndView->getModel());
            $newAction->getMethod($action->getMethod());
            self::dispatch($dispatcher, $viewResolver, $newAction, $mapper, $render);
        } else if ($modelAndView instanceof RedirectModelAndView) {
            header('HTTP/1.1 302 Moved');
            $location = $modelAndView->getName();
            if (!$modelAndView->isEmpty()) {
                $location .= '?' . http_build_query($modelAndView->getModel());
            }
            header('Location: ' . $location);
            self::$_logger->debug(
               	'Redirecting ModelAndView: ' . $modelAndView->getName()
                . " -> $location"
            );
        } else if ($modelAndView instanceof ModelAndView) {
            self::$_logger->debug(
               	'Using ModelAndView: ' . $modelAndView->getName()
            );
            $view = $viewResolver->resolve($modelAndView);
            $render->render($view);
        }
    }
    /**
     * Handles the request. This will instantiate the container with the given
     * properties (via static method configure(), see below). Then it will
     * getBean(HttpDispatcher) and call dispatch() on it with an Action created
     * based on the request uri and method parameters (get, post, etc).
     *
     * @return void
     */
    public static function handle(array $properties = array(), $baseUrl = '/')
    {
        $exceptionThrown = null;
        $filtersPassed = true;
        $container = ContainerImpl::getInstance($properties);
        self::$_logger = \Logger::getLogger(__CLASS__);
        $baseUrlLen = strlen($baseUrl);
        ob_start();
        $exceptionMapper = $render = $dispatcher = $viewResolver = false;
        $interceptors = array();
        try
        {
            $dispatcher = $container->getBean('HttpDispatcher');
            $viewResolver = $container->getBean('HttpViewResolver');
            $exceptionMapper = $container->getBean('HttpExceptionMapper');
			$render = $container->getBean('HttpViewRender');
			$render->setSession($container->getBean('SessionHandler'));

            $method = strtolower($_SERVER['REQUEST_METHOD']);
            $url = $_SERVER['REQUEST_URI'];
            $urlStart = strpos($url, $baseUrl);

            self::$_logger->debug('Trying to match: ' . $url);
            if ($urlStart === false || $urlStart > 0) {
                throw new MvcException($url . ' is not a base url.');
            }
            $url = substr($url, $baseUrlLen);
            $variables = array();
            if (!empty($_GET)) {
                $variables = array_merge($variables, $_GET);
            }
            if (!empty($_POST)) {
                $variables = array_merge($variables, $_POST);
            }
			if (!empty($_FILES)) {
                $variables = array_merge($variables, $_FILES);
            }

            $action = new HttpAction($url, $variables);
            $action->setMethod($method);
            $mapper = $container->getBean('HttpUrlMapper');
            self::dispatch($dispatcher, $viewResolver, $action, $mapper, $render);
        } catch(\Exception $exception) {
            $exceptionThrown = $exception;
            self::$_logger->debug('Got Exception: ' . $exception);
            ob_end_clean();
            ob_start();
            if ($exceptionMapper === false) {
                header('HTTP/1.1 500 Error.');
            } else {
                $action = new HttpAction(
                    get_class($exception), array('exception' => $exception)
                );
                self::dispatch($dispatcher, $viewResolver, $action, $exceptionMapper, $render);
            }
        }
        ob_end_flush();
    }

}


text:
<?php

namespace Main\UserBundle\Controller;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

class AdminController extends Controller
{
    public function confirmAction()
    {
        $id = $this->get('request')->get($this->admin->getIdParameter());

        $user = $this->admin->getObject($id);

        if (!$user) {
            throw new NotFoundHttpException(sprintf('unable to find the user with id : %s', $id));
        }

		$user->addRole('ROLE_PROF');
		$user->removeRole('ROLE_PROF_TBC');
        $userManager = $this->get('fos_user.user_manager');
		$userManager->updateUser($user);

        $this->addFlash('sonata_flash_success', 'prof confirmé !');

        return new RedirectResponse($this->admin->generateUrl('list'));
    }
}


text:
namespace Smi.Sample.AppCore.Player.Events
{
	using System;
	using System.Collections.Generic;
	using Commands;
	using Smi.Infra.Messages;

	[Serializable]
	public class PlayerCreatedEvent : DomainEvent<ICreatePlayer>
	{
		public PlayerCreatedEvent(IDictionary<string, object> parameters)
			: base(parameters)
		{ }
	}
}


text:
Before you decide to use this library, be aware that [OpenType.js](https://nodebox.github.io/opentype.js)
has become better at doing what you were probably thinking
of using Font.js for - I still think JavaScript needs
a Font object, but at this point rewriting it from
scratch so that it's backed by OpenType.js is far more
sensible than using Font.js in its current form. So:
head on over there and discover an amazing library.

With that said....

Font.js
=======

Font.js adds new Font() functionality to the JavaScript
toolbox, akin to how you use new Image() for images. It
adds an onload event hook so that you don't deploy a
font resource on your webpage before it's actually ready
for use, as browsers can tell you when a font has
downloaded, but not when it has been parsed and made
ready for on-page rendering. This object can. It can
also do this for system fonts, so you can also use
Font.js to detect whether a specific system font is
installed at the client, for fallbacks and failsafes.

The API is pretty straight forward:

  * constructor

      var font = new Font();

  * load event handler

    font.onload = function() {
      /* your code here */
    };

  * error event handler

    font.onerror = function(error_message) {
      /* your code here */
    };

  * name assignment

    font.fontFamily = "name goes here";

  * font loading

    - remote fonts:

      font.src = "http://your.font.location/here.ttf";

    (!) This line will kick off font loading and
    will make the font available on-page (if a
    remote font was requested).

    - system fonts / already @font-face loaded fonts:

      font.src = font.fontFamily;

    (!) Note that this also works for google webfont and
    typekit fonts that have been loaded through an HTML
    stylesheet. Any font that is available by name, rather
    than by font file, can be loaded using the above
    "src=fontFamily" solution.

  * DOM removal

    document.head.removeChild(font.toStyleNode());

    (!) this only applies to fonts loaded from a
    remote resource. System fonts do not have an
    associated style node.

  * DOM (re)insertion

    document.head.appendChild(font.toStyleNode());

    (!) This is only required if you removed the
    font from the page, as the font is added to the
    DOM for use on-page during font loading already.

    (!) this only applies to fonts loaded from a
    remote resource. System fonts do not have an
    associated style node.

Font Metrics API
----------------

  * font.metrics.quadsize

    The font-indicated number of units per em

  * font.metrics.leading

    The font-indicated line height, in font units
    (this vaue is, often, useless)

  * font.metrics.ascent

    The maximum ascent for this font, as a ratio
    of the fontsize

  * font.metrics.decent

    The maximum descent for this font, as a ratio
    of the fontsize

  * font.metrics.weightclass

    The font-indicated weight class

  (!) As system font files cannot be inspected, they
  do not have an associated font.metrics object.
  Instead, font.metrics is simply "false".

Text Metrics API
----------------

  * font.measureText(string, size)

    Compute the metrics for a particular string, with
    this font applied at the specific font size in pixels

  * font.measureText(...).width

    the width of the string in pixels, using this font
    at the specified font size

  * font.measureText(...).fontsize

    the specified font size

  * font.measureText(...).height

    the height of the string. This may differ from the
    font size

  * font.measureText(...).leading

    the actual line spacing for this font based on ten
    lines.

  * font.measureText(...).ascent

    the ascent above the baseline for this string

  * font.measureText(...).descent

    the descent below the baseline for this string

  * font.measureText(...).bounds

    An object {xmin:<num>, ymin:<num>, xmax:<num>,
    ymax:<num>} indicating the string's bounding box.

When font.src is set, the whole shebang kicks in, just
like for new Image(), so make sure to define your onload()
handler BEFORE setting the "src" property, or your handler
may not get called.

Demonstrator
------------

A demonstrator of this object can be found at:

  * http://pomax.nihongoresources.com/pages/Font.js

Font.js is compatible with all browsers that support
canvas and Object.defineProperty --  This includes all
versions of Firefox, Chrome, Opera, IE and Safari that
were 'current' (Firefox 9, Chrome 16, Opera 11.6, IE9,
Safari 5.1) at the time Font.js was released.

Note: Font.js will not work on IE8 or below due to the lack of
Object.defineProperty

This code is (c) Mike "Pomax" Kamermans, 2012, but
licensed under the MIT ("expat" flavour) license.