text:
package jj.repl.telnet;

import static jj.repl.telnet.TelnetProtocol.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * encapsulates the current status of a telnet connection
 *
 * @author jason
 *
 */
class TelnetSessionStatus {

	TelnetSessionStatus() {}

	TelnetSessionStatus parseResponse(final ByteBuf byteBuf) {
		int index = Unpooled.wrappedBuffer(byteBuf).forEachByte(this::nextToken);
		System.out.println(index);
		return this;
	}

	private enum State {
		AwaitingIAC,       // obv.
		AwaitingMode,      // WILL, WONT, DO, DONT, SE, SB, IAC
		AwaitingCommand,   // just so
		AwaitingSubcommand,
		AwaitingSubcommandEnd
	}

	private State state = State.AwaitingIAC;
	private int mode = 0;

	private boolean nextToken(byte value) {
		switch (state) {
		case AwaitingIAC:
			if (value == (byte)IAC) {
				System.out.println("IAC");
				state = State.AwaitingMode;
			} else {
				// pass the byte through
				System.out.println("got " + value );
			}
			break;

		case AwaitingMode:
			switch (value) {
			case (byte)WILL:
				System.out.println("WILL");
				mode = WILL;
				state = State.AwaitingCommand;
				break;

			case (byte)WONT:
				System.out.println("WONT");
				mode = WONT;
				state = State.AwaitingCommand;
				break;

			case (byte)DO:
				System.out.println("DO");
				mode = DO;
				state = State.AwaitingCommand;
				break;

			case (byte)DONT:
				System.out.println("DONT");
				mode = DONT;
				state = State.AwaitingCommand;
				break;

			case (byte)SE:
			case (byte)SB:

				break;
			case (byte)IAC:
				state = State.AwaitingIAC;
				// pass the 255 through
				break;
			default:
				throw new AssertionError("what");
			}

			break;

		case AwaitingCommand:
			Command command = Command.commandFor(value);
			System.out.println(command);
			switch (mode) {
			case WILL:

				break;

			case WONT:

				break;

			case DO:

				break;

			case DONT:

				break;
			}
			state = State.AwaitingIAC;
			break;

		default:
			throw new AssertionError("fell through!");
		}
		return true;
	}

//	IAC WILL AUTHENTICATION      -- ff fb 25
//	IAC DO SUPPRESS-GO-AHEAD     -- ff fd 3
//	IAC WILL TERMINAL-TYPE       -- ff fb 18
//	IAC WILL NAWS                -- ff fb 1f
//	IAC WILL TERMINAL-SPEED      -- ff fb 20
//	IAC WILL TOGGLE-FLOW-CONTROL -- ff fb 21
//	IAC WILL LINEMODE            -- ff fb 22
//	IAC WILL NEW-ENVIRON         -- ff fb 27
//	IAC DO STATUS                -- ff fd 5
//	IAC WILL X-DISPLAY-LOCATION  -- ff fb 23

	private boolean linemode = true;

	boolean linemode() {
		return linemode;
	}

	// SLC_SYNCH 3 0

	// SLC_IP 62 3
	// SLC_AO 2 f
	// SLC_AYT 2 14
	// SLC_ABORT 62 1c
	// SLC_EOF 2 4
	// SLC_SUSP 42 1a
	// SLC_EC 2 7f
	// SLC_EL 2 15
	// SLC_EW 2 17
	// SLC_RP 2 12
	// SLC_LNEXT 2 16
	// SLC_XON 2 11
	// SLC_XOFF 2 13
	// SLC_FORW1 0 FF
	// SLC_FORW2 0 FF
}


text:
namespace gl {
class GLImage;
class SurfaceTexture;
}

namespace gpu {

class GPU_EXPORT GpuMemoryBufferFactorySurfaceTexture
    : public GpuMemoryBufferFactory,
      public ImageFactory {
 public:
  GpuMemoryBufferFactorySurfaceTexture();
  ~GpuMemoryBufferFactorySurfaceTexture() override;

  // Overridden from GpuMemoryBufferFactory:
  gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer(
      gfx::GpuMemoryBufferId id,
      const gfx::Size& size,
      gfx::BufferFormat format,
      gfx::BufferUsage usage,
      int client_id,
      SurfaceHandle surface_handle) override;
  void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
                              int client_id) override;
  ImageFactory* AsImageFactory() override;

  // Overridden from ImageFactory:
  scoped_refptr<gl::GLImage> CreateImageForGpuMemoryBuffer(
      const gfx::GpuMemoryBufferHandle& handle,
      const gfx::Size& size,
      gfx::BufferFormat format,
      unsigned internalformat,
      int client_id,
      SurfaceHandle surface_handle) override;

 private:
  typedef std::pair<int, int> SurfaceTextureMapKey;
  typedef base::hash_map<SurfaceTextureMapKey,
                         scoped_refptr<gl::SurfaceTexture>>
      SurfaceTextureMap;
  SurfaceTextureMap surface_textures_;
  base::Lock surface_textures_lock_;
};

}  // namespace gpu

#endif  // GPU_IPC_SERVICE_GPU_MEMORY_BUFFER_FACTORY_SURFACE_TEXTURE_H_

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe DocsController do
  it 'renders docs#index' do
    get :index
    response.should have_rendered(:index)
  end

  it 'renders docs#analysis' do
    sign_in User.make!

    get :analysis
    response.should have_rendered(:analysis)
  end
end


text:
define(["require", "exports", "../util"], function (require, exports, util) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function isDrawer(element) {
        return isClassPresent(element, 'mdc-drawer__drawer') ||
            isClassPresent(element, 'mdc-drawer--permanent');
    }
    exports.isDrawer = isDrawer;
    function isClassPresent(parent, className) {
        if (parent) {
            var elementFound = util.findAncestor(parent, className, 5);
            if (elementFound) {
                return true;
            }
        }
        return false;
    }
});


text:
'use strict';

var autoprefixer = require('gulp-autoprefixer');
var babelify = require('babelify');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var livereload = require('gulp-livereload');
var minifycss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var util = require('gulp-util');

// project config

var config = {
  scripts: {
    src: './src/**/*.js',
    dest: './dist/js/',
    entries: './src/index.js', // array or string, if only one entry
    output: 'bundle.js' // name of bundled file
  },
  styles: {
    src: './src/_assets/scss/**/*.scss',
    dest: './dist/css/'
  },
  views: {
    src: './src/views/**/*.html',
    dest: './dist/views/'
  }
};

// scripts task

gulp.task('scripts', function() {
  // verify that env.js exists
  var defaultEnvFile = './env.default.js';
  var userEnvFile = './env.js';
  var fs = require('fs');
  fs.access(userEnvFile, fs.F_OK, function(err) {
    if (err) {
      console.log('\nenv.js does not exist\ncreating one...\n');
      fs.createReadStream(defaultEnvFile).pipe(fs.createWriteStream(userEnvFile));
    }
  });

  var b = browserify({
    entries: config.scripts.entries,
    debug: true,
    transform: [babelify]
  });

  return b.bundle()
    .pipe(source(config.scripts.output))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
      // add transformation tasks to the pipeline here.
      .on('error', util.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(config.scripts.dest))
    .pipe(livereload());
});

// styles task

gulp.task('styles', function() {
  gulp.src(config.styles.src)
    .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
      .pipe(autoprefixer())
      .pipe(rename({suffix : '.min'}))
      .pipe(minifycss())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(config.styles.dest))
    .pipe(livereload());
});

// views task

gulp.task('views', function() {
  gulp.src(config.views.src)
    .pipe(gulp.dest(config.views.dest))
    .pipe(livereload());
});

// watch task

gulp.task('watch', function() {
  livereload.listen();
  gulp.watch(config.styles.src, ['styles']);
  gulp.watch(config.scripts.src, ['scripts']);
  gulp.watch(config.views.src, ['views']);
});

// default & build tasks

gulp.task('build', ['scripts', 'styles', 'views']);
gulp.task('default', ['build', 'watch']);


text:
html2text [![Build Status](https://travis-ci.org/soundasleep/html2text.svg?branch=master)](https://travis-ci.org/soundasleep/html2text) [![Total Downloads](https://poser.pugx.org/soundasleep/html2text/downloads.png)](https://packagist.org/packages/soundasleep/html2text)
=========

html2text is a very simple script that uses PHP's DOM methods to load from HTML, and then iterates over the resulting DOM to correctly output plain text. For example:

```html
<html>
<title>Ignored Title</title>
<body>
  <h1>Hello, World!</h1>

  <p>This is some e-mail content.
  Even though it has whitespace and newlines, the e-mail converter
  will handle it correctly.

  <p>Even mismatched tags.</p>

  <div>A div</div>
  <div>Another div</div>
  <div>A div<div>within a div</div></div>

  <a href="http://foo.com">A link</a>

</body>
</html>
```

Will be converted into:

```text
Hello, World!

This is some e-mail content. Even though it has whitespace and newlines, the e-mail converter will handle it correctly.

Even mismatched tags.
A div
Another div
A div
within a div
[A link](http://foo.com)
```

See the [original blog post](http://journals.jevon.org/users/jevon-phd/entry/19818) or the related [StackOverflow answer](http://stackoverflow.com/a/2564472/39531).

## Installing

You can use [Composer](http://getcomposer.org/) to add the [package](https://packagist.org/packages/soundasleep/html2text) to your project:

```json
{
  "require": {
    "soundasleep/html2text": "~0.3"
  }
}
```

And then use it quite simply:

```php
$text = Html2Text\Html2Text::convert($html);
```

You can also include the supplied `html2text.php` and use `$text = convert_html_to_text($html);` instead.

## Tests

Some very basic tests are provided in the `tests/` directory. Run them with `composer install --dev && vendor/bin/phpunit`.

## License

`html2text` is dual licensed under both [EPL v1.0](https://www.eclipse.org/legal/epl-v10.html) and [LGPL v3.0](http://www.gnu.org/licenses/lgpl.html), making it suitable for both Eclipse and GPL projects.

## Other versions

Also see [html2text_ruby](https://github.com/soundasleep/html2text_ruby), a Ruby implementation.


text:
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

  <!-- Additional meta info -->
  {% if page.description %}
    <meta name="description" content="{{ page.description }}">
  {% else %}
    <meta name="description" content="Blogs written by wqlin">
  {% endif %}
  <meta name="author" content="wqlin">
  <meta name="keywords" content="Programming, Scala, Blogging">

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>
    {% if page.title == "Home" %}
      Blog | {{ site.title }} · {{ site.tagline }} by {{ site.author.name }}
    {% else %}
      Blog | {{ page.title }} · {{ site.title }} by {{ site.author.name }}
    {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/poole.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/lanyon.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/hljs.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/custom.css">
  {% if page.layout == '404page' %}
    <link rel="stylesheet" href="{{ site.baseurl }}/public/css/404page.css">
  {% endif %}

  <!-- JS -->
  <script src="{{ site.baseurl }}/public/js/highlight.pack.js"></script>
  <script>hljs.initHighlightingOnLoad();</script>

  <script type="text/x-mathjax-config">
      MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
  </script>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML">
  </script>

  <!-- Fonts -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400">

  <!-- RSS -->
  <link href="/atom.xml" rel="alternate" title="Atom" type="application/atom+xml">

  <!-- Google Analytics -->
  {% include google_analytics.html %}

  <!-- Baidu Verification -->
  <meta name="baidu-site-verification" content="nHyk0bx6u9" />
</head>


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/temples/hermosillo-sonora-mexico#hermosillo-mexico-temple-lds-171162" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">hermosillo-mexico-temple-lds-171162</uri-title>
      <source>hermosillo-mexico-temple-lds-171162</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-12-14">2012-12-14</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>hermosillo sonora</subject>
          <subject>mexico</subject>
          <subject>temples</subject>
          <subject>sunset</subject>
          <subject>trees</subject>
          <subject>landscape</subject>
          <subject>steeple</subject>
          <subject>angle</subject>
          <subject>moroni</subject>
          <subject>house</subject>
          <subject>holy</subject>
          <subject>lord</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/temples/hermosillo-sonora-mexico/hermosillo-mexico-temple-lds-171162-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/temples/hermosillo-sonora-mexico/hermosillo-mexico-temple-lds-171162-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>117 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/hermosillo-sonora-mexico/hermosillo-mexico-temple-lds-171162-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>150 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/hermosillo-sonora-mexico/hermosillo-mexico-temple-lds-171162-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>344 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/hermosillo-sonora-mexico/hermosillo-mexico-temple-lds-171162-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>635 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/hermosillo-sonora-mexico/hermosillo-mexico-temple-lds-171162-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>


text:
<form ng-submit="saveParty()" class="form-inline party-form">

		Party name
		<input ng-model ="newParty.name" type="text" class="form-control" id="partyName" placeholder="Name">

		Phone Number
		<input ng-model = "newParty.phone" type="text" class="form-control" id="phoneNumber" placeholder="Phone number">

		Size of Party
		<input ng-model = "newParty.size" type="text" class="form-control" id="partySize" placeholder="Party Size">

	<button type="submit" class="btn btn-primary">Add party</button>
</form>

		Done?
		Info
		Notified
		Actions

		<input type="checkbox">

{{party.name}} ({{party.size}} people)

{{party.phone}}

			<button type ="submit" class = "btn btn-success">Send SMS</button>
			<button ng-click="parties.$remove(party.$id)" type ="submit" class = "btn btn-danger">Remove</button>


text:
import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';

const TrendingDown = forwardRef(({ color = 'currentColor', size = 24, ...rest }, ref) => {
  return (
    <svg
      ref={ref}
      xmlns="http://www.w3.org/2000/svg"
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke={color}
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      {...rest}
    >
      <polyline points="23 18 13.5 8.5 8.5 13.5 1 6" />
      <polyline points="17 18 23 18 23 12" />
    </svg>
  );
});

TrendingDown.propTypes = {
  color: PropTypes.string,
  size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};

TrendingDown.displayName = 'TrendingDown';

export default TrendingDown;


text:
<?php

namespace Sonata\Component\Product;

use Symfony\Component\Validator\Constraints as Validation;

class AddBasket
{

    /**
     * @Validation\NotBlank()
     * @var int
     */
    private $productId;

    /**
     * @Validation\NotBlank()
     * @Validation\Type(type="object")
     * @var ProductInterface
     */
    private $product;

    /**
     * @Validation\NotBlank()
     * @Validation\Range(min=1, max=64)
     * @var int
     */
    private $quantity;

    /**
     * @return integer the product id
     */
    public function getProductId()
    {
        return $this->product->getId();
    }

    /**
     * The product id is only set if there is not product attached to this object
     *
     * @param integer $productId the product id
     */
    public function setProductId($productId)
    {
        // never erase this value
        if ($this->productId !== null) {
           return;
        }

        $this->productId = $productId;
    }

    /**
     * Set the related product
     *
     * @param ProductInterface $product
     */
    public function setProduct(ProductInterface $product)
    {
        $this->productId = $product->getId();
        $this->product = $product;
    }

    /**
     * Set the quantity
     *
     * @param integer $quantity
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
    }

    /**
     * @return the quantity
     */
    public function getQuantity()
    {
        return $this->quantity;
    }
}


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

/* Read a list of integers on the first line of the console. After that, find the smallest element in the array and print it on the console.*/

namespace SmallestElementInArray
{
    class Program
    {
        static void Main(string[] args)
        {
            var numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            var smallestInt = numbers[0];

            for (int i = 0; i < numbers.Length; i++)
            {
                if (smallestInt > numbers[i])
                {
                    smallestInt = numbers[i];
                }
            }
            Console.WriteLine(smallestInt);
        }
    }
}


text:
SYNONYM

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

#### Published in
Ges. naturf. Freunde, Berlin 2: 2, tab. 104, fig. 4 (1884)

#### Original name
Agaricus togularis var. filaris Fr., 1884

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TodoList React Sass App</title>
    <meta name="author" content="Marius Bieliauskas">
    <meta name="description" content="Example todo list application based on Bootstrap Sass, React and Webpack">
    <meta name="keywords" content="">

2016  Marius Bieliauskas Project on GitHub


text:
package main.downloader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;

import main.downloader.downloaders.EncogYahooStockDownloader;
import main.downloader.loaders.CSVTickerLoader;
import main.downloader.writers.JSONFileWriter;
import main.downloader.writers.MySQLStockWriter;

/**
 * TODO: Implement me
 *
 * The download service is supposed to be a service which downloads all the
 * history once a day.
 *
 * @author cseibert
 */
public class DownloaderService
{
	/** */
	private CSVTickerLoader theTickerLoader;

	/** */
	private StockDownloader theStockDownloader;

	/** */
	private StockWriter theStockWriter;

	/**
	 *
	 * @param args
	 * @throws IOException
	 * @throws SQLException
	 * @throws ParseException
	 */
	public static void main(String[] args)
			throws IOException, SQLException, ParseException
	{
		DownloaderService service = new DownloaderService();
	}

	/**
	 * @throws IOException
	 * @throws SQLException
	 * @throws ParseException
	 */
	public DownloaderService() throws IOException, SQLException, ParseException
	{
		setStockWriter(new MySQLStockWriter());
		setStockDownloader(new EncogYahooStockDownloader());
		setTickerLoader(new CSVTickerLoader());
		run();
	}

	public void setTickerLoader(CSVTickerLoader loader)
	{
		theTickerLoader = loader;
	}

	public void setStockDownloader(StockDownloader downloader)
	{
		theStockDownloader = downloader;
	}

	public void setStockWriter(StockWriter writer)
	{
		theStockWriter = writer;
	}

	/**
	 * @throws SQLException
	 * @throws ParseException
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public void run() throws SQLException, ParseException, FileNotFoundException, IOException
	{
		ArrayList<Ticker> tickers = (ArrayList<Ticker>)theTickerLoader.getTickers(new FileInputStream("resources/tickers.csv"));
		StockDownloader stockDownloader = new EncogYahooStockDownloader();
		HashMap<Ticker, StockHistory> stocks = (HashMap<Ticker, StockHistory>)stockDownloader.downloadAll(tickers);
		theStockWriter.write(stocks);
	}
}


text:
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class GameController : MonoBehaviour {

	public bool isGameStartedFirstTime; // used for initialization

	public static GameController instance;
	private GameData data;

	public bool isMusicOn; // keep track of the music

	public int selectedPlayer; // which skin has been selected
	public int highScore;

	public int currentScore;
	public String name;

	public bool[] players; //how much skins are unlocked ?
	public bool[] achievements;

	void Start () {

	}

	private void Awake()
	{
		//MakeSingleton();
		InitializeGameVariables();
	}

	public int getPlayed(){
		return this.data.getSelectedPlayer();
	}
	public void setPlayed(int character){
		print (character);
		this.data.setSelectedPlayer(character);
	}

	public String getName(){
		return this.data.getName ();
	}

	public void setName(String nom){
		print (nom);
		this.name = nom;
	}
	void InitializeGameVariables()
	{
		Load();

		if(data != null)
		{
			isGameStartedFirstTime = data.getIsGameStartedFirstTime();
		}
		else
		{
			isGameStartedFirstTime = true;
		}

		if (isGameStartedFirstTime)
		{
			// The game is started for the first time
			// Initialisation of the variables
			highScore = 0;

			selectedPlayer = 0;

			name = "Bob";

			isGameStartedFirstTime = false;
			isMusicOn = false;

			players = new bool[2];
			achievements = new bool[8];

			players[0] = true;
			for(int i = 1; i < players.Length; i++)
			{
				players[i] = false;
			}

			for(int i = 0; i < achievements.Length; i++)
			{
				achievements[i] = false;
			}

			data = new GameData();

			data.setHighScore(highScore);
			data.setSelectedPlayer(selectedPlayer);
			data.setIsGameStartedFirstTime(isGameStartedFirstTime);
			data.setIsMusicOn(isMusicOn);
			data.setPlayers(players);
			data.setAchivements(achievements);

			Save();

			Load();
		}
		else
		{
			// The game has been played already so load game data

			highScore = data.getHighScore();
			selectedPlayer = data.getSelectedPlayer();
			isGameStartedFirstTime = data.getIsGameStartedFirstTime();
			isMusicOn = data.getIsGameStartedFirstTime();
			players = data.getPlayers();
			achievements = data.getAchievements();
		}
	}

	public void MakeSingleton()
	{
		if(instance != null)
		{
			Destroy(gameObject);
		}
		else
		{
			instance = this;
			DontDestroyOnLoad(gameObject);
		}
	}

	public void Load()
	{
		FileStream file = null;

		try
		{
			BinaryFormatter bf = new BinaryFormatter();
			// We open the encrypted save file
			file = File.Open(Application.persistentDataPath + "/GameData.dat", FileMode.Open);
			data = (GameData)bf.Deserialize(file);

		} catch(Exception e)
		{

		}finally
		{
			if(file != null)
			{
				file.Close();
			}
		}
	}

	/**
	 *  Encrypted saves, so that the lurky hacky players
	 *  can't hack their stats :3
	 **/
	public void Save()
	{
		FileStream file = null;
		try
		{
			BinaryFormatter bf = new BinaryFormatter();
			// we create a encrypted file with all the saves from the current player
			file = File.Create(Application.persistentDataPath + "/GameData.dat");

			if(data != null)
			{
				// setting our data
				data.setHighScore(highScore);
				data.setIsGameStartedFirstTime(isGameStartedFirstTime);
				data.setPlayers(players);
				data.setSelectedPlayer(selectedPlayer);
				data.setAchivements(achievements);
				data.setIsMusicOn(isMusicOn);

				bf.Serialize(file, data);
			}
		}
		// no crash if the file don't yet exists
		catch (Exception e)
		{
			print (e);
		}
		// executed no matter what
		finally
		{
			if(file != null)
			{
				file.Close();
			}
		}
	}

}

[Serializable]
class GameData
{
	private bool isGameStartedFirstTime; // used for initialization

	private bool isMusicOn; // keep track of the music

	private int selectedPlayer; // which skin has been selected
	private int highScore;
	private String name;

	private bool[] players; //how much skins are unlocked ?
	private bool[] achievements;

	// GETTERS - SETTERS
	public void setIsGameStartedFirstTime(bool isGameStartedFirstTime)
	{
		this.isGameStartedFirstTime = isGameStartedFirstTime;
	}

	public bool getIsGameStartedFirstTime()
	{
		return this.isGameStartedFirstTime;
	}

	public void setIsMusicOn(bool isMusicOn)
	{
		this.isMusicOn = isMusicOn;
	}

	public bool getIsMusicOn()
	{
		return this.isMusicOn;
	}
	public String getName(){
		return this.name;
	}
	public void setName(String nom){
		this.name = nom;
	}

	public void setSelectedPlayer(int selectedPlayer)
	{
		this.selectedPlayer = selectedPlayer;
	}

	public int getSelectedPlayer()
	{
		return this.selectedPlayer;
	}

	public void setHighScore(int highScore)
	{
		this.highScore = highScore;
	}

	public int getHighScore()
	{
		return this.highScore;
	}

	public bool[] getPlayers()
	{
		return this.players;
	}

	public void setPlayers(bool[] players)
	{
		this.players = players;
	}

	public void setAchivements(bool[] achievements)
	{
		this.achievements = achievements;
	}

	public bool[] getAchievements()
	{
		return this.achievements;
	}

}


text:
import { combineReducers } from 'redux';
import {
    START_SNAPSHOT_GENERATION,
    END_SNAPSHOT_GENERATION,
    UPDATE_VERSION_LIST
} from './../actions/actions'
import { IVersion } from "../models/IVersion";

function started(state:boolean = false, action?:any) {
    switch (action.type) {
        case START_SNAPSHOT_GENERATION:
            return true;
        case END_SNAPSHOT_GENERATION:
            return false;
        default:
            return state;
    }
}

function versions(state:IVersion[] = [], action?:any) {
    switch (action.type) {
        case UPDATE_VERSION_LIST:
            return action.versionList;
        default:
            return state;
    }
}

export const snapshotApp = combineReducers({
    started,
    versions
});


text:
.class Landroid/webkit/AutoCompletePopup$1;
.super Landroid/os/Handler;
.source "AutoCompletePopup.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/webkit/AutoCompletePopup;-><init>(Landroid/webkit/WebViewClassic;Landroid/webkit/WebViewClassic$WebViewInputConnection;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/webkit/AutoCompletePopup;

# direct methods
.method constructor <init>(Landroid/webkit/AutoCompletePopup;)V
    .locals 0
    .parameter

    .prologue
    .line 58
    iput-object p1, p0, Landroid/webkit/AutoCompletePopup$1;->this$0:Landroid/webkit/AutoCompletePopup;

    invoke-direct {p0}, Landroid/os/Handler;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 2
    .parameter "msg"

    .prologue
    .line 61
    iget v0, p1, Landroid/os/Message;->what:I

    packed-switch v0, :pswitch_data_0

    .line 66
    :goto_0
    return-void

    .line 63
    :pswitch_0
    iget-object v0, p0, Landroid/webkit/AutoCompletePopup$1;->this$0:Landroid/webkit/AutoCompletePopup;

    #getter for: Landroid/webkit/AutoCompletePopup;->mWebView:Landroid/webkit/WebViewClassic;
    invoke-static {v0}, Landroid/webkit/AutoCompletePopup;->access$100(Landroid/webkit/AutoCompletePopup;)Landroid/webkit/WebViewClassic;

    move-result-object v0

    iget-object v1, p0, Landroid/webkit/AutoCompletePopup$1;->this$0:Landroid/webkit/AutoCompletePopup;

    #getter for: Landroid/webkit/AutoCompletePopup;->mQueryId:I
    invoke-static {v1}, Landroid/webkit/AutoCompletePopup;->access$000(Landroid/webkit/AutoCompletePopup;)I

    move-result v1

    invoke-virtual {v0, v1}, Landroid/webkit/WebViewClassic;->autoFillForm(I)V

    goto :goto_0

    .line 61
    :pswitch_data_0
    .packed-switch 0x64
        :pswitch_0
    .end packed-switch
.end method


text:
import { createFragmentContainer, graphql } from 'react-relay'

const BlogPostPreview = ({ post }) => <li>{post.title}</li>

export default createFragmentContainer(BlogPostPreview, {
  post: graphql`
    fragment BlogPostPreview_post on BlogPost {
      id
      title
    }
  `,
})


text:
"""
bmorph: modify a time series by removing elements of persistent differences
        (aka bias correction)

Persistent differences are inferred by comparing a 'ref' sample with a
'training' sample. These differences are then used to correct a 'raw' sample
that is presumed to have the same persistent differences as the 'training'
sample. The resulting 'bmorph' sample should then be consistent with the
'ref' sample.
"""

import numpy as np
import pandas as pd
import scipy.stats
from sklearn.neighbors import KernelDensity

# Done fail silently on divide by zero, but raise an error instead
np.seterr(divide='raise')

def kde2D(x, y, xbins=200, ybins=10, **kwargs):
    """ Estimate a 2 dimensional pdf via kernel density estimation """
    xx, yy = np.mgrid[x.min():x.max():(xbins * 1j), y.min():y.max():(ybins * 1j)]
    xy_sample = np.vstack([yy.ravel(), xx.ravel()]).T
    xy_train  = np.vstack([y, x]).T
    kde = KernelDensity(**kwargs)
    kde.fit(xy_train)
    # Need to exponentiate to get true probabilities
    z = np.exp(kde.score_samples(xy_sample))
    return xx[:, 0], yy[0, :], np.reshape(z, yy.shape)

def hist2D(x, y, xbins, ybins, **kwargs):
    """ Create a 2 dimensional pdf vias numpy histogram2d"""
    H, xedg, yedg = np.histogram2d(x=x, y=y, bins=[xbins,ybins], density=True, **kwargs)
    xcen = (xedg[:-1] + xedg[1:]) / 2
    ycen = (yedg[:-1] + yedg[1:]) / 2
    return xcen, ycen, H

def marginalize_cdf(y_raw, z_raw, vals):
    """Find the marginalized cdf by computing cumsum(P(x|y=val)) for each val"""
    y_raw = np.array(y_raw)
    z_raw = np.array(z_raw)
    z_raw[z_raw == 0] = 1e-15
    vals = np.array(vals)
    locs = np.argmin(np.abs(vals[:, np.newaxis] - y_raw), axis=1)
    z = np.cumsum(z_raw[:, locs], axis=0)
    z /= z[-1, :]
    return z

def cqm(raw_x: pd.Series, train_x: pd.Series, ref_x: pd.Series,
        raw_y: pd.Series, train_y: pd.Series, ref_y: pd.Series=None,
        method='hist', xbins=200, ybins=10, bw=3, rtol=1e-7, atol=0,
        nsmooth=5, train_cdf_min=1e-6) -> pd.Series:
    """Conditional Quantile Mapping

    Multidimensional conditional equidistant CDF matching function:
    \tilde{x_{mp}} = x_{mp} + F^{-1}_{oc}(F_{mp}(x_{mp}|y_{mp})|y_{oc})
                            - F^{-1}_{mc}(F_{mp}(x_{mp}|y_{mp})|y_{mc})
    """
    if method == 'kde':
        x_raw, y_raw, z_raw = kde2D(raw_x, raw_y, xbins, ybins,
                                    bandwidth=bw, rtol=rtol, atol=atol)
        x_train, y_train, z_train = kde2D(train_x, train_y, xbins, ybins,
                                          bandwidth=bw, rtol=rtol, atol=atol)
        x_ref, y_ref, z_ref = kde2D(ref_x, ref_y, xbins, ybins,
                                          bandwidth=bw, rtol=rtol, atol=atol)
    elif method == 'hist':
        x_raw, y_raw, z_raw = hist2D(raw_x, raw_y, xbins, ybins)
        x_train, y_train, z_train = hist2D(train_x, train_y, xbins, ybins)
        x_ref, y_ref, z_ref = hist2D(ref_x, ref_y, xbins, ybins)
    else:
        raise Exception("Current methods for cqm only include 'hist' to use hist2D "
                        "and 'kde' to use kde2D, please select one.")

    # Lookup tables of actual cdfs with dimensions (xbins, time)
    raw_cdfs = marginalize_cdf(y_raw, z_raw, raw_y)
    # Lookup tables of actual cdfs with dimensions (time, xbins)
    # These are transposed to do the inverse lookup
    # Note we always marginalize with respect to the raw values
    train_cdf = marginalize_cdf(y_train, z_train, raw_y).T
    ref_cdf = marginalize_cdf(y_ref, z_ref, raw_y).T

    # Quantiles of the raw flows
    nx_raw = np.arange(len(raw_x))
    u_t = raw_cdfs[np.argmin(np.abs(raw_x.values[:, np.newaxis] - x_raw), axis=1), nx_raw]
    u_t = u_t[:, np.newaxis]

    # Lookup the associated flow values in the CDFs for the reference and training periods
    mapped_ref = x_ref[np.argmin(np.abs(u_t - ref_cdf[nx_raw, :]), axis=1)]
    mapped_train = x_train[np.argmin(np.abs(u_t - train_cdf[nx_raw, :]), axis=1)]
    mapped_train[mapped_train < train_cdf_min] = train_cdf_min
    multipliers = pd.Series(mapped_ref / mapped_train, index=raw_x.index, name='multiplier')
    if method == 'hist':
        # Do some smoothing just to reduce effects of histogram bin edges
        multipliers = multipliers.rolling(nsmooth, win_type='triang', min_periods=1).mean()
    return multipliers

def edcdfm(raw_x, raw_cdf, train_cdf, ref_cdf, train_cdf_min=1e-6):
    '''Calculate  multipliers using an adapted version of the EDCDFm technique

    This routine implements part of the PresRat bias correction method from
    Pierce et al. (2015; http://dx.doi.org/10.1175/JHM-D-14-0236.1), which is
    itself an extension of the Equidistant quantile matching (EDCDFm) technique
    of Li et al. (2010; http://dx.doi.org/10.1029/94JD00483). The part that is
    implemented here is the amended form of EDCDFm that determines
    multiplicative changes in the quantiles of a CDF.

    In particular, if the value `raw_x` falls at quantile `u_t` (in `raw_cdf`),
    then the bias-corrected value is the value in `ref_cdf` at `u_t`
    (`ref_x`) multiplied by the model-predicted change at `u_t` evaluated as
    a ratio (i.e., model future (or `raw_x`) / model historical (or
    `ref_x`)). Thus, the bias-corrected value is `raw_x` multiplied by
    `ref_x`/`train_x`. Here we only return the multiplier
    `ref_x`/`train_x`. This method preserves the model-predicted median
    (not mean) change evaluated multiplicatively. Additional corrections
    are required to preserve the mean change. Inclusion of these additional
    corrections constitutes the PresRat method.

    Parameters
    ----------
    raw_x : pandas.Series
        Series of raw values that will be used to determine the quantile `u_t`
    raw_cdf : pandas.Series
        Series of raw values that represents the CDF that is used to
        determine the non-parametric quantile of `raw_x`
    train_cdf: pandas.Series
        Series of training values that represents the CDF based on
        the same process as `raw_cdf`, but overlapping in time with `ref_cdf`
    ref_cdf: pandas.Series
         Series of ref values that represents the ref CDF and that
         overlaps in time with `train_cdf`

    Returns
    -------
    multiplier : pandas.Series
        Multipliers for `raw_x`. The pandas.Series has the same index as
        `raw_x`
    '''
    # Type checking (note that the checking is more strict here then it
    # probably needs to be)
    assert isinstance(raw_x, pd.Series)
    assert isinstance(raw_cdf, pd.Series)
    assert isinstance(train_cdf, pd.Series)
    assert isinstance(ref_cdf, pd.Series)

    # Given raw_x and raw_cdf determine the quantiles u_t
    # This method is slightly more efficient than using
    # scipy.percentileofscore, especially on large arrays
    cdf_idx = np.argsort(raw_cdf)
    cdf_sort = raw_cdf[cdf_idx]
    cdf_rank = 100 * scipy.stats.rankdata(cdf_sort) / len(cdf_idx)
    offset = 100 / len(cdf_idx)
    u_t = [cdf_rank[np.searchsorted(cdf_sort, x, side='left')]-offset for x in raw_x]

    # Given u_t and train_cdf determine train_x
    train_x = np.percentile(train_cdf, u_t)
    train_x[train_x < train_cdf_min] = train_cdf_min

    # Given u_t and ref_cdf determine ref_x
    ref_x = np.percentile(ref_cdf, u_t)

    # Calculate multiplier
    multiplier = ref_x / train_x
    return pd.Series(multiplier, index=raw_x.index, name='multiplier')

def bmorph(raw_ts, train_ts, ref_ts,
           raw_apply_window, raw_train_window, ref_train_window, raw_cdf_window,
           raw_y=None, ref_y=None, train_y=None,
           nsmooth=12, bw=3, xbins=200, ybins=10, rtol=1e-7, atol=0, method='hist',
           smooth_multipliers=True, train_cdf_min=1e-6):
    '''Morph `raw_ts` based on differences between `ref_ts` and `train_ts`

    bmorph is an adaptation of the PresRat bias correction procedure from
    Pierce et al. (2015; http://dx.doi.org/10.1175/JHM-D-14-0236.1), which is
    itself an extension of the Equidistant quantile matching (EDCDFm) technique
    of Li et al. (2010; http://dx.doi.org/10.1029/94JD00483). The method as
    implemented here uses a multiplicative change in the quantiles of a CDF,
    followed by a simple correction to preserve changes in the long-term mean.
    No further frequency-based corrections are applied.

    The method differs from PresRat in that it is not applied for fixed periods
    (but uses a moving window) to prevent discontinuities in the corrected time
    series and it does not apply a frequency-based correction.

    The method also allows changes to be made through an adapted version of the
    EDCDFm technique or through the multiDimensional ConDitional EquiDistant CDF
    matching function if a second timeseries variable is passed.

    Parameters
    ----------
    raw_ts : pandas.Series
        Raw time series that will be bmorphed
    raw_cdf_window : slice
        Slice used to determine the CDF for `raw_ts`
    raw_bmorph_window : slice
        Slice of `raw_ts` that will be bmorphed
    ref_ts : pandas.Series
        Target time series. This is the time series with ref values that
        overlaps with `train_ts` and is used to calculated `ref_cdf`
    train_ts : pandas.Series
        Training time series. This time series is generated by the same process
        as `raw_ts` but overlaps with `ref_ts`. It is used to calculate
        `train_cdf`
    training_window : slice
        Slice used to subset `ref_ts` and `train_ts` when the mapping between
        them is created
    nsmooth : int
        Number of elements that will be smoothed when determining CDFs
    raw_y : pandas.Series
        Raw time series of the second time series variable for cqm
    ref_y : pandas.Series
        Target second time series
    train_y : pandas.Series
        Training second time series
    bw : int
        bandwidth for KernelDensity
    xbins : int
        Bins for the flow time series
    ybins : int
        Bins for the second time series
    train_cdf_min : float (optional)
        Minimum percentile allowed for train cdf. Defaults as 1e-4 to help handle
        data spikes in corrections caused by multipliers being too large from
        the ratio between reference and training flows being large.

    Returns
    -------
    bmorph_ts : pandas.Series
        Returns a time series of length `raw_bmorph_window` with bmorphed
        values
    '''
    # Type checking
    assert isinstance(raw_ts, pd.Series)
    assert isinstance(ref_ts, pd.Series)
    assert isinstance(train_ts, pd.Series)

    assert isinstance(raw_apply_window, slice)
    assert isinstance(raw_train_window, slice)
    assert isinstance(ref_train_window, slice)
    assert isinstance(raw_cdf_window, slice)

    # Smooth the raw Series
    raw_smoothed_ts = raw_ts.rolling(window=nsmooth, min_periods=1, center=True).mean()

    # Create the CDFs that are used for morphing the raw_ts. The mapping is
    # based on the training_window
    ref_cdf = ref_ts[ref_train_window].rolling(window=nsmooth, min_periods=1, center=True).mean()
    train_cdf = train_ts[raw_train_window].rolling(window=nsmooth, min_periods=1, center=True).mean()
    raw_cdf = raw_smoothed_ts[raw_cdf_window]

    # Check if using edcdfm or cqm through second variable being added
    # for the raw and train series because ref can be set as train later
    if (raw_y is None) or (ref_y is None) or (train_y is None):
        # Calculate the bmorph multipliers based on the smoothed time series and
        # PDFs
        bmorph_multipliers = edcdfm(raw_smoothed_ts[raw_apply_window],
                                    raw_cdf, train_cdf, ref_cdf, train_cdf_min)

        # Apply the bmorph multipliers to the raw time series
        bmorph_ts = bmorph_multipliers * raw_ts[raw_apply_window]

    else:
        # Continue Type Checking additionally series
        assert isinstance(raw_y, pd.Series)
        assert isinstance(ref_y, pd.Series)
        assert isinstance(train_y, pd.Series)

        # smooth the y series as well
        raw_smoothed_y = raw_y.rolling(
            window=nsmooth, min_periods=1, center=True).mean()

        ref_smoothed_y = ref_y[ref_train_window].rolling(
            window=nsmooth, min_periods=1, center=True).mean()
        train_smoothed_y = train_y[raw_train_window].rolling(
            window=nsmooth, min_periods=1, center=True).mean()

        bmorph_multipliers = cqm(raw_cdf, train_cdf, ref_cdf,
                                 raw_smoothed_y[raw_cdf_window],
                                 train_smoothed_y, ref_smoothed_y,
                                 bw=bw, xbins=xbins, ybins=ybins,
                                 rtol=rtol, atol=atol, method=method,
                                 train_cdf_min=train_cdf_min)
        if smooth_multipliers:
            bmorph_multipliers = bmorph_multipliers.rolling(window=nsmooth, min_periods=1, center=True).mean()
        bmorph_ts = bmorph_multipliers[raw_apply_window] * raw_ts[raw_apply_window]

    return bmorph_ts, bmorph_multipliers

def bmorph_correct(raw_ts, bmorph_ts, correction_window,
                   ref_mean, train_mean, nsmooth):
    '''Correct bmorphed values to preserve the ratio of change

    Apply a correction to bmorphed values to preserve the mean change over a
    `correction_window`. This is similar to teh correction applied in the
    original PresRat algorithm; Pierce et al. 2015;
    http://dx.doi.org/10.1175/JHM-D-14-0236.1), except that we use a rolling
    mean to determine the correction to avoid discontinuities on the
    boundaries.

    Parameters
    ----------
    raw_ts :    pandas.series
        Series of raw values that have not been bmorphed
    bmorph_ts : Bmorphed version of `raw_ts`
        Series of bmorphed values
    correction_window : slice
        Slice of `raw_ts` and `bmorph_ts` over which the correction is applied
    ref_mean : float
        Mean of target time series (`ref_ts`) for the base period
    train_mean : float
        Mean of training time series (`train_ts`) for the base period
    nsmooth : int
        Number of elements that will be smoothed in `raw_ts` and `bmorph_ts`.
        The nsmooth value in this case is typically much larger than the one
        used for the bmorph function itself. For example, 365 days.

    Returns
    -------
    bmorph_corrected_ts : pandas.Series
       Corrected series of length `correction_window`.

    '''
    # Type checking
    assert isinstance(raw_ts, pd.Series)
    assert isinstance(bmorph_ts, pd.Series)
    assert isinstance(correction_window, slice)

    # Smooth the raw and bmorphed time series
    raw_ts_smoothed = raw_ts.rolling(window=nsmooth, min_periods=1,
                                     center=True).mean()
    bmorph_ts_smoothed = bmorph_ts.rolling(window=nsmooth, min_periods=1,
                                           center=True).mean()

    # Calculate the correction factors
    correction_ts = raw_ts_smoothed[correction_window] / \
        bmorph_ts_smoothed[correction_window] * \
        ref_mean/train_mean

    # Apply the correction to the bmorph time series
    bmorph_corrected_ts = correction_ts * bmorph_ts[correction_window]

    return bmorph_corrected_ts, correction_ts


text:
//
//  CalendarMonthView.cs
//
//  Converted to MonoTouch on 1/22/09 - Eduardo Scoz || http://escoz.com
//  Originally reated by Devin Ross on 7/28/09  - tapku.com || http://github.com/devinross/tapkulibrary
//

using System;
using System.Collections.Generic;
using System.Drawing;
using CoreGraphics;
using Foundation;
using UIKit;
using TodoApp.Helpers;

namespace TodoApp.iOS.Controls {
	public delegate void DateSelected( DateTime date );

	public delegate void MonthChanged( DateTime monthSelected );

	public sealed class CalendarMonthView : UIView {
		private readonly int headerHeight;
		private readonly bool showHeader;
		private readonly float width;

		public DateTime CurrentMonthYear;
		public DateTime CurrentSelectedDate;

		public Func<DateTime, bool> IsDateAvailable;
		public Func<DateTime, bool> IsDayMarkedDelegate;

		public Action<DateTime> MonthChanged;
		public Action<DateTime> OnDateSelected;
		public Action<DateTime> OnFinishedDateSelection;
		public Action SwipedUp;

		private bool calendarIsLoaded;

		private MonthGridView monthGridView;
		private UIScrollView scrollView;

		#region Calendar view settings

		public int BoxHeight = 33;
		public int BoxWidth = 46;

		public float DayCellPadding = 1.5f;
		public int HorizontalPadding = 10;
		public int LinesCount = 6;
		public int VerticalPadding = 10;

		#endregion

		public CalendarMonthView( DateTime selectedDate, bool showHeader, float width = 320 ) {
			if (Math.Abs(width - 320) < 0.1)
				width = (float) UIScreen.MainScreen.Bounds.Size.Width;
			this.width = width;
			this.showHeader = showHeader;

			if (showHeader)
				headerHeight = 20;

			BoxWidth = Convert.ToInt32(Math.Ceiling(width/7)) - (int) Math.Ceiling(2*HorizontalPadding/7.0);

			int height = BoxHeight*LinesCount + 2*VerticalPadding + 10;

			// Calendar view frame (header, calendar, paddings).
			Frame = showHeader ? new RectangleF(0, 0, width, height + headerHeight) : new RectangleF(0, 0, width, height);

			BackgroundColor = UIColor.White;
			ClipsToBounds = true;

			CurrentSelectedDate = selectedDate;
			CurrentDate = DateTime.Now.Date;
			CurrentMonthYear = new DateTime(CurrentSelectedDate.Year, CurrentSelectedDate.Month, 1);

			// Actions on swipe.
			var swipeLeft = new UISwipeGestureRecognizer(MonthViewSwipedLeft) {
				Direction = UISwipeGestureRecognizerDirection.Left
			};
			AddGestureRecognizer(swipeLeft);

			var swipeRight = new UISwipeGestureRecognizer(MonthViewSwipedRight) {
				Direction = UISwipeGestureRecognizerDirection.Right
			};
			AddGestureRecognizer(swipeRight);

			var swipeUp = new UISwipeGestureRecognizer(MonthViewSwipedUp) {
				Direction = UISwipeGestureRecognizerDirection.Up
			};
			AddGestureRecognizer(swipeUp);
		}

		private DateTime CurrentDate { get; set; }

		public void SetDate( DateTime newDate ) {
			bool right = true;

			CurrentSelectedDate = newDate;

			int monthsDiff = (newDate.Month - CurrentMonthYear.Month) + 12*(newDate.Year - CurrentMonthYear.Year);
			if (monthsDiff != 0) {
				if (monthsDiff < 0) {
					right = false;
					monthsDiff = -monthsDiff;
				}

				for (int i = 0; i < monthsDiff; i++) {
					MoveCalendarMonths(right, true);
				}
			} else {
				RebuildGrid(right, false);
			}
		}

		private void MonthViewSwipedUp( UISwipeGestureRecognizer ges ) {
			SwipedUp.Dispatch();
		}

		private void MonthViewSwipedRight( UISwipeGestureRecognizer ges ) {
			// Move to previous month.
			MoveCalendarMonths(false, true);
		}

		private void MonthViewSwipedLeft( UISwipeGestureRecognizer ges ) {
			// Move to next month.
			MoveCalendarMonths(true, true);
		}

		/// <summary>
		///    Update calendar month view.
		/// </summary>
		public override void SetNeedsDisplay() {
			base.SetNeedsDisplay();
			if (monthGridView != null)
				monthGridView.Update();
		}

		public override void LayoutSubviews() {
			if (calendarIsLoaded) return;

			scrollView = new UIScrollView {
				ContentSize = new SizeF(width, 260),
				ScrollEnabled = false,
				Frame = new RectangleF(0, 16 + headerHeight, width, (float) Frame.Height - 16),
				BackgroundColor = UIColor.White
			};

			LoadInitialGrids();

			BackgroundColor = UIColor.Clear;

			AddSubview(scrollView);

			scrollView.AddSubview(monthGridView);

			calendarIsLoaded = true;
		}

		public void DeselectDate() {
			if (monthGridView != null)
				monthGridView.DeselectDayView();
		}

		/// <summary>
		///    Change calendar month.
		/// </summary>
		/// <param name="right">Direction of the transition.</param>
		/// <param name="animated">Animate transition.</param>
		public void MoveCalendarMonths( bool right, bool animated ) {
			CurrentMonthYear = CurrentMonthYear.AddMonths(right ? 1 : -1);
			RebuildGrid(right, animated);
		}

		/// <summary>
		///    Rebuild month grid.
		/// </summary>
		/// <param name="right">Direction of the transition.</param>
		/// <param name="animated">Animate transition.</param>
		public void RebuildGrid( bool right, bool animated ) {
			UserInteractionEnabled = false;

			// Get new month grid.
			MonthGridView gridToMove = CreateNewGrid(CurrentMonthYear);
			nfloat pointsToMove = (right ? Frame.Width : -Frame.Width);

			gridToMove.Frame = new RectangleF(new PointF((float) pointsToMove, VerticalPadding/2.0f), (SizeF) gridToMove.Frame.Size);

			scrollView.AddSubview(gridToMove);

			if (animated) {
				BeginAnimations("changeMonth");
				SetAnimationDuration(0.4);
				SetAnimationDelay(0.1);
				SetAnimationCurve(UIViewAnimationCurve.EaseInOut);
			}

			monthGridView.Center = new PointF((float) (monthGridView.Center.X - pointsToMove), (float) monthGridView.Center.Y);
			gridToMove.Center = new PointF((float) (gridToMove.Center.X - pointsToMove + HorizontalPadding), (float) gridToMove.Center.Y);

			monthGridView.Alpha = 0;

			SetNeedsDisplay();

			if (animated)
				CommitAnimations();

			monthGridView = gridToMove;

			UserInteractionEnabled = true;

			if (MonthChanged != null)
				MonthChanged(CurrentMonthYear);
		}

		/// <summary>
		///    Create new month grid.
		/// </summary>
		/// <param name="date">Needed month.</param>
		/// <returns>Return new calendar month grid view.</returns>
		private MonthGridView CreateNewGrid( DateTime date ) {
			var grid = new MonthGridView(this, date) {CurrentDate = CurrentDate};
			grid.BuildGrid();
			grid.Frame = new RectangleF(HorizontalPadding, VerticalPadding/2.0f, width - HorizontalPadding, (float) Frame.Height - 16);
			return grid;
		}

		private void LoadInitialGrids() {
			monthGridView = CreateNewGrid(CurrentMonthYear);
		}

		public override void Draw( CGRect rect ) {
			using (CGContext context = UIGraphics.GetCurrentContext()) {
				context.SetFillColor(UIColor.White.CGColor);
				context.FillRect(new RectangleF(0, 0, width, 18 + headerHeight));
			}

			// Add day of week labels (monday, tuesday, etc).
			DrawDayLabels(rect);

			// Displat month header.
			if (showHeader)
				DrawMonthLabel(rect);
		}

		private void DrawMonthLabel( CGRect rect ) {
			var r = new RectangleF(new PointF(0, 2), new SizeF {Width = width - HorizontalPadding*2, Height = 42});
			UIColor.DarkGray.SetColor();
			new NSString(CurrentMonthYear.ToString("MMMM yyyy")).DrawString(r, UIFont.BoldSystemFontOfSize(16),
				UILineBreakMode.WordWrap, UITextAlignment.Center);
		}

		/// <summary>
		///    Draw day of week labels.
		/// </summary>
		private void DrawDayLabels( CGRect rect ) {
			// Font size.
			UIFont font = UIFont.BoldSystemFontOfSize(11);
			// Font color.
			UIColor.Gray.SetColor();

			CGContext context = UIGraphics.GetCurrentContext();
			context.SaveState();

			int i = 0;
			foreach (string d in Enum.GetNames(typeof (DayOfWeek))) {
				new NSString(d.Substring(0, 3)).DrawString(
					new RectangleF(i*BoxWidth + HorizontalPadding, VerticalPadding/2.0f + headerHeight, BoxWidth, 10),
					font,
					UILineBreakMode.WordWrap,
					UITextAlignment.Center);
				i++;
			}
			context.RestoreState();
		}
	}

	public sealed class MonthGridView : UIView {
		private readonly CalendarMonthView calendarMonthView;

		private readonly IList<CalendarDayView> dayTiles = new List<CalendarDayView>();

		public int WeekdayOfFirst;
		private DateTime currentMonth;

		public MonthGridView( CalendarMonthView calendarMonthView, DateTime month ) {
			this.calendarMonthView = calendarMonthView;
			currentMonth = month.Date;

			var tapped = new UITapGestureRecognizer(OnTap);
			AddGestureRecognizer(tapped);
		}

		public DateTime CurrentDate { get; set; }

		public int Lines { get; set; }
		private CalendarDayView SelectedDayView { get; set; }
		public IList<DateTime> Marks { get; set; }

		private void OnTap( UITapGestureRecognizer tapRecg ) {
			CGPoint loc = tapRecg.LocationInView(this);
			if (SelectDayView((PointF) loc) && calendarMonthView.OnDateSelected != null)
				calendarMonthView.OnDateSelected(new DateTime(currentMonth.Year, currentMonth.Month,
					(int) SelectedDayView.Tag));
		}

		public void Update() {
			foreach (CalendarDayView v in dayTiles)
				UpdateDayView(v);

			SetNeedsDisplay();
		}

		public void UpdateDayView( CalendarDayView dayView ) {
			dayView.Marked = calendarMonthView.IsDayMarkedDelegate != null && calendarMonthView.IsDayMarkedDelegate(dayView.Date);
			dayView.Available = calendarMonthView.IsDateAvailable == null || calendarMonthView.IsDateAvailable(dayView.Date);
		}

		/// <summary>
		///    Build month grid.
		/// </summary>
		public void BuildGrid() {
			DateTime previousMonth = currentMonth.AddMonths(-1);
			int daysInPreviousMonth = DateTime.DaysInMonth(previousMonth.Year, previousMonth.Month);

			int daysInMonth = DateTime.DaysInMonth(currentMonth.Year, currentMonth.Month);
			WeekdayOfFirst = (int) currentMonth.DayOfWeek;

			int lead = daysInPreviousMonth - (WeekdayOfFirst - 1);

			int boxWidth = calendarMonthView.BoxWidth;
			int boxHeight = calendarMonthView.BoxHeight;

			// Build previous month's days.
			for (int i = 1; i <= WeekdayOfFirst; i++) {
				var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i);
				var dayView = new CalendarDayView(calendarMonthView) {
					Frame = new RectangleF((i - 1)*boxWidth - 1, 0, boxWidth, boxHeight),
					Date = viewDay,
					Text = lead.ToString()
				};

				AddSubview(dayView);
				dayTiles.Add(dayView);
				lead++;
			}

			int position = WeekdayOfFirst + 1;
			int line = 0;

			// Current month.
			for (int i = 1; i <= daysInMonth; i++) {
				var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i);
				var dayView = new CalendarDayView(calendarMonthView) {
					Frame = new RectangleF((position - 1)*boxWidth - 1, line*boxHeight, boxWidth, boxHeight),
					Today = (CurrentDate.Date == viewDay.Date),
					Text = i.ToString(),
					Active = true,
					Tag = i,
					Selected = (viewDay.Date == calendarMonthView.CurrentSelectedDate.Date),
					Date = viewDay
				};

				UpdateDayView(dayView);

				if (dayView.Selected)
					SelectedDayView = dayView;

				AddSubview(dayView);
				dayTiles.Add(dayView);

				position++;
				if (position > 7) {
					position = 1;
					line++;
				}
			}

			// Next month.
			int dayCounter = 1;
			if (position != 1) {
				for (int i = position; i < 8; i++) {
					var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i);
					var dayView = new CalendarDayView(calendarMonthView) {
						Frame = new RectangleF((i - 1)*boxWidth - 1, line*boxHeight, boxWidth, boxHeight),
						Text = dayCounter.ToString(),
						Date = viewDay,
					};
					UpdateDayView(dayView);

					AddSubview(dayView);
					dayTiles.Add(dayView);
					dayCounter++;
				}
			}

			while (line < calendarMonthView.LinesCount - 1) {
				line++;
				for (int i = 1; i < 8; i++) {
					var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i);
					var dayView = new CalendarDayView(calendarMonthView) {
						Frame = new RectangleF((i - 1)*boxWidth - 1, line*boxHeight, boxWidth, boxHeight),
						Text = dayCounter.ToString(),
						Date = viewDay,
					};
					UpdateDayView(dayView);

					AddSubview(dayView);
					dayTiles.Add(dayView);
					dayCounter++;
				}
			}

			Frame = new RectangleF((PointF) Frame.Location, new SizeF((float) Frame.Width, (line + 1)*boxHeight));

			Lines = (position == 1 ? line - 1 : line);

			if (SelectedDayView != null)
				BringSubviewToFront(SelectedDayView);
		}

		private bool SelectDayView( PointF p ) {
			int index = ((int) p.Y/calendarMonthView.BoxHeight)*7 + ((int) p.X/calendarMonthView.BoxWidth);
			if (index < 0 || index >= dayTiles.Count)
				return false;

			CalendarDayView newSelectedDayView = dayTiles[index];
			if (newSelectedDayView == SelectedDayView)
				return false;

			if (!newSelectedDayView.Active) {
				int day = int.Parse(newSelectedDayView.Text);
				if (day > 15)
					calendarMonthView.MoveCalendarMonths(false, true);
				else
					calendarMonthView.MoveCalendarMonths(true, true);
				return false;
			}
			if (!newSelectedDayView.Active && !newSelectedDayView.Available) {
				return false;
			}

			if (SelectedDayView != null)
				SelectedDayView.Selected = false;

			BringSubviewToFront(newSelectedDayView);
			newSelectedDayView.Selected = true;

			SelectedDayView = newSelectedDayView;
			calendarMonthView.CurrentSelectedDate = SelectedDayView.Date;
			SetNeedsDisplay();
			return true;
		}

		public void DeselectDayView() {
			if (SelectedDayView == null)
				return;

			SelectedDayView.Selected = false;
			SelectedDayView = null;
			SetNeedsDisplay();
		}
	}

	public sealed class CalendarDayView : UIView {
		private readonly CalendarMonthView monthView;
		private bool isActive;
		private bool isAvailable;
		private bool isMarked;
		private bool isSelected;
		private bool isToday;
		private string text;

		public CalendarDayView( CalendarMonthView monthView ) {
			this.monthView = monthView;
			BackgroundColor = UIColor.White;
		}

		public DateTime Date { get; set; }

		public bool Available {
			get { return isAvailable; }
			set {
				isAvailable = value;
				SetNeedsDisplay();
			}
		}

		public string Text {
			get { return text; }
			set {
				text = value;
				SetNeedsDisplay();
			}
		}

		public bool Active {
			get { return isActive; }
			set {
				isActive = value;
				SetNeedsDisplay();
			}
		}

		public bool Today {
			get { return isToday; }
			set {
				isToday = value;
				SetNeedsDisplay();
			}
		}

		public bool Selected {
			get { return isSelected; }
			set {
				isSelected = value;
				SetNeedsDisplay();
			}
		}

		public bool Marked {
			get { return isMarked; }
			set {
				isMarked = value;
				SetNeedsDisplay();
			}
		}

		public override void Draw( CGRect rect ) {
			// Day cell background.
			UIImage img;
			// Text color.
			UIColor color = UIColor.Gray;

			if (!Active || !Available) {
				// Day of next or previous month.
				img = UIImage.FromBundle("Images/Calendar/datecell_unactive.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4));
			} else if (Today && Selected) {
				// Selected today.
				color = UIColor.White;
				img = UIImage.FromBundle("Images/Calendar/todayselected.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4));
			} else if (Today) {
				// Unselected today.
				img = UIImage.FromBundle("Images/Calendar/today.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4));
			} else if (Selected || Marked) {
				// Selected day.
				img = UIImage.FromBundle("Images/Calendar/datecellselected.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4));
			} else {
				// Default day.
				img = UIImage.FromBundle("Images/Calendar/datecell.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4));
			}

			img.Draw(new RectangleF(0, 0, monthView.BoxWidth - monthView.DayCellPadding, monthView.BoxHeight - monthView.DayCellPadding));

			color.SetColor();
			var inflated = new RectangleF(0, 7, (float) Bounds.Width, (float) Bounds.Height);
			new NSString(Text).DrawString(
				inflated,
				UIFont.BoldSystemFontOfSize(12),
				UILineBreakMode.WordWrap,
				UITextAlignment.Center);
		}
	}
}


text:
package com.toolazydogs.aunit;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Lexer;
import org.antlr.runtime.Parser;
import org.antlr.runtime.RuleReturnScope;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.antlr.runtime.tree.Tree;
import org.antlr.runtime.tree.TreeParser;

import com.toolazydogs.aunit.internal.ParserWrapper;
import com.toolazydogs.aunit.internal.TreeParserWrapper;

/**
 * A holder of static methods that assist in testing.
 *

 * These methods will usually feed results into methods of {@link Assert}.
 *
 * @see Assert
 */
public final class Work
{
    /**
     * Scans a set of characters and returns results which can be fed into
     * Assert.assertToken(...).
     *
     * @param characters the characters to be scanned
     * @return results from the lexer that can be used by assert
     * @throws Exception if there is an error obtaining the lexer results
     */
    public static LexerResults scan(String characters) throws Exception
    {
        if (characters == null) throw new IllegalArgumentException("Characters cannot be null");
        if (AunitRuntime.getLexerFactory() == null) throw new IllegalStateException("Lexer factory not set by configuration");

        Lexer lexer = AunitRuntime.getLexerFactory().generate(new ANTLRStringStream(characters));
        return new LexerResults(lexer);
    }

    /**
     * Parse a set of characters and return an instance of {@link Tree}.
     * This tree can then be fed into Assert.assertTree(...).
     *

     * This method will throw an exception if there was an error parsing.  It
     * will also throw {@link ParserException} if the parsing failed and the
     * test has indicated that the parser should fail on error; see
     * {@link ParserOption#failOnError(boolean)}.
     *
     * @param characters   the characters to be parsed
     * @param selectedRule the starting rule
     * @return the tree that results from a successful parse
     * @throws Exception if there is an error parsing the characters
     * @see #rule(String, com.toolazydogs.aunit.Work.ArgumentBuilder)
     */
    public static Tree parse(String characters, SelectedRule selectedRule) throws Exception
    {
        if (characters == null) throw new IllegalArgumentException("Characters cannot be null");
        if (selectedRule == null) throw new IllegalArgumentException("SelectedRule cannot be null, please use rule()");
        if (AunitRuntime.getLexerFactory() == null) throw new IllegalStateException("Lexer factory not set by configuration");
        if (AunitRuntime.getParserFactory() == null) throw new IllegalStateException("Parser factory not set by configuration");

        Lexer lexer = AunitRuntime.getLexerFactory().generate(new ANTLRStringStream(characters));
        Parser parser = AunitRuntime.getParserFactory().generate(new CommonTokenStream(lexer));

        RuleReturnScope rs = selectedRule.invoke(parser);

        ParserWrapper wrapper = (ParserWrapper)parser;
        if (wrapper.isFailOnError() && !wrapper.getErrors().isEmpty())
        {
            throw new ParserException(wrapper.getErrors());
        }

        return (Tree)rs.getTree();
    }

    /**
     * Select a rule to be used as a starting point in
     *
     * @param rule the name of the rule to select
     * @return the selected rule
     * @throws Exception if no rule can be found
     * @see #parse(String, SelectedRule)
     */
    public static SelectedRule rule(String rule) throws Exception
    {
        return rule(rule, args());
    }

    /**
     * Select a rule to be used as a starting point in
     *
     * @param rule      the name of the rule to select
     * @param arguments arguments to be passed in the invocation of the rule when parsing
     * @return the selected rule
     * @throws Exception if no rule can be found
     * @see #parse(String, SelectedRule)
     * @see #args(Object...)
     */
    public static SelectedRule rule(String rule, ArgumentBuilder arguments) throws Exception
    {
        if (AunitRuntime.getParserFactory() == null) throw new IllegalStateException("Parser factory not set by configuration");

        for (Method method : collectMethods(AunitRuntime.getParserFactory().getParserClass()))
        {
            if (method.getName().equals(rule))
            {
                return new SelectedRule(method, arguments.get());
            }
        }

        throw new Exception("Rule " + rule + " not found");
    }

    /**
     * Select a tree rule be used as a starting point in tree walking
     *
     * @param rule the name of the rule to select
     * @return the selected rule
     * @throws Exception if no rule can be found
     */
    public static SelectedRule withRule(String rule) throws Exception
    {
        return withRule(rule, args());
    }

    /**
     * Select a tree rule be used as a starting point in tree walking
     *
     * @param rule      the name of the rule to select
     * @param arguments arguments to be passed in the invocation of the rule when parsing
     * @return the selected rule
     * @throws Exception if no rule can be found
     */
    public static SelectedRule withRule(String rule, ArgumentBuilder arguments) throws Exception
    {
        if (AunitRuntime.getTreeParserFactory() == null) throw new IllegalStateException("TreeParser factory not set by configuration");

        for (Method method : collectMethods(AunitRuntime.getTreeParserFactory().getTreeParserClass()))
        {
            if (method.getName().equals(rule))
            {
                return new SelectedRule(method, arguments.get());
            }
        }

        throw new Exception("Rule " + rule + " not found");
    }

    /**
     * Parse a set of characters and return an instance of {@link Tree}.
     * This tree can then be fed into Assert.assertTree(...).
     *

     * This method will throw an exception if there was an error parsing.  It
     * will also throw {@link ParserException} if the parsing failed and the
     * test has indicated that the parser should fail on error; see
     * {@link ParserOption#failOnError(boolean)}.
     *
     * @param walkerRule the starting walker rule
     * @param tree       the tree to be walked
     * @return true on success
     * @throws Exception if there is an error during walking
     * @see #withRule(String, com.toolazydogs.aunit.Work.ArgumentBuilder)
     */
    public static boolean walk(SelectedRule walkerRule, TreeBuilder tree) throws Exception
    {
        if (walkerRule == null) throw new IllegalArgumentException("WalkerRule cannot be null, please use rule()");
        if (tree == null) throw new IllegalArgumentException("Tree cannot be null");
        if (AunitRuntime.getTreeParserFactory() == null) throw new IllegalStateException("Walker factory not set by configuration");

        TreeParser treeParser = AunitRuntime.getTreeParserFactory().generate(new CommonTreeNodeStream(tree.get()));

        RuleReturnScope rs = walkerRule.invoke(treeParser);

        TreeParserWrapper wrapper = (TreeParserWrapper)treeParser;
        if (wrapper.isFailOnError() && !wrapper.getErrors().isEmpty())
        {
            throw new ParserException(wrapper.getErrors());
        }

        return true;
    }

    public static ArgumentBuilder args(Object... arguments)
    {
        return new ArgumentBuilder(arguments);
    }

    public static TreeBuilder resultOf(Tree tree)
    {
        return new TreeBuilder(tree);
    }

    public static class ArgumentBuilder
    {
        private final Object[] arguments;

        ArgumentBuilder(Object... arguments)
        {
            this.arguments = arguments;
        }

        Object[] get()
        {
            return this.arguments;
        }
    }

    public static class TreeBuilder
    {
        private final Tree tree;

        TreeBuilder(Tree tree)
        {
            this.tree = tree;
        }

        Tree get()
        {
            return this.tree;
        }
    }

    /**
     * Generate an instance of the configured parser using a string as a
     * source for input.
     *
     * @param src the string to use as input to the new parser instance.
     * @param <T> the type of the parser
     * @return an instance of the configured parser
     * @throws Exception if there is an error generating the parser
     */
    public static <T> T generateParser(String src) throws Exception
    {
        ANTLRInputStream input = new ANTLRInputStream(new ByteArrayInputStream(src.getBytes()));
        Lexer lexer = AunitRuntime.getLexerFactory().generate(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        //noinspection unchecked
        return (T)AunitRuntime.getParserFactory().generate(tokens);
    }

    /**
     * Generate an instance of the configured parser using a file as a
     * source for input.
     *
     * @param src the file to use as input to the new parser instance.
     * @param <T> the type of the parser
     * @return an instance of the configured parser
     * @throws Exception if there is an error generating the parser
     */
    public static <T> T generateParser(File src) throws Exception
    {
        ANTLRInputStream input = new ANTLRInputStream(new FileInputStream(src));
        Lexer lexer = AunitRuntime.getLexerFactory().generate(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        //noinspection unchecked
        return (T)AunitRuntime.getParserFactory().generate(tokens);
    }

    /**
     * Recursively collect the set of declared methods of a class and
     * its super class.
     *
     * @param clazz the class whose methods to collect
     * @return the set of declared methods of a class
     */
    private static Set<Method> collectMethods(Class clazz)
    {
        if (clazz == null) return Collections.emptySet();

        Set<Method> s = new HashSet<Method>();

        s.addAll(Arrays.asList(clazz.getDeclaredMethods()));
        s.addAll(collectMethods(clazz.getSuperclass()));

        return s;
    }

    private Work() { }
}


text:
var fs = require('fs');
var path = require('path');

var Server = require('../../lib/main');

var sandboxPath = path.resolve('features/sandbox/');
var configPath = path.join(sandboxPath, 'bower.conf.json');
var originalConfigPath = path.resolve('bower.conf.json');

module.exports = function() {
    var server;

    function _start(configurationModifier) {
        createSandbox();

        goToSandbox();

        copyConfig();

        return startServer();

        function createSandbox() {
            if(!fs.existsSync(sandboxPath)) {
                fs.mkdir(sandboxPath);
            }
        }

        function goToSandbox() {
            if(process.cwd() !== sandboxPath) {
                process.chdir(sandboxPath);
            }
        }

        function copyConfig() {
            var config = JSON.parse(fs.readFileSync(originalConfigPath).toString());

            if(configurationModifier) {
                config = configurationModifier(config);
            }

            fs.writeFileSync(configPath, JSON.stringify(config, null, '    '));
        }

        function startServer() {
            server = Server();

            return server.start(configPath);
        }
    }

    function _stop() {
        try {
            server.shutDown(true);
        }
        catch(e) {}

        require('../../lib/service/packageStores/privatePackageStore').packages = {};

        clearSandbox();

        function clearSandbox() {
            forAllItemsInDirectory(sandboxPath, deleteItemsSync);

            function deleteItemsSync(itemPath) {
                if(fs.statSync(itemPath).isDirectory()) {
                    forAllItemsInDirectory(itemPath, deleteItemsSync);

                    fs.rmdirSync(itemPath);
                }
                else {
                    fs.unlinkSync(itemPath);
                }
            }

            function forAllItemsInDirectory(folderPath, callback) {
                fs.readdirSync(folderPath)
                    .forEach(function(childName) {
                        callback(path.join(folderPath, childName));
                    });
            }
        }
    }

    return {
        start: _start,
        stop: _stop
    };
};


text:
#ifndef COMICDATABASERESOURCE_H
#define COMICDATABASERESOURCE_H

#include <QObject>
#include <QSqlDatabase>

class Comic;

class ComicDatabaseResource : public QObject
{
    Q_OBJECT

    static const QString _databaseName;
    static const QString _comicsTableName;

public:
    static ComicDatabaseResource* instance();
    bool openDb();
    bool load(Comic* comic);
    bool save(Comic* comic);
    QStringList favoriteIds();
    bool saveFavorites(QStringList favoriteIds);

private:
    explicit ComicDatabaseResource(QObject *parent = 0);
    QString dbDirPath();
    QString dbFilePath();
    void checkStructure();
    bool createStructure();
    bool createDbFile();

private:
    static ComicDatabaseResource* m_instance;
    QSqlDatabase db;
    QString m_dbDirPath;
    QString m_dbFilePath;
};

#endif // COMICDATABASERESOURCE_H


text:
package org.ofbiz.service.config.model;

import org.ofbiz.base.lang.ThreadSafe;
import org.ofbiz.service.config.ServiceConfigException;
import org.w3c.dom.Element;

/**
 * An object that models the <notification> element.
 */
@ThreadSafe
public final class Notification {

    private final String screen;
    private final String service;
    private final String subject;

    Notification(Element notificationElement) throws ServiceConfigException {
        String subject = notificationElement.getAttribute("subject").intern();
        if (subject.isEmpty()) {
            throw new ServiceConfigException("<notification> element subject attribute is empty");
        }
        this.subject = subject;
        String screen = notificationElement.getAttribute("screen").intern();
        if (subject.isEmpty()) {
            throw new ServiceConfigException("<notification> element screen attribute is empty");
        }
        this.screen = screen;
        String service = notificationElement.getAttribute("service").intern();
        if (service.isEmpty()) {
            service = "sendMailFromScreen";
        }
        this.service = service;

    }

    public String getScreen() {
        return screen;
    }

    public String getService() {
        return this.service;
    }

    public String getSubject() {
        return subject;
    }
}


text:
class TournamentHelper {
  constructor(db) {
    this.db = db
  }

  async list() {
    const tournamentsRef = this.db.ref('tournaments')
    const snapshot = await tournamentsRef.once('value')
    const val = snapshot.val()
    const tournaments = []
    if (!val) return []
    Object.keys(val).forEach((key) => {
      tournaments.push({...val[key], key})
    })
    return tournaments
  }

  async restart(tournament) {
    const id = tournament.id
    const tablesRef = this.db.ref(`tables/${id}`)
    const snapshot = await tablesRef.once('value')
    const val = snapshot.val()
    const tables = []
    if (!val) return []
    Object.keys(val).forEach((key) => {
      tables.push({...val[key], key})
    })
    tables.forEach((table) => {
      if (table.number > tournament.end || table.number < tournament.start) {
        this.db.ref(`tables/${id}/${table.number}`).remove()
        return
      }
      this.db.ref(`tables/${id}/${table.key}`).set({
        number: table.number,
        time: table.time,
        teamTime: {
          A: table.teamTime.A,
          B: table.teamTime.B,
          C: table.teamTime.C,
        },
        status: '',
        teamStatus: {
          A: '',
          B: '',
          C: '',
        },
        doneTime: null,
        hasResult: false,
        result: null,
        isFeatured: false,
        zoneId: table.zoneId,
      })
    })
  }

  delete(id) {
    return this.db.ref(`tournaments/${id}`).remove()
  }

  async getPassword(id) {
    const snapshot = await this.db.ref(`passwords/${id}`).once('value')
    return snapshot.val()
  }
}

module.exports = TournamentHelper


text:
package com.github.sawied.jweb.api.bean;

import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Length;

public class PersonInfo {

	@NotNull
	@Length(max=50,min=1)
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


text:
package guardgate

import (
	"net"
	"net/http"
	"os"
	"reflect"
	"testing"
	"time"

	spec "knative.dev/security-guard/pkg/apis/guard/v1alpha1"
)

var gateCanceled int

func fakeGateCancel() {
	gateCanceled++
}

func fakeGateState() *gateState {
	gs := new(gateState)
	gs.init(fakeGateCancel, false, "myurl", "mysid", "myns", true)
	srv, _ := fakeClient(http.StatusOK, "Problem in request")
	gs.srv = srv
	return gs
}

func Test_gateState_loadConfig(t *testing.T) {
	t.Run("simple", func(t *testing.T) {
		gs := fakeGateState()

		gs.loadConfig()
		if gs.criteria == nil || gs.ctrl == nil {
			t.Error("nil after load")
		}
		gs.criteria.Active = false
		gs.profileAndDecidePod()
		if gateCanceled != 0 {
			t.Error("expected no cancel")
		}

		// this test only checks if panic
		// we cant be sure what the response will be as it depends on the /proc
		gs.monitorPod = true
		gs.criteria.Active = true
		gateCanceled = 0
		gs.profileAndDecidePod()

		var pp spec.PodProfile
		gs.monitorPod = false
		gs.copyPodProfile(&pp)
		gs.monitorPod = true
		gs.copyPodProfile(&pp)
		if !reflect.DeepEqual(&gs.pod, &pp) {
			t.Errorf("expected %v to be equal to %v", pp, gs.pod)
		}

		gs.stat.Init()
		gs.alert = ""
		gs.addStat("XX")
		gs.addStat("XX")
		if ret := gs.stat.Log(); ret != "map[XX:2]" {
			t.Errorf("expected stat.log to be %s received %s", "map[XX:2]", ret)
		}
		if gs.shouldBlock() != false {
			t.Error("expected false in shouldBlock")
		}
		if gs.hasAlert() != false {
			t.Error("expected false in hasAlert")
		}
		if gs.shouldLearn(true) != false {
			t.Error("expected false in shouldLearn")
		}

		// envelop
		ep := new(spec.EnvelopProfile)
		now := time.Now()
		ep.Profile(now, now, now)
		if ret := gs.decideEnvelop(ep); ret != "" {
			t.Error("expected no alert")
		}
		ep.Profile(time.Unix(1, 1), time.Unix(3, 3), time.Unix(5, 5))
		gs.decideEnvelop(ep)
		if ret := gs.decideEnvelop(ep); ret == "" {
			t.Error("expected alert")
		}

		// req
		req := new(spec.ReqProfile)
		r, _ := http.NewRequest("Get", "", nil)
		cip := net.ParseIP("1.2.3.4")
		req.Profile(r, cip)
		gs.criteria.Active = false
		if ret := gs.decideReq(req); ret != "" {
			t.Error("expected no alert")
		}
		gs.criteria.Active = true
		if ret := gs.decideReq(req); ret == "" {
			t.Error("expected alert")
		}

		// resp
		resp := new(spec.RespProfile)
		rs := &http.Response{ContentLength: 20}

		resp.Profile(rs)
		gs.criteria.Active = false
		if ret := gs.decideResp(resp); ret != "" {
			t.Error("expected no alert")
		}
		gs.criteria.Active = true
		if ret := gs.decideResp(resp); ret == "" {
			t.Error("expected alert")
		}

		// reqBody
		body := new(spec.BodyProfile)
		body.ProfileUnstructured("x")
		gs.criteria.Active = false
		if ret := gs.decideReqBody(body); ret != "" {
			t.Error("expected no alert")
		}
		if ret := gs.decideRespBody(body); ret != "" {
			t.Error("expected no alert")
		}
		gs.criteria.Active = true
		if ret := gs.decideReqBody(body); ret == "" {
			t.Error("expected alert")
		}
		if ret := gs.decideRespBody(body); ret == "" {
			t.Error("expected alert")
		}

		gs.flushPile()
		if gs.srv.pile.Count != 0 {
			t.Error("expected pile too have 1")
		}
		profile := new(spec.SessionDataProfile)
		gs.addProfile(profile)
		if gs.srv.pile.Count != 1 {
			t.Error("expected pile too have 1")
		}
		gs.flushPile()
		if gs.srv.pile.Count != 0 {
			t.Error("expected pile too have 1")
		}
	})

}

func Test_gateState_init(t *testing.T) {
	tests := []struct {
		name  string
		cert  string
		newCA bool
	}{
		{
			name: "empty",
			cert: "",
		},
		{
			name: "bad",
			cert: "xx",
		},
		{
			name:  "good",
			cert:  testCert,
			newCA: true,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			os.Setenv("ROOT_CA", tt.cert)
			gs := new(gateState)
			// certPool, _ := x509.SystemCertPool()
			gs.init(fakeGateCancel, false, "myurl", "mysid", "myns", true)
			// TBD will be added when we move to go 1.19
			// if !certPool.Equal(gs.certPool) && !tt.newCA {
			// 	 t.Errorf("expected no new cert to be added")
			// }
			// if certPool.Equal(gs.certPool) && tt.newCA {
			//	 t.Errorf("expected new cert to be added")
			// }
			os.Unsetenv("ROOT_CA")
		})
	}
}


text:
<?php
namespace jp3cki\homado;

use Normalizer;
use RuntimeError;
use Abraham\TwitterOAuth\TwitterOAuth;
use jp3cki\homado\config\Config;
use jp3cki\homado\config\TargetWord as TargetWordConfig;

class Application
{
    private $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function run()
    {
        $twitter = $this->getTwitterClient();
        foreach ($this->makeTweets() as $message) {
            $twitter->post('statuses/update', ['status' => $message]);
        }
    }

    private function makeTweets()
    {
        $targetConfig = $this->config->getTargetConfig();

        $tweetList = $this->getTweetList($targetConfig->getTargetId());
        if (empty($tweetList)) {
            return [];
        }

        $ret = [];
        foreach ($targetConfig->getTargetWords() as $targetWord) {
            $text = $this->makeTweet($tweetList, $targetWord);
            if ($text !== false && $text != '') {
                $ret[] = $text;
            }
        }
        return $ret;
    }

    private function makeTweet(array $tweets, TargetWordConfig $word)
    {
        $matchedTweets = array_filter(
            $tweets,
            function ($tweet) use ($word) {
                return $word->isMatch($tweet['text']);
            }
        );
        if (!empty($matchedTweets)) {
            $firstMatchedAt = min(
                array_map(
                    function ($tweet) {
                        return $tweet['at'];
                    },
                    $matchedTweets
                )
            );
            $lastMatchedAt = max(
                array_map(
                    function ($tweet) {
                        return $tweet['at'];
                    },
                    $matchedTweets
                )
            );
        } else {
            $firstMatchedAt = null;
            $lastMatchedAt = null;
        }

        $matchedCount = count($matchedTweets);
        $replace = [
            'totalCount' => count($tweets),
            'matchCount' => $matchedCount,
            'avgMin' => $matchedCount >= 2
                ? number_format(
                    ($lastMatchedAt - $firstMatchedAt) / $matchedCount / 60,
                    1,
                    '.',
                    ''
                )
                : null,
            'ratio' => empty($tweets)
                ? null
                : number_format($matchedCount * 100 / count($tweets), 1, '.', ''),
            'lastMatchAgo' => time() - $lastMatchedAt >= 3600
                ? (floor((time() - $lastMatchedAt) / 3600) . '時間')
                : (floor((time() - $lastMatchedAt) / 60) . '分間'),
        ];
        return preg_replace_callback(
            '/\{([[:alnum:]]+)\}/',
            function ($match) use ($replace) {
                return isset($replace[$match[1]])
                    ? $replace[$match[1]]
                    : $match[0];
            },
            $word->getFormat($matchedCount)
        );
    }

    // returns array<['text' => ..., 'at' => int]>
    private function getTweetList($twitterUserId)
    {
        $list = $this->getTwitterClient()->get(
            'statuses/user_timeline',
            [
                'user_id' => $twitterUserId,
                'count' => 200,
                'exclude_replies' => 'true',
                'include_rts' => 'false',
                'trim_user' => 'true',
            ]
        );
        if (!is_array($list) || empty($list)) {
            return [];
        }
        return array_map(
            function (\stdClass $tweet) {
                $text = html_entity_decode($tweet->text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $text = Normalizer::normalize($text, Normalizer::FORM_C);
                $text = mb_convert_kana($text, 'asKV', 'UTF-8');
                $text = preg_replace('/[[:space:]]+/s', ' ', $text);
                return [
                    'text' => $text,
                    'at' => strtotime($tweet->created_at)
                ];
            },
            $list
        );
    }

    private function getTwitterClient()
    {
        $tw = $this->config->getTwitterConfig();
        return new TwitterOAuth(
            $tw->getConsumerKey(),
            $tw->getConsumerSecret(),
            $tw->getUserToken(),
            $tw->getUserSecret()
        );
    }
}


text:
package com.nm019689.breakout;

import android.graphics.Rect;

/**
 * Represents a single game block object. Extends a ShapeDrawable to include a
 * Color value and a method for exporting the coordinates and color in order to
 * save its state.
 */
public class Block extends Entity {

    public Block(Rect rect, int color) {
        super(rect, color);
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.youtube.model;

/**
 * Basic details about rating of a video.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the YouTube Data API v3. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class VideoRating extends com.google.api.client.json.GenericJson {

  /**
   * Rating of a video.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String rating;

  /**
   * The ID that YouTube uses to uniquely identify the video.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String videoId;

  /**
   * Rating of a video.
   * @return value or {@code null} for none
   */
  public java.lang.String getRating() {
    return rating;
  }

  /**
   * Rating of a video.
   * @param rating rating or {@code null} for none
   */
  public VideoRating setRating(java.lang.String rating) {
    this.rating = rating;
    return this;
  }

  /**
   * The ID that YouTube uses to uniquely identify the video.
   * @return value or {@code null} for none
   */
  public java.lang.String getVideoId() {
    return videoId;
  }

  /**
   * The ID that YouTube uses to uniquely identify the video.
   * @param videoId videoId or {@code null} for none
   */
  public VideoRating setVideoId(java.lang.String videoId) {
    this.videoId = videoId;
    return this;
  }

  @Override
  public VideoRating set(String fieldName, Object value) {
    return (VideoRating) super.set(fieldName, value);
  }

  @Override
  public VideoRating clone() {
    return (VideoRating) super.clone();
  }

}