text:
/*--------------------------------------------------
// JCalculator - A Calculator Plugin for jQuery   //
//                                                //
// Author: Hitesh Agarwal                         //
// Version: 1.0                                   //
// Date: 14-feb 11                                //
// License: GNU General Public License v2.0       //
//                                                //
--------------------------------------------------*/

/*
	1. Must include jquery and jquery-ui[js and css] before the script
	2. Must include calculator.css

	usage:
		html:

		  js: later
*/

// @param params = later

(function($) {

	$.fn.calculator = function(params){
		var settings = jQuery.extend({},$.fn.calculator.defaults, params);

		//iterate over every matched element
		return this.each(function(){
			var calc = $(this);

			if(!calc.hasClass('converted2calc')){

				calc.settings = $.meta ?  $.extend({}, settings, calc.data()) : settings;

				$.fn.calculator.init(calc);

				// add class to chack later if calculator is ready to use
				calc.addClass('converted2calc');
			}
		});
	}

	$.fn.calculator.init = function(calc){
		calc.expression = '';
		calc.text = '0';
		calc._cleartextflag = false;
		calc._executable = true;
		calc._lastresult = null;

		//format calculator
		$.fn.calculator.format(calc).find('.calc-title-bar').text(calc.settings.title);

		/* Append Buttons
		------------------*/
		for(i in $.fn.calculator.buttons){
			$.fn.calculator.format.addButton(calc, $.fn.calculator.buttons[i]);
		}

		calc.keydown(function(event){
			event.preventDefault();
			if($.fn.calculator.buttons[event.keyCode]){
				$.fn.calculator.buttons[event.keyCode].onPress(calc);		// calling button's onPress event specified in button itself
				$.fn.calculator.action.updateDisplay(calc);					// updating calculator's display as calculator text or expression may have changed during button's onpress event
				calc.settings.buttonPressed();								// firing event buttonPressed to execute custom code passed in calculator params
			}
		})

		// hide it if defaultOpen is false
		calc.settings.defaultOpen?'':calc.css({display:'none'});

		// make it draggable if movable is true
		(calc.settings.movable&&$.fn.draggable)?(calc.draggable({handle:'.calc-title-bar-container'}).find('.calc-title-bar-container').css('cursor','move')):'';

		// make it closable if movable is true
		calc.settings.movable?( $('

').button({icons: {primary: "ui-icon-close"}, text: false}).appendTo(calc.find('.calc-title-bar-container')).css({position:'absolute',right:2,top:2,width:15,height:14}).click(function(){calc.settings.hide(calc)}) ):'';

		// make it resizable if resizable is true
		(calc.settings.resizable&&$.fn.resizable)?calc.resizable({handles:'se'}).css({minHeight:160, minWidth:130}):'';

		$.fn.calculator.action.updateDisplay(calc);
	}

	$.fn.calculator.hide = function(calc) {
		calc.hide();
	};

	$.fn.calculator.show = function(calc) {
		calc.show();
	};

	// define our format function
	$.fn.calculator.format = function(calc) {
		return calc.addClass('calculator calc-wrapper ui-widget ui-corner-all ui-widget-content').html('

').attr('tabindex',0).css({width:calc.settings.width, height:calc.settings.height, outline:'none', position:'relative', zIndex:99999}).focusin(function(){calc.find('.calc-text').css({backgroundColor:'#FFFFF2'})}).focusout(function(){calc.find('.calc-text').css({backgroundColor:''})});
	};

	$.fn.calculator.format.createButton = function(button){
		var style = (button.left)?'left:'+button.left+';':'';
		style += (button.top)?'top:'+button.top+';':'';
		style += (button.width)?'width:'+button.width+';':'';
		style += (button.height)?'height:'+button.height+';':'';
		return $('

'+button.symbol+'

');
	}

	// function to add button
	$.fn.calculator.format.addButton = function(calc,button){
		$.fn.calculator.format.createButton(button).button().appendTo(calc.find('.calc-buttons-wrapper')).click(function(){
			button.onPress(calc);							// calling button's onPress event specified in button itself
			$.fn.calculator.action.updateDisplay(calc);		// updating calculator's display as calculator text or expression may have changed during button's onpress event
			calc.settings.buttonPressed();					// firing event buttonPressed to execute custom code passed in calculator params
		});

	}

	// calculator actions
	$.fn.calculator.action = {
		updateDisplay: function(calc){
			calc.find('.calc-text').text(calc.text);
			calc.settings.displayChanged();					// firing event displayChanged to execute custom code passed in calculator params
		},
		input: function(calc, button){
			if(calc._executable){
				if(calc.text.length < calc.settings.accuracy||calc._cleartextflag){
					var input = (calc.text=='0'||calc._cleartextflag)?((button.symbol=='.')?'0.':(button.symbol=='0')?'':button.symbol):calc.text+button.symbol;

					if($.fn.calculator.validate.input(input)){
						calc.text = input;
						calc.expression = calc.expression+((input=='0.')?input:button.symbol);
						calc._cleartextflag = false;
					}
				}
				calc._lastresult = null;
			}
			else{
				if($.fn.calculator.validate.expression(calc.expression)){
					calc.text = eval(calc.expression);
					calc._lastresult = calc.text + '';
					calc.text = (calc.text.toPrecision(calc.settings.accuracy).indexOf('e') == -1)?parseFloat( calc.text.toPrecision(calc.settings.accuracy)) + '':calc.text.toPrecision(calc.settings.accuracy);
					//calc.expression = calc.text;
					calc.expression = '';
					calc._executable = false;
					calc._cleartextflag = true;					// clear display on next user input
				}
				if(calc._lastresult){
					calc.expression = calc._lastresult;
					calc._lastresult = null;
				}
				calc._cleartextflag = true;					// clear display on next user input
				calc.expression = (calc.expression=='')?button.symbol:($.fn.calculator.validate.operation(calc.expression)?calc.expression.replace(/[-+/\*]$/,button.symbol):calc.expression+button.symbol);
			}
		}
	}

	$.fn.calculator.buttons = {
		/* index:{
				symbol:<button's symbol to show on calc>,
				onpress: <event to execute on button pressed [event param calc | the calculator itself]>,
				left:<button's left position in percentage inside calc buttons container>,
				top:<button's top position in percentage inside calc buttons container>,
				width:<button's width in percentage inside calc buttons container [optional | handle inside css either]>,
				height:<button's height in percentage inside calc buttons container [optional | handle inside css either]>,
			}
		*/
		96:{symbol:'0', keycode: 48, left:'4%', top:'80%', width:'44%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);} },
		97:{symbol:'1', keycode: 49, left:'4%', top:'61%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);} },
		98:{symbol:'2', keycode: 50, left:'28%', top:'61%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);} },
		99:{symbol:'3', keycode: 51, left:'52%', top:'61%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);} },
		100:{symbol:'4', keycode: 52, left:'4%', top:'42%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);}  },
		101:{symbol:'5', keycode: 53, left:'28%', top:'42%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);}  },
		102:{symbol:'6', keycode: 54, left:'52%', top:'42%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);}  },
		103:{symbol:'7', keycode: 55, left:'4%', top:'23%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);}  },
		104:{symbol:'8', keycode: 56, left:'28%', top:'23%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);}  },
		105:{symbol:'9', keycode: 57, left:'52%', top:'23%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);}  },
		110:{symbol:'.', keycode: 110, left:'52%', top:'80%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;$.fn.calculator.action.input(calc, this);} },
		111:{symbol:'/', keycode: 111, left:'4%', top:'4%', width:'20%', height:'15%', onPress:function(calc){calc._executable = false;$.fn.calculator.action.input(calc, this);} },
		106:{symbol:'*', keycode: 106, left:'28%', top:'4%', width:'20%', height:'15%', onPress:function(calc){calc._executable = false;$.fn.calculator.action.input(calc, this);} },
		107:{symbol:'+', keycode: 107, left:'76%', top:'23%', width:'20%',height:'34%', onPress:function(calc){calc._executable = false;$.fn.calculator.action.input(calc, this);} },
		109:{symbol:'-', keycode: 109, left:'52%', top:'4%', width:'20%', height:'15%', onPress:function(calc){calc._executable = false;$.fn.calculator.action.input(calc, this);} },
		13:{symbol:'=', keycode: 13, left:'76%', top:'61%', width:'20%', height:'34%', onPress:function(calc){
				if($.fn.calculator.validate.expression(calc.expression)){
					calc.text = eval(calc.expression);
					calc._lastresult = calc.text + '';
					calc.text = (calc.text.toPrecision(calc.settings.accuracy).indexOf('e') == -1)?parseFloat( calc.text.toPrecision(calc.settings.accuracy)) + '':calc.text.toPrecision(calc.settings.accuracy);
					//calc.expression = calc.text;
					calc.expression = '';
					calc._executable = false;
					calc._cleartextflag = true;					// clear display on next user input
				}
				else{
					calc.expression = calc.text;
				}
			}
		},
		27:{symbol:'C', keycode: 27, left:'76%', top:'4%', width:'20%', height:'15%', onPress:function(calc){calc._executable = true;calc.expression = '';calc.text='0';}}
	}

	$.fn.calculator.validate = {
		input: function(text){
			return text.match(/^((0|(0\.[0-9]*))|([1-9][0-9]*|([1-9][0-9]*\.[0-9]*)|([1-9][0-9]*\.[0-9]*)|([1-9][0-9]*)))$/);
		},
		expression: function(expr){
			//alert(expr);
			return expr.match(/^\d{1,}(\.\d{1,})?[-+*/]\d{1,}(\.\d{1,})?$/);
		},
		operation: function(expr){
			return expr.match(/[-+/\*]$/);
		}
	}

	/* implementing jQuery UI functions in case no jquery ui found
	----------------------------------------------------------------*/
	if(!$.fn.button){
		$.fn.button = function(){
			return this.each(function(){
				button = $(this);
				button.find('.calc-button').css({borderWidth:1,borderStyle:'solid',borderColor:'#CCCCCC',lineHeight:1.4,fontSize:'1em',cursor:'pointer',fontWeight:'bold'});
			})
		}
	}

	// plugin defaults
	$.fn.calculator.defaults = {
		defaultOpen: true,
		title: 'Calculator',
		accuracy: 12,
		width: '100%',
		height: '100%',
		movable: false,
		resizable: false,
		show: function(calc){
			$.fn.calculator.show(calc);
		},
		hide: function(calc){
			$.fn.calculator.hide(calc);
		},
		buttonPressed: function(calc, button){},
		displayChanged: function(calc, text, expression){}
		//expressionChanged: function(){calc, expression},
		//textChanged: function(){calc, text}
		//animations: false,
	};

})(jQuery);


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.slick.protocol.yahoo;

import java.util.*;

import junit.framework.*;

import org.osgi.framework.*;

/**
 * Yahoo specific testing for a Yahoo Protocol Provider Service implementation.
 * The test suite registers three accounts for
 *
 * @author Damian Minkov
 * @author Valentin Martinet
 */
public class YahooProtocolProviderServiceLick
    extends    TestSuite
    implements BundleActivator
{
    /**
     * The prefix used for property names containing settings for our first
     * testing account.
     */
    public static final String ACCOUNT_1_PREFIX
        = "accounts.yahoo.account1.";

    /**
     * The prefix used for property names containing settings for our second
     * testing account.
     */
    public static final String ACCOUNT_2_PREFIX
        = "accounts.yahoo.account2.";

    /**
     * The prefix used for property names containing settings for our third
     * testing account.
     */
    public static final String ACCOUNT_3_PREFIX
        = "accounts.yahoo.account3.";

    /**
     * The name of the property that indicates whether the user would like to
     * only run the offline tests.
     */
    public static final String DISABLE_ONLINE_TESTS_PROPERTY_NAME
        = "accounts.yahoo.DISABLE_ONLINE_TESTING";

    /**
     * The name of the property the value of which is a formatted string that
     * contains the contact list that.
     */
    public static final String CONTACT_LIST_PROPERTY_NAME
        = "accounts.yahoo.CONTACT_LIST";

    /**
     * Initializes and registers all tests that we'll run as a part of this
     * slick.
     *
     * @param context a currently valid bundle context.
     */
    public void start(BundleContext context)
    {
        setName("YahooProtocolProviderSlick");

        Hashtable<String, String> properties = new Hashtable<String, String>();
        properties.put("service.pid", getName());

        YahooSlickFixture.bc = context;

        // verify whether the user wants to avoid online testing
        String offlineMode = System.getProperty(
            DISABLE_ONLINE_TESTS_PROPERTY_NAME, null);

        if (offlineMode != null && offlineMode.equalsIgnoreCase("true"))
            YahooSlickFixture.onlineTestingDisabled = true;

        addTestSuite(TestAccountInstallation.class);
        addTestSuite(TestProtocolProviderServiceYahooImpl.class);

        addTest(TestOperationSetPresence.suite());

        //the following should only be run when we want online testing.
        if(!YahooSlickFixture.onlineTestingDisabled)
        {
            addTest(TestOperationSetPersistentPresence.suite());

            addTest(TestOperationSetBasicInstantMessaging.suite());

            addTest(TestOperationSetTypingNotifications.suite());

            addTestSuite(TestOperationSetFileTransferImpl.class);

            //addTest(TestOperationSetAdHocMultiUserChatYahooImpl.suite());
        }

        addTest(TestAccountUninstallation.suite());
        addTestSuite(TestAccountUninstallationPersistence.class);

        context.registerService(getClass().getName(), this, properties);
    }

    /**
     * Prepares the slick for shutdown.
     *
     * @param context a currently valid bundle context.
     */
    public void stop(BundleContext context)
    {

    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./queryparser/src/java/org/apache/lucene/queryparser/flexible/standard/builders/AnyQueryNodeBuilder.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder")
#ifdef RESTRICT_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder
#define INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder 0
#else
#define INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder 1
#endif
#undef RESTRICT_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder_) && (INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder || defined(INCLUDE_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder))
#define OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder_

#define RESTRICT_OrgApacheLuceneQueryparserFlexibleStandardBuildersStandardQueryBuilder 1
#define INCLUDE_OrgApacheLuceneQueryparserFlexibleStandardBuildersStandardQueryBuilder 1
#include "org/apache/lucene/queryparser/flexible/standard/builders/StandardQueryBuilder.h"

@class OrgApacheLuceneSearchBooleanQuery;
@protocol OrgApacheLuceneQueryparserFlexibleCoreNodesQueryNode;

/*!
 @brief Builds a BooleanQuery of SHOULD clauses, possibly with
  some minimum number to match.
 */
@interface OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder : NSObject < OrgApacheLuceneQueryparserFlexibleStandardBuildersStandardQueryBuilder >

#pragma mark Public

- (instancetype __nonnull)init;

- (OrgApacheLuceneSearchBooleanQuery *)buildWithOrgApacheLuceneQueryparserFlexibleCoreNodesQueryNode:(id<OrgApacheLuceneQueryparserFlexibleCoreNodesQueryNode>)queryNode;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder)

FOUNDATION_EXPORT void OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder_init(OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder *self);

FOUNDATION_EXPORT OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder *new_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder_init(void) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder *create_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder_init(void);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneQueryparserFlexibleStandardBuildersAnyQueryNodeBuilder")


text:
package vcs.citydb.wfs.kvp.parser;

import vcs.citydb.wfs.exception.KVPParseException;

import java.math.BigInteger;

public class BigIntegerParser extends ValueParser<BigInteger> {

	@Override
	public BigInteger parse(String key, String value) throws KVPParseException {
		try {
			return new BigInteger(value.trim());
		} catch (NumberFormatException e) {
			throw new KVPParseException("The value '" + value + "' is not allowed for the parameter " + key + ".", key);
		}
	}

}


text:
package quanlynhansu.model.entity;

import java.io.Serializable;

import javax.persistence.*;

@Entity
@Table(name = "dantoc")
@NamedQuery(name = "Dantoc.findAll", query = "SELECT d FROM Dantoc d")
public class Dantoc implements Serializable {
	private static final long serialVersionUID = -654521177995353456L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer pk;
	private String tenDanToc;
	@Version
	@Column(name = "VERSION", nullable = false)
	private Integer version = 0;

	public Dantoc() {
	}

	public Integer getPk() {
		return pk;
	}

	public void setPk(Integer pk) {
		this.pk = pk;
	}

	public String getTenDanToc() {
		return tenDanToc;
	}

	public void setTenDanToc(String tenDanToc) {
		this.tenDanToc = tenDanToc;
	}

	public Integer getVersion() {
		return version;
	}

	public void setVersion(Integer version) {
		this.version = version;
	}

}


text:
package com.xeiam.xchange.ripple.service.polling;

import java.io.IOException;
import java.math.BigDecimal;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.currency.Currency;
import com.xeiam.xchange.dto.account.AccountInfo;
import com.xeiam.xchange.exceptions.ExchangeException;
import com.xeiam.xchange.exceptions.NotAvailableFromExchangeException;
import com.xeiam.xchange.exceptions.NotYetImplementedForExchangeException;
import com.xeiam.xchange.ripple.RippleAdapters;
import com.xeiam.xchange.ripple.dto.account.RippleAccountBalances;
import com.xeiam.xchange.service.polling.account.PollingAccountService;

public class RippleAccountService extends RippleAccountServiceRaw implements PollingAccountService {

  public RippleAccountService(final Exchange exchange) {
    super(exchange);
  }

  /**
   * A wallet's currency will be prefixed with the issuing counterparty address for all currencies other than XRP.
   */
  @Override
  public AccountInfo getAccountInfo()
      throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException {
    final RippleAccountBalances account = getRippleAccountBalances();
    final String username = exchange.getExchangeSpecification().getApiKey();
    return RippleAdapters.adaptAccountInfo(account, username);
  }

  @Override
  public String withdrawFunds(Currency currency, BigDecimal amount, String address)
      throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException {
    throw new NotYetImplementedForExchangeException();
  }

  @Override
  public String requestDepositAddress(Currency currency, String... args)
      throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException {
    throw new NotYetImplementedForExchangeException();
  }

}


text:
package de.sydsoft.sg_wolfskrone.appstates;

import com.jme3.animation.LoopMode;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.app.state.ScreenshotAppState;
import com.jme3.bullet.collision.shapes.HeightfieldCollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.terrain.geomipmap.TerrainLodControl;
import com.jme3.terrain.geomipmap.TerrainQuad;
import com.jme3.ui.Picture;
import de.sydsoft.libst.util.Constants;
import de.sydsoft.sg_wolfskrone.gui.GameClient;
import de.sydsoft.sg_wolfskrone.gui.screens.IngameScreen;
import de.sydsoft.sg_wolfskrone.logic.ChatMessage;
import de.sydsoft.sg_wolfskrone.logic.ClientListener;
import de.sydsoft.sg_wolfskrone.logic.ServerAnswerMessage;
import de.sydsoft.sg_wolfskrone.logic.ServerRequestMessage;
import de.sydsoft.sg_wolfskrone.util.AdvancedChaseCamera;
import de.sydsoft.sg_wolfskrone.util.LocHelper;
import org.lwjgl.Sys;

/**
 *
 * @author sythelux
 */
public class IngameState extends ClientMainAppState {

    private AdvancedChaseCamera chaseCam;
    //private Quaternion camRot;
    private BitmapText ch;
    private BitmapText charAttributs;
    private ClientListener clientListener;
    private TerrainQuad terrain;
    //private Geometry viewSphere;
    private Vector3f walkDirection = new Vector3f(0, 0, 0);
    private Vector3f viewDirection = new Vector3f(0, 0, 0);

    @Override
    public void initialize(AppStateManager stateManager, Application app) {
        super.initialize(stateManager, app);
        //add PhysicsAppState
        stateManager.attach(g.getBulletAppState());
        if (Constants.DEBUG) {
            g.getBulletAppState().getPhysicsSpace().enableDebug(g.getAssetManager());
        }
        //add Chatability, apstateDownload
        initNetwork();
        //clamb screenshot ability
        initAppStates();
        //clamb Nifty
        initGui();
        //initPlayer
        initPlayer();
        //initNPCS
        initNPCs();
        //initInputs
        g.getInputHandler().initialize();
        stateManager.attach(this);
        enabled = true;
    }

    private void initNetwork() {
        clientListener = new ClientListener(((IngameScreen) screenController).getChatArea());
        g.getClient().addMessageListener(clientListener, ServerAnswerMessage.class);
    }

    public void initAppStates() {
        ScreenshotAppState state = new ScreenshotAppState();
        g.getStateManager().attach(state);
    }

    public void initGui() {
        g.getClient().addMessageListener(clientListener, ChatMessage.class);

        Picture pic = new Picture("HUD Picture");
        pic.setImage(g.getAssetManager(), "Interface/Textures/GUI-idee1.1280x1024.png", true);
        pic.setWidth(g.getSettings().getWidth());
        pic.setHeight(g.getSettings().getHeight());
        //pic.setPosition(g.getSettings().getWidth() / 4, g.getSettings().getHeight() / 4);
//        g.getGuiNode().attachChild(pic);
        BitmapFont guiFont = g.getAssetManager().loadFont("Interface/Fonts/NimbusSansL.fnt");
        ch = new BitmapText(guiFont, false);
        //ch.setSize(guiFont.getCharSet().getRenderedSize() * 2);
        ch.setText("airtime: 0\r\nHealth: 0");
        ch.setLocalTranslation(0, g.getSettings().getHeight(), 0);
        g.getGuiNode().attachChild(ch);
//        g.getNifty().fromXml("Interface/Nifty/Ingame.xml", "start", ingameScreen);
//        ingameScreen.bind(g.getNifty(), g.getNifty().getScreen("start"));
        charAttributs = new BitmapText(guiFont);
        charAttributs.setLocalTranslation(0, g.getSettings().getHeight() / 2, 0);
        g.getGuiNode().attachChild(charAttributs);
    }

    public void initPlayer() {
        g.getActualCharacter().initialize((GameClient) g, g.getPlayer().getChoosenName());
        g.getClient().send(new ServerRequestMessage(ServerRequestMessage.PLAYERPOSITION, new String[]{g.getPlayer().getChoosenName()}));
        chaseCam = new AdvancedChaseCamera(g.getCamera(), (Node) g.getActualCharacter().getNode(), g.getInputManager());
        chaseCam.setInvertHorizontalAxis(false);
        chaseCam.setInvertVerticalAxis(true);
        chaseCam.setDefaultDistance(3f);
        chaseCam.setMinDistance(3f);
        chaseCam.setMaxDistance(10f);
        StringBuilder sb = new StringBuilder(g.getActualCharacter().getFullyName());
        sb.append(" (").append(g.getActualCharacter().getCharLevel()).append(")\r\n").append(g.getActualCharacter().getAttributs().toString());
        charAttributs.setText(sb);
        terrain = ((TerrainQuad) g.getRootNode().getChild("my terrain"));
        terrain.addControl(new RigidBodyControl(new HeightfieldCollisionShape(terrain.getHeightMap(), terrain.getLocalScale()), 0));
        g.getBulletAppState().getPhysicsSpace().add(terrain);
        clientListener.getPlayerPos().setY(terrain.getHeight(new Vector2f(clientListener.getPlayerPos().x, clientListener.getPlayerPos().z)));
        g.getActualCharacter().getCharacterControl().setPhysicsLocation(clientListener.getPlayerPos().add(0,1,0));
        TerrainLodControl control = new TerrainLodControl(terrain, g.getActualCharacter().getCamNode().getCamera());
        terrain.addControl(control);
    }

    public void initNPCs() {
        //TODO: load NPCs from server
//        NonPlayerCharacter ele = new NonPlayerCharacter();
//        ele.initialize(g, "Elephant");
//        ele.setLocalTranslation(g.getActualCharacter().getPhysicsLocation().add(-50, -20, -20));
//        NonPlayerCharacter pika = new NonPlayerCharacter();
//        pika.initialize(g, "Pikachu");
//        pika.setLocalTranslation(g.getActualCharacter().getPhysicsLocation().add(-50, -20, -20));
    }

    @Override
    public void update(float tpf) {
        super.update(tpf);
        // <editor-fold defaultstate="collapsed" desc="Autoheal example">
        float maxHealth = g.getActualCharacter().getMaxHealth();
        float actHealth = g.getActualCharacter().getActHealth();
        if ((actHealth + 0.01f) > maxHealth) {
            g.getActualCharacter().setActHealth(maxHealth);
        } else {
            g.getActualCharacter().heal(0.01f);//TODO: NOT RIGHT !!!
        }
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="Anti-Lag screen">
        if (tpf >= 0.15f) {
            ((IngameScreen) screenController).startWaitScreen();
        } else if (((IngameScreen) screenController).isWaitscreenactive()) {
            ((IngameScreen) screenController).stopWaitScreen();
        }
        // </editor-fold>
        // <editor-fold defaultstate="collapsed" desc="walking">
        Vector3f camDir = g.getCamera().getDirection().mult(tpf);
        camDir.y = 0;
        Vector3f camLeft = g.getCamera().getLeft().mult(tpf);
        camLeft.y = 0;
        viewDirection.set(camDir);
        walkDirection.set(0, 0, 0);
        if (g.getInputHandler().left) {
            if (!g.getInputHandler().rightC) {
                viewDirection.addLocal(camLeft.mult(tpf));
            } else {
                walkDirection.addLocal(camLeft);
            }
        }
        if (g.getInputHandler().right) {
            if (!g.getInputHandler().rightC) {
                viewDirection.addLocal(camLeft.mult(tpf).negate());
            } else {
                walkDirection.addLocal(camLeft.negate());
            }
        }
        if (g.getInputHandler().ahead || g.getInputHandler().aheadLock) {
            walkDirection.addLocal(camDir);
        }
        if (g.getInputHandler().back) {
            walkDirection.addLocal(camDir.negate());
        }
        // </editor-fold>
        if (g.getInputHandler().jump) {
            g.getActualCharacter().setAnimation("JumpStart", 1f);
            g.getActualCharacter().getCharacterControl().jump();
        }
        if (g.getActualCharacter().getCharacterControl().onGround()) {
            if (g.getActualCharacter().getAirTime() > 3) {
                g.getActualCharacter().hurt(g.getActualCharacter().getAirTime());
            }
            g.getActualCharacter().setAirTime(0);
        } else {
            g.getActualCharacter().addAirTime(tpf);
        }
        if (walkDirection.length() == 0) {
            if (g.getActualCharacter().getAirTime() > .3f) {
                if (!"JumpLoop".equals(g.getActualCharacter().getAnimation())) {
                    g.getActualCharacter().setAnimation("JumpLoop");
                }
            } else if ("JumpLoop".equals(g.getActualCharacter().getAnimation())) {
                g.getActualCharacter().setAnimation("JumpEnd", 1f);
            } else if (!"IdleBase".equals(g.getActualCharacter().getAnimation())) {
                g.getActualCharacter().setAnimation("IdleTop", 1f);
                g.getActualCharacter().setAnimation("IdleBase", 1f);
                g.getActualCharacter().setLoopMode(LoopMode.Loop);
            }
        } else {
            g.getActualCharacter().getCharacterControl().setViewDirection(walkDirection);
            if (g.getActualCharacter().getAirTime() > .3f) {
                if (!"JumpLoop".equals(g.getActualCharacter().getAnimation())) {
                    g.getActualCharacter().setAnimation("JumpLoop");
                }
            } else if ("JumpLoop".equals(g.getActualCharacter().getAnimation())) {
                g.getActualCharacter().setAnimation("JumpEnd", 1f);
            } else if (!"RunBase".equals(g.getActualCharacter().getAnimation())) {
                g.getActualCharacter().setAnimation("RunTop", 1f);
                g.getActualCharacter().setAnimation("RunBase", 1f);
                g.getActualCharacter().setLoopMode(LoopMode.Loop);
            }
        }
        ch.setText("CharPos:" + g.getActualCharacter().getCharacterControl().getPhysicsLocation().toString() + "\r\nTime: " + Sys.getTime() + "\r\ntpf: " + tpf + "\r\nairtime: " + g.getActualCharacter().getAirTime() + "\r\nHealth: " + LocHelper.roundTwoDecimals(g.getActualCharacter().getActHealth()) + "/" + g.getActualCharacter().getMaxHealth());
        //System.out.println(g.getActualCharacter().getWalkDirection().toString()+"|"+g.getActualCharacter().getWalkDirection().length());
        g.getActualCharacter().getCharacterControl().setWalkDirection(walkDirection.normalize().multLocal(0.1f));
        g.getActualCharacter().getCharacterControl().setViewDirection(viewDirection.normalize().multLocal(0.1f));
    }

    @Override
    public void cleanup() {
        //super.cleanup();
    }
}


text:
Tetris with Impact.js
=============

A Tetris game that uses the Impact.js game engine written in JavaScript.

Demo: http://www.ntaso.com/tetris/

Tutorial: http://www.ntaso.com/tutorial-tetris-with-impact-js/

### How to Install

Get the sources, download Impact.js (you need a license), unzip it. You have a folder in there called `impact/lib/impact` that contains the engine's source code.

Copy it and place it in the Tetris source code under `lib/`.
There's a text file showing the right location.

Have fun.


text:
Angular-Learning
================

tests with Angular


text:
//
//  FFCircleScrollPhotoView.h
//  CollectionsOfExample
//
//  Created by mac on 16/7/31.
//  Copyright © 2016年 chenfanfang. All rights reserved.
//

#import <UIKit/UIKit.h>
/**
 *  无限滚动轮播图view
 */
@interface FFCircleScrollPhotoView : UIView

/**
 *  快速实例化一个无限轮播图对象
 *
 *  @param frame         frame
 *  @param imageNames    图片名称数组
 *  @param timerInterval 定时器的多久换一张图
 *
 *  @return 实例化的无限轮播图对象
 */
+ (instancetype)circleScrollPhotoViewWithFrame:(CGRect)frame imageNames:(NSArray *)imageNames timerInterval:(CGFloat)timerInterval;

@end


text:
using Ds3.Helpers.Strategies.ChunkStrategies;
using Ds3.Helpers.Strategies.StreamFactory;

namespace Ds3.Helpers.Strategies
{
    /// <summary>
    /// The WriteStreamHelperStrategy bundle WriteStreamChunkStrategy with WriteStreamStreamFactory
    /// </summary>
    public class WriteStreamHelperStrategy : IHelperStrategy<string>
    {
        private readonly IChunkStrategy _writeStreamChunkStrategy;
        private readonly IStreamFactory<string> _writeStreamStreamFactory;

        public WriteStreamHelperStrategy(int retryAfter = -1)
        {
            this._writeStreamChunkStrategy = new WriteStreamChunkStrategy(retryAfter);
            this._writeStreamStreamFactory = new WriteStreamStreamFactory();
        }

        public IChunkStrategy GetChunkStrategy()
        {
            return this._writeStreamChunkStrategy;
        }

        public IStreamFactory<string> GetStreamFactory()
        {
            return this._writeStreamStreamFactory;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="15dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/number_of_questions_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

    <TextView
        android:id="@+id/continue_to_section_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/continue_to_section"
        android:textStyle="italic"/>

    <TextView
        android:id="@+id/auto_fill_section_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/auto_fill_section"
        android:textStyle="italic"/>

    <TextView
        android:id="@+id/section_navigation_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/section_navigation"
        android:textStyle="italic"/>

    <RadioGroup
        android:id="@+id/default_responses_radio_group"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

    </RadioGroup>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/section_cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@color/red"
            android:gravity="center"
            android:text="@string/cancel"
            android:textColor="@color/white" />

        <Button
            android:id="@+id/section_proceed"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@color/green"
            android:gravity="center"
            android:text="@string/proceed"
            android:textColor="@color/white" />

    </LinearLayout>

</LinearLayout>


text:
from ctypes import *
from ctypes import util

from rubicon.objc import *

######################################################################

# QUARTZ / COREGRAPHICS

quartz = cdll.LoadLibrary(util.find_library('quartz'))

CGDirectDisplayID = c_uint32  # CGDirectDisplay.h
CGError = c_int32  # CGError.h
CGBitmapInfo = c_uint32  # CGImage.h

# /System/Library/Frameworks/ApplicationServices.framework/Frameworks/...
#     ImageIO.framework/Headers/CGImageProperties.h
kCGImagePropertyGIFDictionary = c_void_p.in_dll(quartz, 'kCGImagePropertyGIFDictionary')
kCGImagePropertyGIFDelayTime = c_void_p.in_dll(quartz, 'kCGImagePropertyGIFDelayTime')

# /System/Library/Frameworks/ApplicationServices.framework/Frameworks/...
#     CoreGraphics.framework/Headers/CGColorSpace.h
kCGRenderingIntentDefault = 0

quartz.CGDisplayIDToOpenGLDisplayMask.restype = c_uint32
quartz.CGDisplayIDToOpenGLDisplayMask.argtypes = [c_uint32]

quartz.CGMainDisplayID.restype = CGDirectDisplayID
quartz.CGMainDisplayID.argtypes = []

quartz.CGShieldingWindowLevel.restype = c_int32
quartz.CGShieldingWindowLevel.argtypes = []

quartz.CGCursorIsVisible.restype = c_bool

quartz.CGDisplayCopyAllDisplayModes.restype = c_void_p
quartz.CGDisplayCopyAllDisplayModes.argtypes = [CGDirectDisplayID, c_void_p]

quartz.CGDisplaySetDisplayMode.restype = CGError
quartz.CGDisplaySetDisplayMode.argtypes = [CGDirectDisplayID, c_void_p, c_void_p]

quartz.CGDisplayCapture.restype = CGError
quartz.CGDisplayCapture.argtypes = [CGDirectDisplayID]

quartz.CGDisplayRelease.restype = CGError
quartz.CGDisplayRelease.argtypes = [CGDirectDisplayID]

quartz.CGDisplayCopyDisplayMode.restype = c_void_p
quartz.CGDisplayCopyDisplayMode.argtypes = [CGDirectDisplayID]

quartz.CGDisplayModeGetRefreshRate.restype = c_double
quartz.CGDisplayModeGetRefreshRate.argtypes = [c_void_p]

quartz.CGDisplayModeRetain.restype = c_void_p
quartz.CGDisplayModeRetain.argtypes = [c_void_p]

quartz.CGDisplayModeRelease.restype = None
quartz.CGDisplayModeRelease.argtypes = [c_void_p]

quartz.CGDisplayModeGetWidth.restype = c_size_t
quartz.CGDisplayModeGetWidth.argtypes = [c_void_p]

quartz.CGDisplayModeGetHeight.restype = c_size_t
quartz.CGDisplayModeGetHeight.argtypes = [c_void_p]

quartz.CGDisplayModeCopyPixelEncoding.restype = c_void_p
quartz.CGDisplayModeCopyPixelEncoding.argtypes = [c_void_p]

quartz.CGGetActiveDisplayList.restype = CGError
quartz.CGGetActiveDisplayList.argtypes = [c_uint32, POINTER(CGDirectDisplayID), POINTER(c_uint32)]

quartz.CGDisplayBounds.restype = CGRect
quartz.CGDisplayBounds.argtypes = [CGDirectDisplayID]

quartz.CGImageSourceCreateWithData.restype = c_void_p
quartz.CGImageSourceCreateWithData.argtypes = [c_void_p, c_void_p]

quartz.CGImageSourceCreateImageAtIndex.restype = c_void_p
quartz.CGImageSourceCreateImageAtIndex.argtypes = [c_void_p, c_size_t, c_void_p]

quartz.CGImageSourceCopyPropertiesAtIndex.restype = c_void_p
quartz.CGImageSourceCopyPropertiesAtIndex.argtypes = [c_void_p, c_size_t, c_void_p]

quartz.CGImageGetDataProvider.restype = c_void_p
quartz.CGImageGetDataProvider.argtypes = [c_void_p]

quartz.CGDataProviderCopyData.restype = c_void_p
quartz.CGDataProviderCopyData.argtypes = [c_void_p]

quartz.CGDataProviderCreateWithCFData.restype = c_void_p
quartz.CGDataProviderCreateWithCFData.argtypes = [c_void_p]

quartz.CGImageCreate.restype = c_void_p
quartz.CGImageCreate.argtypes = [c_size_t, c_size_t, c_size_t, c_size_t, c_size_t, c_void_p, c_uint32, c_void_p, c_void_p, c_bool, c_int]

quartz.CGImageRelease.restype = None
quartz.CGImageRelease.argtypes = [c_void_p]

quartz.CGImageGetBytesPerRow.restype = c_size_t
quartz.CGImageGetBytesPerRow.argtypes = [c_void_p]

quartz.CGImageGetWidth.restype = c_size_t
quartz.CGImageGetWidth.argtypes = [c_void_p]

quartz.CGImageGetHeight.restype = c_size_t
quartz.CGImageGetHeight.argtypes = [c_void_p]

quartz.CGImageGetBitsPerPixel.restype = c_size_t
quartz.CGImageGetBitsPerPixel.argtypes = [c_void_p]

quartz.CGImageGetBitmapInfo.restype = CGBitmapInfo
quartz.CGImageGetBitmapInfo.argtypes = [c_void_p]

quartz.CGColorSpaceCreateDeviceRGB.restype = c_void_p
quartz.CGColorSpaceCreateDeviceRGB.argtypes = []

quartz.CGDataProviderRelease.restype = None
quartz.CGDataProviderRelease.argtypes = [c_void_p]

quartz.CGColorSpaceRelease.restype = None
quartz.CGColorSpaceRelease.argtypes = [c_void_p]

quartz.CGWarpMouseCursorPosition.restype = CGError
quartz.CGWarpMouseCursorPosition.argtypes = [CGPoint]

quartz.CGDisplayMoveCursorToPoint.restype = CGError
quartz.CGDisplayMoveCursorToPoint.argtypes = [CGDirectDisplayID, CGPoint]

quartz.CGAssociateMouseAndMouseCursorPosition.restype = CGError
quartz.CGAssociateMouseAndMouseCursorPosition.argtypes = [c_bool]

quartz.CGBitmapContextCreate.restype = c_void_p
quartz.CGBitmapContextCreate.argtypes = [c_void_p, c_size_t, c_size_t, c_size_t, c_size_t, c_void_p, CGBitmapInfo]

quartz.CGBitmapContextCreateImage.restype = c_void_p
quartz.CGBitmapContextCreateImage.argtypes = [c_void_p]

quartz.CGFontCreateWithDataProvider.restype = c_void_p
quartz.CGFontCreateWithDataProvider.argtypes = [c_void_p]

quartz.CGFontCreateWithFontName.restype = c_void_p
quartz.CGFontCreateWithFontName.argtypes = [c_void_p]

quartz.CGContextDrawImage.restype = None
quartz.CGContextDrawImage.argtypes = [c_void_p, CGRect, c_void_p]

quartz.CGContextRelease.restype = None
quartz.CGContextRelease.argtypes = [c_void_p]

quartz.CGContextSetTextPosition.restype = None
quartz.CGContextSetTextPosition.argtypes = [c_void_p, CGFloat, CGFloat]

quartz.CGContextSetShouldAntialias.restype = None
quartz.CGContextSetShouldAntialias.argtypes = [c_void_p, c_bool]


text:
//
//  Created by Jesse Squires
//  http://www.hexedbits.com
//
//
//  Documentation
//  http://cocoadocs.org/docsets/JSMessagesViewController
//
//
//  The MIT License
//  Copyright (c) 2013 Jesse Squires
//  http://opensource.org/licenses/MIT
//

#import <UIKit/UIKit.h>
#import "JSMessageTextView.h"

/**
 *  The appearance style of the input bar view for composing a new message.
 */
typedef NS_ENUM(NSUInteger, JSMessageInputViewStyle) {
    /**
     *  An input view style that has the appearance as seen in iOS 6 and before.
     */
    JSMessageInputViewStyleClassic,
    /**
     *  An input view style that has the appearance as seen in iOS 7 and later.
     */
    JSMessageInputViewStyleFlat
};

/**
 *  An instance of `JSMessageInputView` defines the input toolbar for composing a new message that is to be displayed above the keyboard.
 */
@interface JSMessageInputView : UIImageView

/**
 *  Returns the style appearance for the input view.
 *  @see JSMessageInputViewStyle.
 */
@property (assign, nonatomic, readonly) JSMessageInputViewStyle style;

/**
 *  Returns the textView into which a new message is composed. This property is never `nil`.
 */
@property (weak, nonatomic, readonly) JSMessageTextView *textView;

/**
 *  The send button for the input view. The default value is an initialized `UIButton` whose appearance is styled according to the value of style during initialization.
 *  @see JSMessageInputViewStyle.
 */
@property (weak, nonatomic) UIButton *sendButton;

#pragma mark - Initialization

/**
 *  Initializes and returns an input view having the given frame, style, delegate, and panGestureRecognizer.
 *
 *  @param frame                A rectangle specifying the initial location and size of the bubble view in its superview's coordinates.
 *  @param style                The style of the input view. @see JSMessageInputViewStyle.
 *  @param delegate             An object that conforms to the `UITextViewDelegate` protocol and `JSDismissiveTextViewDelegate` protocol.
 *  @see JSDismissiveTextViewDelegate.
 *  @param panGestureRecognizer A `UIPanGestureRecognizer` used to dismiss the input view by dragging down.
 *
 *  @return An initialized `JSMessageInputView` object or `nil` if the object could not be successfully initialized.
 */
- (instancetype)initWithFrame:(CGRect)frame
                        style:(JSMessageInputViewStyle)style
                     delegate:(id<UITextViewDelegate, JSDismissiveTextViewDelegate>)delegate
         panGestureRecognizer:(UIPanGestureRecognizer *)panGestureRecognizer;

#pragma mark - Message input view

/**
 *  Adjusts the input view's frame height by the given value.
 *
 *  @param changeInHeight The delta value by which to increase or decrease the existing height for the input view.
 */
- (void)adjustTextViewHeightBy:(CGFloat)changeInHeight;

/**
 *  @return A constant indicating the height of one line of text in the input view.
 */
+ (CGFloat)textViewLineHeight;

/**
 *  @return A contant indicating the maximum number of lines of text that can be displayed in the textView.
 */
+ (CGFloat)maxLines;

/**
 *  @return The maximum height of the input view as determined by `maxLines` and `textViewLineHeight`. This value is used for controlling the animation of the growing and shrinking of the input view as the text changes in the textView.
 */
+ (CGFloat)maxHeight;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/LinearLayout.allmember_header"
    android:orientation="horizontal" >

    <RelativeLayout
        android:id="@+id/acty_head_btn_back"
        style="@style/RelativeLayout.allmember_header_btn"
        android:clickable="true" >

        <ImageView
            android:id="@+id/acty_head_iv_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@drawable/ic_acty_head_back_big" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/acty_head_iv_hr"
        android:layout_width="2px"
        android:layout_height="match_parent"
        android:background="@drawable/ic_acty_head_hr" />

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="4" >

        <TextView
            android:id="@+id/acty_head_tv_title"
            style="@style/navigtion_head_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="创建" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/acty_head_iv_hr2"
        android:layout_width="2px"
        android:layout_height="match_parent"
        android:background="@drawable/ic_acty_head_hr" />

    <RelativeLayout
        android:id="@+id/acty_head_btn_create"
        style="@style/RelativeLayout.allmember_header_btn"
        android:clickable="true" >

        <TextView
            style="@style/TextView.navigtion_head_base"
            android:layout_centerInParent="true"
            android:text="确定"/>
    </RelativeLayout>

</LinearLayout>


text:
package org.elkoserver.server.context;

import org.elkoserver.foundation.actor.BasicProtocolHandler;
import org.elkoserver.foundation.json.Deliverer;
import org.elkoserver.foundation.json.JSONMethod;
import org.elkoserver.foundation.json.MessageHandlerException;
import org.elkoserver.foundation.json.OptBoolean;
import org.elkoserver.foundation.json.OptString;
import org.elkoserver.foundation.server.Server;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.json.JSONLiteralArray;
import org.elkoserver.json.JSONObject;
import org.elkoserver.util.trace.Trace;
import org.elkoserver.util.trace.TraceController;

/**
 * Singleton administrative object for entering and exiting contexts.
 *
 * <p>Unlike most objects, JSON messages may be sent to this object when the
 * user is in either the entered or exited state.  The behavior is somewhat
 * different in the two cases.  For example, when a user has not yet entered a
 * context, they can enter but not exit, and vice versa.  These states are
 * distinguished by whether the message seems to be arriving from a UserActor
 * (the pre-entry state) or from a User (the post-entry state).
 */
class Session extends BasicProtocolHandler {
    /** The contextor for this session. */
    private Contextor myContextor;

    /** Server object. */
    Server myServer;

    /** Trace object for handling the 'log' verb. */
    private Trace myLogger;

    /**
     * Construct.
     *
     * @param contextor  The contextor for this session.
     */
    Session(Contextor contextor, Server server) {
        myContextor = contextor;
        myLogger = Trace.trace("clientlogger");
        TraceController.setProperty("trace_clientlogger", "EVENT");
        myServer = server;
    }

    /**
     * Get this object's reference string.  This singleton object is always
     * known as 'session'.
     *
     * @return a string referencing this object.
     */
    public String ref() {
        return "session";
    }

    /**
     * Handle the 'log' verb.
     *
     * Write the text given to the log.
     *
     * @param text  The text to log.
     */
    @JSONMethod({ "text" })
    public void log(User from, String text) {
        myLogger.eventi(text);
    }

    /**
     * Handle the 'dump' verb
     *
     * Return various blobs of information about the state of this context
     * server.
     *
     * @param what  Indicator of which type of information is desired
     * @param context  Optional context parameter, when relevant
     * @param password  Password to verify that sender is allowed to do this
     */
    @JSONMethod({ "what", "password", "context" })
    public void dump(Deliverer from, String what, OptString testPassword,
                     OptString optContext) {
        String password =
           myServer.props().getProperty("conf.context.shutdownpassword", null);
        String contextRef = optContext.value(null);
        if (password == null || password.equals(testPassword.value(null))) {
            JSONLiteral reply = new JSONLiteral("session", "dump");
            reply.addParameter("what", what);
            if (what.equals("contexts")) {
                JSONLiteralArray list = new JSONLiteralArray();
                for (Context ctx : myContextor.contexts()) {
                    list.addElement(ctx.ref());
                }
                list.finish();
                reply.addParameter("contexts", list);
            } else if (what.equals("users")) {
                JSONLiteralArray list = new JSONLiteralArray();
                for (User user : myContextor.users()) {
                    if (contextRef == null ||
                            user.context().ref().equals(contextRef)) {
                        list.addElement(user.ref());
                    }
                }
                list.finish();
                reply.addParameter("users", list);
            } else if (what.equals("items")) {
                // dump items in 'context' or all items
            } else {
                reply.addParameter("error", "unknown 'what' value: " + what);
            }
            reply.finish();
            from.send(reply);
        }
    }

    /**
     * Handle the 'entercontext' verb.
     *
     * Enter the user who sent it into the context they asked for.
     *
     * @param user  The ID of the user who is entering.
     * @param name  The alleged name of the user who is entering.
     * @param context  Reference to the context they wish to enter.
     * @param contextTemplate  Optional reference to the template context from
     *    which the context should be derived.
     * @param sess  Client session ID for the connection to the context.
     * @param auth  Authorization code for a reserved entry.
     * @param utag  Factory tag string for synthetic user
     * @param uparam  Arbitrary object parameterizing synthetic user
     * @param debug This session will use debug settings, if enabled.
     * @param scope  Application scope for filtering mods
     */
    @JSONMethod({ "user", "name", "context", "ctmpl", "sess", "auth", "utag",
                  "?uparam", "debug", "scope" })
    public void entercontext(Deliverer from, OptString user, OptString name,
                             String context, OptString contextTemplate,
                             OptString sess, OptString auth, OptString utag,
                             JSONObject uparam, OptBoolean debug,
                             OptString scope)
        throws MessageHandlerException
    {
        if (from instanceof User) {
            throw new MessageHandlerException("already in a context");
        } else /* if (from instanceof UserActor) */ {
            UserActor fromActor = (UserActor) from;
            fromActor.enterContext(user.value(null), name.value(null), context,
                                   contextTemplate.value(null),
                                   sess.value(null), auth.value(null),
                                   utag.value(null), uparam,
                                   debug.value(false), scope.value(null));
        }
    }

    /**
     * Handle the 'exit' verb.
     *
     * Exit the context and disconnect the user who sent it -- except that the
     * user isn't in any context, so there's nothing to do.
     */
    @JSONMethod
    public void exit(Deliverer from) throws MessageHandlerException {
        throw new MessageHandlerException("not in a context");
    }

    /**
     * Handle the 'shutdown' verb.
     *
     * Shutdown the server.
     *
     * @param password  Password to verify that sender is allowed to do this.
     * @param kill  If true, shutdown immediately instead of cleaning up.
     */
    @JSONMethod({ "password", "kill" })
    public void shutdown(Deliverer from, OptString testPassword,
                         OptBoolean kill)
        throws MessageHandlerException
    {
        User fromUser = null;
        if (from instanceof User) {
            fromUser = (User) from;
        }
        String password =
            myServer.props().getProperty("conf.context.shutdownpassword", null);
        if (password == null || password.equals(testPassword.value(null))) {
            myContextor.shutdownServer(kill.value(false));
            if (fromUser != null) {
                fromUser.exitContext("server shutting down", "shutdown",
                                     false);
            } else {
                from.send(Msg.msgExit(this, "server shutting down", "shutdown",
                                      false));
                ((UserActor) from).close();
            }
        } else {
            if (fromUser != null) {
                fromUser.exitContext(null, null, false);
            } else {
                ((UserActor) from).close();
            }
        }
    }
}


text:
<?php
namespace sideshow_bob\throttle;

use sideshow_bob\throttle\Storage\ArrayStorage;

/**
 * Class ThrottleTest
 */
class ThrottleTest extends \PHPUnit_Framework_TestCase
{
    const IDENTIFIER = "identifier";
    const BAN = 10;
    const LOG = 20;
    const TIME_SPAN = 10;

    /**
     * @var Throttle
     */
    private $throttle;

    /**
     * @inheritdoc
     */
    public function setUp()
    {
        $this->throttle = new Throttle(
            new ArrayStorage(),
            [
                "ban" => static::BAN,
                "log" => static::LOG,
                "timespan" => static::TIME_SPAN,
            ]
        );
    }

    public function testSuccessfulValidate()
    {
        $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
    }

    public function testBan()
    {
        for ($i = 0; $i < static::BAN; $i++) {
            $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
        }
        $this->assertFalse($this->throttle->validate(static::IDENTIFIER));
    }

    public function testLog()
    {
        for ($i = 0; $i < static::BAN; $i++) {
            $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
        }
        for ($i = static::BAN; $i < static::LOG - 1; $i++) {
            $this->assertFalse($this->throttle->validate(static::IDENTIFIER));
        }
        $this->assertFalse($this->throttle->validate(static::IDENTIFIER));
    }

    public function testBanExpiration()
    {
        for ($i = 0; $i < static::BAN; $i++) {
            $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
        }
        $this->assertFalse($this->throttle->validate(static::IDENTIFIER));
        sleep(10);
        $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
    }

    public function testReset()
    {
        for ($i = 0; $i < static::BAN; $i++) {
            $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
        }
        $this->assertFalse($this->throttle->validate(static::IDENTIFIER));
        $this->throttle->reset(static::IDENTIFIER);
        $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
    }

    public function testRemaining()
    {
        $this->assertTrue($this->throttle->validate(static::IDENTIFIER));
        $this->assertEquals(static::BAN - 1, $this->throttle->remaining(static::IDENTIFIER));
    }
}


text:
package org.ocpsoft.rewrite.servlet.impl;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.junit.Test;
import org.ocpsoft.rewrite.servlet.DispatcherType;
import org.ocpsoft.rewrite.servlet.spi.DispatcherTypeProvider;

public class Servlet25DispatcherTypeProviderTest
{

   @Test
   public void testShouldReturnRequestDispatcherTypeForNoAttributes()
   {

      // GIVEN a request without any attributes set
      HttpServletRequest request = mock(HttpServletRequest.class);

      // WHEN the provider is asked for the DispatcherType
      DispatcherTypeProvider provider = new Servlet25DispatcherTypeProvider();
      DispatcherType dispatcherType = provider.getDispatcherType(request, mock(ServletContext.class));

      // THEN it should return REQUEST
      assertEquals(DispatcherType.REQUEST, dispatcherType);

   }

   @Test
   public void testShouldReturnIncludeDispatcherTypeWithCorrectAttributeSet()
   {

      // GIVEN a request with the INCLUDE attribute set
      HttpServletRequest request = mock(HttpServletRequest.class);
      when(request.getAttribute("javax.servlet.include.request_uri")).thenReturn("/some/url");

      // WHEN the provider is asked for the DispatcherType
      DispatcherTypeProvider provider = new Servlet25DispatcherTypeProvider();
      DispatcherType dispatcherType = provider.getDispatcherType(request, mock(ServletContext.class));

      // THEN it should return INCLUDE
      assertEquals(DispatcherType.INCLUDE, dispatcherType);

   }

   @Test
   public void testShouldReturnForwardDispatcherTypeWithCorrectAttributeSet()
   {

      // GIVEN a request with the FORWARD attribute set
      HttpServletRequest request = mock(HttpServletRequest.class);
      when(request.getAttribute("javax.servlet.forward.request_uri")).thenReturn("/some/url");

      // WHEN the provider is asked for the DispatcherType
      DispatcherTypeProvider provider = new Servlet25DispatcherTypeProvider();
      DispatcherType dispatcherType = provider.getDispatcherType(request, mock(ServletContext.class));

      // THEN it should return INCLUDE
      assertEquals(DispatcherType.FORWARD, dispatcherType);

   }

}


text:
import {
    Component, Input, Output, EventEmitter, ContentChildren, QueryList, forwardRef,
    ViewEncapsulation, ChangeDetectionStrategy, ChangeDetectorRef, ViewChildren, OnInit
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

import { InputBoxComponent } from './box';
import { uuid as getUUID } from '../util/uuid';
import { OnChange } from '../core/decorators';

/** box group value type */
export interface BoxGroupValue {
    /** current changed box value */
    currentValue: any;

    /** all box group value, usually an array */
    value: any[];
}

/** box group item type */
export interface BoxGroupItem {
    value: string | number;
    text: string;
    checked?: boolean;
    disabled?: boolean;
    [key: string]: any;
}

/*
 * Provider Expression that allows component to register as a ControlValueAccessor.
 * This allows it to support [(ngModel)].
 * @docs-private
 */
const BOXGROUP_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => BoxGroupComponent),
    multi: true
};

/**
 * Box Group Component
 */
@Component({
    selector: 'nb-boxgroup',
    templateUrl: './box-group.html',
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush,
    preserveWhitespaces: false,
    providers: [BOXGROUP_VALUE_ACCESSOR],
    host: {
        'class': 'nb-widget nb-boxgroup',
        '[class.nb-boxgroup-disabled]': 'disabled'
    },
    exportAs: 'nbBoxGroup'
})
export class BoxGroupComponent implements ControlValueAccessor, OnInit {

    /**
     * when box group value change, emit a change event with the `BoxGroupValue`, which contains
     * the `currentValue` and `value` property
     */
    @Output() change: EventEmitter<BoxGroupValue> = new EventEmitter<BoxGroupValue>();

    /**
     * box group type, either 'checkbox' or 'radio'
     * @default checkbox
     */
    @OnChange()
    @Input() type: 'radio' | 'checkbox' = 'checkbox';

    /**
     * Whether the box group is disabled
     * @default false
     */
    @OnChange(true)
    @Input() disabled: boolean = false;

    /**
     * box group datasource, when datasource exists, the inner boxes will be overwrited
     */
    @Input() datasource: BoxGroupItem[];

    /**
     * @docs-private
     */
    disabledChange: EventEmitter<boolean> = new EventEmitter<boolean>();

    /**
     * the value associated with the box group
     */
    @OnChange()
    @Input() value: any;

    /**
     * the unique name of the box group
     * @docs-private
     */
    @OnChange()
    @Input() uuid: string = getUUID();

    /** children box components */
    @ContentChildren(
        forwardRef(() => InputBoxComponent)
    ) _contentBoxList: QueryList<InputBoxComponent>;

    /**
     * button toggle view children
     */
    @ViewChildren(
        forwardRef(() => InputBoxComponent)
    ) _viewBoxList: QueryList<InputBoxComponent>;

    constructor(private _cd: ChangeDetectorRef) {

        // listen to disabled property, and update sub child disabled state
        this.disabledChange.subscribe(disabled => {
            const boxList = this._getBoxList();
            if (boxList) {
                boxList.forEach(box => {
                    box.disabled = disabled;
                });
            }
        });
    }

    ngOnInit() {

    }

    /**
     * select some value, according to the type, change sub box component behavior
     *
     * @param {any} value - box value
     * @docs-private
     */
    select(value: any) {
        const boxList = this._getBoxList();
        if (!boxList) {
            return;
        }

        if (this.type === 'radio') {
            boxList.forEach(item => {
                item.checked = (item.value + '') === (value + '');
            });
            this.value = [value];
            this.change.emit({
                currentValue: value,
                value: this.value
            });
        }
        else if (this.type === 'checkbox') {
            const box = boxList.find(v => (v.value + '') === (value + ''));

            // de-duplicate value items
            const valueSet = new Set(this.value);
            if (box) {
                box.checked = !box.checked;
                box.checked ? valueSet.add(value) : valueSet.delete(value);
                this.value = Array.from(valueSet);
                this.change.emit({
                    currentValue: value,
                    value: this.value
                });
            }
        }

        this._cd.markForCheck();
        this._updateFormModel();
    }

    /**
     * The method to be called in order to update ngModel.
     * Now `ngModel` binding is not supported in multiple selection mode.
     */
    private _onModelChange: Function;

    /**
     * Registers a callback that will be triggered when the value has changed.
     * Implemented as part of ControlValueAccessor.
     * @param fn On change callback function.
     */
    registerOnChange(fn: Function) {
        this._onModelChange = fn;
    }

    /** onTouch function registered via registerOnTouch (ControlValueAccessor). */
    private _onTouch: Function;

    /**
     * Registers a callback that will be triggered when the control has been touched.
     * Implemented as part of ControlValueAccessor.
     * @param fn On touch callback function.
     */
    registerOnTouched(fn: Function) {
        this._onTouch = fn;
    }

    /**
     * Sets the model value. Implemented as part of ControlValueAccessor.
     * @param value Value to be set to the model. It must be an array.
     */
    writeValue(value: (string | number)[]) {
        if (value && !Array.isArray(value)) {
            throw new Error('使用表单赋值时,box-group 的值必须传入数组形式,即使单选框也一样');
        }

        if (value) {
            this.value = value;

            // when init, set children toggle button state
            this._forceUpdateValue(value);
        }
    }

    /**
     * force update box group value
     *
     * @param {any[]} value
     * @returns
     */
    _forceUpdateValue(value: (string | number)[]) {
        const boxList = this._getBoxList();
        if (!boxList) {
            return;
        }

        if (this.type === 'radio') {
            boxList.forEach(item => {
                item.checked = (item.value + '') === (value + '');
            });
        }
        else if (this.type === 'checkbox') {
            value = value.map(v => v + '');
            boxList.forEach(v => v.checked = value.includes(v.value + ''));
        }

        // emit change value
        // checkbox's current value is the last value in the array, and radiobox's current value is
        // the value
        const currentValue = Array.isArray(value) && value.length ? value[value.length - 1] : '';
        this.change.emit({
            currentValue,
            value: this.value
        });

        this._cd.markForCheck();
    }

    /**
     * Toggles the disabled state of the component. Implemented as part of ControlValueAccessor.
     * @param isDisabled Whether the component should be disabled.
     */
    setDisabledState(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }

    /**
     * update form model value and mark for check
     */
    _updateFormModel() {
        if (this._onModelChange) {
            this._onModelChange(this.value);
        }

        if (this._onTouch) {
            this._onTouch(this.value);
        }
    }

    _getBoxList() {
        const hasDatasource = this.datasource && this.datasource.length;
        return hasDatasource ? this._viewBoxList : this._contentBoxList;
    }

    /**
     * reset box group value
     */
    reset() {
        this._getBoxList().forEach(box => {
            box.checked = false;
        });
        this.value = [];
    }
}


text:
<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" />
        <meta name = "author" content = "colourBEER" >
        <title>Heisenberg engine test only</title>
    </head>
    <body>

    </body>
    <script type="text/javascript" src = "HUtils.js"></script>
    <script type="text/javascript" src = "HDebug.js"></script>
    <script type="text/javascript" src = "HCore.js"></script>
    <script type="text/javascript" src = "HAnimation.js"></script>
    <script type="text/javascript" src = "HVideo.js"></script>
    <script type="text/javascript" src = "HActor.js"></script>

    <script type="text/javascript">

    </script>

    <script type="text/javascript" src = "HTest.js"></script>

</html>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Early Tertiary Spores and Pollen Grains from the Costal Region of Bohai (Beijing) 33 + pl. 1, fig. 18 (1978)

#### Original name
Dicellaesporites major P. Ke & Z.Y. Shi

### Remarks
null


text:
package parser

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"
)

func normalizePath(path string) string {
	// use lower case, as Windows file systems will almost always be case insensitive
	return strings.ToLower(strings.Replace(path, "\\", "/", -1))
}

func getPkgPath(fname string, isDir bool) (string, error) {
	// path.IsAbs doesn't work properly on Windows; use filepath.IsAbs instead
	if !filepath.IsAbs(fname) {
		pwd, err := os.Getwd()
		if err != nil {
			return "", err
		}
		fname = path.Join(pwd, fname)
	}

	fname = normalizePath(fname)

	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		var err error
		gopath, err = getDefaultGoPath()
		if err != nil {
			return "", fmt.Errorf("cannot determine GOPATH: %s", err)
		}
	}

	for _, p := range strings.Split(os.Getenv("GOPATH"), ";") {
		prefix := path.Join(normalizePath(p), "src") + "/"
		if rel := strings.TrimPrefix(fname, prefix); rel != fname {
			if !isDir {
				return path.Dir(rel), nil
			} else {
				return path.Clean(rel), nil
			}
		}
	}

	return "", fmt.Errorf("file '%v' is not in GOPATH", fname)
}


text:
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tab;

import static com.google.common.truth.Truth.assertThat;

import android.content.Context;
import android.content.res.Configuration;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;

import org.chromium.base.ContextUtils;
import org.chromium.base.test.BaseRobolectricTestRunner;

/**
 * Tests for {@link TabUtils}.
 */
@RunWith(BaseRobolectricTestRunner.class)
public final class TabUtilsUnitTest {
    @Test
    public void testGetTabThumbnailAspectRatio_withNullContext() {
        assertThat(TabUtils.getTabThumbnailAspectRatio(null))
                .isEqualTo(TabUtils.TAB_THUMBNAIL_ASPECT_RATIO);
    }

    @Test
    @Config(qualifiers = "sw320dp")
    public void testGetTabThumbnailAspectRatio_withNonTabletContext() {
        assertThat(TabUtils.getTabThumbnailAspectRatio(ContextUtils.getApplicationContext()))
                .isEqualTo(TabUtils.TAB_THUMBNAIL_ASPECT_RATIO);
    }

    @Test
    @Config(qualifiers = "sw800dp-port")
    public void testGetTabThumbnailAspectRatio_withTabletPortraitContext() {
        assertThat(TabUtils.getTabThumbnailAspectRatio(ContextUtils.getApplicationContext()))
                .isEqualTo(TabUtils.TAB_THUMBNAIL_ASPECT_RATIO);
    }

    @Test
    @Config(qualifiers = "sw800dp-land")
    public void testGetTabThumbnailAspectRatio_withTabletLandscapeContext() {
        final Context applicationContext = ContextUtils.getApplicationContext();
        final Configuration configuration = applicationContext.getResources().getConfiguration();
        float expectedAspectRatio =
                (configuration.screenWidthDp * 1f) / (configuration.screenHeightDp * 1f);
        assertThat(TabUtils.getTabThumbnailAspectRatio(applicationContext))
                .isEqualTo(expectedAspectRatio);
    }
}


text:
#ifndef __MCP_CONFIG_H
#define __MCP_CONFIG_H

#include "mcp_hal_types.h"
#include "mcp_hal_config.h"

/*
*   Indicates that a feature is enabled
*/
#define MCP_CONFIG_ENABLED                                          (MCP_HAL_CONFIG_ENABLED)

/*
*   Indicates that a feature is disabled
*/
#define MCP_CONFIG_DISABLED                                         (MCP_HAL_CONFIG_DISABLED)

/*-------------------------------------------------------------------------------
 * MCP_CONFIG_USE_STATIC_KEYWORD
 *
 *  Determines how program symbols using the MCP_STATIC will be declared.
 *
 * Values:
 *  MCP_CONFIG_ENABLED: The symbols will be declared as static (using the c 'static' keyword)
 *  MCP_CONFIG_DISABLED: The symbols will have global scope
*/
#define     MCP_CONFIG_USE_STATIC_KEYWORD                               (MCP_CONFIG_ENABLED)

#define MCP_CONFIG_BT_HCI_IF_MAX_NUM_OF_REGISTERED_CLIENTS      ((McpUint)2)

/*-------------------------------------------------------------------------------
 * MCP config parser Module
 *
 *     Represents configuration parameters for MCP config parser -
 *          affects the amount of memory reserved for configuration
 */
#define     MCP_CONFIG_PASRER_MAX_SECTION_LEN                   15
#define     MCP_CONFIG_PASRER_MAX_KEY_NAME_LEN                  40
#define     MCP_CONFIG_PASRER_MAX_KEY_VALUE_LEN                 35
#define     MCP_CONFIG_PARSER_SECTION_NUMBER                    7
#define     MCP_CONFIG_PARSER_KEY_NUMBER                        83

#endif


text:
angular.module('main', [])

.directive('paintangular', function() {

	return {
		restrict: 'E',
		replace: true,
		scope: {},

		controller: ['$scope', function($scope) {
			$scope.color = 'black'; // default stroke color
			$scope.tool = 'pencil';
			$scope.size = 2;
			$scope.clear = false;
			$scope.ud = false;
			$scope.rd = false;
			$scope.down = false;

			$scope.setColor = function(c) {
				$scope.color = c;
				console.log(c);
			}

			$scope.setTool = function(t) {
				$scope.tool = t;
				console.log(t);
			}

			$scope.chooseSize = function(s) {
				$scope.size = s;
				console.log(s);
			}

			$scope.cls = function() {
				$scope.clear = true;
			}
			// call this function from link of child directive
			this.noClear = function() {
				$scope.clear = false;
			}

			$scope.undo = function() {
				$scope.ud = true;
			}

			$scope.redo = function() {
				$scope.rd = true;
			}

			this.noUndo = function() {
				$scope.ud = false;
			}

			this.noRedo = function() {
				$scope.rd = false;
			}

			$scope.download = function() {
				$scope.down = true;
			}

			this.noDownload = function() {
				$scope.down = false;
			}
		}],

		templateUrl: "/static/demo/paintangular/template.html"

	}
})

.directive('canvasable', function() {

	return {
		restrict: 'A',
		require: '^paintangular',
		scope: true,

		link: function(scope, element, attrs, paintCtrl) {
			//element.css('background-color', 'red'); // set the background color
			var canvas = element.children().eq(0)[0];
			var temp_canvas = element.children().eq(1)[0];
			var dragger = element.children().eq(2)[0];
			// A temporary canvas is required because we have to continuously redraw a shpae
			// to give live feel of drawing. eg. while drawing a circle, circles of radii
			// starting from 0 is drawn. But only upon 'mouseup', the final cirlce is copied to canvas
			canvas.width = element[0].clientWidth; // offsetWidth include borders and padding
			canvas.height = element[0].clientHeight;
			temp_canvas.width = canvas.width;
			temp_canvas.height = canvas.height;
			// Disable scrolling, zooming etc
			//temp_canvas.style.touchAction = 'none';
			//canvas.style.touchAction = 'none';
			//sketch.style.touchAction = 'none';

			var ctx = canvas.getContext('2d');
			var temp_ctx = temp_canvas.getContext('2d');

			var undo_canvas = [];
			var undo_canvas_num = 7;
			for (var i=0; i<undo_canvas_num; ++i) {
				var ucan = document.createElement('canvas');
				ucan.width = canvas.width;
				ucan.height = canvas.height;
				var uctx = ucan.getContext('2d');
				undo_canvas.push({'ucan':ucan, 'uctx':uctx, 'redoable':false});
			}

			var undo_canvas_top = 0;

			var next_undo_canvas = function(top) {
				if (top === undo_canvas_num-1)
					return 0;
				else
					return top+1;
			}

			var prev_undo_canvas = function(top) {
				if (top === 0)
					return undo_canvas_num-1;
				else
					return  top-1;
			}

			/* Drawing on the temporary canvas and later copying into the canvas*/
			temp_ctx.lineJoin = 'round';
			temp_ctx.lineCap = 'round';

			var mouse = {x: 0, y: 0};
			var start_mouse = {x:0, y:0};
			// Pencil Points
			var ppts = [];
			// eraser size minimum is 5
			var eraser_width = 10;
			// text minimum size 10px
			var fontSize = '14px';

			// no watching, we just simply assign the color when mousedown
			// Watch for color change, size change or tool change
			//scope.$watch('color', function(val) {
			//	temp_ctx.strokeStyle = val;
			//	temp_ctx.fillStyle = val;
			//});

			// watch for size change, required because of move_eraser
			scope.$watch('size', function(s) {

				if (s===1) {
					//temp_ctx.lineWidth = 1; // we assign this in mousedown
					eraser_width = 5;
					fontSize = '10px';
				}
				if (s===2) {
					//temp_ctx.lineWidth = 3;
					eraser_width = 10;
					fontSize = '14px';
				}
				if (s===3) {
					//temp_ctx.lineWidth = 6;
					eraser_width = 15;
					fontSize = '18px';
				}
				if (s===4) {
					//temp_ctx.lineWidth = 10;
					eraser_width = 20;
					fontSize = '22px';
				}

			});

			// watch for tool change, if eraser hide the crosshair
			scope.$watch('tool', function(tool, prev_tool) {
				//console.log('prev_tool '+prev_tool);
				temp_canvas.removeEventListener('mousemove', tools_func[prev_tool], false);

				if (tool === 'eraser') {
					temp_canvas.addEventListener('mousemove', move_eraser, false);
					temp_canvas.style.cursor = 'none';
				}
				else {
					temp_canvas.removeEventListener('mousemove', move_eraser, false);
					temp_canvas.style.cursor = 'crosshair';
					temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);
				}
			});

			// watch for clear button click
			scope.$watch('clear', function(c) {
				if (c) {
					ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);
					// keep the image in the undo_canvas
					undo_canvas_top = next_undo_canvas(undo_canvas_top);
					var uctx = undo_canvas[undo_canvas_top]['uctx'];
					uctx.clearRect(0, 0, canvas.width, canvas.height);
					uctx.drawImage(canvas, 0, 0);
					undo_canvas[undo_canvas_top]['redoable'] = false;

					paintCtrl.noClear();
				}
			});
			// undoing
			scope.$watch('ud', function(ud) {
				if(ud) {
					var prev = prev_undo_canvas(undo_canvas_top);
					if (!undo_canvas[prev].redoable) {
						var ucan = undo_canvas[prev]['ucan'];
						ctx.clearRect(0, 0, canvas.width, canvas.height);
						ctx.drawImage(ucan, 0, 0);
						undo_canvas[undo_canvas_top].redoable = true;
						undo_canvas_top = prev;
					}

					paintCtrl.noUndo();
				}
			});
			// redoing
			scope.$watch('rd', function(rd) {
				if(rd) {
					var next = next_undo_canvas(undo_canvas_top);
					if (undo_canvas[next].redoable) {
						var ucan = undo_canvas[next]['ucan'];
						ctx.clearRect(0, 0, canvas.width, canvas.height);
						ctx.drawImage(ucan, 0, 0);
						undo_canvas[next].redoable = false;
						undo_canvas_top = next;
					}

					paintCtrl.noRedo();
				}
			});
			// download picture
			scope.$watch('down', function(d) {
				if(d) {
					var link = document.createElement('a');
					link.href = canvas.toDataURL();
					link.download = 'paint.png';
					//window.location = canvas.toDataURL();
					link.click();

					paintCtrl.noDownload();
				}
			})

			// mousemove paint functions
			var paint_pencil = function(e) {
				e.preventDefault();
				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				//console.log(mouse.x + " "+mouse.y);
				// Saving all the points in an array
				// ppts is for the smoothness of the pencil drawings, o/w it'll be jarred
				ppts.push({x: mouse.x, y: mouse.y});

				if (ppts.length < 3) {
					var b = ppts[0];
					temp_ctx.beginPath();
					temp_ctx.arc(b.x, b.y, temp_ctx.lineWidth / 2, 0, Math.PI * 2, !0);
					temp_ctx.fill();
					temp_ctx.closePath();
					return;
				}

				// Tmp canvas is always cleared up before drawing.
				temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);

				temp_ctx.beginPath();
				temp_ctx.moveTo(ppts[0].x, ppts[0].y);

				for (var i = 0; i < ppts.length; i++)
					temp_ctx.lineTo(ppts[i].x, ppts[i].y);

				temp_ctx.stroke();

			};

			var paint_line = function(e) {

				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				// Tmp canvas is always cleared up before drawing.
		    	temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);

		    	temp_ctx.beginPath();
		    	temp_ctx.moveTo(start_mouse.x, start_mouse.y);
		    	temp_ctx.lineTo(mouse.x, mouse.y);
		    	temp_ctx.stroke();
		    	temp_ctx.closePath();
			}

			var paint_square = function(e) {
				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				// Tmp canvas is always cleared up before drawing.
		    	temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);
		 		temp_ctx.beginPath();
		    	temp_ctx.moveTo(start_mouse.x, start_mouse.y);

				var x = Math.min(mouse.x, start_mouse.x);
				var y = Math.min(mouse.y, start_mouse.y);
				var width = Math.abs(mouse.x - start_mouse.x);
				var height = Math.abs(mouse.y - start_mouse.y);
				temp_ctx.strokeRect(x, y, width, height);
				temp_ctx.closePath();
			}

			var paint_circle = function(e) {
				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				// Tmp canvas is always cleared up before drawing.
		    	temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);

		    	var x = (mouse.x + start_mouse.x) / 2;
		    	var y = (mouse.y + start_mouse.y) / 2;

		    	//var radius = Math.max(Math.abs(mouse.x - start_mouse.x), Math.abs(mouse.y - start_mouse.y)) / 2;
		    	var a = mouse.x - start_mouse.x;
		    	var b = mouse.y - start_mouse.y;
		    	var r = Math.sqrt(a*a + b*b);

			    temp_ctx.beginPath();
		    	//temp_ctx.arc(x, y, radius, 0, Math.PI*2, false);
		    	temp_ctx.arc(start_mouse.x, start_mouse.y, r, 0, 2*Math.PI);
		    	// temp_ctx.arc(x, y, 5, 0, Math.PI*2, false);
		    	temp_ctx.stroke();
		    	temp_ctx.closePath();
			}

			var paint_ellipse = function(e) {
				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				// Tmp canvas is always cleared up before drawing.
		    	temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);

		    	var x = start_mouse.x;
		    	var y = start_mouse.y;
		    	var w = (mouse.x - x);
		    	var h = (mouse.y - y);

		  		temp_ctx.save(); // save state
		        temp_ctx.beginPath();

		        temp_ctx.translate(x, y);
		        temp_ctx.scale(w/2, h/2);
		        temp_ctx.arc(1, 1, 1, 0, 2 * Math.PI, false);

		        temp_ctx.restore(); // restore to original state
		        temp_ctx.stroke();
		        temp_ctx.closePath();

			}

			var move_eraser = function(e){
				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				// Tmp canvas is always cleared up before drawing.
				temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);
				var tmp_lw = temp_ctx.lineWidth;
				var tmp_ss = temp_ctx.strokeStyle;
				temp_ctx.lineWidth = 1;
				temp_ctx.strokeStyle = 'black';
				temp_ctx.beginPath();
		    	temp_ctx.strokeRect(mouse.x, mouse.y, eraser_width, eraser_width);
		    	temp_ctx.stroke();
		    	temp_ctx.closePath();
		    	// restore linewidth
		    	temp_ctx.lineWidth = tmp_lw;
		    	temp_ctx.strokeStyle = tmp_ss;
			}

			var paint_text = function(e) {
				// Tmp canvas is always cleared up before drawing.
		    	temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);
		     	//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;

		    	var x = Math.min(mouse.x, start_mouse.x);
		    	var y = Math.min(mouse.y, start_mouse.y);
		    	var width = Math.abs(mouse.x - start_mouse.x);
		    	var height = Math.abs(mouse.y - start_mouse.y);

		    	text_tool.style.left = x + 'px';
		    	text_tool.style.top = y + 'px';
		    	text_tool.style.width = width + 'px';
		    	text_tool.style.height = height + 'px';

		    	text_tool.style.display = 'block';
			}

			var paint_eraser = function(e) {
				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				// erase from the main ctx
		    	ctx.clearRect(mouse.x, mouse.y, eraser_width, eraser_width);
			}

			// Event listeners
			// Mouse-Down
			temp_canvas.addEventListener('mousedown', function(e) {

				//mouse.x = typeof e.offsetX !== 'undefined' ? e.offsetX : e.layerX;
				//mouse.y = typeof e.offsetY !== 'undefined' ? e.offsetY : e.layerY;
				var rect = temp_canvas.getBoundingClientRect();
				mouse.x = e.clientX - rect.left;
				mouse.y = e.clientY - rect.top;
				//console.log('mouseX: '+mouse.x+' mouseY: '+mouse.y)

				start_mouse.x = mouse.x;
		    	start_mouse.y = mouse.y;
		    	console.log('mousedown: '+mouse.x+' '+mouse.y);
		    	temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);

		    	// Assign color & size
		    	temp_ctx.strokeStyle = scope.color;
				temp_ctx.fillStyle = scope.color;
				temp_ctx.lineWidth = scope.size * (scope.size+1) / 2; // just for 1,3,6 & 10

		    	var tool = scope.tool;
				if (tool === 'pencil') {
					temp_canvas.addEventListener('mousemove', paint_pencil, false);
					ppts.push({x: mouse.x, y: mouse.y});
					paint_pencil(e);
				}

				if (tool === 'line') {
					temp_canvas.addEventListener('mousemove', paint_line, false);
		    	}

				if (tool === 'square') {
					temp_canvas.addEventListener('mousemove', paint_square, false);
				}

				if (tool === 'circle') {
					temp_canvas.addEventListener('mousemove', paint_circle, false);
		    		// Mark the center

		    		temp_ctx.beginPath();
					//ctx.moveTo(b.x, b.y);
					//ctx.lineTo(b.x+50, b.y+50);
					temp_ctx.arc(start_mouse.x, start_mouse.y, temp_ctx.lineWidth / 2, 0, Math.PI * 2, !0);
					temp_ctx.fill();
					temp_ctx.closePath();
					// copy to real canvas
					ctx.drawImage(temp_canvas, 0, 0);
				}

				if (tool === 'ellipse') {
					temp_canvas.addEventListener('mousemove', paint_ellipse, false);
		    	}

		    	if (tool === 'text') {
		    		temp_canvas.addEventListener('mousemove', paint_text, false);
		    		text_tool.style.display = 'none'; // important to hide when clicked outside
		    		text_tool.style.color = temp_ctx.strokeStyle;
					text_tool.style['font-size'] = fontSize;
		    	}

		    	if (tool === 'eraser') {
		    		temp_canvas.addEventListener('mousemove', paint_eraser, false);
		    		// erase from the main ctx
		    		ctx.clearRect(mouse.x, mouse.y, eraser_width, eraser_width);
		    	}

		    	if (tool === 'fill') {
		    		var replacement_color = hex_to_color(temp_ctx.strokeStyle);
		    		//console.log(temp_ctx.strokeStyle);
		    		var red_component = {'red':255, 'lime':0, 'blue':0, 'orange':255, 'yellow':255, 'magenta':255,
								'cyan':0, 'purple':128, 'brown':165, 'gray':128, 'lavender':230,
								'white':255, 'black':0};
					var green_component = {'red':0, 'lime':255, 'blue':0, 'orange':165, 'yellow':255, 'magenta':0,
								'cyan':255, 'purple':0, 'brown':42, 'gray':128, 'lavender':230,
								'white':255, 'black':0};
					var blue_component = {'red':0, 'lime':0, 'blue':255, 'orange':0, 'yellow':0, 'magenta':255,
								'cyan':255, 'purple':128, 'brown':42, 'gray':128, 'lavender':250,
								'white':255, 'black':0};

		    		var replace_r = red_component[replacement_color];
		    		var replace_g = green_component[replacement_color];
		    		var replace_b = blue_component[replacement_color];

		    		var imgd = ctx.getImageData(0, 0, canvas.width, canvas.height);
					var pix = imgd.data;
					// pix is row-wise straightened array
					var pos = 4 * (canvas.width * mouse.y + mouse.x);
					var target_color = map_to_color(pix[pos],pix[pos+1],pix[pos+2],pix[pos+3]);

					// start the flood fill algorithm
					if (replacement_color !== target_color) {
						var Q = [pos];
						while (Q.length > 0) {
							pos = Q.shift();
							if (map_to_color(pix[pos],pix[pos+1],pix[pos+2],pix[pos+3]) !== target_color)
								continue; // color is already changed

							var left = find_left_most_similar_pixel(pix, pos, target_color);
							var right = find_right_most_similar_pixel(pix, pos, target_color);
							// replace color
							//console.log('right: '+ (right/4)%canvas.width + ' '+ Math.floor(right/(4*canvas.width))  );
							//console.log(j+'. '+(right-left));
							for (var i=left; i<=right; i=i+4) {
								pix[i] = replace_r;
								pix[i+1] = replace_g;
								pix[i+2] = replace_b;
								pix[i+3] = 255; // not transparent

								var top = i - 4*canvas.width;
								var down = i + 4*canvas.width;

								if (top >= 0 && map_to_color(pix[top], pix[top+1], pix[top+2], pix[top+3]) === target_color)
									Q.push(top);

								if (down < pix.length && map_to_color(pix[down], pix[down+1],pix[down+2],pix[down+3]) === target_color)
									Q.push(down);
							}

						}

						// Draw the ImageData at the given (x,y) coordinates.
						ctx.putImageData(imgd, 0, 0);

					}

		    	} // tool==='fill'

			}, false); // event listener

			var tools_func = {'pencil':paint_pencil, 'line':paint_line, 'square':paint_square,
					'circle':paint_circle, 'ellipse':paint_ellipse, 'eraser':paint_eraser,
					'text':paint_text};

			//console.log(tmp_canvas === temp_canvas) //true in chrome and IE. id is available in window
			temp_canvas.addEventListener('mouseup', function() {
				//console.log('mouseup')	;
				var tool = scope.tool;
				temp_canvas.removeEventListener('mousemove', tools_func[tool], false);
				// Writing down to real canvas now
				// text-tool is managed when textarea.blur() event
				if (tool !=='text') {
					if (tool !=='eraser')
						ctx.drawImage(temp_canvas, 0, 0);
					// keep the image in the undo_canvas
					undo_canvas_top = next_undo_canvas(undo_canvas_top);
					var uctx = undo_canvas[undo_canvas_top]['uctx'];
					uctx.clearRect(0, 0, canvas.width, canvas.height);
					uctx.drawImage(canvas, 0, 0);
					undo_canvas[undo_canvas_top]['redoable'] = false;
				}

				// Clearing tmp canvas
				temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);

				// Emptying up Pencil Points
				ppts = [];
			}, false);

			// text-tool
			var text_tool = document.createElement('textarea');
			text_tool.id = 'text_tool'; // create only one, change the absolute positioning
			sketch.appendChild(text_tool);

			text_tool.addEventListener('mouseup', function(e) {
				temp_canvas.removeEventListener('mousemove', paint_text, false);
			}, false);

			// set the color
			text_tool.addEventListener('mousedown', function(e){
				text_tool.style.color = temp_ctx.strokeStyle;
				text_tool.style['font-size'] = fontSize;
			}, false);

			text_tool.addEventListener('blur', function(e) {
				var text_lines = text_tool.value.split('\n');
					var comp_style = window.getComputedStyle(text_tool);
		    		var fs = comp_style.getPropertyValue('font-size');

		    		var ff = comp_style.getPropertyValue('font-family');

		    		temp_ctx.font = fs + ' ' + ff;
		    		temp_ctx.textBaseline = 'bottom'; // bottom, middle, alphabetic, hanging

		    		for (var n = 0; n < text_lines.length; n++) {
		        		var line = text_lines[n];

		         		// consider padding of the text_tool
		        		temp_ctx.fillText(
		            		line,
		            		parseInt(text_tool.style.left) + 8,
		            		parseInt(text_tool.style.top) + 2 +
		            			parseInt(comp_style.lineHeight) + n*parseInt(fs)
		        		);

		    		}

		    		// Writing down to real canvas now
		    		ctx.drawImage(temp_canvas, 0, 0);
		    		text_tool.style.display = 'none';
		    		text_tool.value = '';
		    		// Clearing tmp canvas
					temp_ctx.clearRect(0, 0, temp_canvas.width, temp_canvas.height);

					// keep the image in the undo_canvas
					undo_canvas_top = next_undo_canvas(undo_canvas_top);
					var uctx = undo_canvas[undo_canvas_top]['uctx'];
					uctx.clearRect(0, 0, canvas.width, canvas.height);
					uctx.drawImage(canvas, 0, 0);
					undo_canvas[undo_canvas_top]['redoable'] = false;
			});

			// uitility functions
			// for filling
			var find_left_most_similar_pixel = function(pix, pos, target_color) {
				var y = Math.floor(pos/(4*canvas.width));
				var left = pos;
				var end = y * canvas.width * 4;
				while (end < left) {
					if (map_to_color(pix[left-4],pix[left-3],pix[left-2],pix[left-1]) === target_color)
						left = left - 4;
					else
						break;
				}
				return left;
			}

			var find_right_most_similar_pixel = function(pix, pos, target_color) {
				var y = Math.floor(pos/(4*canvas.width));
				var right = pos;
				var end = (y+1) * canvas.width * 4 - 4;
				while (end > right) {
					if (map_to_color(pix[right+4],pix[right+5],pix[right+6],pix[right+7]) === target_color)
						right = right + 4;
					else
						break;
				}
				return right;
			}

			var hex_to_color = function(hex) {
			    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
		    	var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
		    	hex = hex.replace(shorthandRegex, function(m, r, g, b) {
		        	return r + r + g + g + b + b;
		    		});

		    	var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		    	var r = parseInt(result[1], 16),
		            g = parseInt(result[2], 16),
		            b = parseInt(result[3], 16);

				return map_to_color(r, g, b, 255);
			}

			var map_to_color = function(r,g,b,a) {
				if (a === 0)
					return 'white';
				else {
					if (r===255 && g===0 && b===0)
						return 'red';
					if (r===0 && g===255 && b===0)
						return 'lime';
					if (r===0 && g===0 && b===255)
						return 'blue';
					if (r===255 && g===255 && b===0)
						return 'yellow';
					if (r===255 && g===0 && b===255)
						return 'magenta';
					if (r===0 && g===255 && b===255)
						return 'cyan';
					if (r===255 && g===165 && b===0)
						return 'orange';
					if (r===128 && g===0 && b===128)
						return 'purple';
					if (r===128 && g===128 && b===128)
						return 'gray';
					if (r===0 && g===0 && b===0)
						return 'black';
					if (r===230 && g===230 && b===250)
						return 'lavender';
					if (r===165 && g===42 && b===42)
						return 'brown';
				}

				return 'white';
			}

			// touch
			// Prevent scrolling when touching the canvas
			temp_canvas.addEventListener("touchstart", function (e) {
			    e.preventDefault();
				e.stopPropagation();

			    var touch = e.touches[0];
			    // for mozilla, hold first finger and draw with the second
			  	if (e.touches.length > 1) {
			  		touch = e.touches[1];
			  		ppts = []; // a new drawing
			  		// remove event listeners
					temp_canvas.removeEventListener('mousemove', tools_func[scope.tool], false);
			  	}

			    //alert(touch.clientX + ' '+touch.clientY)
			    var mouseEvent = new MouseEvent("mousedown", {
				    clientX: touch.clientX,//typeof touch.offsetX !== 'undefined' ? touch.offsetX : touch.layerX,
				    clientY: touch.clientY//typeof touch.offsetY !== 'undefined' ? touch.offsetY : touch.layerY
			    });

			    temp_canvas.dispatchEvent(mouseEvent);

			}, false);

			temp_canvas.addEventListener("touchend", function (e) {
			  e.preventDefault();

			  var mouseEvent = new MouseEvent("mouseup", {});
  			  temp_canvas.dispatchEvent(mouseEvent);

			}, false);

			temp_canvas.addEventListener("touchmove", function (e) {
			  e.preventDefault();
			  e.stopPropagation();

			  e.stopPropagation();

			  var touch = e.touches[0];
			  // for mozilla, hold first finger and draw with the second
			  if (e.touches.length > 1) {
			  	touch = e.touches[1];
			  	console.log('second finger');
			  }
			  else
			  	console.log('one finger only');

		  	  var mouseEvent = new MouseEvent("mousemove", {
		      	clientX: touch.clientX,//typeof touch.offsetX !== 'undefined' ? touch.offsetX : touch.layerX,
				clientY: touch.clientY//typeof touch.offsetY !== 'undefined' ? touch.offsetY : touch.layerY
		  	  });

		  	  temp_canvas.dispatchEvent(mouseEvent);

			}, false);

			// Dragging to resize the canvas
			var keep_canvas = document.createElement('canvas');
			keep_canvas.width = canvas.width; // width doesn't change
			var keep_ctx = keep_canvas.getContext('2d');
			var flag = false;

			dragger.addEventListener('mousedown', function(e) {
				e.preventDefault();
				console.log('Event listener added');
				// it can't be dragger.addEventListener - it only decrease in size
				document.addEventListener('mousemove', resize_canvas, false);

			});

			document.addEventListener('mouseup', function(e) {
				//console.log('Event listener removed');
				document.removeEventListener('mousemove', resize_canvas, false);
			});

			var resize_canvas = function(e) {
				var rect = temp_canvas.getBoundingClientRect();
				var height = e.clientY - rect.top;
				console.log('height '+height)

				// keep the original picture as changing dimensions of the
				// canvas removes the image
				keep_canvas.height = canvas.height;
				keep_ctx.drawImage(canvas, 0, 0);

				element[0].style.height = height+'px';
				canvas.height = height;
				temp_canvas.height = height;

				// copy back the image
				ctx.drawImage(keep_canvas, 0, 0);
			}

		}

	}
})


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls Univ. turku. , A II (Rep. Kevo Subarct. Res. Stn 17) 66: 32 (1981)

#### Original name
Entoloma kallioi Noordel.

### Remarks
null