text:
<?php

namespace HanischIt\KrakenApi\Call\SpreadData;

use HanischIt\KrakenApi\Enum\VisibilityEnum;
use HanischIt\KrakenApi\Model\RequestInterface;

/**
 * Class SpreadDataRequest
 * @package HanischIt\KrakenApi\Call\SpreadData
 */
class SpreadDataRequest implements RequestInterface
{
    /**
     * @var
     */
    private $assetPair;
    /**
     * @var null
     */
    private $since;

    /**
     * OrderBookRequest constructor.
     * @param $assetPair
     * @param null|mixed $since
     */
    public function __construct($assetPair, $since = null)
    {
        $this->assetPair = $assetPair;
        $this->since = $since;
    }

    /**
     * Returns the api request name
     *
     * @return string
     */
    public function getMethod()
    {
        return 'Spread';
    }

    /**
     * @return string
     */
    public function getVisibility()
    {
        return VisibilityEnum::VISIBILITY_PUBLIC;
    }

    /**
     * @return array
     */
    public function getRequestData()
    {
        $arr = [];
        $arr["pair"] = $this->assetPair;
        if ($this->since) {
            $arr["since"] = $this->since;
        }
        return $arr;
    }

    /**
     * @return string
     */
    public function getResponseClassName()
    {
        return SpreadDataResponse::class;
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Page\Admin\ProductVariant;

use Sylius\Behat\Behaviour\ChecksCodeImmutability;
use Sylius\Behat\Page\Admin\Crud\UpdatePage as BaseUpdatePage;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Currency\Model\CurrencyInterface;

class UpdatePage extends BaseUpdatePage implements UpdatePageInterface
{
    use ChecksCodeImmutability;

    /**
     * {@inheritdoc}
     */
    protected function getCodeElement()
    {
        return $this->getElement('code');
    }

    /**
     * {@inheritdoc}
     */
    public function specifyPrice($price)
    {
        $this->getDocument()->fillField('Price', $price);
    }

    public function disableTracking()
    {
        $this->getElement('tracked')->uncheck();
    }

    public function enableTracking()
    {
        $this->getElement('tracked')->check();
    }

    /**
     * {@inheritdoc}
     */
    public function isTracked()
    {
        return $this->getElement('tracked')->isChecked();
    }

    /**
     * {@inheritdoc}
     */
    public function getPricingConfigurationForChannelAndCurrencyCalculator(ChannelInterface $channel, CurrencyInterface $currency)
    {
        $priceElement = $this->getElement('pricing_configuration')->find('css', sprintf('label:contains("%s %s")', $channel->getCode(), $currency->getCode()))->getParent();

        return $priceElement->find('css', 'input')->getValue();
    }

    /**
     * {@inheritdoc}
     */
    public function getPriceForChannel($channelName)
    {
        return $this->getElement('price', ['%channelName%' => $channelName])->getValue();
    }

    /**
     * {@inheritdoc}
     */
    public function getOriginalPriceForChannel($channelName)
    {
        return $this->getElement('original_price', ['%channelName%' => $channelName])->getValue();
    }

    /**
     * {@inheritdoc}
     */
    public function getNameInLanguage($language)
    {
        return $this->getElement('name', ['%language%' => $language])->getValue();
    }

    /**
     * {@inheritdoc}
     */
    public function specifyCurrentStock($amount)
    {
        $this->getElement('on_hand')->setValue($amount);
    }

    /**
     * {@inheritdoc}
     */
    public function isShippingRequired()
    {
        return $this->getElement('shipping_required')->isChecked();
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefinedElements()
    {
        return array_merge(parent::getDefinedElements(), [
            'code' => '#sylius_product_variant_code',
            'name' => '#sylius_product_variant_translations_%language%_name',
            'on_hand' => '#sylius_product_variant_onHand',
            'original_price' => '#sylius_product_variant_channelPricings > .field:contains("%channelName%") input[name$="[originalPrice]"]',
            'price' => '#sylius_product_variant_channelPricings > .field:contains("%channelName%") input[name$="[price]"]',
            'pricing_configuration' => '#sylius_calculator_container',
            'shipping_required' => '#sylius_product_variant_shippingRequired',
            'tracked' => '#sylius_product_variant_tracked',
        ]);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<head>
<script>
// Test that the very first navigation made on a newly created IFRAME does not
// create another session history entry, even if the IFRAME is already attached
// to the document and the page has fully loaded.
function runTest() {
  var f = document.createElement("iframe");
  document.body.appendChild(f);

  f.src = "data:,hello";

  f.onload = function() {
    document.body.innerText = "history.length = " + history.length;
    if (window.testRunner)
      testRunner.notifyDone();
  }
}

onunload = function() {
  // Disable page cache
}

onload = function() {
  if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.dumpBackForwardList();
    testRunner.clearBackForwardList();
    testRunner.waitUntilDone();
  }
  setTimeout(runTest, 0);
}
</script>
</head>
<body></body>


text:
Executes multiple programs concurrently to generate output for bars

## Table of Contents

* [Introduction](#introduction)
	* [What Admiral Does](#what-admiral-does)
* [Getting Started](#getting-started)
	* [Prerequisites](#prerequisites)
	* [Installation](#installation)
* [Configuration](#configuration)
	* [[admiral]](#admiral-1)
	* [Sections of the admiral.toml](#sections-of-the-admiraltoml)
		* [path](#path)
		* [shell](#shell)
		* [reload](#reload)
		* [static](#static)
	* [Newlines](#newlines)
* [Example](#example)
	* [[admiral]](#admiral-2)
	* [Scripts](#scripts)
	* [Formatting](#formatting)
* [Bugs](#bugs)

## Introduction

*If you just want to get Admiral running, skip to the [next section](#getting-started).*

Programs like [lemonbar](https://github.com/LemonBoy/bar) and
[i3bar](https://i3wm.org/i3bar/) have become popular in recent years,
and with good reason. For those of you who are unfamiliar with them,
these programs read from standard input and then output what they receive on a bar.
For the most part, their output is identical to their input, but they accept
some format strings which allow the user to specify things like colors,
justification, and clickable areas.

The advantage of this system is that it is very powerful. The disadvantage is that
it can be rather difficult to configure.

A typical bar script looks something like this: a shell script, probably bash,
is used to collect and format the output of various commands. This is done in
an infinite loop, probably ending with `sleep 0.1` or something similar.
The output of this script is then piped into the bar program, which receives a new
line (which may be identical to its previous line) ten times per second.

The main problem with this method is that it's rather difficult to
handle timing correctly. A counter showing the number of
outdated programs on the system can be updated less frequently than a clock.

Actually, a previous bar script I had contained both of the aforementioned
items. One day, I noticed the clock on my bar had stopped working.
The cause? The internet had died. This prevented the package counter command
(`checkupdates | wc -l`) from ever finishing, which caused the entire
bar to stop working.

Another major problem is that shell scripts of these types are bug-prone and
tend to become very bloated.
Admiral has a declarative style which allows you to configure your bar with ease
and avoid pesky bugs.

### What Admiral Does

Admiral runs programs specified by the user and prints their output. It allows
for a clear separation of different sections, which simplifies configuration.

The best part? **Each program is run in its own thread.**
This means that each section is updated independently of the other sections.
It also means that **if something fails, it fails independently** of the other
sections.
That example where the clock stopped? This would never happen with Admiral.
Sure, `checkupdates` would still hang indefinitely and prevent that
number from changing. But the clock (and the rest of the bar) would be unaffected.

Admiral also limits its output. Whenever one of its programs updates, it checks to see
if anything has actually changed since it last printed a message. If nothing has
changed, Admiral prints nothing—this limits the amount of refreshing that your bar
program has to do.

## Getting Started

### Prerequisites

* `rustc` — the Rust compiler

* `cargo` — the Rust package manager

* `git` (optional but recommended)

These can probably be installed via your distribution's package manager.
If the Rust compiler and Cargo are not packaged for your distro,
you can download them [here](https://www.rust-lang.org/).

### Installation

1. Clone this repository with `git clone https://github.com/sector-f/admiral.git`
	* Alternatively, a .zip file of the master branch can
	be downloaded [here](https://github.com/sector-f/admiral/archive/master.zip)
2. `cd` into the newly-created `admiral/` directory
3. Run `cargo build --release`

This will create an `admiral` excutable in the `./target/release/` directory.
You may want to copy this to somewhere in your `$PATH`,
like `/usr/local/bin/` or `~/.local/bin/`

You may then copy the provided `admiral.d/` directory to `~/.config/`
(or your `$XDG_CONFIG_HOME` directory, if you have that environment variable set).

## Configuration

Configuration is done with an `admiral.toml` file. This file is looked for in
`~/.config/admiral.d/` (Or `$XDG_CONFIG_HOME/admiral.d/`, if that environment
variable is set). Alternatively, a configuration file may be specified with
the `-c` flag, e.g. `admiral -c /path/to/file.toml`.

An example `admiral.d/` (complete with the `admiral.toml`) is included in this
repository.

### [admiral]

`[admiral]` is the section where Admiral's output is configured.
It has one required entry: `items`. Here is an example `[admiral]` section:

```
[admiral]
items = ["music", "workspaces", "clock"]
```

Each entry in the `items` table specifies a section of the config file that will be run.
Note that the order specified here is the order that Admiral will use
for the scripts' output.

### Sections of the admiral.toml

Each section of the `admiral.toml` contains a command that produces some output;
you can use shell scripts, python scripts, executable binaries, etc.

Here is an example script section:

```
[clock]
path = "date '+%I:%M %p'"
reload = 1
```

#### path

`path` is the only required entry for a script. The specified command is executed
by a shell running in the same directory as the `admiral.toml`.
So, `path = "./mpd.sh"` will run the `mpd.sh` in the same directory as the
`admiral.toml`, and `path = "echo 'Hello, world!'"` will output "Hello, world!" using
your shell. Note that the shell is determined via the `$SHELL` environment variable.

#### shell

`shell` is an optional variable that specifies an alternate shell to execute commands
with. The default shell is your `$SHELL` environment variable. Using an alternate
shell may be useful if you wish to leverage features of a specific shell for a certain
command. An example use is `shell = "/usr/bin/fish"`.

#### reload

The `reload` value is the optional duration in seconds between
each execution of the script. It may be either an integer such as `10`
or a float such as `0.5`.

If no `reload` value is specified, and `static` is not set to `true`, this indicates
that the script should never exit. It will be run, and each line it outputs will be
used separately. This is for commands such as `xtitle -s`, which handle polling
themselves and output new information on a new line. If the process is killed, it will
automatically be restarted.

#### static

`static` is an optional boolean variable. It is set to false by default. It is for
scripts that only need to be run once. Here is an example:

```
[center]
path = "echo '%{c}'"
static = true
```

This script is used to add a format sequence for `lemonbar`. It only needs to be
run once, and its output will never change.

### Newlines

Bars expect newline characters to be used only at the end of each full line of input;
Admiral tries to respect this by trimming newline characters from the output
of scripts. Users should be aware of how this is handled:

* Both `\r` and `\n` characters are removed from the start and end of a script's
output

* If no `reload` value is specified and `static` is false, Admiral
uses each line produced by the script. This means that each line meant to be displayed
must end in either `\n` or `\r\n`. However, these characters will still be
stripped from Admiral's output so as to keep its complete output on a single line.

## Example

An example `admiral.d/` directory is included with admiral. The example is designed for
use with [bspwm](https://github.com/baskerville/bspwm), and also relies on
[xtitle](https://github.com/baskerville/xtitle) to get the window title. Its
output is designed to be piped to `lemonbar`.
The command `admiral | lemonbar -g x30 | sh` should work for a demonstration, although
a greater number of clickable areas may need to be specified with `lemonbar -a`
if you have more than 8 desktops.

The example bar has three sections: BSPWM workspace information, the current window
title, and the current time. The workspace section uses the
letters `f`, `o`, and `u` to represent free (empty), occupied, and urgent desktops,
respectively. Lowercase letters represent unfocused desktops, and an uppercase
letter represents the focused desktop.

This workspace section is clickable. Left-clicking on a letter will switch to the
corresponding desktop. Scrolling up with the mouse wheel while the cursor is over
the workspace section will switch to the previous desktop, and scrolling
down with the mouse wheel will switch to the next desktop.

This directory contains two files: an `admiral.toml` file and `bspwm_workspaces.sh`.
Let's look at the example `admiral.toml`:

### [admiral]

This is the provided `[admiral]` section:

```
[admiral]
items = ["left", "workspaces",
         "center", "title",
         "right", "clock"]
```

Six scripts are listed. Three are used to provide information, and the other
three are used for formatting the output.

### Scripts

These are the first three scripts listed in the example `admiral.toml` file:

```
[workspaces]
path = "./bspwm_workspaces.sh"

[title]
path = "xtitle -s -t 100"

[clock]
path = "date '+%-I:%M %p  '"
reload = 1
```

`bspwm_workspaces.sh` is a Bash script that parses the output of `bspc subscribe report`
and converts it into a clickable, human-readable format for `lemonbar`. Because
`bspc subscribe report` (and therefore `bspwm_workspaces.sh`) never exits, no reload
value is specified.

### Formatting

These are the last three scripts:

```
[left]
path = "echo '%{l}'"
static = true

[center]
path = "echo '%{c}'"
static = true

[right]
path = "echo '%{r}'"
static = true
```

These output format strings to be interpreted by `lemonbar`. As their output only
needs to be captured once, `static` is set to `true`.
Remember that `admiral` removes trailing newline characters; this means that
using `echo` rather than `echo -n` will still work here.

Keeping the format strings outside of the main scripts allows for quicker, easier
formatting.

## Bugs

* Specifying a toml file in the current directory as `admiral -c admiral.toml`
causes scripts with relative paths to fail.
	* Workaround: Give the "directory name" as well, i.e. `admiral -c ./admiral.toml`

Any bugs that are found should be reported
[here](https://github.com/sector-f/admiral/issues).


text:
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;

/// Generated files are compatible only with the same version
/// of protobuf runtime.

static file_descriptor_proto_data: &'static [u8] = b"\
    \n\x1bgrpc/testing/services.proto\x12\x0cgrpc.testing\x1a\x1bgrpc/testin\
    g/messages.proto\x1a\x1agrpc/testing/control.proto\x1a\x18grpc/testing/s\
    tats.proto2\xa6\x03\n\x10BenchmarkService\x12F\n\tUnaryCall\x12\x1b.grpc\
    .testing.SimpleRequest\x1a\x1c.grpc.testing.SimpleResponse\x12N\n\rStrea\
    mingCall\x12\x1b.grpc.testing.SimpleRequest\x1a\x1c.grpc.testing.SimpleR\
    esponse(\x010\x01\x12R\n\x13StreamingFromClient\x12\x1b.grpc.testing.Sim\
    pleRequest\x1a\x1c.grpc.testing.SimpleResponse(\x01\x12R\n\x13StreamingF\
    romServer\x12\x1b.grpc.testing.SimpleRequest\x1a\x1c.grpc.testing.Simple\
    Response0\x01\x12R\n\x11StreamingBothWays\x12\x1b.grpc.testing.SimpleReq\
    uest\x1a\x1c.grpc.testing.SimpleResponse(\x010\x012\x97\x02\n\rWorkerSer\
    vice\x12E\n\tRunServer\x12\x18.grpc.testing.ServerArgs\x1a\x1a.grpc.test\
    ing.ServerStatus(\x010\x01\x12E\n\tRunClient\x12\x18.grpc.testing.Client\
    Args\x1a\x1a.grpc.testing.ClientStatus(\x010\x01\x12B\n\tCoreCount\x12\
    \x19.grpc.testing.CoreRequest\x1a\x1a.grpc.testing.CoreResponse\x124\n\n\
    QuitWorker\x12\x12.grpc.testing.Void\x1a\x12.grpc.testing.Void2^\n\x18Re\
    portQpsScenarioService\x12B\n\x0eReportScenario\x12\x1c.grpc.testing.Sce\
    narioResult\x1a\x12.grpc.testing.Voidb\x06proto3\
";

static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
    lock: ::protobuf::lazy::ONCE_INIT,
    ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};

fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
    ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}

pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
    unsafe {
        file_descriptor_proto_lazy.get(|| {
            parse_descriptor_proto()
        })
    }
}

pub use super::services_grpc::*;


text:
"use strict";

/**
 *
 */
function Ship() {
	Enemy.call(this);

	this._firingTimer = new Timer();

	this._up_anim = g_assets.getAnimation('enemy-ship-up');
	this._down_anim = g_assets.getAnimation('enemy-ship-down');
	this._up_framerate = this._up_anim.getFramerate();
	this._down_framerate = this._down_anim.getFramerate();
	this._up_anim.setLooping(true).play();
	this._down_anim.setLooping(true).play();
	this._sprite = new Sprite(this._up_anim);

	// Debug draw hack
	if(g_config.global.debug) {
		var that = this;
		var debug_draw = function(canvas,context,matrix) {
			Sprite.prototype.draw.call(this,canvas,context,matrix);

			// Undo rotation for correct display of lines
			matrix.rotate(this.getRotation() * DEG_TO_RAD);
			matrix.applyTo(context);

			var scale = 1.0 / this.getScale();

			context.beginPath();
			context.strokeStyle = "rgba(255,255,255,1)";
			context.arc(0, 0, that.getAttackRadius() * scale, 0, Math.PI * 2, true);
			context.stroke();

			if(that._currentTarget) {
				var tx = that._currentTarget.x - this._x;
				var ty = that._currentTarget.y - this._y;
				context.strokeStyle = "rgba(255,64,64,1)";
				context.beginPath();
				context.moveTo(0,0);
				context.lineTo(tx * scale,ty * scale);
				context.stroke();
				context.beginPath();
				context.arc(tx * scale,ty * scale,that.getAccuracy() * scale,0,Math.PI * 2,true);
				context.stroke();
			}

			that.debug_drawWaypoints(context,this._x,this._y,scale);

		};

		this._sprite.draw = debug_draw;
	}

	this._sprite.setScale(g_config.enemies.ship.scale);
	this._sprite.setOffset(0,0);

	// Set hit rectangle size
	this.setHitRectSize(this._sprite.getWidth(),this._sprite.getHeight());
	this.setHitOffset(-this._sprite.getWidth() * 0.5,-this._sprite.getHeight() * 0.5);

	this._direction = 0;
	this._currentTarget = null;

	this._sound_destroy = g_assets.getSound('destroyShip');

	this.setScoreValue(g_config.enemies.ship.score);
	this.setHitpoints(g_config.enemies.ship.health);
	this.setAccuracy(g_config.enemies.ship.accuracy);
	this.setShotDamage(g_config.enemies.ship.damage.value);
	this.setShotDamageVariance(g_config.enemies.ship.damage.variance);
	this.setAttackRadius(g_config.enemies.ship.range);

	this._sound_shoot = g_assets.getSound('enemyCannonFire');

	this.setActive(false);
};

Ship.inherits(Enemy);

/**
 * Get a direct reference to the ship sprite
 *
 */
Ship.prototype.getSprite = function() {
	return this._sprite;
};

Ship.prototype.isReady = function() {
	return !this.isActive();
};

/**
 * We assume all levels are top-to-bottom, and provide minimum and maximum
 * X coordinate for the water area.
 *
 */
Ship.prototype.spawn = function() {

	// Reset params
	this.setHitpoints(g_config.enemies.ship.health);
	this.setAccuracy(g_config.enemies.ship.accuracy);
	this.setShotDamage(g_config.enemies.ship.damage.value);
	this.setSpeed(Math.rand(g_config.enemies.ship.speed.min,g_config.enemies.ship.speed.max));
	this._firingTimer.setTarget(g_config.enemies.ship.reloadTime).reset().addTime(Math.random() * -1.5).start();

	var gsizex = g_game.getGridSizeX();
	var gsizey = g_game.getGridSizeY();

	var water_min_gx = g_game.getMap().getWaterVerticalMin() + 1;
	var water_max_gx = g_game.getMap().getWaterVerticalMax();

	var gx  = Math.rand(water_min_gx,water_max_gx);
	var step = 4; // One waypoint every 4 grid tiles

	this.clearWaypoints();

	// Decide whether to build a path from up to down or from down to up
	if(Math.random() >= 0.5) {

		var gy0 = g_game.getLevelHeight() + (((this._sprite.getHeight() / g_game.getGridSizeY()) + 1) | 0);
		var gy1 = -(((this._sprite.getHeight() / g_game.getGridSizeY()) + 1) | 0);

		this._direction = 0;

		// Build path from down to up
		for(var gy = gy0; gy >= gy1; gy -= step) {
			var move_chance = Math.random();
			if(gx > water_min_gx) {

				// Magic chance values ftw (:E)
				if(move_chance > 0.6) {
					gx--;
				} else if(move_chance > 0.225) {
					// nothing
				} else {
					gx++;
				}

			} else {
				var move_chance = Math.random();
				if(gx > water_min_gx) {

					// Magic chance values ftw (:E)
					if(move_chance > 0.6) {
						gx++;
					} else if(move_chance > 0.225) {
						// nothing
					} else {
						gx--;
					}
				}
			}

			this.addWaypoint(gx * gsizex + (gsizex * 0.5),gy * gsizey + (gsizey * 0.5));
		}

		this._sprite.setImageSource(this._up_anim);

	} else {

		var gy0 = -(((this._sprite.getHeight() / g_game.getGridSizeY()) + 1) | 0);
		var gy1 = g_game.getLevelHeight() + (((this._sprite.getHeight() / g_game.getGridSizeY()) + 1) | 0);

		this._direction = 1;

		// Build path from up to down
		for(var gy = gy0; gy <= gy1; gy += step) {
			var move_chance = Math.random();
			if(gx > water_min_gx) {

				// Magic chance values ftw (:E)
				if(move_chance > 0.6) {
					gx--;
				} else if(move_chance > 0.225) {
					// nothing
				} else {
					gx++;
				}

			} else {
				var move_chance = Math.random();
				if(gx > water_min_gx) {

					// Magic chance values ftw (:E)
					if(move_chance > 0.6) {
						gx++;
					} else if(move_chance > 0.225) {
						// nothing
					} else {
						gx--;
					}
				}
			}
			this.addWaypoint(gx * gsizex + (gsizex * 0.5),gy * gsizey + (gsizey * 0.5));
		}

		this._sprite.setImageSource(this._down_anim);
	}

	this.moveToFirstWaypoint();
	this.setActive(true);
	this.update(0);

};

/**
 * Overridden update function. Will be called
 * from Engine update loop.
 */
Ship.prototype.update = function(sync) {
	if(this.isActive()) {

		this._up_anim.update(sync);
		this._down_anim.update(sync);

		this._firingTimer.update(sync);

		//var sw = this._sprite.getWidth();
		var sh = this._sprite.getHeight();

		this.moveForward(sync,this._sprite);
		var x = this.getX();
		var y = this.getY();

		// Make ship face the next waypoint
		if(this._direction) {
			this._sprite.setRotation(Math.atan2(this.getNextWaypointY() - y,this.getNextWaypointX() - x) * RAD_TO_DEG - 90);
		} else {
			this._sprite.setRotation(90 + Math.atan2(this.getNextWaypointY() - y,this.getNextWaypointX() - x) * RAD_TO_DEG);
		}

		// See if we're ready to shoot...
		if(this._firingTimer.isComplete()) {

			if(y > sh && y < (g_game.getLevelHeight() * g_game.getGridSizeY())) {

				// Find something to shoot at
				var target = g_game.getWalls().getRandomWallCoordinates();
				if(target) {
					var dx = target.x - x;
					var dy = target.y - y;
					var dr = this.getAttackRadius();
					if(Math.sqrt((dx * dx) + (dy * dy)) <= dr ) {

						this._currentTarget = target;

						// Target is non-null only if there's something left to shoot...
						target = this.getImpactCoordinates(target.x,target.y);

						// Actually shoot it..
						var bullet;
						if(Math.random() < g_game.getCowProbability()){
							bullet = g_game.getCowBullet();
						}else{
							bullet = g_game.getBullet();
						}
						bullet.shoot(this,this._sprite.getX(),this._sprite.getY(),target.x,target.y,350);
						this._firingTimer.reset().addTime(Math.random() * -1.5).start();
						this._sound_shoot.play();
					} else {
						this._currentTarget = null;
					}
				} else {
					this._currentTarget = null;
				}
			}
		}

		if(!this.hasWaypoints()) this.remove();
	}
};

/**
 * Process a potential hit by a bullet at x,y
 */
Ship.prototype.processHit = function(bullet, x, y) {

	if(this.testHit(this._sprite.getX(),this._sprite.getY(),x,y,bullet.getRadius())) {
		this.gotHitByBullet(bullet);
		return true;
	}

	return false;
};

/**
 * Remove the ship from the playing area. Also mark the Ship as inactive.
 *
 */
Ship.prototype.remove = function() {
	g_game.removeEnemy(this);
	this._sprite.removeFromParent();
	this.setActive(false);
	this._currentTarget = null;
};

/**
 * Destruction function.
 */
Ship.prototype.destroy = function() {

	this._sprite.removeFromParent();
	this.setActive(false);

	var w = this._sprite.getWidth();
	var h = this._sprite.getHeight();

	for(var i = 0; i < 9; ++i) {
		var x = (Math.random() * w) + this._sprite.getX() - (w * 0.5);
		var y = (Math.random() * h) + this._sprite.getY() - (h * 0.5);
		g_game.createExplosion(x,y);
	}

	g_game.removeEnemy(this);
	g_game.addScore(this.getScoreValue());
	g_game.createScoreMarker(this._sprite.getX(),this._sprite.getY(),this.getScoreValue());

	this._sound_destroy.play();

};


text:
codesake is a security source code scanning engine. It's used as core engine in
[codesake.com](http://codesake.cokm) application security portal with a closed
knowledge base inside the web application itself.

codesake gem can be used in a security source code review to scan sources with
regular expressions in order to detect insecure software patterns.

## Installation

Add this line to your application's Gemfile:

    gem 'codesake'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install codesake

## Usage

To run codesake over a single file or a directory you simply specify the target
name as parameter on command line.

If you want to review a ruby source file named file1.rb, your command line will
be:

  $ codesake file1.rb

## Known limitations

Known limitation for version 0.1x are:

* Only JSP, Plain text files are analysed
* If target is a directory or a glob file expression codesake will understand
  it but it doesn't expand the file list
* codesake will use only stdout, stderr for output purposes

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.netflix.spinnaker.kork.retrofit;

import com.netflix.spinnaker.config.okhttp3.OkHttpClientProvider;
import com.netflix.spinnaker.kork.client.ServiceClientFactory;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

@Configuration
@ConditionalOnProperty(value = "retrofit2.enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(Retrofit2ConfigurationProperties.class)
public class Retrofit2ServiceFactoryAutoConfiguration {

  @Bean
  @Order(Ordered.LOWEST_PRECEDENCE - 1)
  ServiceClientFactory serviceClientFactory2(OkHttpClientProvider clientProvider) {
    return new Retrofit2ServiceFactory(clientProvider);
  }

  @Bean
  @ConditionalOnMissingBean
  HttpLoggingInterceptor httpLoggingInterceptor(
      Retrofit2ConfigurationProperties retrofit2ConfigurationProperties) {
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(retrofit2ConfigurationProperties.getLogLevel());
    return httpLoggingInterceptor;
  }
}


text:
/* eslint-disable import/export */
import {Encoding as CryptoEncoding} from 'crypto';
import {LiteralUnion} from 'type-fest';

export type Encoding = CryptoEncoding | 'buffer';
export type Algorithm = LiteralUnion<'md5' | 'sha1' | 'sha256' | 'sha512', string>;

export interface Options {
	/**
	Encoding of the returned hash.

	@default 'hex'
	*/
	readonly encoding?: Encoding;

	/**
	_Don't use `'md5'` or `'sha1'` for anything sensitive. [They're insecure.](http://googleonlinesecurity.blogspot.no/2014/09/gradually-sunsetting-sha-1.html)_

	@default 'sha512'
	*/
	readonly algorithm?: Algorithm;
}

export interface BufferOptions extends Options {
	readonly encoding: 'buffer';
}

/**
Get the hash of an object.

@example
```
import hashObject from 'hash-obj';

hashObject({'🦄': '🌈'}, {algorithm: 'sha1'});
//=> '3de3bc784035b559784fc276f47493d60555fba3'
```
*/
export default function hashObject(
	object: Record<string, any>,
	options: BufferOptions
): Buffer;
export default function hashObject(
	object: Record<string, any>,
	options?: Options
): string;


text:
SET NAMES 'utf8';

ALTER TABLE `PREFIX_order_invoice_tax` ADD INDEX (`id_tax`);

INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'product', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'product');
INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'category', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'category');
INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'cms', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'cms');
INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'products-comparison', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'products-comparison');
INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'module-bankwire-payment', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'module-bankwire-payment');
INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'module-bankwire-validation', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'module-bankwire-validation');
INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'module-cheque-validation', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'module-cheque-validation');
INSERT INTO `PREFIX_meta` (`page`, `configurable`) SELECT * FROM (SELECT 'module-cheque-payment', '0') AS tmp WHERE NOT EXISTS (SELECT `page` FROM `PREFIX_meta` WHERE `page` = 'module-cheque-payment');

INSERT IGNORE INTO `PREFIX_theme_meta` ( `id_theme` , `id_meta` , `left_column` , `right_column` )
  SELECT `PREFIX_theme`.`id_theme` , `PREFIX_meta`.`id_meta` , `default_left_column` , `default_right_column`
  FROM `PREFIX_theme` , `PREFIX_meta`;

ALTER TABLE `PREFIX_tab` ADD `hide_host_mode` tinyint(1) NOT NULL DEFAULT '0' AFTER  `active`;

UPDATE `PREFIX_employee` SET `bo_theme` = 'default';

DELETE FROM `PREFIX_image_type` WHERE `name` = 'cart_default';

INSERT INTO `PREFIX_image_type` (`id_image_type`,`name`,`width`,`height`,`products`,`categories`,`manufacturers`,`suppliers`,`scenes`,`stores`)
VALUES (NULL, 'cart_default', '80', '80', '1', '0', '0', '0', '0', '0');

ALTER TABLE `PREFIX_cart_rule_combination` ADD INDEX `id_cart_rule_1` (`id_cart_rule_1`);
ALTER TABLE `PREFIX_cart_rule_combination` ADD INDEX `id_cart_rule_2` (`id_cart_rule_2`);

/* PHP:p1606module_exceptions(); */;


text: Moved to https://github.com/Homebrew/brew/blob/master/share/doc/homebrew/Brew-Test-Bot.md.


text:
void MainMenuState::enter(ScreenActor & screen)
{
	ScreenState::enter(screen);

	knowCommands["mail"] = Command::mail;
	knowCommands["Mail"] = Command::mail;
    knowCommands["Game"] = Command::mail;
    knowCommands["game"] = Command::mail;
    knowCommands["start"] = Command::mail;
    knowCommands["Start"] = Command::mail;
    knowCommands["Logout"] = Command::logout;
    knowCommands["logout"] = Command::logout;
    knowCommands["music"] = Command::music;

    Login* login = dynamic_cast<Login*>(Command::login);
    screen.addText("Welcome " + login->currentUser);
    screen.addText("Type *sgame*e to start playing");
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0.1 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Flyweight Documentation - Tutorial - Key-value flyweights</title>
<link rel="stylesheet" href="../style.css" type="text/css">
<link rel="start" href="../index.html">
<link rel="prev" href="basics.html">
<link rel="up" href="index.html">
<link rel="next" href="configuration.html">

Boost.Flyweight Tutorial: Key-value flyweights

Basics

Boost.Flyweight tutorial

Configuring Boost.Flyweight

Contents

Key-value flyweights

Key extractors

Type requirements

Key-value flyweights

Continuing with our online game example, suppose we have a huge class for
handling rendering textures:

class texture
{
public:
  texture(const std::string& filename){/* loads texture file */}

  const std::string& get_filename()const;

  // rest of the interface
};

and we decide to use flyweight<texture> to ease the
manipulation of these objects. Now consider this seemingly innocent
expression:

flyweight<texture> fw("grass.texture");

Note that in order to construct fw we are implicitly
constructing a full grass texture object. The expression is mostly
equivalent to

flyweight<texture> fw(texture("grass.texture"));

This is unnaceptably costly: we are constructing a massive temporary
object just to throw it away in most cases, since Boost.Flyweight most
likely already has an internal equivalent object to which fw
will be bound --value sharing is the key feature behind the flyweight
pattern after all. In this particular example, texture filenames act
as a key to the actual texture objects: two texture objects
constructed from the same filename are equivalent. So, we would like
for filenames to be used for texture lookup and somehow be sure that
the costly texture construction is only performed when no equivalent
value has been found.

flyweight<T> makes this distinction between key and value
blurry because it uses T both as the key type and
its associated value type. When this is inefficient, as in our texture
example, we can explicity specify both types using the
key_value
construct:

#include <boost/flyweight.hpp>
#include <boost/flyweight/key_value.hpp>
...
flyweight<key_value<std::string,texture> > fw("grass.texture");

So called key-value flyweights have then the form
flyweight<key_value<K,T> >: the key type K is
used to do the internal lookup for the associated values of type T. Key-value
flyweights guarantee that T values are not constructed except when
no other equivalent value exists; such construction is done from the associated
K value.

Key extractors

Besides the key-based semantics on construction time, key-value flyweights
behave much the same as regular flyweights, although some differences persist.
Consider the following code, which poses no problems with regular
flyweights:

const texture& get_texture(const object&);
...
flyweight<key_value<std::string,texture> > fw;
...
fw=get_texture(obj);

The assignment cannot possibly work, because a key of type std::string
is needed to do the internal lookup whereas we are passing a full texture object.
Indeed, the code produces a compilation error similar to this:

error: 'boost::mpl::assertion_failed' : cannot convert parameter 1 from
'boost::mpl::failed ************(__thiscall boost::flyweights::detail::
regular_key_value<Key,Value>::rep_type::no_key_from_value_failure::
NO_KEY_FROM_VALUE_CONVERSION_PROVIDED::* ***********)(std::string,texture)'
to 'boost::mpl::assert<false>::type'...

It turns out that we can make the assignment work if only we provide a means
to retrieve the key from the value. This is not always possible, but in
our particular example the texture class does store the filename used for
construction, as indicated by the texture::get_filename
member function. We take advantage of this by specifying a
suitable key
extractor as part of the flyweight type definition:

struct texture_filename_extractor
{
  const std::string& operator()(const texture& x)const
  {
    return x.get_filename();
  }
};

flyweight<key_value<std::string,texture,texture_filename_extractor> > fw;
...
fw=get_texture(obj); // OK now

The specification of a key extractor in the
definition of a key-value flyweight results in internal space optimizations,
as the keys need not be stored along the values but are retrieved from
them instead. So, it is always a good idea to provide a key extractor when
possible even if your program does not contain assignment statements like
the one above.

Examples 2 and
5
of the examples section make use of key-value flyweights.

Type requirements

Many of the requirements imposed on T for
regular flyweights move to the key
type in the case of a key-value flyweight<key_value<K,T> >.
Now it is K that must be
Assignable,
Equality
Comparable and interoperate with
Boost.Hash, where equality and
hash compatibility are requirements imposed by the default internal factory of
Boost.Flyweight and can change if this factory is further configured or replaced
by the user. The only requisite retained on T is that it must be
constructible from K; only in the case that a flyweight is directly
assigned a T object is also T required to be
Assignable.

Basics

Boost.Flyweight tutorial

Configuring Boost.Flyweight

Revised February 21st 2009

© Copyright 2006-2009 Joaquín M López Muñoz.
Distributed under the Boost Software
License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)


text:
<?php

namespace Database\Seeders\Users;

use App\Models\Permission;
use App\Models\Role;
use Illuminate\Database\Seeder;

class RoleTableSeeder extends Seeder
{
    /**
     * @var array|\Illuminate\Support\Collection
     */
    public $roles = [
        ['name' => 'Administrator'],
        ['name' => 'User'],
    ];

    /**
     * @var array|\Illuminate\Support\Collection
     */
    public $permissions = [
        'users' => [
            ['name' => 'List users'],
            ['name' => 'Create users'],
            ['name' => 'Delete users'],
            ['name' => 'Update users'],
        ],
        'roles' => [
            ['name' => 'List roles'],
            ['name' => 'Create roles'],
            ['name' => 'Delete roles'],
            ['name' => 'Update roles'],
        ],
        'permissions' => [
            ['name' => 'List permissions'],
        ],
    ];

    /**
     * Run the database seeders.
     *
     * @return void
     */
    public function run()
    {
        $this->createRoles()->createPermissions()->assignAllPermissionsToAdminRole();
    }

    /**
     * @return $this
     */
    public function createRoles()
    {
        $this->roles = collect($this->roles)->map(function ($role) {
            return Role::create($role);
        });

        return $this;
    }

    /**
     * @return $this
     */
    public function createPermissions()
    {
        $this->permissions = collect($this->permissions)->map(function ($group) {
            return collect($group)->map(function ($permission) {
                return Permission::create($permission);
            });
        });

        return $this;
    }

    /**
     * @return $this
     */
    public function assignAllPermissionsToAdminRole()
    {
        $role = Role::where('name', 'Administrator')->firstOrFail();
        $this->permissions->flatten()->each(function ($permission) use ($role) {
            $role->givePermissionTo($permission);
        });

        return $this;
    }
}


text:
using Models.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Tournaments.Models;
using Tournaments.Models_project;
using Tournaments.Presenters;
using Tournaments.Views;
using WebFormsMvp;
using WebFormsMvp.Web;

namespace Tournaments
{
    [PresenterBinding(typeof(PlayerPresenter))]
    public partial class PlayerManager : MvpPage<PlayerViewModel>, IPlayerView
    {
        public event EventHandler MyInit;
        public event EventHandler OnGetData;
        public event EventHandler OnInsertItem;
        public event EventHandler<IdEventArgs> OnDeleteItem;
        public event EventHandler<IdEventArgs> OnUpdateItem;
        public event EventHandler<GenericEventArgs<Player>> SendPlayer;

        protected void Page_Load(object sender, EventArgs e)
        {
            //Change String.Empty with the role if needed
            this.EnableGridViewButtions(this.GridViewPlayers, String.Empty);
        }

        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression

        public IQueryable<Player> GridViewPlayers_GetData()
        {
            this.OnGetData?.Invoke(this, null);

            return this.Model.Players.AsQueryable();
        }

        public void GridViewPlayers_InsertItem()
        {
            this.OnInsertItem?.Invoke(this, null);
        }

        // The id parameter name should match the DataKeyNames value set on the control
        public void GridViewTeams_DeleteItem(int? id)
        {

            this.OnDeleteItem?.Invoke(this, new IdEventArgs(id));
        }

        // The id parameter name should match the DataKeyNames value set on the control
        public void GridViewPlayers_UpdateItem(int? id)
        {
            this.OnUpdateItem?.Invoke(this, new IdEventArgs(id));
        }

        private void EnableGridViewButtions(GridView view, string role)
        {
            //if the role is needed, just add ViewContext.HttpContext.User.IsInRole("Your role")
            bool isLoggedIn = (HttpContext.Current.User != null) &&
                HttpContext.Current.User.Identity.IsAuthenticated;

            if (isLoggedIn)
            {
                view.AutoGenerateEditButton = true;
                view.AutoGenerateDeleteButton = true;
            }
        }
    }
}


text:
id co_tupleSentinel() {
    static id sentin;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sentin = [[NSObject alloc] init];
    });
    return sentin;
}

#ifdef DEBUG

int co_tuple_dealloc_count = 0;
int co_untuple_dealloc_count = 0;

#endif

void** co_unpackSentinel(){
    static id sentin;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sentin = [[NSObject alloc] init];
    });
    return (void**)&sentin;
}

@implementation COTuple
{
    NSPointerArray* storage;
}

- (NSPointerArray*)_storage {
    return storage;
}
- (void)_setStorage:(NSPointerArray*)newstorage {
    storage = newstorage;
}

- (int)count {
    return (int)storage.count;
}

// Initialization
- (id)init {
    self = [super init];
    if (!self)
        return nil;

    storage = [[NSPointerArray alloc] initWithOptions:NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPersonality];

    return self;
}
- (id)initWithArray:(NSArray*)arr {
    self = [self init];
    if (!self)
        return nil;

    for (id obj in arr) {
        [storage addPointer:arc_bridge(void*, obj)];
    }

    return self;
}
- (id)initWithObjects:(id)objects, ... {
    self = [self init];
    if (!self)
        return nil;

    va_list ap;
    va_start(ap, objects);

    id obj = objects;
    id sentin = co_tupleSentinel();
    while (obj != sentin) {
        [storage addPointer:arc_bridge(void*, obj)];
        obj = va_arg(ap, id);
    }
    va_end(ap);

    return self;
}

// Protocolic Obligations
//- (id)copyWithZone:(NSZone *)zone {
//    id newtup = [[[self class] alloc] init];
//    [newtup _setStorage:[[self _storage] copy]];
//    return newtup;
//}
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id arc_unsafe_unretained [])stackbuf count:(NSUInteger)len {
    return [storage countByEnumeratingWithState:state objects:stackbuf count:len];
}

// Getting an object at an index
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
    return [self objectAtIndex:(int)idx];
}
- (id)objectAtIndex:(int)idx {
    if (idx < 0 || idx >= (int)[storage count])
        return nil;
    return (__strong id)[storage pointerAtIndex:idx];
}

- (id)first {
    return [self objectAtIndex:0];
}
- (id)second {
    return [self objectAtIndex:1];
}
- (id)third {
    return [self objectAtIndex:2];
}

// Unpacking
- (void)unpack:(id*)pointypointers, ... {

    va_list ap;
    va_start(ap, pointypointers);

    arc_autoreleasing id* pp = pointypointers;
    int i = 0;
    while (pp != NULL) {
        *pp = [self objectAtIndex:i];

        pp = va_arg(ap, arc_autoreleasing id*);
        i++;
    }
    va_end(ap);

}

- (void)dealloc
{
    if (storage) {
        [storage release];
        storage = nil;
    }
#ifdef DEBUG

    co_tuple_dealloc_count++;

#endif
    [super dealloc];
}

@end

@implementation COTupleUnpack{
    NSMutableArray *storage;
}

@synthesize tuple = _tuple;

- (void)setTuple:(COTuple *)tuple{
    NSAssert([tuple isKindOfClass:[COTuple class]], @"tuple must be COTuple");
    if (tuple == NULL) {
        return;
    }
    if (![tuple isKindOfClass:[COTuple class]]) {
        return;
    }
    _tuple = [tuple retain];
    int index = 0;
    for (NSNumber *number in storage) {
        if (index >= [tuple count]) {
            break;
        }
        uintptr_t p = [number unsignedLongValue];
        if (p > 0) {
            __autoreleasing id* pointer = (id*)p;

            *pointer = [[tuple objectAtIndex:index] retain];
        }

        index++;
    }
#ifdef DEBUG
    for (NSNumber *number in storage) {

        uintptr_t p = [number unsignedLongValue];
        if (p > 0) {
            __autoreleasing id* pointer = (id*)p;

            NSLog(@"%@", *pointer);
        }

    }
#endif

}

- (instancetype)initWithPointers:(int)startIndex, ...{
    self = [super init];
    if (self) {
        storage = [[NSMutableArray alloc] init];
        va_list ap;
        va_start(ap, startIndex);

        if (startIndex <= 0) {
            startIndex = 0;
        }
        int i = 0;
        id* sentin = (id*)co_unpackSentinel();

        do {
            arc_autoreleasing id* pp = va_arg(ap, arc_autoreleasing id*);
            if (pp == sentin) {
                break;
            }
            if (i >= startIndex) {
                uintptr_t pointer = (uintptr_t)pp;
                [storage addObject:@(pointer)];
            }
            i++;

        } while (1);
        va_end(ap);
    }
    return self;
}

- (void)dealloc{
    [storage removeAllObjects];
    storage = nil;
    if (_tuple) {
        [_tuple release];
        _tuple = nil;
    }
#ifdef DEBUG

    co_untuple_dealloc_count++;

#endif
    [super dealloc];
}

@end

@implementation COTuple1

@end

@implementation COTuple2

@end

@implementation COTuple3

@end

@implementation COTuple4

@end

@implementation COTuple5

@end

@implementation COTuple6

@end

@implementation COTuple7

@end

@implementation COTuple8

@end


text:
using Kudu.Services.Infrastructure;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;

namespace SimpleWAWS.Models
{
    public static class MobileHelper
    {
        public static PushStreamContent CreateClientZip(MobileClientPlatform platform, string templateName, Dictionary<string, string> replacements)
        {
            var clientPath = HostingEnvironment.MapPath(string.Format(CultureInfo.InvariantCulture, "~/App_Data/MobileClientApp/{0}/{1}", templateName, platform.ToString()));
            return CreateZip(string.Format(CultureInfo.InvariantCulture, "{0}.zip", platform.ToString()), zip =>
            {
                foreach (var fileName in Directory.GetFiles(clientPath, "*", SearchOption.AllDirectories))
                {
                    var replacedFileName = fileName;

                    if (string.IsNullOrEmpty(Path.GetExtension(fileName)) ||
                        new[] { ".png", ".jpg", ".keystore", ".exe", ".dll", ".sketch" }
                        .Any(ext => ext.Equals(Path.GetExtension(fileName), StringComparison.OrdinalIgnoreCase)))
                    {
                        foreach (var pair in replacements)
                        {
                            replacedFileName = replacedFileName.Replace(pair.Key, pair.Value);
                        }

                        zip.AddFile(fileName, replacedFileName, clientPath);
                    }
                    else
                    {
                        var fileEncoding = GetEncoding(fileName);
                        var content = File.ReadAllText(fileName, fileEncoding);
                        foreach (var pair in replacements)
                        {
                            content = content.Replace(pair.Key, pair.Value);
                            replacedFileName = replacedFileName.Replace(pair.Key, pair.Value);
                        }

                        using (var contentStream = content.AsStream(fileEncoding))
                        {
                            zip.AddFile(replacedFileName, clientPath, contentStream);
                        }
                    }
                }
            });
       }

        /// <summary>
        /// http://stackoverflow.com/a/19283954
        /// Determines a text file's encoding by analyzing its byte order mark (BOM).
        /// Defaults to ASCII when detection of the text file's endianness fails.
        /// </summary>
        /// <param name="filename">The text file to analyze.</param>
        /// <returns>The detected encoding.</returns>
        private static Encoding GetEncoding(string filename)
        {
            // Read the BOM
            var bom = new byte[4];
            using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                file.Read(bom, 0, 4);
            }

            // Analyze the BOM
            if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
            if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
            if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
            if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
            if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;
            return Encoding.ASCII;
        }

        private static PushStreamContent CreateZip(string fileName, Action<ZipArchive> onZip)
        {
            var content = new PushStreamContent((outputStream, httpContent, transportContext) =>
            {
                using (var zip = new ZipArchive(new StreamWrapper(outputStream), ZipArchiveMode.Create, leaveOpen: false))
                {
                    onZip(zip);
                }
            });
            content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            content.Headers.ContentDisposition.FileName = fileName;
            return content;
        }
    }
}


text:
using System;
using System.Runtime;

namespace System.Diagnostics
{
    public static class StackFrameExtensions
    {
        /// <summary>
        /// Return load address of the native image pointed to by the stack frame.
        /// </summary>
        public static IntPtr GetNativeImageBase(this StackFrame stackFrame)
        {
            return RuntimeImports.RhGetOSModuleFromPointer(stackFrame.GetNativeIPAddress());
        }

        /// <summary>
        /// Return stack frame native IP address.
        /// </summary>
        public static IntPtr GetNativeIP(this StackFrame stackFrame)
        {
            return stackFrame.GetNativeIPAddress();
        }

        /// <summary>
        /// Return true when the stack frame information can be converted to IL offset information
        /// within the MSIL method body.
        /// </summary>
        public static bool HasILOffset(this StackFrame stackFrame)
        {
            return stackFrame.GetILOffset() != StackFrame.OFFSET_UNKNOWN;
        }

        /// <summary>
        /// Return true when a MethodBase reflection info is available for the stack frame
        /// </summary>
        public static bool HasMethod(this StackFrame stackFrame)
        {
            return stackFrame.HasMethod();
        }

        /// <summary>
        /// Return true when the stack frame information corresponds to a native image
        /// </summary>
        public static bool HasNativeImage(this StackFrame stackFrame)
        {
            // In .NET Native, everything has a native image (at least today)
            return true;
        }

        /// <summary>
        /// Return true when stack frame information supports source file / line information lookup
        /// </summary>
        public static bool HasSource(this StackFrame stackFrame)
        {
            return stackFrame.GetFileName() != null;
        }
    }
}


text:
angular.module('userController', ['userService'])

.controller('UserController', function(User) {
    var vm = this;
    User.all()
        .success(function(data) {
            vm.users = data;
        })
})
.controller('UserCreateController', function(User, $location, $window, toastr) {
    vm = this;
    vm.signupUser = function() {
        vm.message = '';
        User.create(vm.userData)
            .then(function(response) {
                vm.userData = {};
                vm.message = response.data.message;
                //Need set the token since this is separate from Auth
                $window.localStorage.setItem('token', response.data.token);
                $location.path('/');
                toastr.success('Welcome to Mean-Library!')
            })
    }
});


text:
[![Build Status](https://travis-ci.com/grrr-amsterdam/garp3.svg?branch=master)](https://travis-ci.com/grrr-amsterdam/garp3)

# Garp 3

Garp is a flexible opensource PHP and frontend framework and CMS.

## Developed with ❤ by [GRRR](https://grrr.nl)

- GRRR is a [B Corp](https://grrr.nl/en/b-corp/)
- GRRR has a [tech blog](https://grrr.tech/)
- GRRR is [hiring](https://grrr.nl/en/jobs/)
- [@GRRRTech](https://twitter.com/grrrtech) tweets

## Getting started

The easiest way to get setup is by creating a new project using Composer and the [Garp3
Scaffold](https://github.com/grrr-amsterdam/garp_scaffold):

```bash
composer create-project grrr-amsterdam/garp3-scaffold <your-target-directory>
```

See the Garp3 scaffold readme for more information on building assets and such.

[Check out our wonderful wiki](https://github.com/grrr-amsterdam/garp3/wiki) for answers to all
Garp-related questions.


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Diagnostics;
using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
    /// <summary>
    /// The representation of a project to both the project factory and workspace API.
    /// </summary>
    /// <remarks>
    /// Due to the number of interfaces this object must implement, all interface implementations
    /// are in a separate files. Methods that are shared across multiple interfaces (which are
    /// effectively methods that just QI from one interface to another), are implemented here.
    /// </remarks>
    [ExcludeFromCodeCoverage]
    internal abstract partial class CSharpProjectShim : CSharpProject
    {
        /// <summary>
        /// This member is used to store a raw array of warning numbers, which is needed to properly implement
        /// ICSCompilerConfig.GetWarnNumbers. Read the implementation of that function for more details.
        /// </summary>
        private readonly IntPtr _warningNumberArrayPointer;

        private ICSharpProjectRoot _projectRoot;

        private OutputKind _outputKind = OutputKind.DynamicallyLinkedLibrary;
        private Platform _platform = Platform.AnyCpu;
        private string _mainTypeName;
        private object[] _options = new object[(int)CompilerOptions.LARGEST_OPTION_ID];

        public CSharpProjectShim(
            ICSharpProjectRoot projectRoot,
            VisualStudioProjectTracker projectTracker,
            Func<ProjectId, IVsReportExternalErrors> reportExternalErrorCreatorOpt,
            string projectSystemName,
            IVsHierarchy hierarchy,
            IServiceProvider serviceProvider,
            MiscellaneousFilesWorkspace miscellaneousFilesWorkspaceOpt,
            VisualStudioWorkspaceImpl visualStudioWorkspaceOpt,
            HostDiagnosticUpdateSource hostDiagnosticUpdateSourceOpt)
            : base(projectTracker,
                   reportExternalErrorCreatorOpt,
                   projectSystemName,
                   hierarchy,
                   serviceProvider,
                   miscellaneousFilesWorkspaceOpt,
                   visualStudioWorkspaceOpt,
                   hostDiagnosticUpdateSourceOpt)
        {
            _projectRoot = projectRoot;
            _warningNumberArrayPointer = Marshal.AllocHGlobal(0);
        }

        protected override void InitializeOptions()
        {
            // Ensure the default options are set up
            ResetAllOptions();

            base.InitializeOptions();
        }

        public override void Disconnect()
        {
            _projectRoot = null;

            base.Disconnect();
        }

        private string GetIdForErrorCode(int errorCode)
        {
            return "CS" + errorCode.ToString("0000");
        }

        protected override CSharpCompilationOptions CreateCompilationOptions()
        {
            IDictionary<string, ReportDiagnostic> warningOptions = null;

            // Get options from the ruleset file, if any, first. That way project-specific
            // options can override them.
            ReportDiagnostic? ruleSetGeneralDiagnosticOption = null;
            if (this.ruleSet != null)
            {
                ruleSetGeneralDiagnosticOption = this.ruleSet.GetGeneralDiagnosticOption();
                warningOptions = new Dictionary<string, ReportDiagnostic>(this.ruleSet.GetSpecificDiagnosticOptions());
            }
            else
            {
                warningOptions = new Dictionary<string, ReportDiagnostic>();
            }

            UpdateRuleSetError(ruleSet);

            UpdateWarning(warningOptions, CompilerOptions.OPTID_WARNASERRORLIST, ReportDiagnostic.Error);
            UpdateWarning(warningOptions, CompilerOptions.OPTID_WARNNOTASERRORLIST, ReportDiagnostic.Warn);

            // Add the warning supressions second, since the if a warning appears in both lists the
            // supression takes priority
            UpdateWarning(warningOptions, CompilerOptions.OPTID_NOWARNLIST, ReportDiagnostic.Suppress);

            Platform platform;

            if (!Enum.TryParse(GetStringOption(CompilerOptions.OPTID_PLATFORM, ""), ignoreCase: true, result: out platform))
            {
                platform = Platform.AnyCpu;
            }

            int warningLevel;

            if (!int.TryParse(GetStringOption(CompilerOptions.OPTID_WARNINGLEVEL, defaultValue: ""), out warningLevel))
            {
                warningLevel = 4;
            }

            string projectDirectory = this.ContainingDirectoryPathOpt;

            // TODO: #r support, should it include bin path?
            var referenceSearchPaths = ImmutableArray<string>.Empty;

            // TODO: #load support
            var sourceSearchPaths = ImmutableArray<string>.Empty;

            ReportDiagnostic generalDiagnosticOption;
            var warningsAreErrors = GetNullableBooleanOption(CompilerOptions.OPTID_WARNINGSAREERRORS);
            if (warningsAreErrors.HasValue)
            {
                generalDiagnosticOption = warningsAreErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default;
            }
            else if (ruleSetGeneralDiagnosticOption.HasValue)
            {
                generalDiagnosticOption = ruleSetGeneralDiagnosticOption.Value;
            }
            else
            {
                generalDiagnosticOption = ReportDiagnostic.Default;
            }

            MetadataReferenceResolver referenceResolver;
            if (this.Workspace != null)
            {
                referenceResolver = new AssemblyReferenceResolver(
                    new MetadataFileReferenceResolver(referenceSearchPaths, projectDirectory),
                    this.Workspace.CurrentSolution.Services.MetadataService.GetProvider());
            }
            else
            {
                // can only happen in tests
                referenceResolver = null;
            }

            // TODO: appConfigPath: GetFilePathOption(CompilerOptions.OPTID_FUSIONCONFIG), bug #869604
            return new CSharpCompilationOptions(
                allowUnsafe: GetBooleanOption(CompilerOptions.OPTID_UNSAFE),
                checkOverflow: GetBooleanOption(CompilerOptions.OPTID_CHECKED),
                concurrentBuild: false,
                cryptoKeyContainer: GetStringOption(CompilerOptions.OPTID_KEYNAME, defaultValue: null),
                cryptoKeyFile: GetFilePathRelativeOption(CompilerOptions.OPTID_KEYFILE),
                delaySign: GetNullableBooleanOption(CompilerOptions.OPTID_DELAYSIGN),
                generalDiagnosticOption: generalDiagnosticOption,
                mainTypeName: _mainTypeName,
                moduleName: GetStringOption(CompilerOptions.OPTID_MODULEASSEMBLY, defaultValue: null),
                optimizationLevel: GetBooleanOption(CompilerOptions.OPTID_OPTIMIZATIONS) ? OptimizationLevel.Release : OptimizationLevel.Debug,
                outputKind: _outputKind,
                platform: platform,
                specificDiagnosticOptions: warningOptions,
                warningLevel: warningLevel,
                xmlReferenceResolver: new XmlFileResolver(projectDirectory),
                sourceReferenceResolver: new SourceFileResolver(sourceSearchPaths, projectDirectory),
                metadataReferenceResolver: referenceResolver,
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
                strongNameProvider: new DesktopStrongNameProvider(GetStrongNameKeyPaths()));
        }

        private void UpdateWarning(IDictionary<string, ReportDiagnostic> warningOptions, CompilerOptions compilerOptions, ReportDiagnostic reportDiagnostic)
        {
            Contract.ThrowIfFalse(compilerOptions == CompilerOptions.OPTID_NOWARNLIST || compilerOptions == CompilerOptions.OPTID_WARNASERRORLIST || compilerOptions == CompilerOptions.OPTID_WARNNOTASERRORLIST);
            foreach (var warning in GetStringOption(compilerOptions, defaultValue: "").Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                int warningId;
                var warningStringID = warning;
                if (int.TryParse(warning, out warningId))
                {
                    warningStringID = GetIdForErrorCode(warningId);
                }

                warningOptions[warningStringID] = reportDiagnostic;
            }
        }

        private bool? GetNullableBooleanOption(CompilerOptions optionID)
        {
            return (bool?)_options[(int)optionID];
        }

        private bool GetBooleanOption(CompilerOptions optionID)
        {
            return GetNullableBooleanOption(optionID).GetValueOrDefault(defaultValue: false);
        }

        private string GetFilePathRelativeOption(CompilerOptions optionID)
        {
            var path = GetStringOption(optionID, defaultValue: null);

            if (string.IsNullOrEmpty(path))
            {
                return null;
            }

            var directory = this.ContainingDirectoryPathOpt;

            if (!string.IsNullOrEmpty(directory))
            {
                return FileUtilities.ResolveRelativePath(path, directory);
            }

            return null;
        }

        private string GetStringOption(CompilerOptions optionID, string defaultValue)
        {
            string value = (string)_options[(int)optionID];

            if (string.IsNullOrEmpty(value))
            {
                return defaultValue;
            }
            else
            {
                return value;
            }
        }

        protected override CSharpParseOptions CreateParseOptions()
        {
            var symbols = GetStringOption(CompilerOptions.OPTID_CCSYMBOLS, defaultValue: "").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            DocumentationMode documentationMode = DocumentationMode.Parse;
            if (GetStringOption(CompilerOptions.OPTID_XML_DOCFILE, defaultValue: null) != null)
            {
                documentationMode = DocumentationMode.Diagnose;
            }

            var languageVersion = CompilationOptionsConversion.GetLanguageVersion(GetStringOption(CompilerOptions.OPTID_COMPATIBILITY, defaultValue: ""))
                                  ?? CSharpParseOptions.Default.LanguageVersion;

            return new CSharpParseOptions(
                languageVersion: languageVersion,
                preprocessorSymbols: symbols.AsImmutable(),
                documentationMode: documentationMode);
        }

        ~CSharpProjectShim()
        {
            // Free the unmanaged memory we allocated in the constructor
            Marshal.FreeHGlobal(_warningNumberArrayPointer);

            // Free any entry point strings.
            if (_startupClasses != null)
            {
                foreach (var @class in _startupClasses)
                {
                    Marshal.FreeHGlobal(@class);
                }
            }
        }

        internal bool CanCreateFileCodeModelThroughProject(string fileName)
        {
            return _projectRoot.CanCreateFileCodeModel(fileName);
        }

        internal object CreateFileCodeModelThroughProject(string fileName)
        {
            var iid = VSConstants.IID_IUnknown;
            return _projectRoot.CreateFileCodeModel(fileName, ref iid);
        }
    }
}


text:
<?php
namespace Poirot\Std\Interfaces\Pact;

interface ipConfigurable
{
    /**
     * Build Object With Provided Options
     *
     * @param array $options        Associated Array
     * @param bool  $throwException Throw Exception On Wrong Option
     *
     * @return $this
     * @throws \Exception
     * @throws \InvalidArgumentException
     */
    function with(array $options, $throwException = false);

    /**
     * Load Build Options From Given Resource
     *
     * - usually it used in cases that we have to support
     *   more than once configure situation
     *   [code:]
     *     Configurable->with(Configurable::withOf(path\to\file.conf))
     *   [code]
     *
     * !! With this The classes that extend this abstract have to
     *    implement desired parse methods
     *
     * @param array|mixed $optionsResource
     * @param array       $_
     *        usually pass as argument into ::with if self instanced
     *
     * @throws \InvalidArgumentException if resource not supported
     * @return array
     */
    static function parseWith($optionsResource, array $_ = null);

    /**
     * Is Configurable With Given Resource
     *
     * @param mixed $optionsResource
     *
     * @return boolean
     */
    static function isConfigurableWith($optionsResource);
}


text:
<?php

/**
 * Lexes a template string.
 *
 * @package    twig
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class Twig_Lexer implements Twig_LexerInterface
{
    protected $cursor;
    protected $position;
    protected $end;
    protected $pushedBack;
    protected $code;
    protected $lineno;
    protected $filename;
    protected $env;
    protected $options;
    protected $operatorRegex;

    const POSITION_DATA  = 0;
    const POSITION_BLOCK = 1;
    const POSITION_VAR   = 2;

    const REGEX_NAME        = '/[A-Za-z_][A-Za-z0-9_]*/A';
    const REGEX_NUMBER      = '/[0-9]+(?:\.[0-9]+)?/A';
    const REGEX_STRING      = '/(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')/Asm';
    const REGEX_PUNCTUATION = '/[\[\](){}?:.,|]/A';

    public function __construct(Twig_Environment $env = null, array $options = array())
    {
        if (null !== $env) {
            $this->setEnvironment($env);
        }

        $this->options = array_merge(array(
            'tag_comment'  => array('{#', '#}'),
            'tag_block'    => array('{%', '%}'),
            'tag_variable' => array('{{', '}}'),
        ), $options);
    }

    public function sortByLength($a, $b)
    {
        return strlen($a) > strlen($b) ? -1 : 1;
    }

    /**
     * Tokenizes a source code.
     *
     * @param  string $code     The source code
     * @param  string $filename A unique identifier for the source code
     *
     * @return Twig_TokenStream A token stream instance
     */
    public function tokenize($code, $filename = 'n/a')
    {
        if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
            $mbEncoding = mb_internal_encoding();
            mb_internal_encoding('ASCII');
        }

        $this->code = str_replace(array("\r\n", "\r"), "\n", $code);
        $this->filename = $filename;
        $this->cursor = 0;
        $this->lineno = 1;
        $this->pushedBack = array();
        $this->end = strlen($this->code);
        $this->position = self::POSITION_DATA;

        $tokens = array();
        $end = false;
        while (!$end) {
            $token = $this->nextToken();

            $tokens[] = $token;

            $end = $token->getType() === Twig_Token::EOF_TYPE;
        }

        if (isset($mbEncoding)) {
            mb_internal_encoding($mbEncoding);
        }

        return new Twig_TokenStream($tokens, $this->filename);
    }

    public function setEnvironment(Twig_Environment $env)
    {
        $this->env = $env;
    }

    /**
     * Parses the next token and returns it.
     */
    protected function nextToken()
    {
        // do we have tokens pushed back? get one
        if (!empty($this->pushedBack)) {
            return array_shift($this->pushedBack);
        }

        // have we reached the end of the code?
        if ($this->cursor >= $this->end) {
            return new Twig_Token(Twig_Token::EOF_TYPE, '', $this->lineno);
        }

        // otherwise dispatch to the lexing functions depending
        // on our current position in the code.
        switch ($this->position) {
            case self::POSITION_DATA:
                $tokens = $this->lexData();
                break;

            case self::POSITION_BLOCK:
                $tokens = $this->lexBlock();
                break;

            case self::POSITION_VAR:
                $tokens = $this->lexVar();
                break;
        }

        // if the return value is not an array it's a token
        if (!is_array($tokens)) {
            return $tokens;
        }
        // empty array, call again
        else if (empty($tokens)) {
            return $this->nextToken();
        }
        // if we have multiple items we push them to the buffer
        else if (count($tokens) > 1) {
            $first = array_shift($tokens);
            $this->pushedBack = $tokens;

            return $first;
        }
        // otherwise return the first item of the array.
        else {
            return $tokens[0];
        }
    }

    protected function lexData()
    {
        $match = null;

        $pos1 = strpos($this->code, $this->options['tag_comment'][0], $this->cursor);
        $pos2 = strpos($this->code, $this->options['tag_variable'][0], $this->cursor);
        $pos3 = strpos($this->code, $this->options['tag_block'][0], $this->cursor);

        // if no matches are left we return the rest of the template
        // as simple text token
        if (false === $pos1 && false === $pos2 && false === $pos3) {
            $rv = new Twig_Token(Twig_Token::TEXT_TYPE, substr($this->code, $this->cursor), $this->lineno);
            $this->cursor = $this->end;

            return $rv;
        }

        // min
        $pos = -log(0);
        if (false !== $pos1 && $pos1 < $pos) {
            $pos = $pos1;
            $token = $this->options['tag_comment'][0];
        }
        if (false !== $pos2 && $pos2 < $pos) {
            $pos = $pos2;
            $token = $this->options['tag_variable'][0];
        }
        if (false !== $pos3 && $pos3 < $pos) {
            $pos = $pos3;
            $token = $this->options['tag_block'][0];
        }

        // update the lineno on the instance
        $lineno = $this->lineno;

        $text = substr($this->code, $this->cursor, $pos - $this->cursor);
        $this->moveCursor($text.$token);
        $this->moveLineNo($text.$token);

        // array of tokens
        $result = array();

        // push the template text first
        if (!empty($text)) {
            $result[] = new Twig_Token(Twig_Token::TEXT_TYPE, $text, $lineno);
            $lineno += substr_count($text, "\n");
        }

        switch ($token) {
            case $this->options['tag_comment'][0]:
                if (!preg_match('/(.*?)'.preg_quote($this->options['tag_comment'][1], '/').'/As', $this->code, $match, null, $this->cursor)) {
                    throw new Twig_Error_Syntax('unclosed comment', $this->lineno, $this->filename);
                }
                $this->moveCursor($match[0]);
                $this->moveLineNo($match[0]);
                break;

            case $this->options['tag_block'][0]:
                // raw data?
                if (preg_match('/\s*raw\s*'.preg_quote($this->options['tag_block'][1], '/').'(.*?)'.preg_quote($this->options['tag_block'][0], '/').'\s*endraw\s*'.preg_quote($this->options['tag_block'][1], '/').'/As', $this->code, $match, null, $this->cursor)) {
                    $result[] = new Twig_Token(Twig_Token::TEXT_TYPE, $match[1], $lineno);
                    $this->moveCursor($match[0]);
                    $this->moveLineNo($match[0]);
                    $this->position = self::POSITION_DATA;
                } else {
                    $result[] = new Twig_Token(Twig_Token::BLOCK_START_TYPE, '', $lineno);
                    $this->position = self::POSITION_BLOCK;
                }
                break;

            case $this->options['tag_variable'][0]:
                $result[] = new Twig_Token(Twig_Token::VAR_START_TYPE, '', $lineno);
                $this->position = self::POSITION_VAR;
                break;
        }

        return $result;
    }

    protected function lexBlock()
    {
        if (preg_match('/\s*'.preg_quote($this->options['tag_block'][1], '/').'/As', $this->code, $match, null, $this->cursor)) {
            $lineno = $this->lineno;
            $this->moveCursor($match[0]);
            $this->moveLineNo($match[0]);
            $this->position = self::POSITION_DATA;

            return new Twig_Token(Twig_Token::BLOCK_END_TYPE, '', $lineno);
        }

        return $this->lexExpression();
    }

    protected function lexVar()
    {
        if (preg_match('/\s*'.preg_quote($this->options['tag_variable'][1], '/').'/As', $this->code, $match, null, $this->cursor)) {
            $lineno = $this->lineno;
            $this->moveCursor($match[0]);
            $this->moveLineNo($match[0]);
            $this->position = self::POSITION_DATA;

            return new Twig_Token(Twig_Token::VAR_END_TYPE, '', $lineno);
        }

        return $this->lexExpression();
    }

    protected function lexExpression()
    {
        $match = null;

        // whitespace
        while (preg_match('/\s+/As', $this->code, $match, null, $this->cursor)) {
            $this->moveCursor($match[0]);
            $this->moveLineNo($match[0]);
        }

        // sanity check
        if ($this->cursor >= $this->end) {
            throw new Twig_Error_Syntax('Unexpected end of stream', $this->lineno, $this->filename);
        }

        // first parse operators
        if (preg_match($this->getOperatorRegex(), $this->code, $match, null, $this->cursor)) {
            $this->moveCursor(trim($match[0], ' ()'));

            return new Twig_Token(Twig_Token::OPERATOR_TYPE, trim($match[0], ' ()'), $this->lineno);
        }
        // now names
        else if (preg_match(self::REGEX_NAME, $this->code, $match, null, $this->cursor)) {
            $this->moveCursor($match[0]);

            return new Twig_Token(Twig_Token::NAME_TYPE, $match[0], $this->lineno);
        }
        // then numbers
        else if (preg_match(self::REGEX_NUMBER, $this->code, $match, null, $this->cursor)) {
            $this->moveCursor($match[0]);
            $value = (float)$match[0];
            if ((int)$value === $value) {
                $value = (int)$value;
            }

            return new Twig_Token(Twig_Token::NUMBER_TYPE, $value, $this->lineno);
        }
        // punctuation
        else if (preg_match(self::REGEX_PUNCTUATION, $this->code, $match, null, $this->cursor)) {
            $this->moveCursor($match[0]);
            $this->moveLineNo($match[0]);

            return new Twig_Token(Twig_Token::PUNCTUATION_TYPE, $match[0], $this->lineno);
        }
        // and finally strings
        else if (preg_match(self::REGEX_STRING, $this->code, $match, null, $this->cursor)) {
            $this->moveCursor($match[0]);
            $this->moveLineNo($match[0]);
            $value = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));

            return new Twig_Token(Twig_Token::STRING_TYPE, $value, $this->lineno);
        }

        // unlexable
        throw new Twig_Error_Syntax(sprintf("Unexpected character '%s'", $this->code[$this->cursor]), $this->lineno, $this->filename);
    }

    protected function moveLineNo($text)
    {
        $this->lineno += substr_count($text, "\n");
    }

    protected function moveCursor($text)
    {
        $this->cursor += strlen($text);
    }

    protected function getOperatorRegex()
    {
        if (null !== $this->operatorRegex) {
            return $this->operatorRegex;
        }

        $operators = array('=');
        $operators = array_merge($operators, array_keys($this->env->getUnaryOperators()));
        $operators = array_merge($operators, array_keys($this->env->getBinaryOperators()));
        usort($operators, array($this, 'sortByLength'));

        $regex = array();
        foreach ($operators as $operator) {
            $last = ord(substr($operator, -1));
            // an operator that ends with a character must be followed by
            // a whitespace or a parenthese
            if (($last >= 65 && $last <= 90) || ($last >= 97 && $last <= 122)) {
                $regex[] = preg_quote($operator, '/').'(?:[ \(\)])';
            } else {
                $regex[] = preg_quote($operator, '/');
            }
        }

        return $this->operatorRegex = '/'.implode('|', $regex).'/A';
    }
}