text:
package io.github.opencubicchunks.cubicchunks.core.asm.mixin.fixes.common.worldgen.tree;

import io.github.opencubicchunks.cubicchunks.api.world.ICubicWorld;
import io.github.opencubicchunks.cubicchunks.api.util.Coords;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.block.material.Material;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenSwamp;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import java.util.Random;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@Mixin(WorldGenSwamp.class)
public class MixinWorldGenSwamp {

    private int minPos;

    // a bad hack because vanilla has no height check ans assumes it will always reach non-water block
    // while it's "technically mostly true" for cubic chunks, it could go way out of the current cube
    // so cubic chunks needs to make it go down to min. population area instead.
    // Checking for material is the only loop termination condition mixin can intercept here

    // first we need to get the original position to store the minPos because it's the position argument being modified
    // as MC goes down
    @Inject(method = "generate", at = @At("HEAD"))
    private void onGenerate(World worldIn, Random rand, BlockPos position, CallbackInfoReturnable<Boolean> cbi) {
        this.minPos = Coords.getMinCubePopulationPos(position.getY());
    }

    // and then redirect Material.WATER access with ordinal zero,
    // return null to make sure it never succeeds for any block when below minPos
    @Redirect(method = "generate",
            at = @At(value = "FIELD", target = "Lnet/minecraft/block/material/Material;WATER:Lnet/minecraft/block/material/Material;", ordinal = 0))
    @Nullable private Material getReplaceMaterial_HeightCheckHack(World worldIn, Random rand, BlockPos position) {
        if (((ICubicWorld) worldIn).isCubicWorld() && position.getY() < minPos) {
            return null;
        }
        return Material.WATER;
    }

    // normal height check replacement:

    // the ordinal=0 is boolean flag = true
    @ModifyConstant(method = "generate", constant = @Constant(intValue = 1, ordinal = 1))
    private int getMinGenHeight(int orig, World worldIn, Random rand, BlockPos position) {
        return ((ICubicWorld) worldIn).getMinHeight() + 1;
    }

    @ModifyConstant(method = "generate",
                    constant = @Constant(intValue = 0, ordinal = 1,
                                         expandZeroConditions = Constant.Condition.GREATER_THAN_OR_EQUAL_TO_ZERO))
    private int getMinGenHeightCompareZero(int orig, World worldIn, Random rand, BlockPos position) {
        return ((ICubicWorld) worldIn).getMinHeight();
    }

    @ModifyConstant(method = "generate", constant = @Constant(intValue = 256))
    private int getMaxGenHeight(int orig, World worldIn, Random rand, BlockPos position) {
        return ((ICubicWorld) worldIn).getMaxHeight();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<title>three.js webgl - gpgpu - flocking</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js -  webgl gpgpu birds

			Select  birds

			Move mouse to disturb birds.


text:
package jat.core.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *  @author Gary Litvin
 *  @version 1.2, 5/30/02
 *
 *  Written as part of
 *
 *  Java Methods: An Introduction to Object-Oriented Programming
 *  (Skylight Publishing 2001, ISBN 0-9654853-7-4)
 *
 *   and
 *
 *  Java Methods AB: Data Structures
 *  (Skylight Publishing 2003, ISBN 0-9654853-1-5)
 *
 *  EasyReader provides simple methods for reading the console and
 *  for opening and reading text files.  All exceptions are handled
 *  inside the class and are hidden from the user.
 *
 *  <xmp>
 *  Example:
 *  =======
 *
 *  EasyReader console = new EasyReader();
 *  System.out.print("Enter input file name: ");
 *  String fileName = console.readLine();
 *
 *  EasyReader inFile = new EasyReader(fileName);
 *  if (inFile.bad())
 *  {
 *    System.err.println("Can't open " + fileName);
 *    System.exit(1);
 *  }
 *
 *  String firstLine = inFile.readLine();
 *  if (!inFile.eof())   // or:  if (firstLine != null)
 *    System.out.println("The first line is : " + firstLine);
 *
 *  System.out.print("Enter the maximum number of integers to read: ");
 *  int maxCount = console.readInt();
 *  int k, count = 0;
 *
 *  while (count < maxCount && !inFile.eof())
 *  {
 *    k = inFile.readInt();
 *    if (!inFile.eof())
 *    {
 *      // process or store this number
 *      count++;
 *    }
 *  }
 *
 *  inFile.close();    // optional
 *  System.out.println(count + " numbers read");
 *  </xmp>
 *
 */

public class EasyReader
{
  protected String myFileName;
  protected BufferedReader myInFile;
  protected int myErrorFlags = 0;
  protected static final int OPENERROR = 0x0001;
  protected static final int CLOSEERROR = 0x0002;
  protected static final int READERROR = 0x0004;
  protected static final int EOF = 0x0100;

  /**
   *  Constructor.  Prepares console (System.in) for reading
   */
  public EasyReader()
  {
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
                            new InputStreamReader(System.in), 128);
  }

  /**
   *  Constructor.  opens a file for reading
   *  @param fileName the name or pathname of the file
   */
  public EasyReader(String fileName)
  {
    myFileName = fileName;
    myErrorFlags = 0;
    try
    {
      myInFile = new BufferedReader(new FileReader(fileName), 1024);
    }
    catch (FileNotFoundException e)
    {
      myErrorFlags |= OPENERROR;
      myFileName = null;
    }
  }

  /**
   *  Closes the file
   */
  public void close()
  {
    if (myFileName == null)
      return;
    try
    {
      myInFile.close();
    }
    catch (IOException e)
    {
      System.err.println("Error closing " + myFileName + "\n");
      myErrorFlags |= CLOSEERROR;
    }
  }

  /**
   *  Checks the status of the file
   *  @return true if en error occurred opening or reading the file,
   *  false otherwise
   */
  public boolean bad()
  {
    return myErrorFlags != 0;
  }

  /**
   *  Checks the EOF status of the file
   *  @return true if EOF was encountered in the previous read
   *  operation, false otherwise
   */
  public boolean eof()
  {
    return (myErrorFlags & EOF) != 0;
  }

  private boolean ready() throws IOException
  {
    return myFileName == null || myInFile.ready();
  }

  /**
   *  Reads the next character from a file (any character including
   *  a space or a newline character).
   *  @return character read or null character
   *  (Unicode 0) if trying to read beyond the EOF
   */
  public char readChar()
  {
    char ch = '\u0000';

    try
    {
      if (ready())
      {
         ch = (char)myInFile.read();
      }
    }
    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    if (ch == '\u0000')
      myErrorFlags |= EOF;

    return ch;
  }

  /**
   *  Reads from the current position in the file up to and including
   *  the next newline character.  The newline character is thrown away
   *  @return the read string (excluding the newline character) or
   *  null if trying to read beyond the EOF
   */
  public String readLine()
  {
    String s = null;

    try
    {
      s = myInFile.readLine();
    }
    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    if (s == null)
      myErrorFlags |= EOF;
    return s;
  }

  /**
   *  Skips whitespace and reads the next word (a string of consecutive
   *  non-whitespace characters (up to but excluding the next space,
   *  newline, etc.)
   *  @return the read string or null if trying to read beyond the EOF
   */
  public String readWord()
  {
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;

    try
    {
      while (ready() && Character.isWhitespace(ch))
        ch = (char)myInFile.read();
      while (ready() && !Character.isWhitespace(ch))
      {
        count++;
        buffer.append(ch);
        myInFile.mark(1);
        ch = (char)myInFile.read();
      };

      if (count > 0)
      {
        myInFile.reset();
        s = buffer.toString();
      }
      else
      {
        myErrorFlags |= EOF;
      }
    }

    catch (IOException e)
    {
      if (myFileName != null)
        System.err.println("Error reading " + myFileName + "\n");
      myErrorFlags |= READERROR;
    }

    return s;
  }

  /**
   *  Reads the next integer (without validating its format)
   *  @return the integer read or 0 if trying to read beyond the EOF
   */
  public int readInt()
  {
    String s = readWord();
    if (s != null)
      return Integer.parseInt(s);
    else
      return 0;
  }

  /**
   *  Reads the next double (without validating its format)
   *  @return the number read or 0 if trying to read beyond the EOF
   */
  public double readDouble()
  {
	String s = readWord();
	if (s != null)
	  return Double.parseDouble(s);
	  // in Java 1, use: return Double.valueOf(s).doubleValue();
	else
	  return 0.0;
  }

  /**
   *  Reads the next double (without validating its format)
   *  FORTRAN exponential format has D instead of E
   *  @return the number read or 0 if trying to read beyond the EOF
   */
  public double readFORTRANDouble()
  {
	String s = readWord();
	s=s.replace('D','E');
	if (s != null)
	  return Double.parseDouble(s);
	  // in Java 1, use: return Double.valueOf(s).doubleValue();
	else
	  return 0.0;
  }
}


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

/// <summary>
/// Base class for all UI components that should be derived from when creating new widget types.
/// </summary>

public abstract class UIWidget : MonoBehaviour
{
	public enum Pivot
	{
		TopLeft,
		Top,
		TopRight,
		Left,
		Center,
		Right,
		BottomLeft,
		Bottom,
		BottomRight,
	}

	// Cached and saved values
	[HideInInspector][SerializeField] protected Material mMat;
	[HideInInspector][SerializeField] protected Texture mTex;
	[HideInInspector][SerializeField] Color mColor = Color.white;
	[HideInInspector][SerializeField] Pivot mPivot = Pivot.Center;
	[HideInInspector][SerializeField] int mDepth = 0;
	protected Transform mTrans;
	protected UIPanel mPanel;

	protected bool mChanged = true;
	protected bool mPlayMode = true;

	GameObject mGo;
	Vector3 mDiffPos;
	Quaternion mDiffRot;
	Vector3 mDiffScale;
	int mVisibleFlag = -1;

	// Widget's generated geometry
	UIGeometry mGeom = new UIGeometry();

	/// <summary>
	/// Whether the widget is visible.
	/// </summary>

	public bool isVisible { get { return finalAlpha > 0.001f; } }

	/// <summary>
	/// Color used by the widget.
	/// </summary>

	public Color color { get { return mColor; } set { if (!mColor.Equals(value)) { mColor = value; mChanged = true; } } }

	/// <summary>
	/// Widget's alpha -- a convenience method.
	/// </summary>

	public float alpha { get { return mColor.a; } set { Color c = mColor; c.a = value; color = c; } }

	/// <summary>
	/// Widget's final alpha, after taking the panel's alpha into account.
	/// </summary>

	public float finalAlpha { get { if (mPanel == null) CreatePanel(); return (mPanel != null) ? mColor.a * mPanel.alpha : mColor.a; } }

	/// <summary>
	/// Set or get the value that specifies where the widget's pivot point should be.
	/// </summary>

	public Pivot pivot
	{
		get
		{
			return mPivot;
		}
		set
		{
			if (mPivot != value)
			{
				Vector3 before = NGUIMath.CalculateWidgetCorners(this)[0];

				mPivot = value;
				mChanged = true;

				Vector3 after = NGUIMath.CalculateWidgetCorners(this)[0];

				Transform t = cachedTransform;
				Vector3 pos = t.position;
				float z = t.localPosition.z;
				pos.x += (before.x - after.x);
				pos.y += (before.y - after.y);
				cachedTransform.position = pos;

				pos = cachedTransform.localPosition;
				pos.x = Mathf.Round(pos.x);
				pos.y = Mathf.Round(pos.y);
				pos.z = z;
				cachedTransform.localPosition = pos;
			}
		}
	}

	/// <summary>
	/// Depth controls the rendering order -- lowest to highest.
	/// </summary>

	public int depth { get { return mDepth; } set { if (mDepth != value) { mDepth = value; if (mPanel != null) mPanel.MarkMaterialAsChanged(material, true); } } }

	/// <summary>
	/// Helper function that calculates the relative offset based on the current pivot.
	/// </summary>

	public Vector2 pivotOffset
	{
		get
		{
			Vector2 v = Vector2.zero;
			Vector4 p = relativePadding;

			Pivot pv = pivot;

			if (pv == Pivot.Top || pv == Pivot.Center || pv == Pivot.Bottom) v.x = (p.x - p.z - 1f) * 0.5f;
			else if (pv == Pivot.TopRight || pv == Pivot.Right || pv == Pivot.BottomRight) v.x = -1f - p.z;
			else v.x = p.x;

			if (pv == Pivot.Left || pv == Pivot.Center || pv == Pivot.Right) v.y = (p.w - p.y + 1f) * 0.5f;
			else if (pv == Pivot.BottomLeft || pv == Pivot.Bottom || pv == Pivot.BottomRight) v.y = 1f + p.w;
			else v.y = -p.y;

			return v;
		}
	}

	/// <summary>
	/// Transform gets cached for speed.
	/// </summary>

	public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }

	/// <summary>
	/// Returns the material used by this widget.
	/// </summary>

	public virtual Material material
	{
		get
		{
			return mMat;
		}
		set
		{
			if (mMat != value)
			{
				if (mMat != null && mPanel != null) mPanel.RemoveWidget(this);

				mPanel = null;
				mMat = value;
				mTex = null;

				if (mMat != null) CreatePanel();
			}
		}
	}

	/// <summary>
	/// Returns the texture used to draw this widget.
	/// </summary>

	public virtual Texture mainTexture
	{
		get
		{
			// If the material has a texture, always use it instead of 'mTex'.
			Material mat = material;

			if (mat != null)
			{
				if (mat.mainTexture != null)
				{
					mTex = mat.mainTexture;
				}
				else if (mTex != null)
				{
					// The material has no texture, but we have a saved texture
					if (mPanel != null) mPanel.RemoveWidget(this);

					// Set the material's texture to the saved value
					mPanel = null;
					mMat.mainTexture = mTex;

					// Ensure this widget gets added to the panel
					if (enabled) CreatePanel();
				}
			}
			return mTex;
		}
		set
		{
			Material mat = material;

			if (mat == null || mat.mainTexture != value)
			{
				if (mPanel != null) mPanel.RemoveWidget(this);

				mPanel = null;
				mTex = value;
				mat = material;

				if (mat != null)
				{
					mat.mainTexture = value;
					if (enabled) CreatePanel();
				}
			}
		}
	}

	/// <summary>
	/// Returns the UI panel responsible for this widget.
	/// </summary>

	public UIPanel panel { get { if (mPanel == null) CreatePanel(); return mPanel; } set { mPanel = value; } }

	/// <summary>
	/// Flag set by the UIPanel and used in optimization checks.
	/// </summary>

	public int visibleFlag { get { return mVisibleFlag; } set { mVisibleFlag = value; } }

	/// <summary>
	/// Static widget comparison function used for Z-sorting.
	/// </summary>

	static public int CompareFunc (UIWidget left, UIWidget right)
	{
		if (left.mDepth > right.mDepth) return 1;
		if (left.mDepth < right.mDepth) return -1;
		return 0;
	}

	/// <summary>
	/// Only sets the local flag, does not notify the panel.
	/// In most cases you will want to use MarkAsChanged() instead.
	/// </summary>

	public void MarkAsChangedLite () { mChanged = true; }

	/// <summary>
	/// Tell the panel responsible for the widget that something has changed and the buffers need to be rebuilt.
	/// </summary>

	public virtual void MarkAsChanged ()
	{
		mChanged = true;

		// If we're in the editor, update the panel right away so its geometry gets updated.
		if (mPanel != null && enabled && NGUITools.GetActive(gameObject) && !Application.isPlaying && material != null)
		{
			mPanel.AddWidget(this);
			CheckLayer();
#if UNITY_EDITOR
			// Mark the panel as dirty so it gets updated
			UnityEditor.EditorUtility.SetDirty(mPanel.gameObject);
#endif
		}
	}

	/// <summary>
	/// Ensure we have a panel referencing this widget.
	/// </summary>

	public void CreatePanel ()
	{
		if (mPanel == null && enabled && NGUITools.GetActive(gameObject) && material != null)
		{
			mPanel = UIPanel.Find(cachedTransform);

			if (mPanel != null)
			{
				CheckLayer();
				mPanel.AddWidget(this);
				mChanged = true;
			}
		}
	}

	/// <summary>
	/// Check to ensure that the widget resides on the same layer as its panel.
	/// </summary>

	public void CheckLayer ()
	{
		if (mPanel != null && mPanel.gameObject.layer != gameObject.layer)
		{
			Debug.LogWarning("You can't place widgets on a layer different than the UIPanel that manages them.\n" +
				"If you want to move widgets to a different layer, parent them to a new panel instead.", this);
			gameObject.layer = mPanel.gameObject.layer;
		}
	}

	/// <summary>
	/// For backwards compatibility. Use ParentHasChanged() instead.
	/// </summary>

	[System.Obsolete("Use ParentHasChanged() instead")]
	public void CheckParent () { ParentHasChanged(); }

	/// <summary>
	/// Checks to ensure that the widget is still parented to the right panel.
	/// </summary>

	public void ParentHasChanged ()
	{
		if (mPanel != null)
		{
			// This code allows drag & dropping of widgets onto different panels in the editor.
			bool valid = true;
			Transform t = cachedTransform.parent;

			// Run through the parents and see if this widget is still parented to the transform
			while (t != null)
			{
				if (t == mPanel.cachedTransform) break;
				if (!mPanel.WatchesTransform(t)) { valid = false; break; }
				t = t.parent;
			}

			// This widget is no longer parented to the same panel. Remove it and re-add it to a new one.
			if (!valid)
			{
				if (!keepMaterial || Application.isPlaying) material = null;
				mPanel = null;
				CreatePanel();
			}
		}
	}

	/// <summary>
	/// Remember whether we're in play mode.
	/// </summary>

	protected virtual void Awake () { mGo = gameObject; mPlayMode = Application.isPlaying; }

	/// <summary>
	/// Mark the widget and the panel as having been changed.
	/// </summary>

	protected virtual void OnEnable ()
	{
#if UNITY_EDITOR
		if (GetComponents<UIWidget>().Length > 1)
		{
			Debug.LogError("Can't have more than one widget on the same game object!", this);
			enabled = false;
		}
		else
#endif
		{
			mChanged = true;

			if (!keepMaterial)
			{
				mMat = null;
				mTex = null;
			}
			mPanel = null;
		}
	}

	/// <summary>
	/// Set the depth, call the virtual start function, and sure we have a panel to work with.
	/// </summary>

	void Start ()
	{
		OnStart();
		CreatePanel();
	}

	/// <summary>
	/// Ensure that we have a panel to work with. The reason the panel isn't added in OnEnable()
	/// is because OnEnable() is called right after Awake(), which is a problem when the widget
	/// is brought in on a prefab object as it happens before it gets parented.
	/// </summary>

	public void Update ()
	{
		CheckLayer();

		// Ensure we have a panel to work with by now
		if (mPanel == null) CreatePanel();
#if UNITY_EDITOR
		else if (!Application.isPlaying) ParentHasChanged();
#endif

		// Automatically reset the Z scaling component back to 1 as it's not used
		Vector3 scale = cachedTransform.localScale;

		if (scale.z != 1f)
		{
			scale.z = 1f;
			mTrans.localScale = scale;
		}
	}

	/// <summary>
	/// Clear references.
	/// </summary>

	void OnDisable ()
	{
		if (!keepMaterial)
		{
			material = null;
		}
		else if (mPanel != null)
		{
			mPanel.RemoveWidget(this);
		}
		mPanel = null;
	}

	/// <summary>
	/// Unregister this widget.
	/// </summary>

	void OnDestroy ()
	{
		if (mPanel != null)
		{
			mPanel.RemoveWidget(this);
			mPanel = null;
		}
	}

#if UNITY_EDITOR

	/// <summary>
	/// Draw some selectable gizmos.
	/// </summary>

	void OnDrawGizmos ()
	{
		if (mVisibleFlag != 0 && mPanel != null && mPanel.debugInfo == UIPanel.DebugInfo.Gizmos)
		{
			if (UnityEditor.Selection.activeGameObject == gameObject && UnityEditor.EditorPrefs.GetBool("New GUI", true)) return;

			Color outline = new Color(1f, 1f, 1f, 0.2f);

			// Position should be offset by depth so that the selection works properly
			Vector3 pos = Vector3.zero;
			pos.z -= mDepth * 0.25f;

			Vector3 size = relativeSize;
			Vector2 offset = pivotOffset;
			Vector4 padding = relativePadding;

			float x0 = offset.x * size.x - padding.x;
			float y0 = offset.y * size.y + padding.y;

			float x1 = x0 + size.x + padding.x + padding.z;
			float y1 = y0 - size.y - padding.y - padding.w;

			pos.x = (x0 + x1) * 0.5f;
			pos.y = (y0 + y1) * 0.5f;

			size.x = (x1 - x0);
			size.y = (y1 - y0);

			// Draw the gizmo
			Gizmos.matrix = cachedTransform.localToWorldMatrix;
			Gizmos.color = (UnityEditor.Selection.activeGameObject == gameObject) ? Color.green : outline;
			Gizmos.DrawWireCube(pos, size);

			// Make the widget selectable
			size.z = 0.01f;
			Gizmos.color = Color.clear;
			Gizmos.DrawCube(pos, size);
		}
	}
#endif

	/// <summary>
	/// Update the widget and fill its geometry if necessary. Returns whether something was changed.
	/// </summary>

	public bool UpdateGeometry (UIPanel p, ref Matrix4x4 worldToPanel, bool parentMoved, bool generateNormals)
	{
		if (material == null) return false;

		if (OnUpdate() || mChanged)
		{
			mChanged = false;

			if (NGUITools.GetActive(mGo))
			{
				mPanel = p;
				mGeom.Clear();
				OnFill(mGeom.verts, mGeom.uvs, mGeom.cols);

				if (mGeom.hasVertices)
				{
					Vector3 offset = pivotOffset;
					Vector2 scale = relativeSize;

					offset.x *= scale.x;
					offset.y *= scale.y;

					mGeom.ApplyOffset(offset);
					mGeom.ApplyTransform(worldToPanel * cachedTransform.localToWorldMatrix, generateNormals);
				}
				return true;
			}
			else if (mGeom.hasVertices)
			{
				mGeom.Clear();
				return true;
			}
			return false;
		}
		else if (mGeom.hasVertices && parentMoved)
		{
			mGeom.ApplyTransform(worldToPanel * cachedTransform.localToWorldMatrix, generateNormals);
		}
		return false;
	}

	/// <summary>
	/// Append the local geometry buffers to the specified ones.
	/// </summary>

	public void WriteToBuffers (BetterList<Vector3> v, BetterList<Vector2> u, BetterList<Color32> c, BetterList<Vector3> n, BetterList<Vector4> t)
	{
		mGeom.WriteToBuffers(v, u, c, n, t);
	}

	/// <summary>
	/// Make the widget pixel-perfect.
	/// </summary>

	virtual public void MakePixelPerfect ()
	{
		Vector3 scale = cachedTransform.localScale;

		int width  = Mathf.RoundToInt(scale.x);
		int height = Mathf.RoundToInt(scale.y);

		scale.x = width;
		scale.y = height;
		scale.z = 1f;

		Vector3 pos = cachedTransform.localPosition;
		pos.z = Mathf.RoundToInt(pos.z);

		if (width % 2 == 1 && (pivot == Pivot.Top || pivot == Pivot.Center || pivot == Pivot.Bottom))
		{
			pos.x = Mathf.Floor(pos.x) + 0.5f;
		}
		else
		{
			pos.x = Mathf.Round(pos.x);
		}

		if (height % 2 == 1 && (pivot == Pivot.Left || pivot == Pivot.Center || pivot == Pivot.Right))
		{
			pos.y = Mathf.Ceil(pos.y) - 0.5f;
		}
		else
		{
			pos.y = Mathf.Round(pos.y);
		}

		cachedTransform.localPosition = pos;
		cachedTransform.localScale = scale;
	}

	/// <summary>
	/// Visible size of the widget in relative coordinates. In most cases this can remain at (1, 1).
	/// If you want to figure out the widget's size in pixels, scale this value by cachedTransform.localScale.
	/// </summary>

	virtual public Vector2 relativeSize { get { return Vector2.one; } }

	/// <summary>
	/// Extra padding around the sprite, in pixels.
	/// </summary>

	virtual public Vector4 relativePadding { get { return Vector4.zero; } }

	/// <summary>
	/// Dimensions of the sprite's border, if any.
	/// </summary>

	virtual public Vector4 border { get { return Vector4.zero; } }

	/// <summary>
	/// Whether the material will be kept when the widget gets disabled (by default no, it won't be).
	/// </summary>

	virtual public bool keepMaterial { get { return false; } }

	/// <summary>
	/// Whether this widget will automatically become pixel-perfect after resize operation finishes.
	/// </summary>

	virtual public bool pixelPerfectAfterResize { get { return false; } }

	/// <summary>
	/// Virtual Start() functionality for widgets.
	/// </summary>

	virtual protected void OnStart () { }

	/// <summary>
	/// Virtual version of the Update function. Should return 'true' if the widget has changed visually.
	/// </summary>

	virtual public bool OnUpdate () { return false; }

	/// <summary>
	/// Virtual function called by the UIPanel that fills the buffers.
	/// </summary>

	virtual public void OnFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols) { }
}


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "order_details_extend".
 *
 * @property string $name
 * @property string $tax
 * @property double $sell_price
 * @property string $quantity
 * @property double $discount
 * @property string $order_id
 * @property string $order_date
 * @property string $receiving_date
 */
class OrderDetailsExtend extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'order_details_extend';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'sell_price', 'quantity', 'order_date', 'receiving_date'], 'required'],
            [['tax', 'quantity', 'order_id', 'order_date', 'receiving_date'], 'integer'],
            [['sell_price', 'discount'], 'number'],
            [['name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => Yii::t('app', 'Name'),
            'tax' => Yii::t('app', 'Tax'),
            'sell_price' => Yii::t('app', 'Sell Price'),
            'quantity' => Yii::t('app', 'Quantity'),
            'discount' => Yii::t('app', 'Discount'),
            'order_id' => Yii::t('app', 'Order ID'),
            'order_date' => Yii::t('app', 'Order Date'),
            'receiving_date' => Yii::t('app', 'Receiving Date'),
        ];
    }
}


text:
                Caption
                Link
                New window

                    {{link.caption}}
                    <input type="text" ng-model="link.caption" ng-show="link.edit" />

                        {{link.link}}

                            <input type="text" ng-model="link.link" />

                            or choose internal page

                             Choose

                            or enter external link

                    {{link.newWindow}}
                    <input type="checkbox" ng-model="link.newWindow" ng-show="link.edit" />

                        <button type="button" class="btn btn-default" ng-click="edit($index)">Edit</button>
                        <button type="button" class="btn btn-default" ng-click="delete($index)">Delete</button>

                        <button type="button" class="btn btn-default" ng-click="cancelEdit($index)">Cancel</button>
                        <button type="button" class="btn btn-default" ng-click="cancelEdit($index)">Save</button>

                    <input type="text" ng-model="newCaption" placeholder="Enter a new caption" val-highlight="hasError" />

                            <input type="text" ng-model="newLink" placeholder="Enter the link" />

 or
                            choose internal page

                             Choose

                            or enter external link

                    <input type="checkbox" ng-model="newNewWindow" />

                            <button class="btn btn-default" ng-click="add($event)">Add</button>


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.
 */

#ifndef GETPROBS_H
#define GETPROBS_H

#include <fstream>
#include <sys/resource.h>
#include <iostream>
#include <unistd.h>
#include <set>
#include <math.h>
#include "ClassRule.h"
#include "ECArgs.h"
#include "Feature.h"
#include "FeatureTree.h"
#include "InputTree.h"
#include "headFinder.h"
#include "treeHistSf.h"
#include "Pst.h"
#include "Smoother.h"
#include "TreeHist.h"
#include "Term.h"

#include "trainRsUtils.h"

class getProbs{

 public:
  static void init(ECString path);

};
float getProb(InputTree* tree, int pos, int whichInt);
void initGetProb(string path);

#endif


text:
class CreateBankAccounts < ActiveRecord::Migration[5.0]
  def change
    create_table(:bank_accounts) do |t|

      t.string :account_number
      t.string :iban, limit: 56
      t.string :ifsc_swiftcode, limit: 56
      t.string :bank_name
      t.string :branch_name, limit: 56
      t.string :city, limit: 56
      t.references :country

      t.integer :bank_accountable_id
      t.string  :bank_accountable_type

      t.timestamps
    end

    add_index(:bank_accounts, [ :bank_accountable_id, :bank_accountable_type ], :name => 'indx_bank_accountable_id_and_type')
  end
end


text: var app = angular.module('CartaRestaurant', []);


text:
package org.ansj.library;

import org.ansj.domain.Term;
import org.ansj.util.MyStaticValue;

/**
 * 两个词之间的关联
 *
 * @author ansj
 *
 */
public class NgramLibrary {
	static {
		try {
			long start = System.currentTimeMillis();
			MyStaticValue.initBigramTables();
			MyStaticValue.LIBRARYLOG.info("init ngram ok use time :" + (System.currentTimeMillis() - start));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 查找两个词与词之间的频率
	 *
	 * @param from
	 * @param to
	 * @return
	 */
	public static int getTwoWordFreq(Term from, Term to) {
		if (from.item().bigramEntryMap == null) {
			return 0;
		}
		Integer freq = from.item().bigramEntryMap.get(to.item().index);

		if (freq == null) {
			return 0;
		} else {
			return freq;
		}
	}

}


text:
module Mercurial

  class Hook

    attr_reader :repository, :name, :value

    def initialize(repository, name, value)
      @repository = repository
      @name = name
      @value = value
    end

    def save
      repository.config.add_setting('hooks', name, value)
    end

    def destroy!
      repository.config.delete_setting!('hooks', name)
    end

  end

end


text:
[![Version](https://img.shields.io/cocoapods/v/ESPTouchiOS.svg?style=flat)](http://cocoapods.org/pods/ESPTouchiOS)
[![License](https://img.shields.io/cocoapods/l/ESPTouchiOS.svg?style=flat)](http://cocoapods.org/pods/ESPTouchiOS)
[![Platform](https://img.shields.io/cocoapods/p/ESPTouchiOS.svg?style=flat)](http://cocoapods.org/pods/ESPTouchiOS)

## Overview

This project provides the Espressif ESPTouch for iOS code as a cocoapod.  It contains only the minimum source changes necessary
to remove warnings from the build process.

## Installation

ESPTouchiOS is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "ESPTouchiOS"
```

## Author

Zach, Zach@VoidstarSolutions.com

## License

EspTouch is provided by Espressif under the MIT license. See the LICENSE file for more info.


text:
package pl.newicom.dddd.saga

import pl.newicom.dddd.aggregate.EntityId
import pl.newicom.dddd.{BusinessEntity, Eventsourced}

case class BusinessProcessId(processDomain: String, processId: EntityId, department: String = null) extends BusinessEntity with Eventsourced {
  def id: EntityId = processId

  val domain: Eventsourced = BusinessProcessDomain(processDomain, department)
}


text:
namespace TranscendenceChatServer.Areas.HelpPage.ModelDescriptions
{
    public class SimpleTypeModelDescription : ModelDescription
    {
    }
}


text:
(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
    var prev = old && old != CodeMirror.Init;
    if (val && !prev) {
      cm.on("blur", onBlur);
      cm.on("change", onChange);
      onChange(cm);
    } else if (!val && prev) {
      cm.off("blur", onBlur);
      cm.off("change", onChange);
      clearPlaceholder(cm);
      var wrapper = cm.getWrapperElement();
      wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
    }

    if (val && !cm.hasFocus()) onBlur(cm);
  });

  function clearPlaceholder(cm) {
    if (cm.state.placeholder) {
      cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
      cm.state.placeholder = null;
    }
  }
  function setPlaceholder(cm) {
    clearPlaceholder(cm);
    var elt = cm.state.placeholder = document.createElement("pre");
    elt.style.cssText = "height: 0; overflow: visible";
    elt.className = "CodeMirror-placeholder";
    elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
    cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  }

  function onBlur(cm) {
    if (isEmpty(cm)) setPlaceholder(cm);
  }
  function onChange(cm) {
    var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
    wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");

    if (empty) setPlaceholder(cm);
    else clearPlaceholder(cm);
  }

  function isEmpty(cm) {
    return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  }
});


text:
import React, { Component, PropTypes } from 'react'
import { isEmpty, isArray } from 'lodash'
import GoogleMap from 'google-map-react'
import Pin from 'shared/components/addon/maps/pin'
import Marker from 'shared/components/addon/maps/marker'
import SearchMenu from 'shared/components/addon/maps/search-menu'
import shouldPureComponentUpdate from 'react-pure-render/function'
import controllable from 'react-controllables'
import { isFinite } from 'lodash'

@controllable(['zoom', 'hoverKey', 'clickKey'])
export default class Nearby extends Component {

  static propTypes = {
    nearby: PropTypes.func.isRequired,
    updateNearbyCenter: PropTypes.func.isRequired,
    search: PropTypes.object.isRequired,
    defaultCenter: PropTypes.object.isRequired,
    center: PropTypes.object,
    defaultZoom: PropTypes.number.isRequired,
    defaultLocale: PropTypes.string.isRequired,
    history: PropTypes.object.isRequired,
    zoom: PropTypes.number, // @controllable
    hoverKey: PropTypes.any, // @controllable
    clickKey: PropTypes.any, // @controllable
    onZoomChange: PropTypes.func, // @controllable generated fn
    onHoverKeyChange: PropTypes.func, // @controllable generated fn
    onClickKeyChange: PropTypes.func // @controllable generated fn
  }

  static defaultProps = {
    defaultCenter: { lat: 25.0318808, lng: 121.5193721 },
    defaultZoom: 14,
    center: { lat: 25.0318808, lng: 121.5193721 },
    zoom: 14
  }

  constructor (props) {
    super(props)
  }

  shouldComponentUpdate = shouldPureComponentUpdate

  openInfoWindow = (key, childProps) => {
    this.props.onClickKeyChange(key)
    this.props.updateNearbyCenter({
      center: { lat: childProps.lat, lng: childProps.lng }
    })
  }

  handleChange = (event) => {
    const { center, zoom, bounds, marginBounds } = event
    this.props.updateNearbyCenter({ center })
    this.props.onZoomChange(zoom)
  }

  handleTouchStart = (key, childProps) => {
    return this.openInfoWindow(key, childProps)
  }

  handleChildClick = (key, childProps) => {
    return this.openInfoWindow(key, childProps)
  }

  handleChildMouseEnter = (key, childProps) => {
    this.props.onHoverKeyChange(key)
  }

  handleChildMouseLeave = () => {
    this.props.onHoverKeyChange(null)
  }

  handleChildGoClick = (mid) => {
    this.props.history.replaceState({}, `/w/${mid}`)
  }

  handleChildCloseClick = () => {
    this.props.onClickKeyChange(null)
  }

  handleDegreeChange = (dist) => {
    const { pattern } = this.props.search
    if (pattern) {
      this.props.nearby({
        dist: isFinite(+dist) ? +dist : 1000,
        lat: pattern.lat,
        lng: pattern.lng
      }, 50)
    }
  }

  handlePlaceChange = (location) => {
    if (!location) return
    const { pattern, center } = this.props.search
    this.props.nearby({
      dist: pattern.dist ? pattern.dist : 1000,
      lat: location.lat(),
      lng: location.lng()
    }, 50).then(() => {
      this.props.updateNearbyCenter({
        center: { lat: location.lat(), lng: location.lng() }
      })
      this.props.onZoomChange(14)
    })
  }

  createMapOptions (maps) {
    return {
      minZoom: 11,
      fullscreenControl: false,
      zoomControlOptions: {
        position: maps.ControlPosition.RIGHT_CENTER,
        style: maps.ZoomControlStyle.SMALL
      },
      mapTypeControlOptions: {
        position: maps.ControlPosition.LEFT_BOTTOM
      },
      mapTypeControl: true,
      draggable: true
    };
  }

  render () {
    const { center, pattern, data } = this.props.search
    let MyPlace
    if (typeof pattern.lat !== 'undefined'
        && typeof pattern.lng !== 'undefined') {
      MyPlace = (<Pin {...pattern} />)
    } else {
      MyPlace = (<Pin {...this.props.center} />)
    }

    let Markers
    if (data) {
      Markers = data.map((m) => (
        <Marker
          lat={m.lat}
          lng={m.lng}
          data={m}
          key={m.id}
          hover={this.props.hoverKey === m.id}
          pulse={!this.props.hoverKey}
          isOpen={this.props.clickKey === m.id}
          handleGoClick={this.handleChildGoClick.bind(null, m.id)}
          handleCloseClick={this.handleChildCloseClick}
          handleTouchStart={this.handleTouchStart}
          defaultLocale={this.props.defaultLocale}
        />
      ))
    }

    return (

          <GoogleMap
            onGoogleApiLoaded={({ map, maps }) => {}}
            yesIWantToUseGoogleMapApiInternals
            ref="nearby"
            defaultCenter={this.props.defaultCenter}
            center={center}
            onChange={this.handleChange}
            onChildClick={this.handleChildClick}
            onChildMouseEnter={this.handleChildMouseEnter}
            onChildMouseLeave={this.handleChildMouseLeave}
            options={this.createMapOptions}
            hoverDistance={42}
            defaultZoom={this.props.defaultZoom}
            zoom={this.props.zoom}>
            {Markers}
            {MyPlace}
          </GoogleMap>
          <SearchMenu
            onDegreeChange={this.handleDegreeChange}
            onPlaceChange={this.handlePlaceChange}
            placeholder={``}
          />

    )
  }
}


text:
"""Tests for the user interface."""
#
# (C) Pywikibot team, 2008-2019
#
# Distributed under the terms of the MIT license.
#
# NOTE FOR RUNNING WINDOWS UI TESTS
#
# Windows UI tests have to be run using the tests\ui_tests.bat helper script.
# This will set PYTHONPATH and PYWIKIBOT_DIR, and then run the tests. Do not
# touch mouse or keyboard while the tests are running, as this might disturb
# the interaction tests.
#
# The Windows tests were developed on a Dutch Windows 7 OS. You might need to
# adapt the helper functions in TestWindowsTerminalUnicode for other versions.
#
# For the Windows-based tests, you need the following packages installed:
#   - pywin32, for clipboard access, which can be downloaded here:
#     http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/
#     make sure to download the package for the correct python version!
#
#   - pywinauto, to send keys to the terminal, which can be installed using:
#     pip install -U pywinauto
#
#
from __future__ import absolute_import, division, unicode_literals

import inspect
import io
import logging
import os
import subprocess
import sys
import time
import warnings

import pywikibot
from pywikibot.bot import (
    ui, DEBUG, VERBOSE, INFO, STDOUT, INPUT, WARNING, ERROR, CRITICAL
)
from pywikibot.tools import (
    PY2,
    UnicodeType as unicode,
)
from pywikibot.userinterfaces import (
    terminal_interface_win32, terminal_interface_base, terminal_interface_unix,
)
from tests.aspects import TestCase, TestCaseBase
from tests.utils import unittest, FakeModule

if os.name == 'nt':
    from multiprocessing.managers import BaseManager
    import threading

    try:
        import win32api
    except ImportError:
        win32api = None

    try:
        import pywinauto
    except ImportError:
        pywinauto = None

    try:
        import win32clipboard
    except ImportError:
        win32clipboard = None

class Stream(object):

    """Handler for a StringIO or BytesIO instance able to patch itself."""

    def __init__(self, name, patched_streams):
        """
        Create a new stream with a StringIO or BytesIO instance.

        @param name: The part after 'std' (e.g. 'err').
        @type name: str
        @param patched_streams: A mapping which maps the original stream to
            the patched stream.
        @type patched_streams: dict
        """
        self._stream = io.StringIO() if not PY2 else io.BytesIO()
        self._name = 'std{0}'.format(name)
        self._original = getattr(sys, self._name)
        patched_streams[self._original] = self._stream

    def __repr__(self):
        return '<patched {} {!r} wrapping {!r}>'.format(
            self._name, self._stream, self._original)

    def reset(self):
        """Reset own stream."""
        self._stream.truncate(0)
        self._stream.seek(0)

if os.name == 'nt':

    class pywikibotWrapper(object):

        """pywikibot wrapper class."""

        def init(self):
            pywikibot.version._get_program_dir()

        def output(self, *args, **kwargs):
            return pywikibot.output(*args, **kwargs)

        def request_input(self, *args, **kwargs):
            self.input = None

            def threadedinput():
                self.input = pywikibot.input(*args, **kwargs)
            self.inputthread = threading.Thread(target=threadedinput)
            self.inputthread.start()

        def get_input(self):
            self.inputthread.join()
            return self.input

        def set_config(self, key, value):
            setattr(pywikibot.config, key, value)

        def set_ui(self, key, value):
            setattr(pywikibot.ui, key, value)

        def cls(self):
            os.system('cls')

    class pywikibotManager(BaseManager):

        """pywikibot manager class."""

        pass

    pywikibotManager.register(str('pywikibot'), pywikibotWrapper)
    _manager = pywikibotManager(
        address=('127.0.0.1', 47228),
        authkey=b'4DJSchgwy5L5JxueZEWbxyeG')
    if len(sys.argv) > 1 and sys.argv[1] == '--run-as-slave-interpreter':
        s = _manager.get_server()
        s.serve_forever()

def patched_print(text, target_stream):
    try:
        stream = patched_streams[target_stream]
    except KeyError:
        assert isinstance(target_stream,
                          pywikibot.userinterfaces.win32_unicode.UnicodeOutput)
        assert target_stream._stream
        stream = patched_streams[target_stream._stream]
    org_print(text, stream)

def patched_input():
    return strin._stream.readline().strip()

patched_streams = {}
strout = Stream('out', patched_streams)
strerr = Stream('err', patched_streams)
strin = Stream('in', {})

newstdout = strout._stream
newstderr = strerr._stream
newstdin = strin._stream

if PY2:
    # In Python 2 the sys.std* streams use bytes instead of unicode
    # But this module is using unicode_literals so '…' will generate unicode
    # So it'll convert those back into bytes
    original_write = newstdin.write

    def encoded_write(text):
        if isinstance(text, unicode):
            text = text.encode('utf8')
        original_write(text)

    newstdin.write = encoded_write

org_print = ui._print
org_input = ui._raw_input

def patch():
    """Patch standard terminal files."""
    strout.reset()
    strerr.reset()
    strin.reset()
    ui._print = patched_print
    ui._raw_input = patched_input

def unpatch():
    """Un-patch standard terminal files."""
    ui._print = org_print
    ui._raw_input = org_input

logger = logging.getLogger('pywiki')
loggingcontext = {'caller_name': 'ui_tests',
                  'caller_file': 'ui_tests',
                  'caller_line': 0,
                  'newline': '\n'}

class UITestCase(TestCaseBase):

    """UI tests."""

    net = False

    def setUp(self):
        super(UITestCase, self).setUp()
        patch()

        pywikibot.config.colorized_output = True
        pywikibot.config.transliterate = False
        pywikibot.ui.transliteration_target = None
        pywikibot.ui.encoding = 'utf-8'

    def tearDown(self):
        super(UITestCase, self).tearDown()
        unpatch()

    def _encode(self, string, encoding='utf-8'):
        if not PY2:
            return string
        else:
            return string.encode(encoding)

class TestTerminalOutput(UITestCase):

    """Terminal output tests."""

    def testOutputLevels_logging_debug(self):
        logger.log(DEBUG, 'debug', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), '')

    def testOutputLevels_logging_verbose(self):
        logger.log(VERBOSE, 'verbose', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), '')

    def testOutputLevels_logging_info(self):
        logger.log(INFO, 'info', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'info\n')

    def testOutputLevels_logging_stdout(self):
        logger.log(STDOUT, 'stdout', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), 'stdout\n')
        self.assertEqual(newstderr.getvalue(), '')

    def testOutputLevels_logging_input(self):
        logger.log(INPUT, 'input', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'input\n')

    def testOutputLevels_logging_WARNING(self):
        logger.log(WARNING, 'WARNING', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'WARNING: WARNING\n')

    def testOutputLevels_logging_ERROR(self):
        logger.log(ERROR, 'ERROR', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'ERROR: ERROR\n')

    def testOutputLevels_logging_CRITICAL(self):
        logger.log(CRITICAL, 'CRITICAL', extra=loggingcontext)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'CRITICAL: CRITICAL\n')

    def test_output(self):
        pywikibot.output('output', toStdout=False)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'output\n')

    def test_output_stdout(self):
        with warnings.catch_warnings(record=True) as w:
            pywikibot.output('output', toStdout=True)
            self.assertEqual(newstdout.getvalue(), 'output\n')
            self.assertLength(w, 1)
            self.assertEqual(w[0].category, DeprecationWarning)
            message = str(w[0].message)
            self.assertStringMethod(str.startswith, message,
                                    '"toStdout" parameter is deprecated')
            self.assertStringMethod(str.endswith, message,
                                    'use pywikibot.stdout() instead.')

    def test_stdout(self):
        pywikibot.stdout('output')
        self.assertEqual(newstdout.getvalue(), 'output\n')
        self.assertEqual(newstderr.getvalue(), '')

    def test_warning(self):
        pywikibot.warning('warning')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'WARNING: warning\n')

    def test_error(self):
        pywikibot.error('error')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'ERROR: error\n')

    def test_log(self):
        pywikibot.log('log')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), '')

    def test_critical(self):
        pywikibot.critical('critical')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'CRITICAL: critical\n')

    def test_debug(self):
        pywikibot.debug('debug', 'test')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), '')

    def test_exception(self):
        class TestException(Exception):

            """Test exception."""

        try:
            raise TestException('Testing Exception')
        except TestException:
            pywikibot.exception('exception')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(),
                         'ERROR: TestException: Testing Exception\n')

    def test_exception_tb(self):
        class TestException(Exception):

            """Test exception."""

        try:
            raise TestException('Testing Exception')
        except TestException:
            pywikibot.exception('exception', tb=True)
        self.assertEqual(newstdout.getvalue(), '')
        stderrlines = newstderr.getvalue().split('\n')
        self.assertEqual(stderrlines[0],
                         'ERROR: TestException: Testing Exception')
        self.assertEqual(stderrlines[1], 'Traceback (most recent call last):')
        self.assertEqual(stderrlines[3],
                         "    raise TestException('Testing Exception')")
        self.assertTrue(stderrlines[4].endswith(': Testing Exception'))

        self.assertNotEqual(stderrlines[-1], '\n')

class TestTerminalInput(UITestCase):

    """Terminal input tests."""

    input_choice_output = 'question ([A]nswer 1, a[n]swer 2, an[s]wer 3): '

    def testInput(self):
        newstdin.write('input to read\n')
        newstdin.seek(0)

        returned = pywikibot.input('question')

        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(newstderr.getvalue(), 'question: ')

        self.assertIsInstance(returned, unicode)
        self.assertEqual(returned, 'input to read')

    def _call_input_choice(self):
        rv = pywikibot.input_choice(
            'question',
            (('answer 1', 'A'),
             ('answer 2', 'N'),
             ('answer 3', 'S')),
            'A',
            automatic_quit=False)

        self.assertEqual(newstdout.getvalue(), '')

        self.assertIsInstance(rv, unicode)

        return rv

    def testInputChoiceDefault(self):
        newstdin.write('\n')
        newstdin.seek(0)

        returned = self._call_input_choice()

        self.assertEqual(returned, 'a')

    def testInputChoiceCapital(self):
        newstdin.write('N\n')
        newstdin.seek(0)

        returned = self._call_input_choice()

        self.assertEqual(newstderr.getvalue(), self.input_choice_output)

        self.assertEqual(returned, 'n')

    def testInputChoiceNonCapital(self):
        newstdin.write('n\n')
        newstdin.seek(0)

        returned = self._call_input_choice()

        self.assertEqual(newstderr.getvalue(), self.input_choice_output)

        self.assertEqual(returned, 'n')

    def testInputChoiceIncorrectAnswer(self):
        newstdin.write('X\nN\n')
        newstdin.seek(0)

        returned = self._call_input_choice()

        self.assertEqual(newstderr.getvalue(),
                         self.input_choice_output * 2)

        self.assertEqual(returned, 'n')

@unittest.skipUnless(os.name == 'posix', 'requires Unix console')
class TestTerminalOutputColorUnix(UITestCase):

    """Terminal output color tests."""

    str1 = 'text \03{lightpurple}light purple text\03{default} text'

    def testOutputColorizedText(self):
        pywikibot.output(self.str1)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(
            newstderr.getvalue(),
            'text \x1b[95mlight purple text\x1b[0m text\n')

    def testOutputNoncolorizedText(self):
        pywikibot.config.colorized_output = False
        pywikibot.output(self.str1)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(
            newstderr.getvalue(),
            'text light purple text text ***\n')

    str2 = ('normal text \03{lightpurple} light purple '
            '\03{lightblue} light blue \03{previous} light purple '
            '\03{default} normal text')

    def testOutputColorCascade_incorrect(self):
        """Test incorrect behavior of testOutputColorCascade."""
        pywikibot.output(self.str2)
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(
            newstderr.getvalue(),
            'normal text \x1b[95m light purple '
            '\x1b[94m light blue \x1b[95m light purple '
            '\x1b[0m normal text\n')

@unittest.skipUnless(os.name == 'posix', 'requires Unix console')
class TestTerminalUnicodeUnix(UITestCase):

    """Terminal output tests for unix."""

    def testOutputUnicodeText(self):
        pywikibot.output('Заглавная_страница')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(
            newstderr.getvalue(),
            self._encode('Заглавная_страница\n', 'utf-8'))

    def testInputUnicodeText(self):
        newstdin.write(self._encode('Заглавная_страница\n', 'utf-8'))
        newstdin.seek(0)

        returned = pywikibot.input('Википедию? ')

        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(
            newstderr.getvalue(),
            self._encode('Википедию? ', 'utf-8'))

        self.assertIsInstance(returned, unicode)
        self.assertEqual(returned, 'Заглавная_страница')

@unittest.skipUnless(os.name == 'posix', 'requires Unix console')
class TestTransliterationUnix(UITestCase):

    """Terminal output transliteration tests."""

    def testOutputTransliteratedUnicodeText(self):
        pywikibot.ui.encoding = 'latin-1'
        pywikibot.config.transliterate = True
        pywikibot.output('abcd АБГД αβγδ あいうえお')
        self.assertEqual(newstdout.getvalue(), '')
        self.assertEqual(
            newstderr.getvalue(),
            'abcd \x1b[93mA\x1b[0m\x1b[93mB\x1b[0m\x1b[93mG\x1b[0m'
            '\x1b[93mD\x1b[0m \x1b[93ma\x1b[0m\x1b[93mb\x1b[0m\x1b[93mg'
            '\x1b[0m\x1b[93md\x1b[0m \x1b[93ma\x1b[0m\x1b[93mi\x1b[0m'
            '\x1b[93mu\x1b[0m\x1b[93me\x1b[0m\x1b[93mo\x1b[0m\n')

@unittest.skipUnless(os.name == 'nt', 'requires Windows console')
class WindowsTerminalTestCase(UITestCase):

    """MS Windows terminal tests."""

    @classmethod
    def setUpClass(cls):
        if os.name != 'nt':
            raise unittest.SkipTest('requires Windows console')
        if not win32api:
            raise unittest.SkipTest('requires Windows package pywin32')
        if not win32clipboard:
            raise unittest.SkipTest('requires Windows package win32clipboard')
        if not pywinauto:
            raise unittest.SkipTest('requires Windows package pywinauto')
        try:
            # pywinauto 0.5.0
            cls._app = pywinauto.Application()
        except AttributeError as e1:
            try:
                cls._app = pywinauto.application.Application()
            except AttributeError as e2:
                raise unittest.SkipTest('pywinauto Application failed: {}\n{}'
                                        .format(e1, e2))
        super(WindowsTerminalTestCase, cls).setUpClass()

    @classmethod
    def setUpProcess(cls, command):
        si = subprocess.STARTUPINFO()
        si.dwFlags = subprocess.STARTF_USESTDHANDLES
        cls._process = subprocess.Popen(
            command, creationflags=subprocess.CREATE_NEW_CONSOLE)

        cls._app.connect_(process=cls._process.pid)

        # set truetype font (Lucida Console, hopefully)
        try:
            window = cls._app.window_()
        except Exception as e:
            cls.tearDownProcess()
            raise unittest.SkipTest(
                'Windows package pywinauto could not locate window: {!r}'
                .format(e))

        try:
            window.TypeKeys('% {UP}{ENTER}%L{HOME}L{ENTER}', with_spaces=True)
        except Exception as e:
            cls.tearDownProcess()
            raise unittest.SkipTest(
                'Windows package pywinauto could not use window TypeKeys: {!r}'
                .format(e))

    @classmethod
    def tearDownProcess(cls):
        cls._process.kill()

    def setUp(self):
        super(WindowsTerminalTestCase, self).setUp()
        self.setclip('')

    def waitForWindow(self):
        while not self._app.window_().IsEnabled():
            time.sleep(0.01)

    def getstdouterr(self):
        sentinel = '~~~~SENTINEL~~~~cedcfc9f-7eed-44e2-a176-d8c73136c185'
        # select all and copy to clipboard
        self._app.window_().SetFocus()
        self.waitForWindow()
        self._app.window_().TypeKeys(
            '% {UP}{UP}{UP}{RIGHT}{DOWN}{DOWN}{DOWN}{ENTER}{ENTER}',
            with_spaces=True)

        while True:
            data = self.getclip()
            if data != sentinel:
                return data
            time.sleep(0.01)

    def setclip(self, text):
        win32clipboard.OpenClipboard()
        win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT,
                                        unicode(text))
        win32clipboard.CloseClipboard()

    def getclip(self):
        win32clipboard.OpenClipboard()
        data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
        win32clipboard.CloseClipboard()
        data = data.split('\x00')[0]
        data = data.replace('\r\n', '\n')
        return data

    def sendstdin(self, text):
        self.setclip(text.replace('\n', '\r\n'))
        self._app.window_().SetFocus()
        self.waitForWindow()
        self._app.window_().TypeKeys(
            '% {UP}{UP}{UP}{RIGHT}{DOWN}{DOWN}{ENTER}',
            with_spaces=True)

class TestWindowsTerminalUnicode(WindowsTerminalTestCase):

    """MS Windows terminal unicode tests."""

    @classmethod
    def setUpClass(cls):
        super(TestWindowsTerminalUnicode, cls).setUpClass()
        fn = inspect.getfile(inspect.currentframe())
        cls.setUpProcess(['python', 'pwb.py', fn,
                          '--run-as-slave-interpreter'])

        _manager.connect()
        cls.pywikibot = _manager.pywikibot()

    @classmethod
    def tearDownClass(cls):
        del cls.pywikibot
        cls.tearDownProcess()

    def setUp(self):
        super(TestWindowsTerminalUnicode, self).setUp()

        self.pywikibot.set_config('colorized_output', True)
        self.pywikibot.set_config('transliterate', False)
        self.pywikibot.set_config('console_encoding', 'utf-8')
        self.pywikibot.set_ui('transliteration_target', None)
        self.pywikibot.set_ui('encoding', 'utf-8')

        self.pywikibot.cls()

    def testOutputUnicodeText_no_transliterate(self):
        self.pywikibot.output('Заглавная_страница')
        self.assertEqual(self.getstdouterr(), 'Заглавная_страница\n')

    def testOutputUnicodeText_transliterate(self):
        self.pywikibot.set_config('transliterate', True)
        self.pywikibot.set_ui('transliteration_target', 'latin-1')
        self.pywikibot.output('Заглавная_страница')
        self.assertEqual(self.getstdouterr(), 'Zaglavnaya_stranica\n')

    def testInputUnicodeText(self):
        self.pywikibot.set_config('transliterate', True)

        self.pywikibot.request_input('Википедию? ')
        self.assertEqual(self.getstdouterr(), 'Википедию?')
        self.sendstdin('Заглавная_страница\n')
        returned = self.pywikibot.get_input()

        self.assertEqual(returned, 'Заглавная_страница')

class TestWindowsTerminalUnicodeArguments(WindowsTerminalTestCase):

    """MS Windows terminal unicode argument tests."""

    @classmethod
    def setUpClass(cls):
        super(TestWindowsTerminalUnicodeArguments, cls).setUpClass()
        cls.setUpProcess(['cmd', '/k', 'echo off'])

    @classmethod
    def tearDownClass(cls):
        cls.tearDownProcess()

    def testOutputUnicodeText_no_transliterate(self):
        self.sendstdin(
            "python -c \"import os, pywikibot; os.system('cls'); "
            "pywikibot.output('\\n'.join(pywikibot.handleArgs()))\" "
            'Alpha Bετα Гамма دلتا\n')
        lines = []

        for i in range(3):
            lines = self.getstdouterr().split('\n')
            if len(lines) >= 4 and 'Alpha' not in lines:
                # if len(lines) < 4, we assume not all lines had been output
                # yet, and retry. We check at least one of the lines contains
                # "Alpha" to prevent using older clipboard content. We limit
                # the number of retries to 3 so that the test will finish even
                # if neither of these requirements are met.
                break
            time.sleep(1)

        # empty line is the new command line
        self.assertEqual(lines, ['Alpha', 'Bετα', 'Гамма', 'دلتا', ''])

# TODO: add tests for background colors.
class FakeUITest(TestCase):

    """Test case to allow doing uncolorized general UI tests."""

    net = False

    expected = 'Hello world you! ***'
    expect_color = False
    ui_class = terminal_interface_base.UI

    def setUp(self):
        """Create dummy instances for the test and patch encounter_color."""
        super(FakeUITest, self).setUp()
        if PY2:
            self.stream = io.BytesIO()
        else:
            self.stream = io.StringIO()
        self.ui_obj = self.ui_class()
        self._orig_encounter_color = self.ui_obj.encounter_color
        self.ui_obj.encounter_color = self._encounter_color
        self._index = 0

    def tearDown(self):
        """Unpatch the encounter_color method."""
        self.ui_obj.encounter_color = self._orig_encounter_color
        super(FakeUITest, self).tearDown()
        self.assertEqual(self._index,
                         len(self._colors) if self.expect_color else 0)

    def _getvalue(self):
        """Get the value of the stream and also decode it on Python 2."""
        value = self.stream.getvalue()
        if PY2:
            value = value.decode(self.ui_obj.encoding)
        return value

    def _encounter_color(self, color, target_stream):
        """Patched encounter_color method."""
        assert False, 'This method should not be invoked'

    def test_no_color(self):
        """Test a string without any colors."""
        self._colors = ()
        self.ui_obj._print('Hello world you!', self.stream)
        self.assertEqual(self._getvalue(), 'Hello world you!')

    def test_one_color(self):
        """Test a string using one color."""
        self._colors = (('red', 6), ('default', 10))
        self.ui_obj._print('Hello \03{red}world you!', self.stream)
        self.assertEqual(self._getvalue(), self.expected)

    def test_flat_color(self):
        """Test using colors with defaulting in between."""
        self._colors = (('red', 6), ('default', 6), ('yellow', 3),
                        ('default', 1))
        self.ui_obj._print('Hello \03{red}world \03{default}you\03{yellow}!',
                           self.stream)
        self.assertEqual(self._getvalue(), self.expected)

    def test_stack_with_pop_color(self):
        """Test using stacked colors and just popping the latest color."""
        self._colors = (('red', 6), ('yellow', 6), ('red', 3), ('default', 1))
        self.ui_obj._print('Hello \03{red}world \03{yellow}you\03{previous}!',
                           self.stream)
        self.assertEqual(self._getvalue(), self.expected)

    def test_stack_implicit_color(self):
        """Test using stacked colors without popping any."""
        self._colors = (('red', 6), ('yellow', 6), ('default', 4))
        self.ui_obj._print('Hello \03{red}world \03{yellow}you!', self.stream)
        self.assertEqual(self._getvalue(), self.expected)

    def test_one_color_newline(self):
        """Test with trailing new line and one color."""
        self._colors = (('red', 6), ('default', 11))
        self.ui_obj._print('Hello \03{red}world you!\n', self.stream)
        self.assertEqual(self._getvalue(), self.expected + '\n')

class FakeUIColorizedTestBase(TestCase):

    """Base class for test cases requiring that colorized output is active."""

    expect_color = True

    def setUp(self):
        """Force colorized_output to True."""
        super(FakeUIColorizedTestBase, self).setUp()
        self._old_config = pywikibot.config2.colorized_output
        pywikibot.config2.colorized_output = True

    def tearDown(self):
        """Undo colorized_output configuration."""
        pywikibot.config2.colorized_output = self._old_config
        super(FakeUIColorizedTestBase, self).tearDown()

class FakeUnixTest(FakeUIColorizedTestBase, FakeUITest):

    """Test case to allow doing colorized Unix tests in any environment."""

    net = False

    expected = 'Hello world you!'
    ui_class = terminal_interface_unix.UnixUI

    def _encounter_color(self, color, target_stream):
        """Verify that the written data, color and stream are correct."""
        self.assertIs(target_stream, self.stream)
        expected_color = self._colors[self._index][0]
        self._index += 1
        self.assertEqual(color, expected_color)
        self.assertLength(self.stream.getvalue(),
                          sum(e[1] for e in self._colors[:self._index]))

class FakeWin32Test(FakeUIColorizedTestBase, FakeUITest):

    """
    Test case to allow doing colorized Win32 tests in any environment.

    This only patches the ctypes import in the terminal_interface_win32
    module. As the Win32CtypesUI is using the std-streams from another
    import these will be unpatched.
    """

    net = False

    expected = 'Hello world you!'
    ui_class = terminal_interface_win32.Win32UI

    def setUp(self):
        """Patch the ctypes import and initialize a stream and UI instance."""
        super(FakeWin32Test, self).setUp()
        self._orig_ctypes = terminal_interface_win32.ctypes
        ctypes = FakeModule.create_dotted('ctypes.windll.kernel32')
        ctypes.windll.kernel32.SetConsoleTextAttribute = self._handle_setattr
        terminal_interface_win32.ctypes = ctypes
        self.stream._hConsole = object()

    def tearDown(self):
        """Unpatch the ctypes import and check that all colors were used."""
        terminal_interface_win32.ctypes = self._orig_ctypes
        super(FakeWin32Test, self).tearDown()

    def _encounter_color(self, color, target_stream):
        """Call the original method."""
        self._orig_encounter_color(color, target_stream)

    def _handle_setattr(self, handle, attribute):
        """Dummy method to handle SetConsoleTextAttribute."""
        self.assertIs(handle, self.stream._hConsole)
        color = self._colors[self._index][0]
        self._index += 1
        color = terminal_interface_win32.windowsColors[color]
        self.assertEqual(attribute, color)
        self.assertLength(self.stream.getvalue(),
                          sum(e[1] for e in self._colors[:self._index]))

class FakeWin32UncolorizedTest(FakeWin32Test):

    """Test case to allow doing uncolorized Win32 tests in any environment."""

    net = False

    expected = 'Hello world you! ***'
    expect_color = False

    def setUp(self):
        """Change the local stream's console to None to disable colors."""
        super(FakeWin32UncolorizedTest, self).setUp()
        self.stream._hConsole = None

if __name__ == '__main__':  # pragma: no cover
    try:
        try:
            unittest.main()
        except SystemExit:
            pass
    finally:
        unpatch()


text:
package com.badlogic.gdx.backends.gwt;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.graphics.Cursor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.webgl.client.WebGLContextAttributes;
import com.google.gwt.webgl.client.WebGLRenderingContext;

public class GwtGraphics implements Graphics {
	CanvasElement canvas;
	WebGLRenderingContext context;
	GL20 gl;
	String extensions;
	float fps = 0;
	long lastTimeStamp = System.currentTimeMillis();
	long frameId = -1;
	float deltaTime = 0;
	float time = 0;
	int frames;
	GwtApplicationConfiguration config;
	boolean inFullscreenMode = false;

	public GwtGraphics (Panel root, GwtApplicationConfiguration config) {
		Canvas canvasWidget = Canvas.createIfSupported();
		if (canvasWidget == null) throw new GdxRuntimeException("Canvas not supported");
		canvas = canvasWidget.getCanvasElement();
		root.add(canvasWidget);
		canvas.setWidth(config.width);
		canvas.setHeight(config.height);
		this.config = config;

		WebGLContextAttributes attributes = WebGLContextAttributes.create();
		attributes.setAntialias(config.antialiasing);
		attributes.setStencil(config.stencil);
		attributes.setAlpha(config.alpha);
		attributes.setPremultipliedAlpha(config.premultipliedAlpha);
		attributes.setPreserveDrawingBuffer(config.preserveDrawingBuffer);

		context = WebGLRenderingContext.getContext(canvas, attributes);
		context.viewport(0, 0, config.width, config.height);
		this.gl = config.useDebugGL ? new GwtGL20Debug(context) : new GwtGL20(context);
	}

	public WebGLRenderingContext getContext () {
		return context;
	}

	@Override
	public GL20 getGL20 () {
		return gl;
	}

	@Override
	public int getWidth () {
		return canvas.getWidth();
	}

	@Override
	public int getHeight () {
		return canvas.getHeight();
	}

	@Override
	public long getFrameId () {
		return frameId;
	}

	@Override
	public float getDeltaTime () {
		return deltaTime;
	}

	@Override
	public int getFramesPerSecond () {
		return (int)fps;
	}

	@Override
	public GraphicsType getType () {
		return GraphicsType.WebGL;
	}

	@Override
	public float getPpiX () {
		return 96;
	}

	@Override
	public float getPpiY () {
		return 96;
	}

	@Override
	public float getPpcX () {
		return 96 / 2.54f;
	}

	@Override
	public float getPpcY () {
		return 96 / 2.54f;
	}

	@Override
	public boolean supportsDisplayModeChange () {
		return true;
	}

	@Override
	public DisplayMode[] getDisplayModes () {
		return new DisplayMode[] {new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, 8) {}};
	}

	private native int getScreenWidthJSNI () /*-{
															return $wnd.screen.width;
															}-*/;

	private native int getScreenHeightJSNI () /*-{
															return $wnd.screen.height;
															}-*/;

	private native boolean isFullscreenJSNI () /*-{
																if("webkitIsFullScreen" in $doc) {
																return $doc.webkitIsFullScreen;
																}
																if("mozFullScreen" in $doc) {
																return $doc.mozFullScreen;
																}
																return false
																}-*/;

	private void fullscreenChanged () {
		if (!isFullscreen()) {
			canvas.setWidth(config.width);
			canvas.setHeight(config.height);
		}
	}

	private native boolean setFullscreenJSNI (GwtGraphics graphics, CanvasElement element) /*-{
																														if(element.webkitRequestFullScreen) {
																														element.width = $wnd.screen.width;
																														element.height = $wnd.screen.height;
																														element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
																														$doc.addEventListener("webkitfullscreenchange", function() {
																														graphics.@com.badlogic.gdx.backends.gwt.GwtGraphics::fullscreenChanged()();
																														}, false);
																														return true;
																														}
																														if(element.mozRequestFullScreen) {
																														element.width = $wnd.screen.width;
																														element.height = $wnd.screen.height;
																														element.mozRequestFullScreen();
																														$doc.addEventListener("mozfullscreenchange", function() {
																														graphics.@com.badlogic.gdx.backends.gwt.GwtGraphics::fullscreenChanged()();
																														}, false);
																														return true;
																														}
																														return false;
																														}-*/;

	private native void exitFullscreen () /*-{
														if($doc.webkitExitFullscreen) $doc.webkitExitFullscreen();
														if($doc.mozExitFullscreen) $doc.mozExitFullscreen();
														}-*/;

	@Override
	public DisplayMode getDesktopDisplayMode () {
		return new DisplayMode(getScreenWidthJSNI(), getScreenHeightJSNI(), 60, 8) {};
	}

	@Override
	public boolean setDisplayMode (DisplayMode displayMode) {
		if (displayMode.width != getScreenWidthJSNI() && displayMode.height != getScreenHeightJSNI()) return false;
		return setFullscreenJSNI(this, canvas);
	}

	@Override
	public boolean setDisplayMode (int width, int height, boolean fullscreen) {
		if (fullscreen) {
			if (width != getScreenWidthJSNI() && height != getScreenHeightJSNI()) return false;
			return setFullscreenJSNI(this, canvas);
		} else {
			if (isFullscreenJSNI()) exitFullscreen();
			canvas.setWidth(width);
			canvas.setHeight(height);
			return true;
		}
	}

	@Override
	public BufferFormat getBufferFormat () {
		return new BufferFormat(8, 8, 8, 0, 16, config.stencil ? 8 : 0, 0, false);
	}

	@Override
	public boolean supportsExtension (String extension) {
		if (extensions == null) extensions = Gdx.gl.glGetString(GL20.GL_EXTENSIONS);
		return extensions.contains(extension);
	}

	public void update () {
		long currTimeStamp = System.currentTimeMillis();
		deltaTime = (currTimeStamp - lastTimeStamp) / 1000.0f;
		lastTimeStamp = currTimeStamp;
		time += deltaTime;
		frames++;
		if (time > 1) {
			this.fps = frames;
			time = 0;
			frames = 0;
		}
	}

	@Override
	public void setTitle (String title) {
	}

	@Override
	public void setVSync (boolean vsync) {
	}

	@Override
	public float getDensity () {
		return 96.0f / 160;
	}

	@Override
	public void setContinuousRendering (boolean isContinuous) {
	}

	@Override
	public boolean isContinuousRendering () {
		return true;
	}

	@Override
	public void requestRendering () {
	}

	@Override
	public float getRawDeltaTime () {
		return getDeltaTime();
	}

	@Override
	public boolean isFullscreen () {
		return isFullscreenJSNI();
	}

	@Override
	public boolean isGL30Available () {
		return false;
	}

	@Override
	public GL30 getGL30 () {
		return null;
	}

	@Override
	public Cursor newCursor (Pixmap pixmap, int xHotspot, int yHotspot) {
		return null;
	}

	@Override
	public void setCursor (Cursor cursor) {
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<window type="dialog">

	<defaultcontrol always="true">32501</defaultcontrol>
	<include>dialogeffect</include>
	<depth>DepthDialog+</depth>
  <controls>
		<control type="group">
			<control type="image">

				<posx>240</posx>
				<posy>205</posy>
				<width>800</width>
				<height>310</height>
				<texture>AddonWindow/dialog_back.png</texture>
			</control>
			<control type="button" id="32500">

				<posx>981</posx>
				<posy>222</posy>
				<width>32</width>
				<height>32</height>
				<texturefocus>AddonWindow/dialog_close_focus.png</texturefocus>
				<texturenofocus>AddonWindow/dialog_close_nofocus.png</texturenofocus>
				<onup>32508</onup>
				<ondown>32501</ondown>
				<onleft condition="SubString(Control.GetLabel(32501),*)">32505</onleft>
				<onleft condition="SubString(Control.GetLabel(32502),*)">32507</onleft>
			</control>
			<control type="radiobutton" id="32501">

				<posx>820</posx>
				<posy>315</posy>
				<width>180</width>
				<height>43</height>
				<visible>true</visible>
				<colordiffuse>FFFFFFFF</colordiffuse>
				<texturefocus>Button/button-focus.png</texturefocus>
				<texturenofocus>Button/button-nofocus.png</texturenofocus>
				<wrapmultiline>true</wrapmultiline>
				font12
				$ADDON[plugin.video.quasar 30105]
				<textcolor>FFFFFFFF</textcolor>
				<focusedcolor>FFFFFFFF</focusedcolor>
				<disabledcolor>80FFFFFF</disabledcolor>
				<invalidcolor>FFFFFFFF</invalidcolor>
				<align>center</align>
				<aligny>center</aligny>
				<onup>32500</onup>
				<ondown>32502</ondown>
				<onleft condition="SubString(Control.GetLabel(32501),*)">32505</onleft>
				<onleft condition="SubString(Control.GetLabel(32502),*)">32507</onleft>
			</control>
			<control type="radiobutton" id="32502">

				<posx>820</posx>
				<posy>375</posy>
				<width>180</width>
				<height>43</height>
				<visible>true</visible>
				<colordiffuse>FFFFFFFF</colordiffuse>
				<texturefocus>Button/button-focus.png</texturefocus>
				<texturenofocus>Button/button-nofocus.png</texturenofocus>
				<wrapmultiline>true</wrapmultiline>
				font12
				$ADDON[plugin.video.quasar 30106]
				<textcolor>FFFFFFFF</textcolor>
				<focusedcolor>FFFFFFFF</focusedcolor>
				<disabledcolor>80FFFFFF</disabledcolor>
				<invalidcolor>FFFFFFFF</invalidcolor>
				<align>center</align>
				<aligny>center</aligny>
				<onup>32501</onup>
				<ondown>32508</ondown>
				<onleft condition="SubString(Control.GetLabel(32501),*)">32505</onleft>
				<onleft condition="SubString(Control.GetLabel(32502),*)">32507</onleft>
			</control>
			<control type="button" id="32508">

				<posx>820</posx>
				<posy>435</posy>
				<width>180</width>
				<height>43</height>
				<visible>true</visible>
				<colordiffuse>FFFFFFFF</colordiffuse>
				<texturefocus>Button/button-focus.png</texturefocus>
				<texturenofocus>Button/button-nofocus.png</texturenofocus>
				<wrapmultiline>true</wrapmultiline>
				font12
				$ADDON[plugin.video.quasar 30109]
				<textcolor>FFFFFFFF</textcolor>
				<focusedcolor>FFFFFFFF</focusedcolor>
				<disabledcolor>80FFFFFF</disabledcolor>
				<invalidcolor>FFFFFFFF</invalidcolor>
				<align>center</align>
				<aligny>center</aligny>
				<onup>32502</onup>
				<ondown>32500</ondown>
				<onleft condition="SubString(Control.GetLabel(32501),*)">32505</onleft>
				<onleft condition="SubString(Control.GetLabel(32502),*)">32507</onleft>
			</control>
			<control type="label" id="32503">

				<posx>425</posx>
				<posy>225</posy>
				<width>400</width>
				<height>30</height>
				font14
				<align>center</align>
				<aligny>center</aligny>
				[B]$ADDON[plugin.video.quasar 30104][/B]
				<textcolor>silver</textcolor>
				<shadowcolor>AA000000</shadowcolor>
			</control>
			<control type="label" id="32504">

				<posx>280</posx>
				<posy>280</posy>
				<width>500</width>
				<height>30</height>
				<visible>SubString(Control.GetLabel(32501),*)</visible>
				font13
				$ADDON[plugin.video.quasar 30107]
				<align>left</align>
				<aligny>center</aligny>
				<textcolor>silver</textcolor>
				<shadowcolor>AA000000</shadowcolor>
			</control>
			<control type="button" id="32505">

				<posx>280</posx>
				<posy>315</posy>
				<width>500</width>
				<height>43</height>
				<visible>SubString(Control.GetLabel(32501),*)</visible>
				<colordiffuse>FFFFFFFF</colordiffuse>
				<texturefocus>Button/button-focus.png</texturefocus>
				<texturenofocus>Button/button-nofocus.png</texturenofocus>
				<wrapmultiline>false</wrapmultiline>
				font14
				<textcolor>FFB2D4F5</textcolor>
				<focusedcolor>FFFFFFFF</focusedcolor>
				<disabledcolor>80FFFFFF</disabledcolor>
				<invalidcolor>FFFFFFFF</invalidcolor>
				<align>left</align>
				<aligny>center</aligny>
				<onright>32508</onright>
			</control>
			<control type="label" id="32506">

				<posx>280</posx>
				<posy>280</posy>
				<width>500</width>
				<height>30</height>
				<visible>SubString(Control.GetLabel(32502),*)</visible>
				font13
				$ADDON[plugin.video.quasar 30108]
				<align>left</align>
				<aligny>center</aligny>
				<textcolor>silver</textcolor>
				<shadowcolor>AA000000</shadowcolor>
			</control>
			<control type="button" id="32507">

				<posx>280</posx>
				<posy>315</posy>
				<width>500</width>
				<height>43</height>
				<visible>SubString(Control.GetLabel(32502),*)</visible>
				<colordiffuse>FFFFFFFF</colordiffuse>
				<texturefocus>Button/button-focus.png</texturefocus>
				<texturenofocus>Button/button-nofocus.png</texturenofocus>
				<wrapmultiline>false</wrapmultiline>
				font14
				<textcolor>FFB2D4F5</textcolor>
				<focusedcolor>FFFFFFFF</focusedcolor>
				<disabledcolor>80FFFFFF</disabledcolor>
				<invalidcolor>FFFFFFFF</invalidcolor>
				<align>left</align>
				<aligny>center</aligny>
				<onright>32508</onright>
			</control>
		</control>
  </controls>
</window>


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

namespace Agathas.Storefront.Model.Products
{
    public interface IProductAttribute
    {
        int Id { get; set; }
        string Name { get; set; }
    }
}


text:
backbone-init
=============

grunt-init project template for creating Backbone project with using require.js module system


text:
/*
 * Game.cpp
 *
 *  Created on: Aug 31, 2013
 *      Author: antidotcb
 */

#include "Game.h"

namespace minimi {

Game::Game() {
	// TODO Auto-generated constructor stub

}

Game::~Game() {
	// TODO Auto-generated destructor stub
}

} /* namespace minimi */


text:
import express from 'express';
import webpack from 'webpack';
import path from 'path';
import config from '../webpack.config.dev';
import open from 'open';

/* eslint-disable no-console */

const app = express();
const compiler = webpack(config);

app.set('port', (process.env.PORT || 5000));

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
  // res.sendFile(path.join( __dirname, '../src/index.html'));
  res.sendFile(path.join(config.output.publicPath, '/dist/index.html'));
});

app.listen(app.get('port'), function(err) {
  if (err) {
    console.log(err);
  } else {
   // open(`http://localhost:${port}`);
  }
});


text:
// Copyright (c) 2005  Per M.A. Bothner.
// This is free software;  for terms and warranty disclaimer see ./COPYING.

package gnu.kawa.functions;
import gnu.math.*;
import java.math.*;
import gnu.mapping.*;

/**
 * Implement the Scheme standard function "*".
 * @author Per Bothner
 */

public class MultiplyOp extends ArithOp
{
  public static final MultiplyOp $St = new MultiplyOp("*");

  public MultiplyOp(String name)
  {
    super(name, MUL);
    setProperty(Procedure.validateApplyKey,
                "gnu.kawa.functions.CompileArith:validateApplyArithOp");
    Procedure.compilerKey.set(this, "*gnu.kawa.functions.CompileArith:forMul");
  }

  public Object defaultResult ()
  {
    return IntNum.one();
  }

  public static Object apply (Object arg1, Object arg2)
  {
    return ((Numeric) arg1).mul(arg2);
  }

  public Object applyN (Object[] args)
  {
    int len = args.length;
    if (len == 0)
      return IntNum.one ();
    Number result = (Number) args[0];
    int code = Arithmetic.classifyValue(result);
    for (int i = 1; i < len; i++)
      {
	Object arg2 = args[i];
	int code2 = Arithmetic.classifyValue(arg2);
	code = code < code2 ? code2 : code;

	switch (code)
	  {
	  case Arithmetic.INT_CODE:
	    int i1 = Arithmetic.asInt(result);
	    int i2 = Arithmetic.asInt(arg2);
	    result = new Integer(i1 * i2);
	    break;
	  case Arithmetic.LONG_CODE:
	    long l1 = Arithmetic.asLong(result);
	    long l2 = Arithmetic.asLong(arg2);
	    result = new Long(l1 * l2);
	    break;
	  case Arithmetic.BIGINTEGER_CODE:
	    BigInteger bi1 = Arithmetic.asBigInteger(result);
	    BigInteger bi2 = Arithmetic.asBigInteger(arg2);
	    result = bi1.multiply(bi2);
	    break;
	  case Arithmetic.INTNUM_CODE:
	    result = IntNum.times(Arithmetic.asIntNum(result),
				  Arithmetic.asIntNum(arg2));
	    break;
	  case Arithmetic.BIGDECIMAL_CODE:
	    BigDecimal bd1 = Arithmetic.asBigDecimal(result);
	    BigDecimal bd2 = Arithmetic.asBigDecimal(arg2);
	    result = bd1.multiply(bd2);
	    break;
	  case Arithmetic.RATNUM_CODE:
	    result = RatNum.times(Arithmetic.asRatNum(result),
				  Arithmetic.asRatNum(arg2));
	    break;
	  case Arithmetic.FLOAT_CODE:
	    float f1 = Arithmetic.asFloat(result);
	    float f2 = Arithmetic.asFloat(arg2);
	    result = new Float(f1 * f2);
	    break;
	  case Arithmetic.DOUBLE_CODE:
	    double d1 = Arithmetic.asDouble(result);
	    double d2 = Arithmetic.asDouble(arg2);
	    result = new Double(d1 * d2);
	    break;
	  case Arithmetic.FLONUM_CODE:
	    d1 = Arithmetic.asDouble(result);
	    d2 = Arithmetic.asDouble(arg2);
	    result = new DFloNum(d1 * d2);
	    break;
	  default:
	    result = Arithmetic.asNumeric(result)
	      .mul(Arithmetic.asNumeric(arg2));
	  }
      }
    return result;
   }

}


text:
import math
import maya.api.OpenMaya as OpenMaya

nodeName = 'mlExpmapToEuler'

rotateName = ('rotate', 'r', u'回転')
eulerAngleName = (('rotateX', 'rx', u'回転 X'),
                  ('rotateY', 'ry', u'回転 Y'),
                  ('rotateZ', 'rz', u'回転 Z'))
expmapName = ('expmap', 'em', u'Expmap')
expmapElementName = (('expmapX', 'emx', 'Expmap X'),
                     ('expmapY', 'emy', 'Expmap Y'),
                     ('expmapZ', 'emz', 'Expmap Z'))
rotateOrderName  = ('rotateOrder', 'ro', u'回転順序')

def maya_useNewAPI():
    pass

class mlExpmapToEuler(OpenMaya.MPxNode):
    """expmap to euler"""
    rotate = OpenMaya.MObject()
    eulerAngles = []
    expmap = OpenMaya.MObject()
    expmapElement = []
    rotateOrder = OpenMaya.MObject()

    def __init__(self):
        OpenMaya.MPxNode.__init__(self)

    @staticmethod
    def creator():
        return mlExpmapToEuler()

    @staticmethod
    def initialize():
        # output euler rotation
        cAttr = OpenMaya.MFnCompoundAttribute()
        mlExpmapToEuler.rotate = cAttr.create(rotateName[0], rotateName[1])
        cAttr.setNiceNameOverride(rotateName[2])
        mlExpmapToEuler.eulerAngles = []
        for i in xrange(0, 3):
            uAttr = OpenMaya.MFnUnitAttribute()
            mlExpmapToEuler.eulerAngles = mlExpmapToEuler.eulerAngles + \
                [uAttr.create(eulerAngleName[i][0],
                              eulerAngleName[i][1],
                              OpenMaya.MFnUnitAttribute.kAngle,
                              0.0)]
            uAttr.setNiceNameOverride(eulerAngleName[i][2])
            uAttr.keyable = False
            uAttr.writable = False
            cAttr.addChild(mlExpmapToEuler.eulerAngles[-1])
        mlExpmapToEuler.addAttribute(mlExpmapToEuler.rotate);

        # input expmap
        cAttr = OpenMaya.MFnCompoundAttribute()
        mlExpmapToEuler.expmap = cAttr.create(expmapName[0], expmapName[1])
        cAttr.setNiceNameOverride(expmapName[2])
        mlExpmapToEuler.expmapElement = []
        for i in xrange(0, 3):
            nAttr = OpenMaya.MFnNumericAttribute()
            mlExpmapToEuler.expmapElement = mlExpmapToEuler.expmapElement + \
                [nAttr.create(expmapElementName[i][0],
                              expmapElementName[i][1],
                              OpenMaya.MFnNumericData.kDouble,
                              0.0)]
            nAttr.setNiceNameOverride(expmapElementName[i][2])
            nAttr.keyable = True
            nAttr.readable = False
            cAttr.addChild(mlExpmapToEuler.expmapElement[i])
        mlExpmapToEuler.addAttribute(mlExpmapToEuler.expmap)
        mlExpmapToEuler.attributeAffects(mlExpmapToEuler.expmap, mlExpmapToEuler.rotate)

        # rotation order
        nAttr = OpenMaya.MFnNumericAttribute()
        mlExpmapToEuler.rotateOrder = nAttr.create('rotateOrder', 'ro', OpenMaya.MFnNumericData.kInt, 0)
        nAttr.setNiceNameOverride(rotateOrderName[2])
        nAttr.readable = False
        mlExpmapToEuler.addAttribute(mlExpmapToEuler.rotateOrder);
        mlExpmapToEuler.attributeAffects(mlExpmapToEuler.rotateOrder, mlExpmapToEuler.rotate)

    def __init__(self):
        OpenMaya.MPxNode.__init__(self)

    def compute(self, plug, dataBlock):
        if plug is not self.rotate and plug not in self.eulerAngles:
            return

        rv = [0.0, 0.0, 0.0]
        for i in xrange(0, 3):
            inputHandle = dataBlock.inputValue(mlExpmapToEuler.expmapElement[i])
            rv[i] = inputHandle.asDouble()
        orderHandle = dataBlock.inputValue(mlExpmapToEuler.rotateOrder)
        exHandle = dataBlock.outputValue(mlExpmapToEuler.eulerAngles[0])
        eyHandle = dataBlock.outputValue(mlExpmapToEuler.eulerAngles[1])
        ezHandle = dataBlock.outputValue(mlExpmapToEuler.eulerAngles[2])
        mag = math.sqrt(rv[0] * rv[0] + rv[1] * rv[1] + rv[2] * rv[2])
        if math.fabs(mag) < 1.0e-6:
            sina = 0
        else:
            sina = math.sin(mag) / mag
        quat = OpenMaya.MQuaternion(rv[0] * sina,
                                    rv[1] * sina,
                                    rv[2] * sina,
                                    math.cos(mag))
        order = orderHandle.asInt()
        euler = OpenMaya.MEulerRotation(0, 0, 0, order)
        euler *= quat
        exHandle.setDouble(euler.x)
        eyHandle.setDouble(euler.y)
        ezHandle.setDouble(euler.z)
        dataBlock.setClean(plug)