text:
<?php

use crazedsanity\AuthUser;
use crazedsanity\core\ToolBox;
use crazedsanity\dbsession;

class TestOfAuthUser extends crazedsanity\database\TestDbAbstract {

	public $userInfo = array(
		'username'	=> 'test',
		'uid'		=> 1,
	);

	public function __construct() {
		parent::__construct();
	}//end __construct()

	public function setUp() {
		parent::setUp();
		$this->reset_db(dirname(__FILE__) .'/../setup/schema.pgsql.sql');
	}
	public function tearDown(){
//		parent::tearDown();
		unset($_SESSION);
	}

	/**
	 * Ensuring these functions are enabled is really the job of the
	 * application... the "bootstrap.php" script handles this for unit testing.
	 */
	public function test_passwordCompat() {
		$funcList = array(
			'password_hash', 'password_get_info',
			'password_needs_rehash', 'password_verify',
		);

		foreach($funcList as $func) {
			$this->assertTrue(function_exists($func), "Required function '".
					$func ."' is missing, use composer to install the ".
					"'ircmaxell/password-compat' library or upgrade to ".
					"PHP 5.5+");
		}
	}

	public function test_collisionOfConstants() {
		$x = new _empty_testAuthUser();
		$myConstants = array(
			'md5'			=> $x::HASH_MD5,
			'sha1'			=> $x::HASH_SHA1,
			'sha256'		=> $x::HASH_SHA256,
			'sha512'		=> $x::HASH_SHA512,
			'PHP-bcrypt'	=> constant('PASSWORD_BCRYPT'),
//			'PHP-default'	=> constant('PASSWORD_DEFAULT'),	// the default is PHP-bcrypt...
		);

		foreach($myConstants as $yName => $yVal) {
			foreach($myConstants as $zName => $zVal) {
				if($zName == $yName) {
					$this->assertEquals($zVal, $yVal, "constants do not match for '". $zName ."' and '". $yName ."'... but they should");
				}
				else {
					$this->assertNotEquals($zVal, $yVal, "collision detected: '". $zName ."' matches value for '". $yName ."' (". $zVal ."=". $yVal .")");
				}
			}
		}

		$this->assertEquals($x::HASH_PHPDEFAULT, PASSWORD_DEFAULT);
		$this->assertEquals($x::HASH_PHPBCRYPT, PASSWORD_BCRYPT);
	}

	public function test_validBaseData() {
		//$x = new AuthUser($this->dbObj);
		$x = new _test_authUser($this->dbObj);

		$this->assertFalse($x->is_authenticated());

		$numRows = $this->dbObj->run_query('SELECT * FROM cs_authentication_table');
		$this->assertTrue($numRows > 0);
		$data = $this->dbObj->farray_fieldnames();

		$this->assertEquals(0, $data[0]['uid']);
		$this->assertEquals('anonymous', $data[0]['username']);
		$this->assertEquals(0, strlen($data[0]['passwd']));

		$this->assertEquals(1, $data[1]['uid']);
		$this->assertEquals('test', $data[1]['username']);
		$this->assertEquals(40, strlen($data[1]['passwd']));

		$this->assertEquals(2, $data[2]['uid']);
		$this->assertEquals('administrator', $data[2]['username']);
		$this->assertEquals(40, strlen($data[2]['passwd']));
	}

	public function test_sessionStuff() {
		$myAuthData = array(
			'uid'	=> 999,
			'user'	=> 999,
			'stuff'	=> "dsfadsfadsfads"
		);

		$this->assertFalse(isset($_SESSION));
		$x = new _test_authUser($this->dbObj, false);
		$this->assertFalse(isset($_SESSION));
		$_SESSION = array();
		$this->assertTrue(isset($_SESSION));
		$this->assertEquals(array(), $_SESSION);

		$x->update_auth_data($myAuthData);
		$this->assertEquals($myAuthData, $_SESSION['auth']['userInfo']);
		$this->assertEquals(999, $_SESSION['uid']);
	}

	/**
	 */
	public function test_simpleAuthentication() {
		$this->assertFalse(isset($_SESSION));

		$_SESSION = array();
		$this->assertTrue(isset($_SESSION));
		$this->assertEquals(array(), $_SESSION);

		$_SESSION['uid'] = 0;

		$x = new _test_authUser($this->dbObj, false);
		$this->assertFalse(isset($_SESSION['auth']));

		//test that our first attempt doesn't work, because we don't know the password.
		$originalUserData = $x->get_user_data(1,true);
		$this->assertEquals('75eba0f69d185ef816d0cee43ad44d4b2240de02', $originalUserData['passwd']);
		$this->assertTrue(is_array($originalUserData));
//		$oldPassHash = $originalUserData['passwd'];
//		$this->assertNotEquals($originalUserData['passwd'], $x->getPasswordHash(array('test', 'test'), strlen($originalUserData['passwd'])));
		$this->assertFalse((bool)$x->login('test', 'test'));

		//Change test's password...
		$passwd = '_unitTe5t3r';
		$user = 'test';

//		$newHash = $x->getPasswordHash(array('username'=>$user, 'passwd'=>$passwd), $x::HASH_SHA1);
//		$this->assertEquals(
//				$newHash,
//				sha1(implode('-', array($user, $passwd)))
//		);
		$uid = 1;
//		$userInfo = array(
//			'uid'		=> 1,
//			'username'	=> $user,
//		);
		$this->assertEquals(1, $x->update_passwd($uid, $passwd), 'Failed to set password');

		$updatedUserInfo = $x->get_user_data(1);
		$this->assertNotEquals($originalUserData['passwd'], $updatedUserInfo['passwd']);

		$compareOriginal = $originalUserData;
		$compareUpdated = $updatedUserInfo;
		$this->assertEquals(AuthUser::STATUS_ENABLED, $updatedUserInfo['user_status_id']);
		unset($compareOriginal['passwd'], $compareUpdated['passwd']);
		$this->assertEquals($compareOriginal, $compareUpdated);

		$this->assertFalse($x->is_authenticated());

		$_SESSION = array();
		$this->assertEquals(count($_SESSION), 0);

		$this->assertFalse($x->is_authenticated());
		$this->assertTrue($x->update_passwd($uid, $passwd), "Failed to update password");
		$this->assertFalse($x->is_authenticated());
		$this->assertFalse($x->check_sid());

		$this->assertFalse((bool)$x->login(ucfirst($user), $passwd), "Username accepted with incorrect casing");
		$this->assertFalse($x->is_authenticated());
		$this->assertFalse($x->check_sid());

		$this->assertTrue((bool)$x->login($user, $passwd), "Failed to login");
		$this->assertTrue($x->is_authenticated());
		$this->assertTrue($x->check_sid());

		$this->assertTrue((bool)$x->logout_sid());
		$this->assertFalse($x->is_authenticated());
		$this->assertFalse($x->check_sid());

	}

	public function test_update_passwd_with_null() {
		$x = new AuthUser($this->dbObj);

		try {
			$this->assertFalse($x->update_passwd(array('username'=>'test'), null));
			$this->fail("password allowed to be null");
		}
		catch(Exception $ex) {
			if(!preg_match('/update_passwd: invalid ID or password/', $ex->getMessage())) {
				$this->fail("malformed or unexpected content in exception: ". $ex->getMessage());
			}
		}

	}

	public function test_update_password_with_invalid_username() {
		$x = new AuthUser($this->dbObj);
		try {
			$x->update_passwd(99999999, "");
			$this->fail("updating password for non-existent user worked");
		} catch (Exception $ex) {
			if(!preg_match('/update_user_info:.+failed to update user information/', $ex->getMessage())) {
				$this->fail("unexpected exception data: ". $ex->getMessage());
			}
		}
	}

	public function test_get_user_data() {
		$x = new AuthUser($this->dbObj);

		$data = $x->get_user_data('test', $x::STATUS_ENABLED);
		$this->assertTrue(is_array($data), ToolBox::debug_print($data));

		$this->assertTrue(isset($data['uid']));
		$this->assertTrue(isset($data['username']));
		$this->assertTrue(isset($data['passwd']));
//		$this->assertTrue(isset($data['date_created']));
//		$this->assertTrue(isset($data['last_login']));
//		$this->assertTrue(isset($data['email']));
		$this->assertTrue(isset($data['user_status_id']));

		// Ensure retrieval with any other status fails.
		{
			try {
				$this->assertFalse(is_array($x->get_user_data('test', $x::STATUS_DISABLED)));
			} catch (Exception $ex) {
				if(!preg_match('/failed to retrieve a single user \(0\)/', $ex->getMessage())) {
					$this->fail("unexpected or invalid exception message: ". $ex->getMessage());
				}
			}
			try {
				$this->assertFalse(is_array($x->get_user_data('test', $x::STATUS_PENDING)));
			} catch (Exception $ex) {
				if(!preg_match('/failed to retrieve a single user \(0\)/', $ex->getMessage())) {
					$this->fail("unexpected or invalid exception message: ". $ex->getMessage());
				}
			}
			try {
				$this->assertFalse(is_array($x->get_user_data('test', 99999)));
			} catch (Exception $ex) {
				if(!preg_match('/failed to retrieve a single user \(0\)/', $ex->getMessage())) {
					$this->fail("unexpected or invalid exception message: ". $ex->getMessage());
				}
			}
		}
	}

	public function test_update_user_data() {
		$x = new AuthUser($this->dbObj);

		$data = $x->get_user_data('test', $x::STATUS_ENABLED);

		$this->assertTrue(is_array($data));
		$this->assertTrue(isset($data['uid']));
		$this->assertTrue(is_numeric($data['uid']));
		$this->assertEquals($data['user_status_id'], $x::STATUS_ENABLED);

		try {
			$x->update_user_info(array(), $data['uid']);
			$this->fail("Successfully updated... nothing");
		}
		catch(Exception $ex) {
			if(!preg_match("/invalid user info/", $ex->getMessage())) {
				$this->fail("unexpected or invalid exception message: ". $ex->getMessage());
			}
		}

		try {
			$x->update_user_info(array(''=>"test"), $data['uid']);
			$this->fail("Successfully updated without specifying a field");
		} catch (Exception $ex) {
			if(!preg_match("/invalid parameter number/i", $ex->getMessage())) {
				$this->fail("unexpected or invalid exception message: ". $ex->getMessage());
			}
		}

		$updateResult = $x->update_user_info(array('email'=> 'Poop@user.com'), $data['uid']);

		$this->assertEquals(1, $updateResult);

		$newData = $x->get_user_data('test', $x::STATUS_ENABLED);
		$this->assertEquals($newData['uid'], $data['uid']);
		$this->assertNotEquals($data, $newData);

		$disableResult = $x->update_user_info(array('user_status_id'=>$x::STATUS_DISABLED), $data['uid']);
		$this->assertEquals(1, $disableResult);

		try {
			$x->get_user_data('test', $x::STATUS_ENABLED);
			$this->fail("Found user enabled even after disabling them");
		} catch (Exception $ex) {
			if(!preg_match("/failed to retrieve a single user \(0\)/", $ex->getMessage())) {
				$this->fail("unexpected or invalid exception message: ". $ex->getMessage());
			}
		}
//		$this->assertEquals(array(), $x->get_user_data('test', $x::STATUS_ENABLED));
	}
}

class _test_authUser extends AuthUser {
	public function __construct($db){
		parent::__construct($db, false);
	}

	public function update_auth_data(array $data) {
		return parent::update_auth_data($data);
	}

	public function get_user_data($uid, $onlyStatus=self::STATUS_ENABLED) {
		return parent::get_user_data($uid, $onlyStatus);
	}

	public function __sleep() {
		return array();
	}
	public function __wakeup() {
		return array();
	}
}

class _empty_testAuthUser extends AuthUser {
	public function __construct($db=null) {
	}
}


text:
//
// ProxyListener.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2020 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using System;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Collections;

using NetworkStream = MailKit.Net.NetworkStream;

namespace UnitTests.Net.Proxy {
	abstract class ProxyListener : IDisposable
	{
		CancellationTokenSource cancellationTokenSource;
		TcpListener listener;
		Task runningTask;
		bool disposed;

		protected ProxyListener ()
		{
		}

		~ProxyListener ()
		{
			Dispose (false);
		}

		public bool IsRunning {
			get; private set;
		}

		public IPAddress IPAddress {
			get; private set;
		}

		public int Port {
			get; private set;
		}

		public void Start (IPAddress addr, int port)
		{
			listener = new TcpListener (addr, port);
			listener.Start (1);

			IPAddress = ((IPEndPoint) listener.LocalEndpoint).Address;
			Port = ((IPEndPoint) listener.LocalEndpoint).Port;

			cancellationTokenSource = new CancellationTokenSource ();
			var token = cancellationTokenSource.Token;

			runningTask = Task.Run (() => AcceptProxyConnections (token), token);
			IsRunning = true;
		}

		public void Stop ()
		{
			if (listener != null && IsRunning) {
				try {
					cancellationTokenSource.Cancel ();
				} catch {
				}

				try {
					listener.Stop ();
				} catch {
				}

				try {
					runningTask.GetAwaiter ().GetResult ();
				} catch {
				}

				cancellationTokenSource.Dispose ();
				cancellationTokenSource = null;
				IsRunning = false;
			}
		}

		protected abstract Task<Socket> ClientCommandReceived (NetworkStream client, byte[] buffer, int length, CancellationToken cancellationToken);

		async Task AcceptProxyConnection (Socket socket, CancellationToken cancellationToken)
		{
			using (var client = new NetworkStream (socket, true)) {
				var buffer = new byte[4096];
				Socket remote = null;
				int nread;

				while ((nread = await client.ReadAsync (buffer, 0, buffer.Length, cancellationToken).ConfigureAwait (false)) > 0) {
					try {
						remote = await ClientCommandReceived (client, buffer, nread, cancellationToken).ConfigureAwait (false);
						if (remote != null)
							break;
					} catch {
						return;
					}
				}

				if (remote == null)
					return;

				try {
					using (var server = new NetworkStream (remote, true)) {
						do {
							while (client.DataAvailable || server.DataAvailable) {
								if (client.DataAvailable) {
									if ((nread = await client.ReadAsync (buffer, 0, buffer.Length, cancellationToken).ConfigureAwait (false)) > 0)
										await server.WriteAsync (buffer, 0, nread, cancellationToken).ConfigureAwait (false);
								}

								if (server.DataAvailable) {
									if ((nread = await server.ReadAsync (buffer, 0, buffer.Length, cancellationToken).ConfigureAwait (false)) > 0)
										await client.WriteAsync (buffer, 0, nread, cancellationToken).ConfigureAwait (false);
								}
							}

							var checkRead = new ArrayList ();
							checkRead.Add (socket);
							checkRead.Add (remote);

							var checkError = new ArrayList ();
							checkError.Add (socket);
							checkError.Add (remote);

							Socket.Select (checkRead, null, checkError, 250000);

							cancellationToken.ThrowIfCancellationRequested ();
						} while (socket.Connected && remote.Connected);
					}
				} catch (OperationCanceledException) {
					return;
				} catch (SocketException) {
					return;
				}
			}
		}

		async Task AcceptProxyConnections (CancellationToken cancellationToken)
		{
			while (!cancellationToken.IsCancellationRequested) {
				try {
					using (var socket = await listener.AcceptSocketAsync ().ConfigureAwait (false))
						await AcceptProxyConnection (socket, cancellationToken).ConfigureAwait (false);
				} catch (ObjectDisposedException) {
				}
			}
		}

		protected virtual void Dispose (bool disposing)
		{
			if (disposing && !disposed) {
				Stop ();
				disposed = true;
			}
		}

		public void Dispose ()
		{
			Dispose (true);
			GC.SuppressFinalize (this);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.blazeloader.api.world;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.village.VillageCollection;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.storage.WorldSavedData;

import com.blazeloader.api.ApiServer;

import com.blazeloader.api.block.IBlock;
import com.blazeloader.api.block.UpdateType;
import com.blazeloader.api.privileged.IWorld;
import com.blazeloader.api.world.gen.IChunkGenerator;
import com.blazeloader.api.world.gen.WorldSavedDataCollection;
import com.blazeloader.bl.interop.ForgeWorldAccess;
import com.blazeloader.bl.main.BLMain;
import com.blazeloader.util.time.WorldClock;
import com.blazeloader.util.version.Versions;

/**
 * A collection of useful functions relating to worlds.
 */
public class ApiWorld {
    private static List<IChunkGenerator> generators = new ArrayList<IChunkGenerator>();
    // The unmodifiable list just holds a reference to the original. I'd rather keep it instead of creating a new one for each chunk loaded.
    private static List<IChunkGenerator> unmodifiable_generators = Collections.unmodifiableList(generators);

    public static List<IChunkGenerator> getGenerators() {
        return unmodifiable_generators;
    }

    /**
     * Loads custom data alongside the given world.
     *

     * How references to resulting instances are stored and managed is left up to the modder.
     *
     * @param world			World being loaded
     * @param dataClass		Class for the container
     * @param identifier	String filename
     *
     * @return	The resulting {@code T} object associated with this world.
     */
	public static <T extends WorldSavedData> T registerWorldData(World world, Class<T> dataClass, String identifier) {
		@SuppressWarnings("unchecked")
		T loaded = (T)world.loadData(dataClass, identifier);

        if (loaded == null) {
            try {
				loaded = dataClass.getConstructor(World.class).newInstance(world);
			} catch (Throwable e) {
				BLMain.LOGGER_FULL.error(dataClass + " does not implement a basic constructor with param World.class", e);
			}
            world.setData(identifier, loaded);
        } else {
        	if (loaded instanceof WorldSavedDataCollection) {
        		((WorldSavedDataCollection)loaded).setWorldsForAll(world);
        	} else if (loaded instanceof VillageCollection) {
        		((VillageCollection)loaded).setWorldsForAll(world);
        	}
        }
        return loaded;
	}

    /**
     * Registers a chunk generator
     *
     * @param generator The generator to register
     */
    public static void registerChunkGenerator(IChunkGenerator generator) {
        generators.add(generator);
    }

    /**
     * Gets all entities in the world within a certain radius from a given point
     *
     * @param w   World
     * @param x   XCoordinate
     * @param y   YCoordinate
     * @param z   ZCoordinate
     * @param rad Maximum Radius
     * @return List of matching Entities
     */
    public static List<Entity> getEntitiesNear(World w, int x, int y, int z, double rad) {
        return getEntitiesOfTypeNear(w, null, x, y, z, rad);
    }

    /**
	 * Gets an entity by its Unique Identifier
	 *
	 * @param w		The world
	 * @param uuid	A uuid for the entity
	 * @return The matching entity or null if none were found
	 */
	public static Entity getEntityByUUId(World w, UUID uuid) {
		if (w instanceof WorldServer) {
			return ((WorldServer)w).getEntityFromUuid(uuid);
		}
		for (Entity i : (List<Entity>)w.loadedEntityList) {
			if (i.getUniqueID().equals(uuid)) {
				return i;
			}
		}
		return null;
	}

	/**
	 * Gets an entity from the given server by its runtime id
	 * regardless of dimension.
	 *
	 * @param server		The server
	 * @param entityId		Id of the entity to find
	 * @return	An Entity instance or null if none were found.
	 */
	public static Entity getEntityById(MinecraftServer server, int entityId) {
    	for (WorldServer i : server.worlds) {
    		Entity owner = i.getEntityByID(entityId);
    		if (owner != null) return owner;
    	}
    	return null;
    }

    /**
     * Gets entities of type in the world within a certain radius from a given point
     * Acts like getEntitiesNear() when Entity Type is null
     *
     * @param w   World
     * @param c   Entity Type
     * @param x   XCoordinate
     * @param y   YCoordinate
     * @param z   ZCoordinate
     * @param rad Maximum Radius
     * @return List of matching Entities
     */
    public static List<Entity> getEntitiesOfTypeNear(World w, Class<? extends Entity> c, int x, int y, int z, double rad) {
        List<Entity> result = new ArrayList<Entity>();
        for (Entity i : ((List<Entity>) w.loadedEntityList)) {
            if (c == null || i.getClass() == c) {
                if (i.posX >= x - rad && i.posX <= x + rad) {
                    if (i.posY >= y - rad && i.posY <= y + rad) {
                        if (i.posZ >= z - rad && i.posZ <= z + rad) result.add(i);
                    }
                }
            }
        }

        return result;
    }

    /**
     * Gets he closest player withing a certain distance relative to a given location.
     *
     * @param w				World to look in
     * @param pos			BlockPos for the origin to look from
     * @param distance		Distance up to which we will search
     * @return	Closest player of null
     */
    public static EntityPlayer getClosestPlayer(World w, BlockPos pos, double distance) {
    	return w.getClosestPlayer(pos.getX(), pos.getY(), pos.getZ(), distance, false);
    }

	/**
	 * Selects a random spawn list entry for the given creature type and location
	 *
	 * @param w   World
	 * @param creatureType	The type of creature to spawn
	 * @param pos			The location
	 */
	public static Biome.SpawnListEntry getSpawnListEntryForTypeAt(World w, EnumCreatureType creatureType, BlockPos pos) {
		if (w instanceof WorldServer) {
			return ((WorldServer)w).getSpawnListEntryForTypeAt(creatureType, pos);
		}
		return null;
	}

	/**
	 * Gets the current moonphase for a given world.
	 *
	 * @param w		The world
	 * @return A MoonPhase value
	 */
	public static MoonPhase getMoonPhase(World w) {
		return MoonPhase.fromInt(w.getMoonPhase());
	}

	/**
	 * Checks if the given spawn list entry is allowed as a possible spawn for the given creature type and location
	 *
	 * @param w   World
	 * @param creatureType		The type of creature to spawn
	 * @param spawnListEntry	The entry we would like to spawn
	 * @param pos				The location we would like to spawn at
	 * @return	True if we can spawn here
	 */
	public static boolean canSpawnHere(World w, EnumCreatureType creatureType, Biome.SpawnListEntry spawnListEntry, BlockPos pos) {
		if (w instanceof WorldServer) {
			return ((WorldServer)w).canCreatureTypeSpawnHere(creatureType, spawnListEntry, pos);
		}
		return false;
	}

    /**
     * Sets the block at a specified location. And triggers a block update
     *
     * @param world The world to change the block in.
     * @param x     The X-coordinate to change.
     * @param y     The Y-coordinate to change.
     * @param z     The Z-coordinate to change.
     * @param block the block to set.
     */
    public static void setBlockAt(World world, int x, int y, int z, IBlockState block) {
        setBlockAt(world, new BlockPos(x, y, z), block);
    }

    /**
     * Sets the block at a specified location.  And triggers a block update
     *
     * @param world The world to change the block in.
     * @param pos   The position of the block.
     * @param block the block to set.
     */
    public static void setBlockAt(World world, BlockPos pos, IBlockState block) {
    	setBlockAt(world, pos, block, UpdateType.UPDATE_AND_NOTIFY);
    }

    /**
     * Sets the block at a specified location.
     *
     * @param world      The world to change the block in.
     * @param x          The X-coordinate to change.
     * @param y          The Y-coordinate to change.
     * @param z          The Z-coordinate to change.
     * @param block      the block to set
     * @param notifyFlag The notification flags.
     */
    public static void setBlockAt(World world, int x, int y, int z, IBlockState block, UpdateType notifyFlag) {
        setBlockAt(world, new BlockPos(x, y, z), block, notifyFlag);
    }

    /**
     * Sets the block at a specified location.
     *
     * @param world      The world to change the block in.
     * @param pos        The position of the block.
     * @param block      the block to set
     * @param notifyFlag The notification flags.
     */
    public static void setBlockAt(World world, BlockPos pos, IBlockState block, UpdateType notifyFlag) {
        world.setBlockState(pos, block, notifyFlag.getValue());
    }

    /**
     * Destroys a block in the world creating sound and particle effects as if it were broken by a player.
     *
     * @param world     	the world containing the block
     * @param x         	XCoordinate
     * @param y         	YCoordinate
     * @param z         	ZCoordinate
     * @param dropItems		true if the block must drop as an item, or it's contained items
     */
    public static void destroyBlock(World world, int x, int y, int z, boolean dropItems) {
        destroyBlock(world, new BlockPos(x, y, z), dropItems);
    }

    /**
     * Destroys a block in the world creating sound and particle effects as if it were broken by a player.
     *
     * @param world     	the world containing the block
     * @param pos       	the position of the block.
     * @param dropItems		true if the block must drop as an item, or it's contained items
     */
    public static void destroyBlock(World world, BlockPos pos, boolean dropItems) {
        world.destroyBlock(pos, dropItems);
    }

    /**
     * Play sound and particle effect for a block being broken without removing
     * the block
     *
     * @param w World
     * @param x XCoordinate
     * @param y YCoordinate
     * @param z ZCoordinate
     */
    public static void playBlockDestructionEffect(World w, int x, int y, int z) {
        playBlockDestructionEffect(w, new BlockPos(x, y, z));
    }

    /**
     * Play sound and particle effect for a block being broken without removing
     * the block
     *
     * @param w   World
     * @param pos The position of the block.
     */
    public static void playBlockDestructionEffect(World w, BlockPos pos) {
        if (!w.isRemote) {
            playAuxSFX(w, WorldEvent.DESTROY_BLOCK, pos, Block.getStateId(w.getBlockState(pos)));
        }
    }

    /**
     * Spawns dispenser particles in front of the block at the given location in the indicated direction
     *
     * @param w  		World
     * @param pos 		The position of the block.
     * @param direction	The direction the block is facing
     */
    public static void spawnDispenserParticles(World w, BlockPos pos, EnumFacing direction) {
        playAuxSFX(w, WorldEvent.DISPENSE_PARTICLES, pos, direction.getFrontOffsetX() + 1 + (direction.getFrontOffsetZ() + 1) * 3);
    }

	/**
	 * Plays a standard sound effect at the given location.
	 *
	 * @param w  		World
	 * @param soundType	The effect to spawn
	 * @param pos		The location
	 * @param volume	Volume
	 */
	public static void playAuxSFX(World w, WorldEvent soundType, BlockPos pos, int volume) {
		w.playEvent(soundType.getId(), pos, volume);
	}

	/**
	 * Plays a standard sound effect at the given location to the given player.
	 *
	 * @param w  		World
	 * @param player	The player to recieve the sound
	 * @param soundType	The effect to spawn
	 * @param pos		The location
	 * @param volume	Volume
	 */
	public static void playAuxSFX(World w, EntityPlayer player, WorldEvent soundType, BlockPos pos, int volume) {
		w.playEvent(player, soundType.getId(), pos, volume);
	}

    /**
     * Gets the IntegratedServer.worldServers[] index of the specified world.
     *
     * @param dimensionLevel The dimension to get the index of.
     * @return Return the index of the dimension.
     */
    public static int getDimensionIndex(int dimensionLevel) {
        if (dimensionLevel == -1) return 1;
        if (dimensionLevel == 1) return 2;
        return dimensionLevel;
    }

    /**
     * Gets the world for the specified dimension.  Should be a dimension index returned by getDimensionIndex.
     *
     * @param dimension The dimension to get.
     * @return The WorldServer for the specified index.
     */
    public static WorldServer getServerWorldForDimension(int dimension) {
    	WorldServer[] worldServers = null;
    	try {
    		worldServers = ApiServer.getServer().worlds;
    	} catch (Throwable e) {
    		BLMain.LOGGER_FULL.error("Exception in fetching worldservers for side SERVER. Please submit a bug report to Blazeloader devs.", e);
    	}
    	if (worldServers != null) {
    		dimension = getDimensionIndex(dimension);
    		if (dimension < 0 && dimension >= worldServers.length) {
    			dimension = 0;
    			BLMain.LOGGER_FULL.warn("Unsupported dimension index. Make sure you pass in the index of the dimension you want, not the dimension code.");
    		}
    		return worldServers[dimension];
    	}
        return null;
    }

    /**
     * Gets the state of the block found at the specified location.
     *
     * @param world The world to get the block from.
     * @param x     The X-coordinate to get.
     * @param y     The Y-coordinate to get.
     * @param z     The Z-coordinate to get.
     * @return Return the blockstate Mapping at the specified location.
     */
    public static IBlockState getBlockAt(World world, int x, int y, int z) {
        return getBlockAt(world, new BlockPos(x, y, z));
    }

    /**
     * Gets the state of the block found at the specified location.
     *
     * @param world The world to get the block from.
     * @param pos   The position of the block.
     * @return Return the blockstate Mapping at the specified location.
     */
    public static IBlockState getBlockAt(World world, BlockPos pos) {
        return world.getBlockState(pos);
    }

    /**
     * Determine if the given block is considered solid on the
     * specified side. Used by placement logic.
     *

     *
     * @forge This is part of the Forge API specification
     * @param w		The world
     * @param pos	The location
     * @param side	The Side in question
     * @param  def	A default value to return
     * @return True if the side is solid or the default
     */
    public static boolean isSideSolid(World w, BlockPos pos, EnumFacing side, boolean def) {
    	if (((IWorld)w).isCoordValid(pos)) {
			IBlockState state = w.getBlockState(pos);
	        Block block = state.getBlock();
	        if (Versions.isForgeInstalled()) {
	    		def = ((ForgeWorldAccess)w).isSideSolid(pos, side, def);
			}
	        return def || ((IBlock)block).isSideSolid(w, pos, side, def);
    	}
    	return def;
    }

	/**
	 * Rotates a block so that it's 'face' points towards the direction indicated by the provided EnumFacing
	 *
	 * @param w			The world
	 * @param pos		Block coordinates
	 * @param state		Current block state
	 * @param facing	Direction this block must be rotated to face towards
	 * @return	True if the rotation succeeded, false otherwise.
	 */
    public static boolean rotateBlockTo(World w, BlockPos pos, EnumFacing facing) {
    	IBlockState state = w.getBlockState(pos);
    	return ((IBlock)state.getBlock()).rotateBlockTo(w, pos, state, facing);
    }

    /**
	 * Gets a facing for the block at the given position.
	 *
	 * @param w			The world
	 * @param pos		Block coordinates
	 * @param state 	Current block state
	 * @return An EnumFacing corresponding to the block's orientation or null if it cannot be rotated
	 */
    public static EnumFacing getBlockRotation(World w, BlockPos pos) {
    	IBlockState state = w.getBlockState(pos);
    	return ((IBlock)state.getBlock()).getBlockRotation(w, pos, state);
    }

    /**
     * Gets a clock representing the given world's current time.
     * Repeated calls with the same world will return the same clock. Said clock will also maintain correct values.
     *
     * @param w			The world
     * @return WorldClock corresponding to the given world
     */
    public static WorldClock getWorldClock(World w) {
    	return ((IWorld)w).getWorldClock();
    }
}


text:
A port of the seol256-dark [vim theme](https://github.com/junegunn/seoul256.vim)

## To install on ubuntu/ubuntu based distros:

```
git clone https://github.com/anuragsoni/seoul256-gnome-terminal.git ~/.config/seoul256-gnome-terminal
source ~/.config/seoul256-gnome-terminal/seoul256-dark.sh
```

Next, restart or open Gnome terminal. Right click on the terminal to select the scheme you just sourced.


text:
extern "C" {
#endif

// Call at least every 2^32 cycles (every 59.6 seconds @ 72 MHz).
uint64_t GetCycleCount64();

uint64_t GetCycleCount64_NoISR();

#ifdef __cplusplus
}
#endif

#endif //CHASSIS_HPTIMER_H


text:
Contributing to Machina
=======================

Contributor FAQ
---------------

### Q: `src/java/main` vs. `src/java/lombok` – what's going on?

### Q: `StateMachineBuilder<S, E, E, C, StateMachineWithContext<S, E, E>>` – are you f***ing kidding me?!

### Q: `StateMachineBuilder` is immutable?!


text:
package com.fuhj.util;

import java.io.Serializable;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;

import com.fuhj.itower.fliter.SecurityFilter;
import com.fuhj.itower.service.model.Users;
import com.fuhj.itower.ui.IncludeDiv;

public class WebAppUtil implements Serializable {
	private static final long serialVersionUID = 2415268553769076841L;
	public static final String USER_SESSION_KEY = "CURRENT_USER_KEY";
	public static final String SEC_SESSION_KEY = "SEC_SESSION_KEY";
	public static final String GELEC_USER_SESSION_KEY = "CURRENT_GELEC_USER_KEY";

	/**
	 * 取ZK Session中当前用户对象
	 *
	 * @return 当前用户对象
	 */
	public static Users getSessionUser() {
		return (Users) getWebSessionAttribute(USER_SESSION_KEY);
	}

	/**
	 * 设置ZK Session属性名称/值
	 *
	 * @param name
	 * @param value
	 */
	public static void setWebSessionAttribute(String name, Object value) {
		Session session = Sessions.getCurrent();
		if (session != null) {
			session.setAttribute(name, value);
		}
	}

	/**
	 * 取ZK Session属性值
	 *
	 * @param name
	 * @return
	 */
	public static Object getWebSessionAttribute(String name) {
		Session session = Sessions.getCurrent();
		if (session != null) {
			return session.getAttribute(name);
		}
		return null;
	}

	/**
	 * 移除ZK Session属性值
	 *
	 * @param name
	 */
	public static Object removeWebSessionAttribute(String name) {
		Session session = Sessions.getCurrent();
		if (session != null) {
			return session.removeAttribute(name);
		}
		return null;
	}

	/**
	 * 设置HttpSession属性名称/值
	 *
	 * @param name
	 * @param value
	 */
	public static void setHttpSessionAttribute(String name, Object value) {
		HttpSession session = getHttpSession();
		session.setAttribute(name, value);
	}

	/**
	 * 取HttpSession属性值
	 *
	 * @param name
	 * @return
	 */
	public static Object getHttpSessionAttribute(String name) {
		HttpSession session = getHttpSession();
		return session.getAttribute(name);
	}

	/**
	 * 移除HttpSession属性值
	 *
	 * @param name
	 */
	public static Object removeHttpSessionAttribute(String name) {
		HttpSession session = getHttpSession();
		Object obj = session.getAttribute(name);
		session.removeAttribute(name);
		return obj;
	}

	/**
	 * 显示ZK Session所有属性
	 */
	public static void showWebSessionAllAttribute() {
		Session session = Sessions.getCurrent();
		if (session != null) {
			Set<String> keys = session.getAttributes().keySet();
			System.out.println("session attributes: ");
			for (String key : keys) {
				System.out.println(key + ": " + getWebSessionAttribute(key));
			}
		}
	}

	/**
	 * 移除ZK Session中所有属性值
	 *
	 * @param name
	 */
	public static void removeWebSessionAllAttribute() {
		Session session = Sessions.getCurrent();
		if (session != null) {
			Set<String> keys = session.getAttributes().keySet();
			for (String key : keys) {
				session.removeAttribute(key);
			}
		}
	}

	/**
	 * 取当前HttpSession对象
	 *
	 * @return
	 */
	public static HttpSession getHttpSession() {
		HttpSession httpSession = null;
		Session zkSession = Sessions.getCurrent();
		if (zkSession != null) {
			httpSession = ((HttpSession) zkSession.getNativeSession());
		}
		return httpSession;
	}

	/**
	 * 删除当前HttpSession对象
	 */
	public static void destroySession() {
		HttpSession httpSession = getHttpSession();
		if (httpSession != null) {
			httpSession.invalidate();
		}
	}

	public static void saveCookie(String name, String value, int expiry) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(expiry);
		String cp = SecurityFilter.getContextPath();
		if (cp.length() == 0) {
			cp = "/";
		}
		cookie.setPath(cp);
		HttpServletResponse response = ((HttpServletResponse) Executions.getCurrent().getNativeResponse());
		response.addCookie(cookie);
	}

	/**
	 * 取页面中显示内容的Include对象
	 *
	 * @return
	 */
	public static IncludeDiv getIncludePage() {
		// AppLogger.sysDebug(Executions.getCurrent().getDesktop().getPages());
		return (IncludeDiv) Executions.getCurrent().getDesktop().getPage("mainPage").getFellow("xcontents");
	}

	public static IncludeDiv getElecIncludePage() {
		// AppLogger.sysDebug(Executions.getCurrent().getDesktop().getPages());
		return (IncludeDiv) Executions.getCurrent().getDesktop().getPage("elecMainPage").getFellow("elecContent");
	}

	public static void setElecPageTitle(String title) {
		Executions.getCurrent().getDesktop().getPage("elecMainPage").setTitle(title);
	}

	/**
	 * 取客户端IP地址
	 *
	 * @return
	 */
	public static String getIpAddress() {
		Execution execution = Executions.getCurrent();
		if (execution == null) {
			return "";
		}
		String ip = execution.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = execution.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = execution.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = execution.getRemoteAddr();
		}
		return ip;
	}
}


text:
<?php

final class PhabricatorProjectManageController
  extends PhabricatorProjectController {

  public function shouldAllowPublic() {
    return true;
  }

  public function handleRequest(AphrontRequest $request) {
    $response = $this->loadProject();
    if ($response) {
      return $response;
    }

    $viewer = $request->getUser();
    $project = $this->getProject();
    $id = $project->getID();
    $picture = $project->getProfileImageURI();

    $header = id(new PHUIHeaderView())
      ->setHeader(pht('Project History'))
      ->setUser($viewer)
      ->setPolicyObject($project);

    if ($project->getStatus() == PhabricatorProjectStatus::STATUS_ACTIVE) {
      $header->setStatus('fa-check', 'bluegrey', pht('Active'));
    } else {
      $header->setStatus('fa-ban', 'red', pht('Archived'));
    }

    $curtain = $this->buildCurtain($project);
    $properties = $this->buildPropertyListView($project);

    $timeline = $this->buildTransactionTimeline(
      $project,
      new PhabricatorProjectTransactionQuery());
    $timeline->setShouldTerminate(true);

    $nav = $this->getProfileMenu();
    $nav->selectFilter(PhabricatorProject::ITEM_MANAGE);

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb(pht('Manage'));
    $crumbs->setBorder(true);

    require_celerity_resource('project-view-css');

    $manage = id(new PHUITwoColumnView())
      ->setHeader($header)
      ->setCurtain($curtain)
      ->addPropertySection(pht('Details'), $properties)
      ->addClass('project-view-home')
      ->addClass('project-view-people-home')
      ->setMainColumn(
        array(
          $timeline,
        ));

    return $this->newPage()
      ->setNavigation($nav)
      ->setCrumbs($crumbs)
      ->setTitle(
        array(
          $project->getDisplayName(),
          pht('Manage'),
        ))
      ->appendChild(
        array(
          $manage,
        ));
  }

  private function buildCurtain(PhabricatorProject $project) {
    $viewer = $this->getViewer();

    $id = $project->getID();
    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $project,
      PhabricatorPolicyCapability::CAN_EDIT);

    $curtain = $this->newCurtainView($project);

    $curtain->addAction(
      id(new PhabricatorActionView())
        ->setName(pht('Edit Details'))
        ->setIcon('fa-pencil')
        ->setHref($this->getApplicationURI("edit/{$id}/"))
        ->setDisabled(!$can_edit)
        ->setWorkflow(!$can_edit));

    $curtain->addAction(
      id(new PhabricatorActionView())
        ->setName(pht('Edit Menu'))
        ->setIcon('fa-th-list')
        ->setHref($this->getApplicationURI("{$id}/item/configure/"))
        ->setDisabled(!$can_edit)
        ->setWorkflow(!$can_edit));

    $curtain->addAction(
      id(new PhabricatorActionView())
        ->setName(pht('Edit Picture'))
        ->setIcon('fa-picture-o')
        ->setHref($this->getApplicationURI("picture/{$id}/"))
        ->setDisabled(!$can_edit)
        ->setWorkflow(!$can_edit));

    if ($project->isArchived()) {
      $curtain->addAction(
        id(new PhabricatorActionView())
          ->setName(pht('Activate Project'))
          ->setIcon('fa-check')
          ->setHref($this->getApplicationURI("archive/{$id}/"))
          ->setDisabled(!$can_edit)
          ->setWorkflow(true));
    } else {
      $curtain->addAction(
        id(new PhabricatorActionView())
          ->setName(pht('Archive Project'))
          ->setIcon('fa-ban')
          ->setHref($this->getApplicationURI("archive/{$id}/"))
          ->setDisabled(!$can_edit)
          ->setWorkflow(true));
    }

    return $curtain;
  }

  private function buildPropertyListView(
    PhabricatorProject $project) {
    $viewer = $this->getViewer();

    $view = id(new PHUIPropertyListView())
      ->setUser($viewer);

    $view->addProperty(
      pht('Looks Like'),
      $viewer->renderHandle($project->getPHID())->setAsTag(true));

    $slugs = $project->getSlugs();
    $tags = mpull($slugs, 'getSlug');

    $view->addProperty(
      pht('Hashtags'),
      $this->renderHashtags($tags));

    $field_list = PhabricatorCustomField::getObjectFields(
      $project,
      PhabricatorCustomField::ROLE_VIEW);
    $field_list->appendFieldsToPropertyList($project, $viewer, $view);

    return $view;
  }

}


text:
import pygame, sys
from screen import screen
from constants import *

# font_path = pygame.font.match_font('Arial')
font_path = pygame.font.get_default_font()

def draw_text(text, center, color=white, size=30, bold=False, background=None,
              left=False):
    font = pygame.font.Font(font_path, size, bold=bold)
    if background:
        surface = font.render(text, True, color, background)
    else:
        surface = font.render(text, True, color)

    rect = surface.get_rect()
    rect.center = tuple(center)
    if left:
        rect.left = center[0]

    screen.blit(surface, rect)
    return rect

def draw_image(img, center):
    rect = img.get_rect()
    rect.center = tuple(center)
    screen.blit(img, rect)
    return rect

def draw_focus_screen():
    p = screen.get_rect().center
    draw_text('+', p, size=100)

def focus_slide():
    screen.fill(background_color)
    draw_focus_screen()
    pygame.display.flip()

def simple_slide(text, size=100):
    screen.fill(background_color)
    p = screen.get_rect().center
    draw_text(text, p, size=size)
    pygame.display.flip()

def text_slide(text, size=30):
    screen.fill(background_color)
    lines = text.split('\n')
    rect = draw_text('test', (SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
                     size=size, color=background_color)
    height = rect.height + 6
    y = SCREEN_HEIGHT/2 - (len(lines)-1)*(height/2)
    for line in lines:
        draw_text(line.strip(), (SCREEN_WIDTH/2, y), size=size)
        y += height
    pygame.display.flip()

def image_slide(img):
    screen.fill(background_color)
    rect = draw_image(img, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
    pygame.display.update(rect)

def recognize_slide(word, size=100):
    screen.fill(background_color)
    p = screen.get_rect().center
    draw_text(word, p, size=size)

    draw_text("1=unknown", (200, SCREEN_HEIGHT-100), size=50)
    draw_text("4=recognized", (SCREEN_WIDTH-250, SCREEN_HEIGHT-100), size=50)

    pygame.display.flip()


text:
A palindromic number reads the same both ways. The smallest 6 digit palindrome
made from the product of two 3-digit numbers is 101101=143*707.

Find the largest palindrome made from the product of two 3-digit numbers which
is less than N.

## Input Format

First line contains T that denotes the number of test cases. This is followed by
T lines, each containing an integer, N.

## Output Format

Print the required answer for each test case in a new line.

## Constraints

1 <= T <= 100
101101 < N < 1000000

## Sample Input

```
2
101110
800000
```

## Sample Output

```
101101
793397
```


text:
var GradientParser = (window.GradientParser || {});

// Copyright (c) 2014 Rafael Caricio. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var GradientParser = (GradientParser || {});

GradientParser.parse = (function() {

  var tokens = {
    linearGradient: /^(\-(webkit|o|ms|moz)\-)?(linear\-gradient)/i,
    repeatingLinearGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-linear\-gradient)/i,
    radialGradient: /^(\-(webkit|o|ms|moz)\-)?(radial\-gradient)/i,
    repeatingRadialGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-radial\-gradient)/i,
    sideOrCorner: /^to (left (top|bottom)|right (top|bottom)|left|right|top|bottom)/i,
    extentKeywords: /^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,
    positionKeywords: /^(left|center|right|top|bottom)/i,
    pixelValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,
    percentageValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,
    emValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,
    angleValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,
    startCall: /^\(/,
    endCall: /^\)/,
    comma: /^,/,
    hexColor: /^\#([0-9a-fA-F]+)/,
    literalColor: /^([a-zA-Z]+)/,
    rgbColor: /^rgb/i,
    rgbaColor: /^rgba/i,
    number: /^(([0-9]*\.[0-9]+)|([0-9]+\.?))/
  };

  var input = '';

  function error(msg) {
    var err = new Error(input + ': ' + msg);
    err.source = input;
    throw err;
  }

  function getAST() {
    var ast = matchListDefinitions();

    if (input.length > 0) {
      error('Invalid input not EOF');
    }

    return ast;
  }

  function matchListDefinitions() {
    return matchListing(matchDefinition);
  }

  function matchDefinition() {
    return matchGradient(
            'linear-gradient',
            tokens.linearGradient,
            matchLinearOrientation) ||

          matchGradient(
            'repeating-linear-gradient',
            tokens.repeatingLinearGradient,
            matchLinearOrientation) ||

          matchGradient(
            'radial-gradient',
            tokens.radialGradient,
            matchListRadialOrientations) ||

          matchGradient(
            'repeating-radial-gradient',
            tokens.repeatingRadialGradient,
            matchListRadialOrientations);
  }

  function matchGradient(gradientType, pattern, orientationMatcher) {
    return matchCall(pattern, function(captures) {

      var orientation = orientationMatcher();
      if (orientation) {
        if (!scan(tokens.comma)) {
          error('Missing comma before color stops');
        }
      }

      return {
        type: gradientType,
        orientation: orientation,
        colorStops: matchListing(matchColorStop)
      };
    });
  }

  function matchCall(pattern, callback) {
    var captures = scan(pattern);

    if (captures) {
      if (!scan(tokens.startCall)) {
        error('Missing (');
      }

      var result = callback(captures);

      if (!scan(tokens.endCall)) {
        error('Missing )');
      }

      return result;
    }
  }

  function matchLinearOrientation() {
    return matchSideOrCorner() ||
      matchAngle();
  }

  function matchSideOrCorner() {
    return match('directional', tokens.sideOrCorner, 1);
  }

  function matchAngle() {
    return match('angular', tokens.angleValue, 1);
  }

  function matchListRadialOrientations() {
    var radialOrientations,
        radialOrientation = matchRadialOrientation(),
        lookaheadCache;

    if (radialOrientation) {
      radialOrientations = [];
      radialOrientations.push(radialOrientation);

      lookaheadCache = input;
      if (scan(tokens.comma)) {
        radialOrientation = matchRadialOrientation();
        if (radialOrientation) {
          radialOrientations.push(radialOrientation);
        } else {
          input = lookaheadCache;
        }
      }
    }

    return radialOrientations;
  }

  function matchRadialOrientation() {
    var radialType = matchCircle() ||
      matchEllipse();

    if (radialType) {
      radialType.at = matchAtPosition();
    } else {
      var extent = matchExtentKeyword();
      if (extent) {
        radialType = extent;
        var positionAt = matchAtPosition();
        if (positionAt) {
          radialType.at = positionAt;
        }
      } else {
        var defaultPosition = matchPositioning();
        if (defaultPosition) {
          radialType = {
            type: 'default-radial',
            at: defaultPosition
          };
        }
      }
    }

    return radialType;
  }

  function matchCircle() {
    var circle = match('shape', /^(circle)/i, 0);

    if (circle) {
      circle.style = matchLength() || matchExtentKeyword();
    }

    return circle;
  }

  function matchEllipse() {
    var ellipse = match('shape', /^(ellipse)/i, 0);

    if (ellipse) {
      ellipse.style =  matchDistance() || matchExtentKeyword();
    }

    return ellipse;
  }

  function matchExtentKeyword() {
    return match('extent-keyword', tokens.extentKeywords, 1);
  }

  function matchAtPosition() {
    if (match('position', /^at/, 0)) {
      var positioning = matchPositioning();

      if (!positioning) {
        error('Missing positioning value');
      }

      return positioning;
    }
  }

  function matchPositioning() {
    var location = matchCoordinates();

    if (location.x || location.y) {
      return {
        type: 'position',
        value: location
      };
    }
  }

  function matchCoordinates() {
    return {
      x: matchDistance(),
      y: matchDistance()
    };
  }

  function matchListing(matcher) {
    var captures = matcher(),
      result = [];

    if (captures) {
      result.push(captures);
      while (scan(tokens.comma)) {
        captures = matcher();
        if (captures) {
          result.push(captures);
        } else {
          error('One extra comma');
        }
      }
    }

    return result;
  }

  function matchColorStop() {
    var color = matchColor();

    if (!color) {
      error('Expected color definition');
    }

    color.length = matchDistance();
    return color;
  }

  function matchColor() {
    return matchHexColor() ||
      matchRGBAColor() ||
      matchRGBColor() ||
      matchLiteralColor();
  }

  function matchLiteralColor() {
    return match('literal', tokens.literalColor, 0);
  }

  function matchHexColor() {
    return match('hex', tokens.hexColor, 1);
  }

  function matchRGBColor() {
    return matchCall(tokens.rgbColor, function() {
      return  {
        type: 'rgb',
        value: matchListing(matchNumber)
      };
    });
  }

  function matchRGBAColor() {
    return matchCall(tokens.rgbaColor, function() {
      return  {
        type: 'rgba',
        value: matchListing(matchNumber)
      };
    });
  }

  function matchNumber() {
    return scan(tokens.number)[1];
  }

  function matchDistance() {
    return match('%', tokens.percentageValue, 1) ||
      matchPositionKeyword() ||
      matchLength();
  }

  function matchPositionKeyword() {
    return match('position-keyword', tokens.positionKeywords, 1);
  }

  function matchLength() {
    return match('px', tokens.pixelValue, 1) ||
      match('em', tokens.emValue, 1);
  }

  function match(type, pattern, captureIndex) {
    var captures = scan(pattern);
    if (captures) {
      return {
        type: type,
        value: captures[captureIndex]
      };
    }
  }

  function scan(regexp) {
    var captures,
        blankCaptures;

    blankCaptures = /^[\n\r\t\s]+/.exec(input);
    if (blankCaptures) {
        consume(blankCaptures[0].length);
    }

    captures = regexp.exec(input);
    if (captures) {
        consume(captures[0].length);
    }

    return captures;
  }

  function consume(size) {
    input = input.substr(size);
  }

  return function(code) {
    input = code.toString();
    return getAST();
  };
})();

// Copyright (c) 2014 Rafael Caricio. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var GradientParser = (GradientParser || {});

GradientParser.stringify = (function() {

  var visitor = {

    'visit_linear-gradient': function(node) {
      return visitor.visit_gradient(node);
    },

    'visit_repeating-linear-gradient': function(node) {
      return visitor.visit_gradient(node);
    },

    'visit_radial-gradient': function(node) {
      return visitor.visit_gradient(node);
    },

    'visit_repeating-radial-gradient': function(node) {
      return visitor.visit_gradient(node);
    },

    'visit_gradient': function(node) {
      var orientation = visitor.visit(node.orientation);
      if (orientation) {
        orientation += ', ';
      }

      return node.type + '(' + orientation + visitor.visit(node.colorStops) + ')';
    },

    'visit_shape': function(node) {
      var result = node.value,
          at = visitor.visit(node.at),
          style = visitor.visit(node.style);

      if (style) {
        result += ' ' + style;
      }

      if (at) {
        result += ' at ' + at;
      }

      return result;
    },

    'visit_default-radial': function(node) {
      var result = '',
          at = visitor.visit(node.at);

      if (at) {
        result += at;
      }
      return result;
    },

    'visit_extent-keyword': function(node) {
      var result = node.value,
          at = visitor.visit(node.at);

      if (at) {
        result += ' at ' + at;
      }

      return result;
    },

    'visit_position-keyword': function(node) {
      return node.value;
    },

    'visit_position': function(node) {
      return visitor.visit(node.value.x) + ' ' + visitor.visit(node.value.y);
    },

    'visit_%': function(node) {
      return node.value + '%';
    },

    'visit_em': function(node) {
      return node.value + 'em';
    },

    'visit_px': function(node) {
      return node.value + 'px';
    },

    'visit_literal': function(node) {
      return visitor.visit_color(node.value, node);
    },

    'visit_hex': function(node) {
      return visitor.visit_color('#' + node.value, node);
    },

    'visit_rgb': function(node) {
      return visitor.visit_color('rgb(' + node.value.join(', ') + ')', node);
    },

    'visit_rgba': function(node) {
      return visitor.visit_color('rgba(' + node.value.join(', ') + ')', node);
    },

    'visit_color': function(resultColor, node) {
      var result = resultColor,
          length = visitor.visit(node.length);

      if (length) {
        result += ' ' + length;
      }
      return result;
    },

    'visit_angular': function(node) {
      return node.value + 'deg';
    },

    'visit_directional': function(node) {
      return 'to ' + node.value;
    },

    'visit_array': function(elements) {
      var result = '',
          size = elements.length;

      elements.forEach(function(element, i) {
        result += visitor.visit(element);
        if (i < size - 1) {
          result += ', ';
        }
      });

      return result;
    },

    'visit': function(element) {
      if (!element) {
        return '';
      }
      var result = '';

      if (element instanceof Array) {
        return visitor.visit_array(element, result);
      } else if (element.type) {
        var nodeVisitor = visitor['visit_' + element.type];
        if (nodeVisitor) {
          return nodeVisitor(element);
        } else {
          throw Error('Missing visitor visit_' + element.type);
        }
      } else {
        throw Error('Invalid node.');
      }
    }

  };

  return function(root) {
    return visitor.visit(root);
  };
})();


text:
package com.openxc.units;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import com.openxc.units.Boolean;

public class BooleanTest {
    Boolean value;

    @Before
    public void setUp() {
        value = new Boolean(Integer.valueOf(1));
    }

    @Test
    public void constructFromNumber() {
        assertTrue(value.booleanValue());
        value = new Boolean(Integer.valueOf(0));
        assertFalse(value.booleanValue());
    }

    @Test
    public void toStringNotNull() {
        assertThat(value.toString(), instanceOf(String.class));
    }

    @Test
    public void sameEquals() {
        assertThat(value, equalTo(value));
    }

    @Test
    public void sameValueEquals() {
        assertThat(value, equalTo(new Boolean(true)));
    }

    @Test
    public void differentValueNotEquals() {
        assertThat(value, not(equalTo(new Boolean(false))));
    }
}


text:
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Functions for managing full screen status of the DOM.
 *
 */

goog.provide('goog.dom.fullscreen');
goog.provide('goog.dom.fullscreen.EventType');

goog.require('goog.dom');

/**
 * Event types for full screen.
 * @enum {string}
 */
goog.dom.fullscreen.EventType = {
  /** Dispatched by the Document when the fullscreen status changes. */
  CHANGE: (function() {
    var el = goog.dom.getDomHelper().getDocument().documentElement;
    if (el.requestFullscreen) {
      return 'fullscreenchange';
    }
    if (el.webkitRequestFullscreen) {
      return 'webkitfullscreenchange';
    }
    if (el.mozRequestFullScreen) {
      return 'mozfullscreenchange';
    }
    if (el.msRequestFullscreen) {
      return 'MSFullscreenChange';
    }
    // Opera 12-14, and W3C standard (Draft):
    // https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
    return 'fullscreenchange';
  })()
};

/**
 * Options for fullscreen navigation UI:
 * https://fullscreen.spec.whatwg.org/#dictdef-fullscreenoptions
 * @enum {string}
 */
goog.dom.fullscreen.FullscreenNavigationUI = {
  AUTO: 'auto',
  HIDE: 'hide',
  SHOW: 'show'
};

/**
 * @record
 * @extends {FullscreenOptions}
 */
goog.dom.fullscreen.FullscreenOptions = function() {};

/** @type {!goog.dom.fullscreen.FullscreenNavigationUI} */
goog.dom.fullscreen.FullscreenOptions.prototype.navigationUI;

/**
 * Determines if full screen is supported.
 * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
 *     queried. If not provided, use the current DOM.
 * @return {boolean} True iff full screen is supported.
 */
goog.dom.fullscreen.isSupported = function(opt_domHelper) {
  var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  var body = doc.body;
  return !!(
      body.webkitRequestFullscreen ||
      (body.mozRequestFullScreen && doc.mozFullScreenEnabled) ||
      (body.msRequestFullscreen && doc.msFullscreenEnabled) ||
      (body.requestFullscreen && doc.fullscreenEnabled));
};

/**
 * Requests putting the element in full screen.
 * @param {!Element} element The element to put full screen.
 * @param {!goog.dom.fullscreen.FullscreenOptions=} opt_options Options for full
 *     screen. This field will be ignored on older browsers.
 */
goog.dom.fullscreen.requestFullScreen = function(element, opt_options) {
  if (element.requestFullscreen) {
    element.requestFullscreen(opt_options);
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
};

/**
 * Requests putting the element in full screen with full keyboard access.
 * @param {!Element} element The element to put full screen.
 */
goog.dom.fullscreen.requestFullScreenWithKeys = function(element) {
  if (element.mozRequestFullScreenWithKeys) {
    element.mozRequestFullScreenWithKeys();
  } else {
    goog.dom.fullscreen.requestFullScreen(element);
  }
};

/**
 * Exits full screen.
 * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
 *     queried. If not provided, use the current DOM.
 */
goog.dom.fullscreen.exitFullScreen = function(opt_domHelper) {
  var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  if (doc.exitFullscreen) {
    doc.exitFullscreen();
  } else if (doc.webkitCancelFullScreen) {
    doc.webkitCancelFullScreen();
  } else if (doc.mozCancelFullScreen) {
    doc.mozCancelFullScreen();
  } else if (doc.msExitFullscreen) {
    doc.msExitFullscreen();
  }
};

/**
 * Determines if the document is full screen.
 * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
 *     queried. If not provided, use the current DOM.
 * @return {boolean} Whether the document is full screen.
 */
goog.dom.fullscreen.isFullScreen = function(opt_domHelper) {
  var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  // IE 11 doesn't have similar boolean property, so check whether
  // document.msFullscreenElement is null instead.
  return !!(
      doc.webkitIsFullScreen || doc.mozFullScreen || doc.msFullscreenElement ||
      doc.fullscreenElement);
};

/**
 * Get the root element in full screen mode.
 * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
 *     queried. If not provided, use the current DOM.
 * @return {?Element} The root element in full screen mode.
 */
goog.dom.fullscreen.getFullScreenElement = function(opt_domHelper) {
  var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
  var element_list = [
    doc.fullscreenElement, doc.webkitFullscreenElement,
    doc.mozFullScreenElement, doc.msFullscreenElement
  ];
  for (var i = 0; i < element_list.length; i++) {
    if (element_list[i] != null) {
      return element_list[i];
    }
  }
  return null;
};

/**
 * Gets the document object of the dom.
 * @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
 *     queried. If not provided, use the current DOM.
 * @return {!Document} The dom document.
 * @private
 */
goog.dom.fullscreen.getDocument_ = function(opt_domHelper) {
  return opt_domHelper ? opt_domHelper.getDocument() :
                         goog.dom.getDomHelper().getDocument();
};