text:
package io.netty.handler.ssl;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;

import java.io.File;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.x500.X500Principal;

/**
 * A client-side {@link SslContext} which uses JDK's SSL/TLS implementation.
 */
public final class JdkSslClientContext extends JdkSslContext {

    private final SSLContext ctx;
    private final List<String> nextProtocols;

    /**
     * Creates a new instance.
     */
    public JdkSslClientContext() throws SSLException {
        this(null, null);
    }

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format.
     *                      {@code null} to use the system default
     */
    public JdkSslClientContext(File certChainFile) throws SSLException {
        this(certChainFile, null);
    }

    /**
     * Creates a new instance.
     *
     * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
     *                            that verifies the certificates sent from servers.
     *                            {@code null} to use the default.
     */
    public JdkSslClientContext(TrustManagerFactory trustManagerFactory) throws SSLException {
        this(null, trustManagerFactory);
    }

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format.
     *                      {@code null} to use the system default
     * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
     *                            that verifies the certificates sent from servers.
     *                            {@code null} to use the default.
     */
    public JdkSslClientContext(File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException {
        this(certChainFile, trustManagerFactory, null, IdentityCipherSuiteFilter.INSTANCE,
                null, DefaultSslWrapperFactory.INSTANCE, 0, 0);
    }

    /**
     * Creates a new instance.
     *
     * @param certChainFile an X.509 certificate chain file in PEM format.
     *                      {@code null} to use the system default
     * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
     *                            that verifies the certificates sent from servers.
     *                            {@code null} to use the default.
     * @param ciphers the cipher suites to enable, in the order of preference.
     *                {@code null} to use the default cipher suites.
     * @param cipherFilter a filter to apply over the supplied list of ciphers
     * @param nextProtocols the application layer protocols to accept, in the order of preference.
     *                      {@code null} to disable TLS NPN/ALPN extension.
     * @param wrapperFactory a factory used to wrap the underlying {@link SSLEngine}.
     *                       This is required if {@code nextProtocols} is not {@code null} or empty
     * @param sessionCacheSize the size of the cache used for storing SSL session objects.
     *                         {@code 0} to use the default value.
     * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
     *                       {@code 0} to use the default value.
     */
    public JdkSslClientContext(
            File certChainFile, TrustManagerFactory trustManagerFactory,
            Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
            Iterable<String> nextProtocols, SslEngineWrapperFactory wrapperFactory,
            long sessionCacheSize, long sessionTimeout) throws SSLException {

        super(ciphers, cipherFilter, wrapperFactory);

        this.nextProtocols = translateProtocols(nextProtocols);

        try {
            if (certChainFile == null) {
                ctx = SSLContext.getInstance(PROTOCOL);
                if (trustManagerFactory == null) {
                    ctx.init(null, null, null);
                } else {
                    trustManagerFactory.init((KeyStore) null);
                    ctx.init(null, trustManagerFactory.getTrustManagers(), null);
                }
            } else {
                KeyStore ks = KeyStore.getInstance("JKS");
                ks.load(null, null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");

                ByteBuf[] certs = PemReader.readCertificates(certChainFile);
                try {
                    for (ByteBuf buf: certs) {
                        X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteBufInputStream(buf));
                        X500Principal principal = cert.getSubjectX500Principal();
                        ks.setCertificateEntry(principal.getName("RFC2253"), cert);
                    }
                } finally {
                    for (ByteBuf buf: certs) {
                        buf.release();
                    }
                }

                // Set up trust manager factory to use our key store.
                if (trustManagerFactory == null) {
                    trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                }
                trustManagerFactory.init(ks);

                // Initialize the SSLContext to work with the trust managers.
                ctx = SSLContext.getInstance(PROTOCOL);
                ctx.init(null, trustManagerFactory.getTrustManagers(), null);
            }

            SSLSessionContext sessCtx = ctx.getClientSessionContext();
            if (sessionCacheSize > 0) {
                sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
            }
            if (sessionTimeout > 0) {
                sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
            }
        } catch (Exception e) {
            throw new SSLException("failed to initialize the server-side SSL context", e);
        }
    }

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

    @Override
    public List<String> nextProtocols() {
        return nextProtocols;
    }

    @Override
    public SSLContext context() {
        return ctx;
    }
}


text:
SYNONYM

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

#### Published in
Grevillea 14(no. 69): 18 (1885)

#### Original name
Polyporus rhodophaeus Lév., 1844

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
const bcrypt = require('bcrypt-nodejs');
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  email: { type: String, unique: true },
  password: String,
  passwordResetToken: String,
  passwordResetExpires: Date
}, { timestamps: true });

/* Password hash middleware. */
userSchema.pre('save', function save(next) {
  const user = this;
  if (!user.isModified('password')) { return next(); }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) { return next(err); }
    bcrypt.hash(user.password, salt, null, (err, hash) => {
      if (err) { return next(err); }
      user.password = hash;
      next();
    });
  });
});

/* Helper method for validating user's password. */
userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    cb(err, isMatch);
  });
};

const User = mongoose.model('User', userSchema);

module.exports = User;


text:
FROM ubuntu
MAINTAINER http://www.github.com/b7alt/ by b7alt

#RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list

RUN apt-get update && apt-get upgrade -y
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y supervisor openssh-server nginx php5-fpm php5-sqlite php5-gd drush php-apc git emacs
RUN update-rc.d nginx disable
RUN update-rc.d php5-fpm disable
RUN update-rc.d supervisor disable
RUN update-rc.d ssh disable

EXPOSE 22 80

RUN mkdir -p /var/run/sshd /srv/drupal/www /srv/drupal/config /srv/data /srv/logs /tmp

ADD site.conf /srv/drupal/config/site.conf
ADD nginx.conf /nginx.conf
ADD php-fpm.conf /php-fpm.conf
ADD supervisord.conf /supervisord.conf
ADD settings.php.append /settings.php.append

RUN cd /tmp && drush dl drupal && mv /tmp/drupal*/* /srv/drupal/www/ && rm -rf /tmp/*
RUN chmod a+w /srv/drupal/www/sites/default && mkdir /srv/drupal/www/sites/default/files
RUN chown -R www-data:www-data /srv/drupal/www/
RUN cp /srv/drupal/www/sites/default/default.settings.php /srv/drupal/www/sites/default/settings.php
RUN chmod a+w /srv/drupal/www/sites/default/settings.php
RUN chown www-data:www-data /srv/data

#RUN chmod a+w /srv/drupal/www/sites/default/files
RUN cd /srv/drupal/www/ && drush -y site-install standard --account-name=admin --account-pass=test --db-url=sqlite:sites/default/files/.ht.sqlite

RUN cat /settings.php.append >> /srv/drupal/www/sites/default/settings.php

RUN cd /srv/drupal/www/ && drush -y dl environment_indicator devel views responsive_bartik
RUN cd /srv/drupal/www/ && drush -y en environment_indicator devel views views_ui responsive_bartik
RUN cd /srv/drupal/www/ && drush -y vset theme_default responsive_bartik
RUN cd /srv/drupal/www/ && drush -y vset cache 1 --yes
RUN cd /srv/drupal/www/ && drush -y vset block_cache 1 --yes
RUN cd /srv/drupal/www/ && drush -y vset cache_lifetime 300 --yes
RUN cd /srv/drupal/www/ && drush -y vset page_cache_maximum_age 300 --yes

RUN cd /srv/drupal/www/ && drush -y vset preprocess_css 1 --yes
RUN cd /srv/drupal/www/ && drush -y vset preprocess_js  1 --yes

RUN ls -al /srv/drupal/www/sites/default/files
RUN chown -R www-data:www-data /srv/drupal/www/sites/default/files/.ht.sqlite
RUN chmod a-w /srv/drupal/www/sites/default/settings.php

RUN chown -R www-data:www-data /srv/drupal/www/

RUN echo "root:root" | chpasswd
RUN sed --in-place=.bak 's/without-password/yes/' /etc/ssh/sshd_config

ENTRYPOINT [ "/usr/bin/supervisord", "-n", "-c", "/supervisord.conf", "-e", "trace" ]


text:
description: Configuring Twilio for Guardian
topics:
  - mfa
  - guardian
  - twilio
contentType:
  - how-to
useCase:
  - customize-mfa
---
# Configuring Twilio for Guardian SMS

When initially setting up SMS, you have up to 100 SMS to be used for testing. This limit can be removed by setting up a Twilio account. To prevent malicious login attempts, your users will always be limited to up to 10 SMS/Hour (replenishing one message an hour, up to 10).

Click on the **SMS** box to configure your SMS settings.

![](/media/articles/mfa/sms-config.png)

## 1. Open an account with Twilio

You will need a [Twilio Account SID](https://www.twilio.com/help/faq/twilio-basics/what-is-an-application-sid) and a [Twilio Auth Token](https://www.twilio.com/help/faq/twilio-basics/what-is-the-auth-token-and-how-can-i-change-it). These are the Twilio API credentials that Auth0 will use to send an SMS to the user. You may also need to enable permissions for your [geographic region](https://support.twilio.com/hc/en-us/articles/223181108-How-International-SMS-Permissions-work).

## 2. Configure the connection

Enter your **Twilio Account SID** and **Twilio Auth Token** in the appropriate fields.

Choose your **SMS Source**.

* If you choose **Use From**, you will need to enter the **From** phone number that users will see as the sender of the SMS. You may also configure this in Twilio.

* If you choose **Use Copilot**, you will need to enter a [Copilot SID](https://www.twilio.com/docs/api/rest/sending-messages-copilot).

Click **SAVE**.


text:
ELEMENTGROUP_DLL AIElementGroup::AIElementGroup()
{
	mPos=0;
}

ELEMENTGROUP_DLL AIElementGroup::~AIElementGroup()
{
}

ELEMENTGROUP_DLL AIElementGroupSeparate::AIElementGroupSeparate()
{

}

ELEMENTGROUP_DLL AIElementGroupSeparate::~AIElementGroupSeparate()
{

}

ELEMENTGROUP_DLL AIElementGroupSwarm::AIElementGroupSwarm()
{
	mParams.N=10;
	mParams.DIST=200;

	mParams.RULE1_BYPASS=1;
	mParams.RULE2_DISTANCE=200;
	mParams.RULE2_BYPASS=0.05;
	mParams.RULE3_BYPASS=1;
	mParams.XMAX=800;
	mParams.YMAX=600;
	mParams.XMIN=0;
	mParams.YMIN=0;

	mParams.RADIUS=1;

	mParams.VELOCITY_BYPASS=10000;
}

ELEMENTGROUP_DLL AIElementGroupSwarm::~AIElementGroupSwarm()
{

}

ELEMENTGROUP_DLL void AIElementGroupSeparate::commandAny(int num,int command)
{

}

ELEMENTGROUP_DLL void AIElementGroupSeparate::commandAny(int num,String command)
{
	if (command=="gather")
	{
	AIElement* n = nodes[num];
	n->sendCommand1(StringConverter::toString(GOTO_NPC));
	n->sendCommand2(StringConverter::toString(n->getPosition()));
	}
}

ELEMENTGROUP_DLL void AIElementGroup::addAIElement(AIElement* node)
{
	nodes.push_back(node);

}

ELEMENTGROUP_DLL void AIElementGroup::setName(String name)
{
	mName=name;
}

ELEMENTGROUP_DLL String AIElementGroup::getName(void)
{
	return mName;
}

ELEMENTGROUP_DLL void AIElementGroup::command(String name, int command)
{

}

void AIElementGroup::command(String name, String command)
{
	if ((name=="")&&(command=="gather"))
	{
		//Send "message" to leader to gather group to position.
		std::vector<AIElement*>::iterator i;
		for (i=nodes.begin();i!=nodes.end();i++)
		{
			AIElement* n = (*i);
			n->sendCommand1(StringConverter::toString(GOTO_NPC));
			n->sendCommand2(StringConverter::toString(n->getPosition()));
		}
	}
	if ((name=="")&&(command=="activate"))
	{
		//Send "message" to leader to gather group to position.
		std::vector<AIElement*>::iterator i;
		for (i=nodes.begin();i!=nodes.end();i++)
		{
			AIElement* n = (*i);
			n->sendCommand1(StringConverter::toString(SETAI_NPC));
			n->sendCommand2("group_behavior");
		}
	}
	if ((command=="tend_to_pos"))
	{
		LogManager::getSingleton().logMessage("Tend to position:");
		//Send "message" to leader to gather group to position.
		mPos=StringConverter::parseVector3(name);
		LogManager::getSingleton().logMessage(StringConverter::toString(mPos));
	}
	if ((command=="calculate_center"))
	{
		mPos=0;
		//Send "message" to leader to gather group to position.
		std::vector<AIElement*>::iterator i;
		for (i=nodes.begin();i!=nodes.end();i++)
		{
			AIElement* n = (*i);
			mPos+=n->getPosition();
		}
		mPos/=nodes.size();
	}
}

void AIElementGroup::setPos(Vector3 pos)
{
	mPos=pos;
}

Vector3 AIElementGroup::getPos()
{
	return mPos;
}

void AIElementGroup::cleanupAllNodes()
{
	std::vector<AIElement*>::iterator i;
	for (i=nodes.begin();i!=nodes.end();i++)
	{
		AIElement* n = (*i);
		delete n;
	}
	nodes.clear();
}

AIElementGroupLeaderShip::AIElementGroupLeaderShip()
{
}

AIElementGroupLeaderShip::~AIElementGroupLeaderShip()
{
}

void AIElementGroupLeaderShip::commandLeader(int command)
{
}

float AIElementGroupSwarm::distanceFunction(float distance)
{
	if (distance<mParams.RULE2_DISTANCE)
	{
		return distance/mParams.RULE2_DISTANCE;
	}
	else
	{
		return (mParams.RULE2_DISTANCE*mParams.RULE2_DISTANCE/distance/distance);
	}
}

//
void AIElementGroup::step(Real evt)
{
	LogManager::getSingleton().logMessage("Obsolete step.");
}

//
void AIElementGroupSwarm::step(Real evt)
{
	//LogManager::getSingleton().logMessage("Swarm step.");
	int i;
		Vector3 v1,v2,v3,mVel;
		for (i=0;i!=nodes.size();i++)
		{
			AIElement* n = nodes[i];
			v1=rule1(n);
			v2=rule2(n);
			v3=rule3(n);
			mVel=n->getVelocity();
			mVel+=v1+v2+v3;
			//LogManager::getSingleton().logMessage(StringConverter::toString(nodes.size()));
		//	LogManager::getSingleton().logMessage(StringConverter::toString(v2));
		//	LogManager::getSingleton().logMessage(StringConverter::toString(v3));
			//boundPosition(nodes[i]);
			//tend_to_pos(nodes[i]);
			//n->setPosition(n->getPosition()+mVel/(100000)*evt);
			n->setVelocity(mVel*0.0001);
			tendToPos(getPos());
			n->sendCommand1(StringConverter::toString(GOTO_NPC));
			n->sendCommand2(StringConverter::toString(n->getPosition()));
		}
}

void AIElementGroupSwarm::setParameters(SwarmParams params)
{
	mParams=params;
}

Vector3 AIElementGroupSwarm::rule1(AIElement* b)
{
		Vector3 res=Vector3::ZERO;
		int i;
		for (i=0;i!=nodes.size();i++)
		{
			if (nodes[i]!=b)
			{
				res+=(nodes[i]->getPosition());
			}
		}
		res/=nodes.size()-1;
		return (res - b->getPosition())/mParams.RULE1_BYPASS;
}

Vector3 AIElementGroupSwarm::rule2(AIElement* b)
{
	//LogManager::getSingleton().logMessage("Swarm step.");
	Vector3 res=Vector3::ZERO;
		int i;
		for (i=0;i!=nodes.size();i++)
		{
			if (nodes[i]!=b)
			{
				Vector3 dist = nodes[i]->getPosition() - b->getPosition();

				float force = distanceFunction(dist.length());
				res-=(nodes[i]->getPosition() - b->getPosition())*(force);

			}
		}
		return res/mParams.RULE2_BYPASS;
}

Vector3 AIElementGroupSwarm::rule3(AIElement* b)
{
	Vector3 res=Vector3::ZERO;

		int i;
		for (i=0;i!=nodes.size();i++)
		{
			if (nodes[i]!=b)
			{
					res+=nodes[i]->getVelocity();
			}
		}

		res/=nodes.size()-1;

		return (res - b->getVelocity()) / mParams.RULE3_BYPASS;
}

void AIElementGroupSwarm::tendToPos(Vector3 pos)
{
	int i;
	for (i=0;i!=nodes.size();i++)
		{
			Vector3 res=Vector3::ZERO;
			res=nodes[i]->getVelocity()+(pos-nodes[i]->getPosition())/mParams.VELOCITY_BYPASS;
			nodes[i]->setVelocity(res);
		}
}


text:
package dispatch

// Worker 负责完成job
type Worker struct {
	manager     *Manager      //
	jobChannel  chan Job      // 任务队列,从任务队列里获取任务,每一个worker都有一个单独的jobChannel
	stopChannel chan struct{} // 停止工作
}

// NewWorker 创建一个新的worker
func NewWorker(manager *Manager) *Worker {
	return &Worker{
		manager:     manager,
		jobChannel:  make(chan Job),
		stopChannel: make(chan struct{})}
}

// Start 开始接受job
func (worker *Worker) Start() {
	go func() {
		for {
			// tell the manager that I'm ready to work now
			// it will not block because it's a buffer channel
			worker.manager.register(worker)
			select {
			// blocked & waiting for new job
			case job := <-worker.jobChannel:
				job.Do()
			case <-worker.stopChannel:
				return
			}
		}
	}()
}

// Receive 收到新的任务
func (worker *Worker) Receive(job Job) {
	worker.jobChannel <- job
}

// Stop 停止工作
func (worker *Worker) Stop() {
	// send a message
	worker.stopChannel <- struct{}{}
}


text:
/**
 * Objects representing a hat in a row of a rendered
 * block.
 *
 * @class
 */
import * as goog from '../../../closure/goog/goog.js';
goog.declareModuleId('Blockly.blockRendering.Hat');

import type {ConstantProvider} from '../common/constants.js';

import {Measurable} from './base.js';
import {Types} from './types.js';

/**
 * An object containing information about the space a hat takes up during
 * rendering.
 *
 * @alias Blockly.blockRendering.Hat
 */
export class Hat extends Measurable {
  ascenderHeight: number;

  /**
   * @param constants The rendering constants provider.
   * @internal
   */
  constructor(constants: ConstantProvider) {
    super(constants);
    this.type |= Types.HAT;

    this.height = this.constants_.START_HAT.height;
    this.width = this.constants_.START_HAT.width;

    this.ascenderHeight = this.height;
  }
}


text:
package ema.dve.workload;

public class GlobalTime
{
	private static int current = 0;

	public static void increment()
	{
		current ++;
	}

	public static void setTime(int time)
	{
		current = time;
	}

	public static int getCurrent()
	{
		return current;
	}

	public static void reset()
	{
		current = 0;
	}

}


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

<configuration>

	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} %-5level {%thread} (%F:%L\) [%logger{20}] : %msg%n</pattern>
		</encoder>
	</appender>

	<logger name="org.javelin.sws.ext" level="TRACE" />

	<root level="INFO">
		<appender-ref ref="CONSOLE" />
	</root>

</configuration>


text:
/**
 * Created by j on 5/25/17.
 */

function SnakeNodePosition() {
    this.position = {
        x: 0,
        y: 0,
        direction: 'bottom'
    };

    this.lastPosition = {
        x: 0,
        y: 0,
        direction: 'bottom'
    }

}

function SnakeScene(options) {
    this.isPlaying = false;
    this.target = null;
    this.snake = null;
    this.pixelSize = 10;
    this.container = document.getElementById('scene');
    this.score = 0;
    this.scoreContainer = document.getElementById('score');
    this.stepLevel = 0;
    this.frame = null;
    this.speedIncreaseLevel = 1.3;
    this.speed = 100;
    this.mousePosition = {
        last: {
            x: 0,
            y: 0,
            direction: 'bottom'
        },
        direction: 'bottom'
    };
    this.debug = true;
    Object.assign(this, options);

    this.squareSize = this.pixelSize * 50;
    this.originalSquareSize = (this.squareSize + this.pixelSize);

}

SnakeScene.prototype.directionChanged = function(direction){
    this.snake.setDirection(direction);
};

SnakeScene.prototype.snakeDirectionHandler = function (event) {

    switch (event.keyCode) {
        case 40:
            this.directionChanged('bottom');
            break;
        case 38:
            this.directionChanged('top');
            break;
        case 37:
            this.directionChanged('left');
            break;
        case 39:
            this.directionChanged('right');
            break;
    }

    if (event.keyCode === 27) {
        if (this.isPlaying) {
            this.stopMove();
        } else {
            this.startMove();
        }
        this.isPlaying = !this.isPlaying;
    }

};

SnakeScene.prototype.directionHandler = function (event) {
    var direction = this.mousePosition.direction;
    var deltaX = this.mousePosition.last.x - event.clientX,
        deltaY = this.mousePosition.last.y - event.clientY;

    if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0) {
        direction = 'left';
    } else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) {
        direction = 'right';
    } else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY > 0) {
        direction = 'top';
    } else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY < 0) {
        direction = 'bottom';
    }

    this.mousePosition.x = event.clientX - this.container.offsetLeft;
    this.mousePosition.y = event.clientY - this.container.offsetTop;
    this.mousePosition.direction = direction;
    this.mousePosition.last = {
        x: event.clientX,
        y: event.clientY,
        direction: direction
    }

};

SnakeScene.prototype.initListeners = function () {
    this.container.addEventListener('mousemove', this.directionHandler.bind(this));
    document.addEventListener('keydown', this.snakeDirectionHandler.bind(this));
};

SnakeScene.prototype.removeListeners = function () {
    this.container.removeEventListener('mousemove', this.directionHandler.bind(this));
    document.removeEventListener('keydown', this.snakeDirectionHandler.bind(this));
};

SnakeScene.prototype.increaseScore = function (factor) {
    this.score += this.pixelSize;
    this.score *= factor;
    this.score = Math.round(this.score);
    this.scoreContainer.innerText = this.score;
};

SnakeScene.prototype.add = function (element) {
    this.container.appendChild(element);
    return this;
};

SnakeScene.prototype.stopGame = function () {

    this.container.style.boxShadow = 'tomato 0px 0px 4px 3px';
    this.stopMove();
    this.removeListeners();
    if (this.score > (+localStorage.bestscore || 0)) {
        localStorage.bestscore = this.score;
    }
};

SnakeScene.prototype.initScene = function () {
    document.getElementById('bestScore').innerText = (+localStorage.bestscore | 0).toString();

    this.container.style.width = this.container.style.height = this.originalSquareSize + 'px';
    this.container.style.backgroundColor = '#99CC99';
    this.container.style.position = 'relative';

    this.initTarget();
    this.initSnake();
};

SnakeScene.prototype.initTarget = function () {
    var target = new Target(this.pixelSize);
    this.target = target;
    this.add(target.getTargetElement());
    target.setPosition(this.getRandomPosition(), this.getRandomPosition());
};

SnakeScene.prototype.initSnake = function () {
    this.snake = new Snake(this.pixelSize);
    var headNode = new SnakeNode(this.pixelSize);
    this.snake.head = headNode;
    this.add(headNode.getNodeElement());
    this.snake.head.setX(this.getCenterByX());
    this.snake.head.setY(0);
    this.snake.setDirection('bottom');
    this.snake.head.element.style.backgroundColor = 'black';
};

SnakeScene.prototype.shuffleTargetPosition = function () {
    this.target.setPosition(this.getRandomPosition(), this.getRandomPosition());
};

SnakeScene.prototype.isOverlapped = function (x, y) {
    var isOverlapped = false;
    if (x < 0 || x > this.squareSize) {
        isOverlapped = true;
    }
    if (y < 0 || y > this.squareSize) {
        isOverlapped = true;
    }

    return isOverlapped;
};

SnakeScene.prototype.start = function () {
    this.initScene();
    this.initListeners();
    this.startMove();

    this.isPlaying = true;
};

SnakeScene.prototype.getRandomPosition = function () {
    return this.pixelSize * Math.round((Math.random() * this.squareSize) / this.pixelSize);
};

SnakeScene.prototype.getCenterByX = function () {
    return this.pixelSize * Math.round((this.squareSize + this.pixelSize ) / 2 / this.pixelSize);
};

SnakeScene.prototype.stopMove = function () {

    if (this.debug) {
        cancelAnimationFrame(this.frame);
    } else {
        clearInterval(this.frame);
    }
    return this;
};

SnakeScene.prototype.step = function () {
    this.move();
    requestAnimationFrame(this.step.bind(this))
};

SnakeScene.prototype.resume = function () {
    this.stopMove();
    this.startMove();
};

SnakeScene.prototype.startMove = function () {

    if (this.debug) {
        this.frame = requestAnimationFrame(this.step.bind(this));
    } else {
        this.frame = setInterval(this.move.bind(this), this.speed);
    }

    return this;
};

SnakeScene.prototype.addSnakeNode = function () {
    var node = new SnakeNode(this.pixelSize);
    this.add(node.getNodeElement());
    this.snake.addNode(node);
};

SnakeScene.prototype.move = function () {

    if (this.isOverlapped(this.snake.head.position.x, this.snake.head.position.y) || this.snake.isHitSelf()) {
        this.stopMove();
        this.stopGame();
        return false;
    }

    var positionChanged;

    if (!this.debug) {
        positionChanged = this.snake.head.headStep(
            this.snake.head.position.direction
        );
    } else {
        positionChanged = this.snake.head.headMouseStep(
            this.pixelSize * Math.round(this.mousePosition.x / this.pixelSize),
            this.pixelSize * Math.round(this.mousePosition.y / this.pixelSize),
            this.mousePosition.direction
        );
    }

    if (positionChanged) return false;

    if (this.snake.head.isIntersected(this.target.position.x, this.target.position.y)) {
        this.increaseScore(1.2);
        this.addSnakeNode();

        this.speed /= this.speedIncreaseLevel;
        this.shuffleTargetPosition();
        this.resume();
    }

    this.snake.moveNodes();

    if (this.stepLevel > 1000) {
        this.increaseScore(1);
        this.speedIncreaseLevel = 1.05;
    }

    if (this.stepLevel > 300 && this.stepLevel < 1000) {
        this.speedIncreaseLevel = 1.2;
    }

    this.stepLevel++;

    return true;
};

var game = new SnakeScene({
    pixelSize: 10,
    debug: false,
    speed : 200
});

game.start();


text:
package main

import (
	"fmt"
	"io"
	"sort"
)

type info_t struct {
	// Set of libraries. (The values of the map have no meaning.)
	libs map[*library_t]byte

	// Set of executables. (The values of the map have no meaning.)
	executables map[*executable_t]byte

	// Set of executables. (The values of the map have no meaning.)
	tests map[*executable_t]byte
}

func new_info() *info_t {
	return &info_t{
		libs:        make(map[*library_t]byte),
		executables: make(map[*executable_t]byte),
		tests:       make(map[*executable_t]byte),
	}
}

func (info *info_t) Print(w io.Writer) {
	haveEmptyLine := true
	if *flag_debug {
		haveEmptyLine = false
	}

	if len(info.libs) > 0 {
		if !haveEmptyLine {
			fmt.Fprintf(w, "\n")
		}
		fmt.Fprintf(w, "Libraries:\n")

		libs_byPath := make(map[string]*library_t)
		paths := make([]string, len(info.libs))
		i := 0
		for lib := range info.libs {
			libs_byPath[lib.path] = lib
			paths[i] = lib.path
			i++
		}

		sort.Strings(paths)

		for _, path := range paths {
			lib := libs_byPath[path]

			fmt.Fprintf(w, "    %s", path)
			if lib.makefile_orNil != nil {
				fmt.Fprintf(w, " (Makefile)")
			}
			fmt.Fprintf(w, "\n")
			haveEmptyLine = false

			if *flag_verbose {
				var sources []string

				var unit *compilation_unit_t
				for _, unit = range lib.sources {
					for _, src := range unit.sources {
						sources = append(sources, src.Path())
					}
				}

				if lib.makefile_orNil != nil {
					for _, src := range lib.makefile_orNil.sources {
						sources = append(sources, src.Path())
					}
				}

				sortAndPrintNames(w, "        ", sources)
				fmt.Fprintf(w, "\n")
				haveEmptyLine = true
			}
		}
	}

	printExecutables(w, "Executables", /*allowVerbose*/ true, info.executables, &haveEmptyLine)
	printExecutables(w, "Tests", /*allowVerbose*/ false, info.tests, &haveEmptyLine)

	if len(remotePackages) > 0 {
		if !haveEmptyLine {
			fmt.Fprintf(w, "\n")
		}
		fmt.Fprintf(w, "Remote dependencies:\n")

		for _, remotePkg := range remotePackages {
			fmt.Fprintf(w, "    %s  @%s\n", remotePkg.repository.Path(), remotePkg.repository.KindString())
			haveEmptyLine = false

			if *flag_verbose {
				importPaths := make([]string, len(remotePkg.importPaths))
				copy(importPaths, remotePkg.importPaths)

				sortAndPrintNames(w, "        ", importPaths)
				fmt.Fprintf(w, "\n")
				haveEmptyLine = true
			}
		}
	}

	if !haveEmptyLine && *flag_timings {
		fmt.Fprintf(w, "\n")
	}
}

func sortAndPrintNames(w io.Writer, prefix string, names []string) {
	sort.Strings(names)
	for _, name := range names {
		fmt.Fprintf(w, "%s%s\n", prefix, name)
	}
}

func printExecutables(w io.Writer, tag string, allowVerbose bool, executables map[*executable_t]byte, haveEmptyLine *bool) {
	if len(executables) > 0 {
		if !(*haveEmptyLine) {
			fmt.Fprintf(w, "\n")
		}
		fmt.Fprintf(w, "%s:\n", tag)

		exes_byPath := make(map[string]*executable_t)
		paths := make([]string, len(executables))
		i := 0
		for exe := range executables {
			exes_byPath[exe.path] = exe
			paths[i] = exe.path
			i++
		}

		sort.Strings(paths)

		for _, path := range paths {
			exe := exes_byPath[path]

			fmt.Fprintf(w, "    %s", path)
			if exe.makefile_orNil != nil {
				fmt.Fprintf(w, " (Makefile)")
			}
			fmt.Fprintf(w, "\n")
			*haveEmptyLine = false

			if *flag_verbose && allowVerbose {
				var sources []string

				var unit *compilation_unit_t
				for _, unit = range exe.sources {
					for _, src := range unit.sources {
						sources = append(sources, src.Path())
					}
				}

				if exe.makefile_orNil != nil {
					for _, src := range exe.makefile_orNil.sources {
						sources = append(sources, src.Path())
					}
				}

				sortAndPrintNames(w, "        ", sources)
				fmt.Fprintf(w, "\n")
				*haveEmptyLine = true
			}
		}
	}
}


text:
<?php

namespace Magento\GiftMessage\Test\Block\Adminhtml\Order\View;

use Mtf\Block\Form as ParentForm;

/**
 * Class Form
 * Backend item form for gift message.
 */
class Form extends ParentForm
{
    /**
     * Selector for 'Close' button.
     *
     * @var string
     */
    protected $closeButton = '.ui-dialog-titlebar-close';

    /**
     * Close form dialog.
     *
     * @return void
     */
    public function closeDialog()
    {
        $this->_rootElement->find($this->closeButton)->click();
    }
}


text:
(function () {
  'use strict';

  var app = angular.module('makeathons');
  app.config(routeConfig);

  routeConfig.$inject = ['$stateProvider'];

  function routeConfig($stateProvider) {
    $stateProvider
        .state('makeathons', {
          abstract: true,
          url: '/makeathons',
          template: '<ui-view class="makeathon-section"/>'
        })
        .state('makeathons.list', {
          url: '',
          component: 'makeathonsListComponent',
          data: {
            roles: ['user', 'admin'],
            pageTitle: 'Makeathons List'
          }
        })
        .state('makeathons.create', {
          url: '/create',
          component: 'makeathonsCreateComponent',
          resolve: {
            makeathon: newMakeathon,
            menuitems: getSideMenu
          },
          data: {
            roles: ['admin'],
            pageTitle : 'Makeathons Create'
          }
        })
        .state('makeathons.view', {
          url: '/:makeathonId',
          component: 'makeathonsViewComponent',
          resolve: {
            makeathon: getMakeathon
          },
          data:{
            roles: ['user', 'admin'],
            pageTitle: 'Makeathon {{ makeathon.name }}'
          }
        })
        .state('makeathons.thanks', {
          url: '/:makeathonId/thanks',
          component: 'makeathonsThanksComponent',
          resolve: {
            makeathon: getMakeathon
          },
          data:{
            roles: ['user', 'admin'],
            pageTitle: 'Thanks You'
          }
        });
  }

  getMakeathon.$inject = ['$stateParams', 'MakeathonsService'];

  function getMakeathon($stateParams, MakeathonsService) {
    return MakeathonsService.get({
      makeathonId: $stateParams.makeathonId
    }).$promise;
  }

  newMakeathon.$inject = ['MakeathonsService'];

  function newMakeathon(MakeathonsService) {
    return new MakeathonsService();
  }

  getSideMenu.$inject = ['$http', '$resource'];

  function getSideMenu($http, $resource) {
    var Menu = $resource('/api/sideMenu', { menuId:'@id' });
    return Menu.query().$promise;
  }

})();


text:
require 'hashie'
require 'active_record'
require 'active_record_embedded_doc/version'
require 'active_record_embedded_doc/relations/one'
require 'active_record_embedded_doc/relations/many'
require 'active_record_embedded_doc/metadata'
require 'active_record_embedded_doc/field'
require 'active_record_embedded_doc/macros'
require 'active_record_embedded_doc/attribute'
require 'active_record_embedded_doc/type'
require 'active_record_embedded_doc/behaviour'
require 'active_record_embedded_doc/embedded_document'

module ActiveRecordEmbeddedDoc
end

ActiveRecord::Base.send :include, ActiveRecordEmbeddedDoc::Macros


text:
package com.amazonaws.services.cognitoidentity.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.cognitoidentity.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CognitoIdentityProviderMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CognitoIdentityProviderMarshaller {

    private static final MarshallingInfo<String> PROVIDERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ProviderName").build();
    private static final MarshallingInfo<String> CLIENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ClientId").build();
    private static final MarshallingInfo<Boolean> SERVERSIDETOKENCHECK_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ServerSideTokenCheck").build();

    private static final CognitoIdentityProviderMarshaller instance = new CognitoIdentityProviderMarshaller();

    public static CognitoIdentityProviderMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CognitoIdentityProvider cognitoIdentityProvider, ProtocolMarshaller protocolMarshaller) {

        if (cognitoIdentityProvider == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(cognitoIdentityProvider.getProviderName(), PROVIDERNAME_BINDING);
            protocolMarshaller.marshall(cognitoIdentityProvider.getClientId(), CLIENTID_BINDING);
            protocolMarshaller.marshall(cognitoIdentityProvider.getServerSideTokenCheck(), SERVERSIDETOKENCHECK_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package multiverse.server.objects;

public class Fog {
    public Fog() {
    }

    public Fog(String name) {
        setName(name);
    }

    public Fog(String name,
               Color c,
               int start,
               int end) {
        setName(name);
        setColor(c);
        setStart(start);
        setEnd(end);
    }

    public String getName() {
        return name;
    }

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

    public String toString() {
	return "[Fog: color=" + color +
	    ", start=" + fogStart +
	    ", end=" + fogEnd +
	    "]";
    }

    public void setColor(Color c) {
        this.color = c;
    }
    public Color getColor() {
        return color;
    }

    public void setStart(int start) {
        this.fogStart = start;
    }
    public int getStart() {
        return fogStart;
    }

    public void setEnd(int end) {
        this.fogEnd = end;
    }
    public int getEnd() {
        return fogEnd;
    }

    Color color = null;
    int fogStart = -1;
    int fogEnd = -1;

//     public void writeExternal(ObjectOutput out) throws IOException {
//         lock.lock();
// 	try {
//             super.writeExternal(out);
// 	    MVObject.writeObject(out, color);
//             out.writeInt(fogStart);
//             out.writeInt(fogEnd);
//         }
//         finally {
//             lock.unlock();
//         }
//     }

//     public void readExternal(ObjectInput in)
// 	throws IOException, ClassNotFoundException {
//         lock.lock();
// 	try {
// 	    super.readExternal(in);
// 	    this.color = (Color) MVObject.readObject(in);
//             this.fogStart = in.readInt();
//             this.fogEnd = in.readInt();
//         }
//         finally {
//             lock.unlock();
//         }
//     }

//     public void spawn() {
// 	super.spawn();
//     }

    protected String name = null;

    private static final long serialVersionUID = 1L;
}


text:
namespace bfs=boost::filesystem;

#include <gearbox/core/HttpClient.h>

HttpResponse
HttpClient::HEAD(const Uri & uri) {
    std::ostringstream oss;
    oss << uri.scheme() << "://" << uri.hostname() << '_' << uri.port() << "/" << uri.path();
    std::string url = oss.str();
    bfs::path infile = bfs::path("get") / bfs::path( url.substr(url.find('/',6)+1 ), bfs::no_check );
    if( ! bfs::exists(infile) ) {
        return HttpResponse(404);
    }
    return HttpResponse(200);
}


text:
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';

export const VIEWLET_ID = 'workbench.view.search';

export const FindInFilesActionId = 'workbench.action.findInFiles';
export const FocusActiveEditorCommandId = 'search.action.focusActiveEditor';

export const FocusSearchFromResults = 'search.action.focusSearchFromResults';
export const OpenMatchToSide = 'search.action.openResultToSide';
export const CancelActionId = 'search.action.cancel';
export const RemoveActionId = 'search.action.remove';
export const ReplaceActionId = 'search.action.replace';
export const ReplaceAllInFileActionId = 'search.action.replaceAllInFile';
export const ReplaceAllInFolderActionId = 'search.action.replaceAllInFolder';
export const CloseReplaceWidgetActionId = 'closeReplaceInFilesWidget';
export const ToggleCaseSensitiveCommandId = 'toggleSearchCaseSensitive';
export const ToggleWholeWordCommandId = 'toggleSearchWholeWord';
export const ToggleRegexCommandId = 'toggleSearchRegex';

export const SearchViewletVisibleKey = new RawContextKey<boolean>('searchViewletVisible', true);
export const InputBoxFocusedKey = new RawContextKey<boolean>('inputBoxFocus', false);
export const SearchInputBoxFocusedKey = new RawContextKey<boolean>('searchInputBoxFocus', false);
export const ReplaceInputBoxFocusedKey = new RawContextKey<boolean>('replaceInputBoxFocus', false);
export const PatternIncludesFocusedKey = new RawContextKey<boolean>('patternIncludesInputBoxFocus', false);
export const PatternExcludesFocusedKey = new RawContextKey<boolean>('patternExcludesInputBoxFocus', false);
export const ReplaceActiveKey = new RawContextKey<boolean>('replaceActive', false);

export const FirstMatchFocusKey = new RawContextKey<boolean>('firstMatchFocus', false);
export const FileMatchOrMatchFocusKey = new RawContextKey<boolean>('fileMatchOrMatchFocus', false);
export const FileFocusKey = new RawContextKey<boolean>('fileMatchFocus', false);
export const FolderFocusKey = new RawContextKey<boolean>('folderMatchFocus', false);
export const MatchFocusKey = new RawContextKey<boolean>('matchFocus', false);


text:
package org.elasticsearch.cluster.routing.allocation;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.EmptyClusterInfoService;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.routing.allocation.decider.Decision;
import org.elasticsearch.cluster.routing.allocation.decider.FilterAllocationDecider;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESAllocationTestCase;
import org.elasticsearch.test.gateway.NoopGatewayAllocator;

import java.util.Collections;

import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
import static org.elasticsearch.cluster.routing.ShardRoutingState.STARTED;
import static org.elasticsearch.cluster.routing.ShardRoutingState.UNASSIGNED;

public class FilterAllocationDeciderTests extends ESAllocationTestCase {

    public void testFilterInitialAllocation() {
        FilterAllocationDecider filterAllocationDecider = new FilterAllocationDecider(Settings.EMPTY,
            new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS));
        AllocationDeciders allocationDeciders = new AllocationDeciders(Settings.EMPTY,
            Collections.singleton(filterAllocationDecider));
        AllocationService service = new AllocationService(Settings.builder().build(), allocationDeciders,
            NoopGatewayAllocator.INSTANCE, new BalancedShardsAllocator(Settings.EMPTY), EmptyClusterInfoService.INSTANCE);
        ClusterState state = createInitialClusterState(service, Settings.builder().put("index.routing.allocation.initial_recovery._id",
            "node2").build());
        RoutingTable routingTable = state.routingTable();

        // we can initally only allocate on node2
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).state(), INITIALIZING);
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).currentNodeId(), "node2");
        routingTable = service.applyFailedShard(state, routingTable.index("idx").shard(0).shards().get(0)).routingTable();
        state = ClusterState.builder(state).routingTable(routingTable).build();
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).state(), UNASSIGNED);
        assertNull(routingTable.index("idx").shard(0).shards().get(0).currentNodeId());

        RoutingAllocation allocation = new RoutingAllocation(allocationDeciders, state.getRoutingNodes(), state,
            null, 0, false);
        assertEquals(filterAllocationDecider.canAllocate(routingTable.index("idx").shard(0).shards().get(0),
            state.getRoutingNodes().node("node2")
            ,allocation), Decision.YES);
        assertEquals(filterAllocationDecider.canAllocate(routingTable.index("idx").shard(0).shards().get(0),
            state.getRoutingNodes().node("node1")
            ,allocation), Decision.NO);

        // after failing the shard we are unassigned since the node is blacklisted and we can't initialize on the other node
        state = stateFromResult(state, service.reroute(state, "try allocate again"));
        routingTable = state.routingTable();
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).state(), INITIALIZING);
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).currentNodeId(), "node2");

        state = stateFromResult(state, service.applyStartedShards(state, routingTable.index("idx").shard(0).shards()));
        routingTable = state.routingTable();

        // ok now we are started and can be allocated anywhere!! lets see...
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).state(), STARTED);
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).currentNodeId(), "node2");
        assertTrue(routingTable.index("idx").shard(0).shards().get(0).allocatedPostIndexCreate(state.getMetaData().index("idx")));

        // we fail it again to check if we are initializing immediately on the other node
        state = stateFromResult(state, service.applyFailedShard(state, routingTable.index("idx").shard(0).shards().get(0)));
        routingTable = state.routingTable();
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).state(), INITIALIZING);
        assertEquals(routingTable.index("idx").shard(0).shards().get(0).currentNodeId(), "node1");
        assertTrue(routingTable.index("idx").shard(0).shards().get(0).allocatedPostIndexCreate(state.getMetaData().index("idx")));

        allocation = new RoutingAllocation(allocationDeciders, state.getRoutingNodes(), state,
            null, 0, false);
        assertEquals(filterAllocationDecider.canAllocate(routingTable.index("idx").shard(0).shards().get(0),
            state.getRoutingNodes().node("node2")
            ,allocation), Decision.YES);
        assertEquals(filterAllocationDecider.canAllocate(routingTable.index("idx").shard(0).shards().get(0),
            state.getRoutingNodes().node("node1")
            ,allocation), Decision.YES);
    }

    private ClusterState stateFromResult(ClusterState previousState, RoutingAllocation.Result result) {
        return ClusterState.builder(previousState).routingTable(result.routingTable()).metaData(result.metaData()).build();
    }

    private ClusterState createInitialClusterState(AllocationService service, Settings settings) {
        MetaData.Builder metaBuilder = MetaData.builder();
        metaBuilder.put(IndexMetaData.builder("idx").settings(settings(Version.CURRENT).put(settings))
            .numberOfShards(1).numberOfReplicas(0));
        MetaData metaData = metaBuilder.build();
        RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
        routingTableBuilder.addAsNew(metaData.index("idx"));

        RoutingTable routingTable = routingTableBuilder.build();
        ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT)
            .metaData(metaData).routingTable(routingTable).build();
        clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")))
            .build();
        routingTable = service.reroute(clusterState, "reroute", false).routingTable();
        clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
        return clusterState;
    }
}


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\SignupForm */

$this->title = 'Зарегистрироваться';
$this->params['breadcrumbs'][] = 'Регистрация';

$fieldOptions = [];

?>

Создание аккаунта

                        <?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['class' => 'form-horizontal', 'role' => 'form']]); ?>
                        <fieldset>
                            <legend>Персональная информация</legend>
                            <?= $form->field($model, 'name', $fieldOptions)->label('Имя') ?>

                            <?= $form->field($model, 'last_name', $fieldOptions)->label('Фамилия') ?>
                            <?= $form->field($model, 'email', $fieldOptions) ?>
                        </fieldset>
                        <fieldset>
                            <legend>Пароль</legend>
                            <?= $form->field($model, 'password', $fieldOptions)->passwordInput()->label('Пароль'); ?>
                            <?= $form->field($model, 'password_confirm', $fieldOptions)->passwordInput()->label('Еще раз'); ?>
                        </fieldset>

                                <?= Html::submitButton($this->title, ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
                                <?= Html::a('Отмена', Url::home(), ['class' => 'btn btn-default']) ?>

                        <?php ActiveForm::end(); ?>

<?php $this->beginBlock('menu-right'); ?>
<?php $this->endBlock(); ?>


text:
<?php
namespace Composer\Installers;

class DecibelInstaller extends BaseInstaller
{
    /** @var array */
    protected $locations = array(
        'app'    => 'app/{$name}/',
    );
}


text:
#pragma once

#include <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
/*!
 * An object representing a request for a mapscene.
 */
@interface WRLDMapsceneRequest: NSObject

/*!
 * Cancels the current mapscene request if not yet completed.
 */
-(void)cancel;

/*!
 @returns The ID of this request.
 */
- (int)requestId;

@end

NS_ASSUME_NONNULL_END


text:
package com.ilearnrw.api.selectnextword.levels;

import ilearnrw.utils.LanguageCode;

import java.util.List;

import com.ilearnrw.api.selectnextword.GameElement;
import com.ilearnrw.api.selectnextword.GameLevel;
import com.ilearnrw.api.selectnextword.LevelParameters;
import com.ilearnrw.api.selectnextword.WordSelectionUtils;

/**
 *
 * @author hector
 *
 *	Levels configuration for train dispatcher
 *
 *	prefix/suffix split the problem, syllables split the syllables vowels/consonants split the sounds
 *
 */
public class TrainStationUK extends GameLevel {

	@Override
	public List<GameElement> getWords(LevelParameters parameters, int languageArea, int difficulty) {

		return WordSelectionUtils.getTargetWordsWithDistractors(
				LanguageCode.EN,
				 languageArea,
				 difficulty,
				 parameters,
				-1,
				//new ArrayList<String>(),
				false,
				false);

	//	return WordSelectionUtils.getTargetWords(LanguageCode.EN, languageArea, difficulty,parameters.batchSize, parameters.wordLevel);

	}

	@Override
	public int[] modeLevels(int lA, int difficulty) {

		LanguageAreasUK languageArea = LanguageAreasUK.values()[lA];

		if(languageArea==LanguageAreasUK.SYLLABLES)
			return new int[]{0};//Syllables
		else if(languageArea==LanguageAreasUK.SUFFIXES)
			return new int[]{1};//Suffixes
		else if(languageArea==LanguageAreasUK.PREFIXES)
			return new int[]{2};//Prefixes
		else//consonant vowels
			return new int[]{3};//Graphemes

	}

	@Override
	public boolean allowedDifficulty(int languageArea, int difficulty) {

		if(languageArea>=LanguageAreasUK.values().length)
			return false;

		LanguageAreasUK lA = LanguageAreasUK.values()[languageArea];

		switch(lA){
			case CONSONANTS://Consonants
				return true;
			case VOWELS://Vowels
				return true;
			case BLENDS://Blends and letter patterns
				return false;
			case SYLLABLES://Syllables
				return true;
			case SUFFIXES://Suffixes
				return true;
			case PREFIXES://Prefixes
				return true;
			case CONFUSING://Confusing letters
				return false;
			default:
				return false;

		}
	}

	/* Instructions for the games */
	@Override
	public String instructions(int languageArea, int difficulty,LevelParameters param){

		if(param.mode==0){
			return "Separate each syllable of the word";

		}else if (param.mode==1){
			return "Separate the suffix from the rest of the word";

		}else if(param.mode==2){
			return "Separate the prefix from the rest of the word";
		}else if(param.mode==3){
			return "Separate each sound of the word";
		}

		return "Instructions not available";

	}

}


text:
<TITLE>Review for Pitch Black (2000)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Pitch Black (2000)

reviewed by
Scott Hunt

Pitch Black  (2000)

Review by Scott Hunt         Movie Hunt:
http://netdirect.net/~hunt/index.html

Rating: Good Shot  (3 out of 4 stars)

Cast: Vin Diesel, Radha Mitchell, Keith David, Cole Hauser, Rhiana
Griffith, Claudia Black, Lewis Fitz-Gerald
Writers: David Twohy, Ken and Jim Wheat
Director: David Twohy

Pitch Black is a sheep in wolf's clothing. It is full of darkness,
danger and violence and if you buy into the marketing hype, an
unsettling and scary film going experience.

Don't be fooled.  Pitch Black is a morality play masquerading as a
scare-fest.

It starts off with blistering intensity. A cargo spaceship crash lands
on a planet apparently leeched of life by the scorching heat of three
suns.  Among the survivors is Fry (Mitchell), the ship's pilot, who
spends the film wrestling with the fact that she tried to jettison the
other passengers in her effort to land the craft safely. There is Imam
(David), an Islamic leader whose faith in his god is tested repeatedly
throughout the film. There is a law enforcement officer in the form of
Johns (Hauser), who attacks every situation with square jawed
authoritarian zeal. And there is Riddick (Diesel), a menacing,
muscle-bound convicted murderer who's being brought back to justice by
Johns.

The group quickly sizes up the situation and each other. Confident in
their assessment of matters, a plan is set in motion to escape their
hellish environment. Those plans are shredded by the appearance of one
of the planet's wildlife, a predatory,  sometimes winged, species that
enjoys the taste of blood and flesh. Fortunately, the creatures are
light sensitive and are forced to live in networks of catacombs under
the planet's surface. Unfortunately, the group has managed to land on
the planet moments before an eclipse is about to occur, taking away
their one protection from the monsters. The group's savior comes in the
form of Johns, whose decisive leadership looks to deliver them from
purgatory. Or does it?

Pitch Black deviates from the standard sci-fi fare by avoiding some of
the stock "escape the boogieman" conflicts  the genre typically serves
up. Just as the planet gave a false facade of lifelessness, first
appearances given by the survivors proves to be just as false. The
excitement of the film comes not from the danger posed by the creatures,
but rather from watching the shifting allegiances and emotional growth
of the characters as the planet serves as a deus ex machina of sorts to
catalyze emotional growth.

A recurrent theme runs throughout the movie of faith, whether it be
religious or in a person, and how that powers their  motivations. I
found it telling that an accidental death occurs early on due to the
misperception of a self professed atheist. Conversely, Imam constantly
contributes any good fortune to Allah. One by one, his perceived heaven
sent blessings are taken away and crushed. Imam is forced to reassess
his faith. Another character expresses belief in god, along with a life
long hate. Yet another character makes a decision that echoes the
sentiments of Christ about selflessness and has lasting repercussions
for several of group. It is a fascinating character study hiding under
the guise of a scare flick.

Special mention should be made of Vin Diesel, who intriguingly conveys
feral menace combined with a truly mesmerizing presence. His character
could have easily slipped into a parody of the baddass killing machine,
but Twohy and Diesel add surprising depth to Riddick. They can be
excused for the two or three Shwarzenegger-like catch phrases that growl
their way out of Diesel's mouth.

The movie has its flaws that can be nitpicked. The creatures do look
derivative of the ones in Alien. The dialogue isn't the freshest at
times, reminiscent of a bad comic book. Yes, the appearance of Riddick's
vision skills are more than a little timely considering the situation.
These trappings are on the periphery of the story Twohy is really trying
to tell. Twohy may have lured you in under the pretense of scaring you
with film fabricated boogieman, but he shows the real boogieman to be
the prejudices and beliefs we use to direct decisions in our lives.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
DEPRECATED LIBRARY Adafruit Python BMP
===================

This library has been deprecated!

the bmp085 and bmp180 are no longer made, and are replaced by the bmp280 + friends

we are now only using our circuitpython sensor libraries in python

we are leaving the code up for historical/research purposes but archiving the repository.

check out this guide for using the bmp280 with python!
https://learn.adafruit.com/adafruit-bmp280-barometric-pressure-plus-temperature-sensor-breakout

Adafruit Python BMP
------------------------

Python library for accessing the BMP series pressure and temperature sensors like the BMP085/BMP180 on a Raspberry Pi or Beaglebone Black.

Designed specifically to work with the Adafruit BMP085/BMP180 pressure sensors ----> https://www.adafruit.com/products/1603

To install, download the library by clicking the download zip link to the right and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black.  Then execute the following command in the directory of the library:~~

````
sudo python setup.py install
````

Make sure you have internet access on the device so it can download the required dependencies.

See examples of usage in the examples folder.

Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!

Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution


text:
package com.telefonica.euro_iaas.paasmanager.rest.resources;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import junit.framework.TestCase;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.telefonica.fiware.commons.dao.AlreadyExistsEntityException;
import com.telefonica.fiware.commons.dao.EntityNotFoundException;

import com.telefonica.euro_iaas.paasmanager.claudia.QuotaClient;
import com.telefonica.euro_iaas.paasmanager.dao.EnvironmentInstanceDao;
import com.telefonica.euro_iaas.paasmanager.exception.InfrastructureException;
import com.telefonica.euro_iaas.paasmanager.exception.InvalidEntityException;
import com.telefonica.euro_iaas.paasmanager.exception.InvalidOVFException;
import com.telefonica.euro_iaas.paasmanager.exception.QuotaExceededException;
import com.telefonica.euro_iaas.paasmanager.model.ClaudiaData;
import com.telefonica.euro_iaas.paasmanager.model.Environment;
import com.telefonica.euro_iaas.paasmanager.model.EnvironmentInstance;
import com.telefonica.euro_iaas.paasmanager.model.ProductRelease;
import com.telefonica.euro_iaas.paasmanager.model.Tier;
import com.telefonica.euro_iaas.paasmanager.model.dto.EnvironmentInstanceDto;
import com.telefonica.euro_iaas.paasmanager.rest.validation.EnvironmentInstanceResourceValidatorImpl;
import com.telefonica.euro_iaas.paasmanager.rest.validation.ResourceValidator;
import com.telefonica.euro_iaas.paasmanager.rest.validation.TierResourceValidator;
import com.telefonica.euro_iaas.paasmanager.util.SystemPropertiesProvider;

/**
 * Test the EnvironmetnInstanceValidator class.
 */
public class EnvironmetnInstanceValidatorTest extends TestCase {
    private EnvironmentInstanceResourceValidatorImpl validator;
    private TierResourceValidator tierResourceValidator;
    private EnvironmentInstanceDao environmentInstanceDao;
    private Environment environment;
    private SystemPropertiesProvider systemPropertiesProvider;
    private ResourceValidator resourceValidator;

    /**
     * Initialize the Unit Test.
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        validator = new EnvironmentInstanceResourceValidatorImpl();
        tierResourceValidator = mock(TierResourceValidator.class);
        environmentInstanceDao = mock(EnvironmentInstanceDao.class);
        resourceValidator = mock(ResourceValidator.class);
        validator.setEnvironmentInstanceDao(environmentInstanceDao);
        validator.setTierResourceValidator(tierResourceValidator);
        validator.setResourceValidator(resourceValidator);

        Mockito.doNothing().when(resourceValidator).validateName(anyString());
        Mockito.doNothing().when(resourceValidator).validateDescription(anyString());

        ProductRelease productRelease = new ProductRelease("product", "2.0");
        List<ProductRelease> productReleases = new ArrayList<ProductRelease>();
        productReleases.add(productRelease);

        Tier tier = new Tier("name", new Integer(1), new Integer(1), new Integer(1), productReleases, "flavour",
                "image", "icono", "keypair", "floatingip", "payload");

        Set<Tier> tiers = new HashSet<Tier>();
        tiers.add(tier);
        tiers.add(tier);

        environment = new Environment();
        environment.setName("environemntName");
        environment.setDescription("description");

        environment.setTiers(tiers);
        systemPropertiesProvider = mock(SystemPropertiesProvider.class);
        Mockito.doThrow(new EntityNotFoundException(EnvironmentInstance.class, "dd", tiers))
                .when(environmentInstanceDao).load(any(String.class));

        when(systemPropertiesProvider.getProperty(any(String.class))).thenReturn("FIWARE");

    }

    /**
     * Test the creation of an environment instance.
     * @throws Exception
     */
    @Test
    public void testCreateEnviornmentInstance() throws Exception {
        EnvironmentInstanceDto environmentInstanceDto = new EnvironmentInstanceDto();
        environmentInstanceDto.setDescription("description");
        environmentInstanceDto.setEnvironmentDto(environment.toDto());
        environmentInstanceDto.setBlueprintName("blueprintName");
        ClaudiaData claudiaData = mock(ClaudiaData.class);
        QuotaClient quotaClient = mock(QuotaClient.class);
        validator.setQuotaClient(quotaClient);

        // when
        validator.validateCreate(environmentInstanceDto, systemPropertiesProvider, claudiaData);

    }

    /**
     * Test the creation of an environment instance without eny environment.
     * @throws EntityNotFoundException
     * @throws AlreadyExistsEntityException
     * @throws InfrastructureException
     * @throws InvalidOVFException
     * @throws QuotaExceededException
     */
    @Test
    public void testCreateEnviornmentInstanceNoEnvironment() throws
            EntityNotFoundException, AlreadyExistsEntityException, InfrastructureException,
            InvalidOVFException, QuotaExceededException {
        EnvironmentInstanceDto environmentInstanceDto = new EnvironmentInstanceDto();
        environmentInstanceDto.setDescription("description");
        environmentInstanceDto.setBlueprintName("BlueprintName");
        boolean exception = false;
        ClaudiaData claudiaData = mock(ClaudiaData.class);

        try {
            validator.validateCreate(environmentInstanceDto, systemPropertiesProvider, claudiaData);
        } catch (InvalidEntityException e) {
            exception = true;
        }
        assertTrue(exception);

    }

}


text:
package test.core

import business.BaseDaoTrait
import models.{Profiles, Pastes}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{BeforeAndAfter, Matchers, FlatSpec}

/**
 * Standard base trait for main tests.
 * Created by justin on 3/13/15.
 */
trait BaseTestSpec extends FlatSpec with Matchers with BeforeAndAfter with MockFactory {
  trait TestDaoTrait extends BaseDaoTrait {
    override val pastes: Pastes = mock[Pastes]
    override val profiles: Profiles = mock[Profiles]
  }
}


text:
<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

register_activation_hook( SLP_PLUGIN_FILE, 'slp_activate' );
register_deactivation_hook( SLP_PLUGIN_FILE, 'slp_deactivate' );

function slp_activate($networkwide) {
    global $wpdb;

    if (function_exists('is_multisite') && is_multisite()) {
      // check if it is a network activation - if so, run the activation function for each blog id
      if ($networkwide) {
        $old_blog = $wpdb->blogid;
        // Get all blog ids
        $blogids = $wpdb->get_col("SELECT blog_id FROM {$wpdb->blogs}");
        foreach ($blogids as $blog_id) {
          switch_to_blog($blog_id);
          return _slp_activate($networkwide);
        }
        switch_to_blog($old_blog);
        return;
      }
    }
    return _slp_activate($networkwide);
  }

function slp_network_propagate($pfunction, $networkwide) {
    global $wpdb;

    if (function_exists('is_multisite') && is_multisite()) {
        // check if it is a network activation - if so, run the activation function
        // for each blog id
        if ($networkwide) {
            $old_blog = $wpdb->blogid;
            // Get all blog ids
            $blogids = $wpdb->get_col("SELECT blog_id FROM {$wpdb->blogs}");
            foreach ($blogids as $blog_id) {
                switch_to_blog($blog_id);
                call_user_func($pfunction, $networkwide);
            }
            switch_to_blog($old_blog);
            return;
        }
    }
    call_user_func($pfunction, $networkwide);
}

function slp_deactivate($networkwide) {
    slp_network_propagate('_slp_deactivate', $networkwide);
}

add_action( 'wpmu_new_blog', 'slp_new_blog', 10, 6);

function slp_new_blog($blog_id, $user_id, $domain, $path, $site_id, $meta ) {
    global $wpdb;

    if (is_plugin_active_for_network('stealth-login-page/stealth-login-page.php')) {
        $old_blog = $wpdb->blogid;
        switch_to_blog($blog_id);
        _slp_activate(TRUE);
        switch_to_blog($old_blog);
    }
}

function _slp_activate($networkwide) {
  return ;
}

function _slp_deactivate($networkwide) {
  return ;
}

add_action('admin_menu', 'slp_plugin_menu');
function slp_plugin_menu() {
  add_options_page( __( 'Stealth Login Page', 'stealth-login-page' ), __( 'Stealth Login Page', 'stealth-login-page' ), 'manage_options', 'stealth-login-page', 'slp_admin' );
  return;
}

/**
 * Add settings link on plugin page
 *
 * @since 3.0.0
 * @param array $links
 * @param string $file
 * @return array
 */
add_filter( 'plugin_action_links', 'slp_admin_settings_link', 10, 2  );
function slp_admin_settings_link( $links, $file ) {

  if ( plugin_basename(__FILE__) == $file ) {
    $settings_link = '' . __( 'Settings', 'stealth-login-page' ) . '';
  }

  return $links;

}


text:
<?xml version="1.0"?>
<Template
	originator="Matt Ward"
	created="2015/09/22"
	lastModified="2015/09/22">

	<TemplateConfiguration>
		<_Name>Empty web Startup.cs</_Name>
	</TemplateConfiguration>

	<TemplateFiles>
		<File
			name="Startup.cs"
			DefaultName="Startup.cs"
			src="EmptyWebProject.Startup.cs"
			AddStandardHeader="True" />
	</TemplateFiles>
</Template>


text:
struct SubStruct
{
  int a;
  int b;
};

struct MyStruct
{
  int first;
  struct SubStruct second;
};

int
main()
{
  struct MyStruct my_struct = {10, {20, 30}};
  struct MyStruct *my_pointer = &my_struct;
  printf ("Stop here to evaluate expressions: %d %d %p\n", my_pointer->first, my_pointer->second.a, my_pointer);
  return 0;
}


text:
namespace Contracts
{
    public class ChangeName : ICommand
    {
        public int PersonId { get; private set; }

        public string NewName { get; private set; }

        public ChangeName(int personId, string newName)
        {
            PersonId = personId;
            NewName = newName;
        }
    }
}


text:
#include "stdafx.h"

#include <windows.h>
#include <wininet.h>

#include "htmlctrl.h"

#include "IEBrowserEngine.h"
#include "common/RhoConf.h"
#include "MainWindow.h"

IMPLEMENT_LOGCLASS(CIEBrowserEngine,"IEBrowser");

extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal();
extern "C" HWND rho_wmimpl_get_mainwnd();
extern "C" LRESULT rho_wm_appmanager_ProcessOnTopMostWnd( WPARAM wParam, LPARAM lParam );
extern "C" void rho_wmimpl_create_ieBrowserEngine(HWND hwndParent, HINSTANCE rhoAppInstance);
extern "C" bool rho_wmimpl_get_textselectionenabled();

//Default Text Zoom Value
#define ZOOM_TEXT_MEDIUM 2 ///< The text zoom value is in the range 0 to 4.

//////////////////////////////////////////////////////////////////////////

#define NM_PIE_TITLE            (WM_USER + 104)  ///< Message ID indicating the associated message defines the page title.
#define NM_PIE_META             (WM_USER + 105)  ///< Message ID indicating the associated message defines a Meta Tag (HTTP-Equiv only for WM).
#define NM_PIE_BEFORENAVIGATE   (WM_USER + 109)  ///< Message ID indicating the associated message indicates a BeforeNavigate Event.
#define NM_PIE_DOCUMENTCOMPLETE	(WM_USER + 110)  ///< Message ID indicating the associated message defines a DocumentComplete Event.
#define NM_PIE_NAVIGATECOMPLETE (WM_USER + 111)  ///< Message ID indicating the associated message defines a NavigateComplete Event.
#define NM_PIE_KEYSTATE			(WM_USER + 112)  ///< Message ID indicating the associated message notifies that the key state has changed.
#define NM_PIE_ALPHAKEYSTATE	(WM_USER + 113)  ///< Message ID indicating the associated message notifies that the alpha key state has changed.

#define HTML_CONTAINER_NAME		TEXT("HTMLContainer")  ///< Name of the Window which is parent to all HTML components and handles notifications from the components.

//////////////////////////////////////////////////////////////////////////

HWND              CIEBrowserEngine::g_hwndTabHTMLContainer = NULL;
CIEBrowserEngine* CIEBrowserEngine::g_hInstance = NULL;

//////////////////////////////////////////////////////////////////////////

CIEBrowserEngine* CIEBrowserEngine::getInstance()
{
    return g_hInstance;
}

CIEBrowserEngine* CIEBrowserEngine::getInstance(HWND hParentWnd, HINSTANCE hInstance)
{
    if (!g_hInstance)
    {
        g_hInstance = new CIEBrowserEngine(hParentWnd, hInstance);
    }

    return g_hInstance;
}

//////////////////////////////////////////////////////////////////////////

CIEBrowserEngine::CIEBrowserEngine(HWND hParentWnd, HINSTANCE hInstance) :
        m_parentHWND(NULL),
        m_hparentInst(NULL),
        m_bLoadingComplete(FALSE),
        m_hNavigated(NULL),
        m_dwNavigationTimeout(45000),
        m_urlList(NULL),
	m_currentPage(NULL)
{
    m_parentHWND = hParentWnd;
    m_hparentInst = hInstance;
    m_tabID = 0; //tabID;

	m_textZoomValue = ZOOM_TEXT_MEDIUM; //By default the text zoom value is set to ZOOM_TEXT_MEDIUM

    GetWindowRect(hParentWnd, &m_rcViewSize);

    m_tcNavigatedURL[0] = 0;
	//TODO TAU
	//convertFromStringW(rho_wmimpl_getNavTimeOutVal(),m_dwNavigationTimeout);
	if(m_dwNavigationTimeout<=0)
	{
		LOG(WARNING)+" NavigationTimeout  value  from config.xml not correct "+m_dwNavigationTimeout;
		m_dwNavigationTimeout=45000;
	}
    CreateEngine();
}

CIEBrowserEngine::~CIEBrowserEngine()
{
    //  Destroy the Browser Object
    DestroyWindow(m_hwndTabHTML);
    m_hwndTabHTML = NULL;
    DeleteCascade(m_urlList);
    //  Destroy the Browser Object's parent if it exists
    if (g_hwndTabHTMLContainer)
    {
        DestroyWindow(g_hwndTabHTMLContainer);
        g_hwndTabHTMLContainer = NULL;
    }
}

HRESULT CIEBrowserEngine::RegisterWindowClass(HINSTANCE hInstance, WNDPROC appWndProc)
{
    WNDCLASS    wc = { 0 };
    HRESULT     hrResult = 0;

    if (!GetClassInfo(hInstance, HTML_CONTAINER_NAME, &wc))
    {
        wc.style            = CS_HREDRAW | CS_VREDRAW;
        wc.lpfnWndProc      = appWndProc;
        wc.hInstance        = hInstance;
        wc.hIcon			= NULL;
        wc.lpszClassName    = HTML_CONTAINER_NAME;
        wc.hCursor          = LoadCursor(NULL, IDC_ARROW);
        wc.hbrBackground    = (HBRUSH)(COLOR_WINDOW + 1);

        hrResult = (RegisterClass(&wc) ? S_OK : E_FAIL);
    }
    else
        hrResult = S_OK;

    return hrResult;
}

LRESULT CIEBrowserEngine::CreateEngine()
{
    //  Create an HTML container to listen for Engine Events if one does not
    //  already exist
    if (g_hwndTabHTMLContainer == NULL)
    {
        //register the main window
        if (FAILED(RegisterWindowClass(m_hparentInst, &CIEBrowserEngine::WndProc)))
            return S_FALSE;

        //create the main window
        g_hwndTabHTMLContainer = CreateWindowEx( 0, HTML_CONTAINER_NAME, NULL,
            WS_POPUP | WS_VISIBLE,
            CW_USEDEFAULT, CW_USEDEFAULT,
            CW_USEDEFAULT, CW_USEDEFAULT,
            m_parentHWND, NULL, m_hparentInst, 0);

        if(!g_hwndTabHTMLContainer)
            return S_FALSE;

        if (FAILED(rho::browser::InitHTMLControl(m_hparentInst)))
            return S_FALSE;
    }

	DWORD dwTextSelectionStyle = 0;
    //TODO TAU
	//if(!rho_wmimpl_get_textselectionenabled())
	//	dwTextSelectionStyle = HS_NOSELECTION;
	dwTextSelectionStyle = HS_NOSELECTION;

    m_hwndTabHTML = CreateWindow(WC_HTML, NULL,
        WS_POPUP | WS_VISIBLE | dwTextSelectionStyle,
        m_rcViewSize.left, m_rcViewSize.top,
        (m_rcViewSize.right-m_rcViewSize.left),
        (m_rcViewSize.bottom-m_rcViewSize.top),
        g_hwndTabHTMLContainer, NULL, m_hparentInst, NULL);

    if (!m_hwndTabHTML)
        return S_FALSE;

    CloseHandle (CreateThread(NULL, 0,
        &CIEBrowserEngine::RegisterWndProcThread, (LPVOID)this, 0, NULL));

    return S_OK;
}

BOOL CIEBrowserEngine::Navigate(LPCTSTR tcURL, int iTabID)
{
    //  On Windows Mobile devices it has been observed that attempting to
    //  navigate to a Javascript function before the page is fully loaded can
    //  crash PocketBrowser (specifically when using Reload).  This condition
    //  prevents that behaviour.

    if (!m_bLoadingComplete && (wcsnicmp(tcURL, L"JavaScript:", wcslen(L"JavaScript:")) == 0))
    {
        LOG(TRACE) + "Failed to Navigate, Navigation in Progress\n";
        return S_FALSE;
    }

    LRESULT retVal = S_FALSE;

    if (wcsicmp(tcURL, L"history:back") == 0)
    {
		TCHAR tcPreviousURL[MAX_URL];
		LOG(INFO) + "\nDRD history:back tcURL="+tcURL;
		GetPreviousUrl(tcPreviousURL);
		Navigate(tcPreviousURL, iTabID);
		return S_OK;
    }

        //  Engine component does not accept Navigate(page.html), it needs
        //  the absolute URL of the page, add that here (if the user puts a .\ before)
        TCHAR tcDereferencedURL[MAX_URL];
        memset(tcDereferencedURL, 0, MAX_URL * sizeof(TCHAR));
        if (rho::browser::IsRelativeURL(tcURL))
        {
            if (!rho::browser::DereferenceURL(tcURL, tcDereferencedURL, m_tcNavigatedURL))
                return S_FALSE;
        }
        else
            wcscpy(tcDereferencedURL, tcURL);

        //  Test to see if the navigation URL starts with a '\', if it does
        //  then prepend 'file://'
        if (tcDereferencedURL[0] == L'\\')
        {
            if (wcslen(tcDereferencedURL) <= (MAX_URL - wcslen(L"file://")))
            {
                TCHAR tcNewURL[MAX_URL + 1];
                wsprintf(tcNewURL, L"file://%s", tcDereferencedURL);
                retVal = SendMessage(m_hwndTabHTML, DTM_NAVIGATE, 0, (LPARAM) (LPCTSTR)tcNewURL);
            }
        }
        else if (wcslen(tcDereferencedURL) > wcslen(L"www") && wcsnicmp(tcURL, L"www", 3) == 0)
        {
            if (wcslen(tcDereferencedURL) <= (MAX_URL - wcslen(L"http://")))
            {
                TCHAR tcNewURL[MAX_URL + 1];
                wsprintf(tcNewURL, L"http://%s", tcDereferencedURL);
                retVal = SendMessage(m_hwndTabHTML, DTM_NAVIGATE, 0, (LPARAM) (LPCTSTR)tcNewURL);
            }
        }
        else
            retVal = SendMessage(m_hwndTabHTML, DTM_NAVIGATE, 0, (LPARAM) (LPCTSTR)tcDereferencedURL);

    return retVal;
}

BOOL CIEBrowserEngine::ResizeOnTab(int iInstID,RECT rcNewSize)
{
    m_rcViewSize = rcNewSize;

    if(!m_bLoadingComplete)
        return TRUE;

    if (MoveWindow(m_hwndTabHTML,
                   m_rcViewSize.left,
                   m_rcViewSize.top,
                  (m_rcViewSize.right-m_rcViewSize.left),
                  (m_rcViewSize.bottom-m_rcViewSize.top),
                   FALSE))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

BOOL CIEBrowserEngine::BackOnTab(int iInstID,int iPagesBack /*= 1*/)
{
    return Navigate(L"history:back", 0);
}

BOOL CIEBrowserEngine::ForwardOnTab(int iInstID)
{
    int iPagesForward = 1;
    //  iPreviousPages must be greater than 0, otherwise we're not doing anything
    if (iPagesForward == 0)
	return TRUE;

    //  Check to see we can go forward this many pages
    int iHistoryCounter = 0;
    CHistoryElement* tempHistoryElement = m_currentPage;
    while(tempHistoryElement != NULL && tempHistoryElement->pNext != NULL)
    {
    	//  We can go to the previous page
		iHistoryCounter++;
		//  Go forward another item in the history
		tempHistoryElement = tempHistoryElement->pNext;
		//  If we have gone forward the specified number of times navigate to the
		//  page
		if (iPagesForward == iHistoryCounter)
		{
			m_currentPage = tempHistoryElement;
			Navigate(m_currentPage->tcURL, iInstID);
		}
    }
    return TRUE;
}

BOOL CIEBrowserEngine::ReloadOnTab(bool bFromCache, UINT iTab)
{
    if(m_currentPage!=NULL)
    	Navigate(m_currentPage->tcURL,iTab);
    return TRUE;
}

BOOL CIEBrowserEngine::StopOnTab(UINT iTab)
{
    return SendMessage(m_hwndTabHTML, DTM_STOP, 0, 0);
}

BOOL CIEBrowserEngine::ZoomPageOnTab(float fZoom, UINT iTab)
{
    return SendMessage(m_hwndTabHTML, DTM_ZOOMLEVEL, 0, (LPARAM)(DWORD)m_textZoomValue);
}

BOOL CIEBrowserEngine::GetTitleOnTab(LPTSTR szURL, UINT iMaxLen, UINT iTab)
{
    return FALSE;
}

void CIEBrowserEngine::RunMessageLoop(CMainWindow& mainWnd)
{
	MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
		if (RHODESAPP().getExtManager().onWndMsg(msg) )
            continue;

		IDispatch* pDisp;
		SendMessage(m_hwndTabHTML, DTM_BROWSERDISPATCH, 0, (LPARAM) &pDisp); // New HTMLVIEW message
		if (pDisp != NULL) {
			//  If the Key is back we do not want to translate it causing the browser
			//  to navigate back.
			if ( ((msg.message != WM_KEYUP) && (msg.message != WM_KEYDOWN)) || (msg.wParam != VK_BACK) )
			{
				IOleInPlaceActiveObject* pInPlaceObject;
				pDisp->QueryInterface( IID_IOleInPlaceActiveObject, (void**)&pInPlaceObject );
				HRESULT handleKey = pInPlaceObject->TranslateAccelerator(&msg);
			}
		}

        if (!mainWnd.TranslateAccelerator(&msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

		if(msg.message == WM_PAINT)
			RHODESAPP().getExtManager().onHTMLWndMsg(msg);
    }
}

void CIEBrowserEngine::executeJavascript(const wchar_t* szJSFunction, int index)
{
    //  Test to see if the passed function starts with "JavaScript:" and
    //  if it does not then prepend it.
    if (_memicmp(szJSFunction, L"JavaScript:", 22))
    {
        //  Function does not start with JavaScript:
        TCHAR* tcURI = new TCHAR[MAX_URL];
        wsprintf(tcURI, L"JavaScript:%s", szJSFunction);
        LRESULT retVal;
        retVal = Navigate(tcURI, 0);
        delete[] tcURI;
    }
    else
    {
        Navigate(szJSFunction, 0);
    }
}

void CIEBrowserEngine::OnDocumentComplete(LPCTSTR url)
{
    if(!m_bLoadingComplete && wcscmp(url,_T("about:blank")) != 0)
    {
        m_bLoadingComplete = true;

        ResizeOnTab(0, m_rcViewSize);
    }
}

void CIEBrowserEngine::setNavigationTimeout(unsigned int dwMilliseconds)
{
    m_dwNavigationTimeout = dwMilliseconds;
}

HWND CIEBrowserEngine::GetHTMLWND(int /*iTabID*/)
{
    return m_hwndTabHTML;
}

LRESULT CIEBrowserEngine::OnWebKitMessages(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	//TODO TAU
	/*
    bHandled = TRUE;

    switch (uMsg)
    {
	case PB_WINDOW_RESTORE:
		{
			short m_PB_WINRESTORED = 6;
            RHODESAPP().getExtManager().OnWindowChanged((LPVOID) m_PB_WINRESTORED);
		}
		break;
    case PB_ONMETA:
        {
            EngineMETATag* metaTag2 = (EngineMETATag*)lParam;

            RHODESAPP().getExtManager().onSetPropertiesData( (LPCWSTR)wParam, (LPCWSTR)lParam );

            if (metaTag2 && wcscmp(metaTag2->tcHTTPEquiv, L"initialiseRhoElementsExtension") != 0)
            {
                free(metaTag2->tcHTTPEquiv);
                free(metaTag2->tcContents);
                delete metaTag2;
            }
        }
        break;
    case PB_ONTOPMOSTWINDOW:
        LOG(INFO) + "START PB_ONTOPMOSTWINDOW";
        LRESULT rtRes = rho_wm_appmanager_ProcessOnTopMostWnd(wParam, lParam);
        LOG(INFO) + "END PB_ONTOPMOSTWINDOW";
        return rtRes;
        break;
    }
*/
    return 0;
}

//////////////////////////////////////////////////////////////////////////
// invoke methods

void CIEBrowserEngine::InvokeEngineEventMetaTag(LPTSTR tcHttpEquiv, LPTSTR tcContent)
{
    EngineMETATag metaTag;
    LRESULT lRet;

    EngineMETATag *pMeta = new EngineMETATag;
	pMeta->tcHTTPEquiv = tcHttpEquiv;
	pMeta->tcContents = tcContent;

    if(pMeta->tcHTTPEquiv && *pMeta->tcHTTPEquiv){
        metaTag.tcHTTPEquiv = new WCHAR[wcslen(pMeta->tcHTTPEquiv)+1];
        wcscpy(metaTag.tcHTTPEquiv,pMeta->tcHTTPEquiv);
    }

    if(pMeta->tcContents && *pMeta->tcContents){
        metaTag.tcContents = new WCHAR[wcslen(pMeta->tcContents)+1];
        wcscpy(metaTag.tcContents,pMeta->tcContents);
    }

    EngineMETATag* metaTag2 = new EngineMETATag;
    metaTag2->tcHTTPEquiv = _tcsdup(metaTag.tcHTTPEquiv);
    metaTag2->tcContents = _tcsdup(metaTag.tcContents);
    lRet = PostMessage(rho_wmimpl_get_mainwnd(),PB_ONMETA,(WPARAM)m_tabID, (LPARAM)metaTag2);

    delete [] metaTag.tcHTTPEquiv;
    delete [] metaTag.tcContents;
}

void CIEBrowserEngine::InvokeEngineEventLoad(LPTSTR tcURL, EngineEventID eeEventID)
{
	//  Engine component has indicated a load event, this should be
	//  one of BeforeNavigate, NavigateComplete or DocumentComplete.
	wcscpy(m_tcNavigatedURL, tcURL);

	switch (eeEventID)
	{
		case EEID_BEFORENAVIGATE:
			m_bLoadingComplete = FALSE;
			if(m_hNavigated==NULL)
				m_hNavigated = CreateEvent(NULL, TRUE, FALSE, L"PB_IEENGINE_NAVIGATION_IN_PROGRESS");
			//  Do not start the Navigation Timeout Timer if the
			//  navigation request is a script call.
			if((!_memicmp(tcURL, L"javascript:", 11 * sizeof(TCHAR)))
				|| (!_memicmp(tcURL, L"jscript:", 8 * sizeof(TCHAR)))
				|| (!_memicmp(tcURL, L"vbscript:", 9 * sizeof(TCHAR)))
				|| (!_memicmp(tcURL, L"res://\\Windows\\shdoclc.dll/navcancl.htm", 35 * sizeof(TCHAR))))
			{
					break;
			}

			//  Test if the user has attempted to navigate back in the history
			if (wcsicmp(tcURL, L"history:back") == 0)
			{
			}

			CloseHandle (CreateThread(NULL, 0,
									&CIEBrowserEngine::NavigationTimeoutThread,
									(LPVOID)this, 0, NULL));

            PostMessage(m_parentHWND, WM_BROWSER_ONBEFORENAVIGATE, (WPARAM)m_tabID, (LPARAM)_tcsdup(tcURL));
			break;
		case EEID_DOCUMENTCOMPLETE:
			m_bLoadingComplete = TRUE;
            PostMessage(m_parentHWND, WM_BROWSER_ONDOCUMENTCOMPLETE, m_tabID, (LPARAM)_tcsdup(tcURL));
			break;
		case EEID_NAVIGATECOMPLETE:
			SetEvent(m_hNavigated);
			CloseHandle(m_hNavigated);
			m_hNavigated = NULL;
            		SendMessage(m_parentHWND, WM_BROWSER_ONNAVIGATECOMPLETE, (WPARAM)m_tabID, (LPARAM)_tcsdup(tcURL));
        		AddNewUrl(tcURL);
			break;
	}
}

void CIEBrowserEngine::InvokeEngineEventTitleChange(LPTSTR tcTitle)
{
	////  Notify the core the page title has changed, if not specified between
	////  <TITLE> </TITLE> tags this should be set to the page URL.
    TCHAR tcURL[MAX_URL];
    memset(tcURL, 0, sizeof(MAX_URL) * sizeof(TCHAR));
    wcsncpy(tcURL, tcTitle, MAX_URL);

    SendMessage(m_parentHWND, WM_BROWSER_ONTITLECHANGE, (WPARAM)m_tabID, (LPARAM)tcURL);
}

//////////////////////////////////////////////////////////////////////////
// system handlers

/**
* \author	Darryn Campbell (DCC, JRQ768)
* \date		October 2009
*/
LRESULT CIEBrowserEngine::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	LRESULT lResult = S_OK;

	bool m_bFullScreen = RHOCONF().getBool("full_screen");

    switch (uMsg)
	{
		case WM_KILLFOCUS:
		{
			if (m_bFullScreen)
			{
				HWND taskbarWnd = FindWindow(L"HHTaskBar", NULL);
				ShowWindow(taskbarWnd, SW_HIDE);
				return FALSE;
			}
		}
		case WM_NOTIFY:
		{
			//  Received a message from the Pocket Internet Explorer component
			//  to indicate something has happened (BeforeNavigate / DocumentComplete etc).
			//  The lParam contains an NM_HTMLVIEWW containing information about
			//  the event, parse it.
			NM_HTMLVIEWW * pnmHTML;
			LPNMHDR pnmh;
			pnmHTML = (NM_HTMLVIEWW *) lParam;
			pnmh    = (LPNMHDR) &(pnmHTML->hdr);

			//  The message has originated from one of the tabs we created, determine
			//  the tab ID from the hwnd
			//IETab* tab = GetSpecificTab(hwndParentOfOriginator);
            CIEBrowserEngine* mobileTab = CIEBrowserEngine::getInstance();

			//  Invoke the appropriate tab with the event.  The data will vary
			//  depending on which event has been received
			TCHAR tcTarget[MAX_URL + 1];
			memset (tcTarget, 0, sizeof(TCHAR) * MAX_URL + 1);
			switch (pnmh->code)
			{
			case NM_PIE_TITLE:
				//  The Page Title has been received from the Page, convert
				//  the content to a wide string
				if (pnmHTML->szTarget)
					mbstowcs(tcTarget, (LPSTR)pnmHTML->szTarget, MAX_URL);
				if (tcTarget)
					mobileTab->InvokeEngineEventTitleChange(tcTarget);
				break;
			case NM_PIE_META:

				//  A Meta Tag has been received from the Page, convert the content
				//  and data to wide strings.
				if (pnmHTML->szTarget)
					mbstowcs(tcTarget, (LPSTR)pnmHTML->szTarget, MAX_URL);
				TCHAR tcData[MAX_URL+1];
				memset(tcData, 0, sizeof(TCHAR) * MAX_URL + 1);
				if (pnmHTML->szData)
					mbstowcs(tcData, (LPSTR)pnmHTML->szData, MAX_URL);
				//  If there is both an HTTP Equiv and some Content to the Meta
				//  tag then invoke it
				if (tcTarget && tcData)
					mobileTab->InvokeEngineEventMetaTag(tcTarget, tcData);
				break;
			case NM_PIE_BEFORENAVIGATE:
				if (pnmHTML->szTarget)
					mbstowcs(tcTarget, (LPSTR)pnmHTML->szTarget, MAX_URL);

				// GD - stop navigation if target starts with file:// and ends with '\'.
				// This is the generated target when using <a href=""> from a local page.
				// If we don't stop it then the File Explorer is launched.
				if (wcslen (tcTarget) >= 8)
					if (!wcsnicmp (tcTarget, L"file://", 7))
						if (tcTarget [wcslen (tcTarget) - 1] == '\\')
						{
							LOG(TRACE) + "Navigation to file folder aborted\n";
							return S_FALSE;
						}
				if (tcTarget)
					mobileTab->InvokeEngineEventLoad(tcTarget, EEID_BEFORENAVIGATE);
				break;
			case NM_PIE_DOCUMENTCOMPLETE:
				if (pnmHTML->szTarget)
					mbstowcs(tcTarget, (LPSTR)pnmHTML->szTarget, MAX_URL);
				//  If the network is available but the server being reached
				//  is inaccessible the browser component appears to immediately
				//  give a document complete with the current page URL (not the
				//  page being navigated to) which is hiding the hourglass,
				//  stop this behaviour.
				if (tcTarget && !wcsicmp(tcTarget, mobileTab->m_tcNavigatedURL))
					mobileTab->InvokeEngineEventLoad(tcTarget, EEID_DOCUMENTCOMPLETE);
				break;
			case NM_PIE_NAVIGATECOMPLETE:
				if (pnmHTML->szTarget)
					mbstowcs(tcTarget, (LPSTR)pnmHTML->szTarget, MAX_URL);
				if (tcTarget)
					mobileTab->InvokeEngineEventLoad(tcTarget, EEID_NAVIGATECOMPLETE);

				break;
			case NM_PIE_KEYSTATE:
			case NM_PIE_ALPHAKEYSTATE:
				//  Not Used
				break;

			}
		}

		lResult = DefWindowProc(hwnd, uMsg, wParam, lParam);
	}

	return lResult;
}

DWORD WINAPI CIEBrowserEngine::NavigationTimeoutThread( LPVOID lpParameter )
{
    CIEBrowserEngine* pIEEng = reinterpret_cast<CIEBrowserEngine*>(lpParameter);
    DWORD dwWaitResult;

    bool flag=false;
    HWND authwindowhandle;
    if (pIEEng->m_dwNavigationTimeout != 0)
    {
        LOG(TRACE) + "Mobile NavThread Started\n";

        	do
        	{

			dwWaitResult = WaitForSingleObject(pIEEng->m_hNavigated, pIEEng->m_dwNavigationTimeout);

			switch (dwWaitResult)
			{
				// Event object was signaled
				case WAIT_OBJECT_0:
					//
					// TODO: Read from the shared buffer
					//
					LOG(INFO) + "NavigationTimeoutThread:Event object was signaled\n";

					CloseHandle(pIEEng->m_hNavigated);
					pIEEng->m_hNavigated = NULL;
					flag=false;
					break;
				case WAIT_TIMEOUT:
					//
					// TODO: Read from the shared buffer
					//
					LOG(INFO) + "NavigationTimeoutThread:timeout\n";

					HWND currentForeGroundWindowHandle;
					currentForeGroundWindowHandle = GetForegroundWindow();
					wchar_t szBuf[200];
					if(currentForeGroundWindowHandle!=NULL)
					{
					GetWindowText(currentForeGroundWindowHandle,szBuf,199);
					LOG(INFO) + szBuf;
					}

					authwindowhandle = FindWindow(NULL,L"Enter Network Password");

					if(authwindowhandle)
					{
					LOG(INFO) + "Authentication window present";
					LOG(INFO) + "NavigationTimeoutThread:Authentication popup\n";
					flag=true;
					break;
					}
					else
					{
					flag=false;
					LOG(INFO) + "NavigationTimeoutThread:Navigation Timed out\n";
					LOG(INFO) + "Authentication window not present";
					}
					pIEEng->StopOnTab(0);

					CloseHandle(pIEEng->m_hNavigated);
					pIEEng->m_hNavigated = NULL;
					SendMessage(pIEEng->m_parentHWND, WM_BROWSER_ONNAVIGATIONTIMEOUT,
					(WPARAM)pIEEng->m_tabID, (LPARAM)_tcsdup(pIEEng->m_tcNavigatedURL));

					break;

				// An error occurred
				default:
					LOG(INFO) + "Wait error  GetLastError()=\n"+ GetLastError();
					flag=false;
					return 0;
			}

			 LOG(TRACE) + "NavThread Ended\n";
        	}while(flag);
    }

	return 0;
}
BOOL CIEBrowserEngine::AddNewUrl(LPCTSTR urlNew)
{

	CHistoryElement* newElement = new CHistoryElement();
	newElement->pNext = NULL;
	newElement->pPrev = NULL;
	newElement->tcURL = new TCHAR[wcslen(urlNew)+1];
	wcscpy(newElement->tcURL, urlNew);

	//  Base Case, there is no current URL History
	if (m_urlList == NULL)
	{
		//  Start the History List
		m_urlList = newElement;
		m_currentPage = newElement;
	}
	else
	{
		//  There is already at least one item in the history
		//  Check we're not trying to add the same item to the history
		//  twice (Reload)
		if(!wcscmp(m_currentPage->tcURL, urlNew))
		{
			LOG(INFO) + "\nDRD Check we're not trying to add the same item to the history twice";
			delete[] newElement->tcURL;
			delete newElement;
			return FALSE;
		}

		//  Check the History hasn't grown too large
		//  Assume the Maximum history size is sensible, suggest a value of 50
		if (BackListSize() >= MAX_HISTORY && MAX_HISTORY > 2)
		{
			//  History will be too large after the next element is added
			//  Remove the first element in the history list and free the memory
			CHistoryElement* firstElement = m_urlList;
			m_urlList = m_urlList->pNext;
			m_urlList->pPrev = NULL;
			delete[] firstElement->tcURL;
			delete firstElement;
		}

		//  Delete all history items FORWARD of the currentPage
		DeleteCascade(m_currentPage->pNext);

		//  Add the new history item to the List
		m_currentPage->pNext = newElement;
		newElement->pPrev = m_currentPage;
		m_currentPage = newElement;
	}
	return TRUE;
}

void CIEBrowserEngine::DeleteCascade(CHistoryElement* fromThisElementOn)
{
	CHistoryElement* deletingElement = fromThisElementOn;
	while (deletingElement != NULL)
	{
		delete[] deletingElement->tcURL;
		deletingElement->tcURL = NULL;
		CHistoryElement* nextElement = deletingElement->pNext;
		delete deletingElement;
		deletingElement = nextElement;
	}
}

LRESULT  CIEBrowserEngine::GetPreviousUrl(LPTSTR tcURL)
{

	//  Check to see we can go back this many pages
	CHistoryElement* tempHistoryElement = m_currentPage;
	if(tempHistoryElement != NULL && tempHistoryElement->pPrev != NULL)
	{
		//  We can go to the previous page
		//  Go back another item in the history
		tempHistoryElement = tempHistoryElement->pPrev;

			m_currentPage = tempHistoryElement;
			_tcscpy(tcURL,m_currentPage->tcURL);
			return S_OK;

	}

	//  If we exit the While loop we were not able to go back the
	//  specified number of places
	return S_FALSE;
}

UINT CIEBrowserEngine::BackListSize()
{
	UINT iHistoryCounter = 1;
	CHistoryElement* tempHistoryElement = m_currentPage;
	while (tempHistoryElement != NULL && tempHistoryElement->pPrev != NULL)
	{
		//  We can go back
		iHistoryCounter++;
		tempHistoryElement = tempHistoryElement->pPrev;
	}
	return iHistoryCounter;
}
int CIEBrowserEngine::GetTextZoomOnTab(UINT iTab)
{
	return m_textZoomValue;
}
BOOL CIEBrowserEngine::ZoomTextOnTab(int nZoom, UINT iTab)
{
	m_textZoomValue = nZoom;
	BOOL bRetVal = PostMessage(m_hwndTabHTML, DTM_ZOOMLEVEL, 0,
								(LPARAM)(DWORD) nZoom);

	if (bRetVal)
	{
		//m_dwCurrentTextZoomLevel = dwZoomLevel;
		return S_OK;
	}
	else
		return S_FALSE;
}

#define  PB_ENGINE_IE_MOBILE

DWORD WINAPI CIEBrowserEngine::RegisterWndProcThread(LPVOID lpParameter)
{
    //  We are passed a pointer to the engine we are interested in.
    CIEBrowserEngine* pEngine = (CIEBrowserEngine*)lpParameter;

    //  The window tree appears as follows on CE:
    //  +--m_htmlHWND
    //     |
    //     +--child of m_htmlHWND
    //        |
    //        +--child which receives Windows Messages

    //  The window tree appears as follows on WM:
    //  +--m_htmlHWND
    //     |
    //     +--child of m_htmlHWND which receives Windows Messages

    //  Obtain the created HTML HWND
    HWND hwndHTML = NULL;
    HWND hwndHTMLMessageWindow = NULL;

    while (hwndHTMLMessageWindow == NULL)
    {
        hwndHTML = pEngine->GetHTMLWND(0);

        if (hwndHTML != NULL)
        {
            hwndHTMLMessageWindow = GetWindow(hwndHTML, GW_CHILD);
        }

        //  Failed to find the desired child window, take a short nap before
        //  trying again as the window is still creating.
        Sleep(100);
    }

    PostMessage(rho_wmimpl_get_mainwnd(), PB_ONTOPMOSTWINDOW,(LPARAM)0, (WPARAM)hwndHTMLMessageWindow);

    return 0;
}


text:
// Load configuration
var cfg = require("../config");

exports.createTestTableForIssue106 = function (test) {
  test.expect(3);

  var
    conn = cfg.mysql_libmysqlclient.createConnectionSync(cfg.host, cfg.user, cfg.password, cfg.database),
    res,
    tables;

  conn.querySync("DROP TABLE IF EXISTS " + cfg.test_table + ";");
  conn.querySync("CREATE TABLE " + cfg.test_table +
    "(`id` int(11) NOT NULL," +
    " `value` varchar(128)) " + cfg.store_engine + ";");
  res = conn.querySync("SHOW TABLES");
  tables = res.fetchAllSync();

  test.ok(res.fieldCount === 1, "SHOW TABLES result field count === 1");
  test.ok(tables.some(function (r) {
    return r['Tables_in_' + cfg.database] === cfg.test_table;
  }), "Find the test_table in results");

  res = conn.querySync("INSERT INTO " + cfg.test_table +
                   " (`id`, `value`)" +
                   " VALUES (1, 'one'), (2, 'two'), (3, 'three'), (4, 'four');");
  test.ok(res === true, "conn.querySync('INSERT INTO test_table ...')");

  conn.closeSync();

  test.done();
};

exports.issue106 = function (test) {
  test.expect(10);

  var
    conn = cfg.mysql_libmysqlclient.createConnectionSync(cfg.host, cfg.user, cfg.password, cfg.database),
    queryTemplate = "SELECT * FROM " + cfg.test_table + " WHERE `value` = '%'",
    queries = [];

  queries.push(queryTemplate.replace('%', 'one'));
  queries.push(queryTemplate.replace('%', 'three'));

  conn.query(queries.join(' UNION ALL '), function (err, res) {
    test.ok(res instanceof cfg.mysql_bindings.MysqlResult, "Result is defined");
    test.ok(err === null, "Error object is not present");

    res.fetchAll(function (err, rows) {
      test.ok(res instanceof cfg.mysql_bindings.MysqlResult, "Result is defined");
      test.ok(err === null, "Error object is not present");

      test.deepEqual(rows, [ { id: 1, value: 'one' }, { id: 3, value: 'three' } ]);

      conn.query(queries.join(' UNION ALL '), function (err, res) {
        test.ok(res instanceof cfg.mysql_bindings.MysqlResult, "Result is defined");
        test.ok(err === null, "Error object is not present");

        res.fetchAll(function (err, rows) {
          test.ok(res instanceof cfg.mysql_bindings.MysqlResult, "Result is defined");
          test.ok(err === null, "Error object is not present");

          test.deepEqual(rows, [ { id: 1, value: 'one' }, { id: 3, value: 'three' } ]);

          conn.closeSync();

          test.done();
        });
      });
    });
  });
};


text:
const assert = require('assert');
import React from 'react';
import { expect } from 'chai';
import { mount, shallow } from 'enzyme';

import Sample from '../app/components/Sample/index';

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});

describe('<Sample />', () => {
  it('renders Sample Component', () => {
    const wrapper = mount(<Sample />);
    expect(wrapper.contains(
Hello World!
)).to.equal(true);
  });
});