text:
package de.huberlin.wbi.cfjava.parse;

import static org.junit.Assert.*;

import java.io.IOException;
import java.io.StringReader;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.junit.Test;

import de.huberlin.wbi.cfjava.asyntax.App;
import de.huberlin.wbi.cfjava.asyntax.Cnd;
import de.huberlin.wbi.cfjava.asyntax.Expr;
import de.huberlin.wbi.cfjava.asyntax.ForBody;
import de.huberlin.wbi.cfjava.asyntax.InParam;
import de.huberlin.wbi.cfjava.asyntax.Lam;
import de.huberlin.wbi.cfjava.asyntax.Lang;
import de.huberlin.wbi.cfjava.asyntax.Name;
import de.huberlin.wbi.cfjava.asyntax.NatBody;
import de.huberlin.wbi.cfjava.asyntax.Param;
import de.huberlin.wbi.cfjava.asyntax.Sign;
import de.huberlin.wbi.cfjava.asyntax.Str;
import de.huberlin.wbi.cfjava.asyntax.Var;
import de.huberlin.wbi.cfjava.data.Alist;
import de.huberlin.wbi.cfjava.data.Amap;

public class WorkflowListenerTest {

	@SuppressWarnings("static-method")
	@Test
	public void nilShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "nil;";

		query = new Alist<>();
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void varShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "blub;";

		query = new Alist<Expr>().add( new Var( 1, "blub" ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void multiElementCompoundExprShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "bla blub;";

		query = new Alist<Expr>().add( new Var( 1, "blub" ) ).add( new Var( 1, "bla" ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void multipleQueriesShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "bla; blub;";

		query = new Alist<Expr>().add( new Var( 1, "blub" ) ).add( new Var( 1, "bla" ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void strLitShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "\"bla\";";

		query = new Alist<Expr>().add( new Str( "bla" ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void intLitShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "5;";

		query = new Alist<Expr>().add( new Str( "5" ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void cndShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;
		Alist<Expr> xc, xt, xe;

		script = "if nil then \"bla\" else \"blub\" end;";

		xc = new Alist<>();
		xt = new Alist<Expr>().add( new Str( "bla" ) );
		xe = new Alist<Expr>().add( new Str( "blub" ) );

		query = new Alist<Expr>().add( new Cnd( 1, xc, xt, xe ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void appShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "f();";

		query = new Alist<Expr>().add( new App( 1, 1, new Var( 1, "f" ), new Amap<String, Alist<Expr>>() ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void appWithVarArgShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "f( x: x );";

		query = new Alist<Expr>().add( new App( 1, 1, new Var( 1, "f" ), new Amap<String, Alist<Expr>>().put( "x", new Alist<Expr>().add( new Var( 1, "x" ) ) ) ) );
		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void appWithVarAndStrArgShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "f( x: x, y: \"y\" );";

		query = new Alist<Expr>()
			.add( new App(
				1,
				1,
				new Var( 1, "f" ),
				new Amap<String, Alist<Expr>>()
					.put( "x", new Alist<Expr>().add( new Var( 1, "x" ) ) )
					.put( "y", new Alist<Expr>().add( new Str( "y" ) ) ) ) );

		rho = new Amap<>();
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void assignShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "x = \"x\";";

		query = new Alist<>();
		rho = new Amap<String, Alist<Expr>>().put( "x", new Alist<Expr>().add( new Str( "x" ) ) );
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void assignMultipleValuesShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "x y = f();";

		query = new Alist<>();
		rho = new Amap<String, Alist<Expr>>()
			.put( "x", new Alist<Expr>().add( new App( 1, 1, new Var( 1, "f" ), new Amap<String, Alist<Expr>>() ) ) )
			.put( "y", new Alist<Expr>().add( new App( 1, 2, new Var( 1, "f" ), new Amap<String, Alist<Expr>>() ) ) );
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test( expected=ParseException.class )
	public void assignMultipleValuesToStrShouldThrowPeTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;

		script = "x y = \"blub\";";

		query = new Alist<>();
		rho = new Amap<String, Alist<Expr>>()
			.put( "x", new Alist<Expr>().add( new App( 1, 1, new Var( 1, "f" ), new Amap<String, Alist<Expr>>() ) ) )
			.put( "y", new Alist<Expr>().add( new App( 1, 2, new Var( 1, "f" ), new Amap<String, Alist<Expr>>() ) ) );
		gamma = new Amap<>();

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void nativeDeftaskShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;
		Lam lam;
		Sign sign;
		NatBody body;

		script = "deftask f( out : ) { out = \"A\"; }";

		sign = new Sign(
			new Alist<Param>().add( new Param( new Name( "out", false ), false ) ),
			new Alist<InParam>() );
		body = new NatBody(
			new Amap<String, Alist<Expr>>()
				.put( "out", new Alist<Expr>().add( new Str( "A" ) ) ) );
		lam = new Lam( 1, "f", sign, body );

		query = new Alist<>();
		rho = new Amap<>();
		gamma = new Amap<String, Lam>().put( "f", lam );

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}

	@SuppressWarnings("static-method")
	@Test
	public void foreignDeftaskShouldBeRecognizedTest() throws IOException {

		ANTLRInputStream input;
		CuneiformLexer lexer;
		CuneiformParser parser;
		CommonTokenStream tokenStream;
		ParseTree tree;
		WorkflowListener asv;
		String script;
		Alist<Expr> query;
		Amap<String, Alist<Expr>> rho;
		Amap<String, Lam> gamma;
		ParseTreeWalker walker;
		Lam lam;
		Sign sign;
		ForBody body;

		script = "deftask f( out : )in bash *{out=\"A\"}*";

		sign = new Sign(
			new Alist<Param>().add( new Param( new Name( "out", false ), false ) ),
			new Alist<InParam>() );
		body = new ForBody( Lang.BASH, "out=\"A\"" );
		lam = new Lam( 1, "f", sign, body );

		query = new Alist<>();
		rho = new Amap<>();
		gamma = new Amap<String, Lam>().put( "f", lam );

		try( StringReader reader = new StringReader( script ) ) {

			input = new ANTLRInputStream( reader );
			lexer = new CuneiformLexer( input );
			tokenStream = new CommonTokenStream( lexer );
			parser = new CuneiformParser( tokenStream );
			asv = new WorkflowListener();
			walker = new ParseTreeWalker();

			tree = parser.script();

			assertEquals( 0, parser.getNumberOfSyntaxErrors() );

			walker.walk( asv, tree );

			assertEquals( query, asv.getQuery() );
			assertEquals( rho, asv.getRho() );
			assertEquals( gamma, asv.getGamma() );
		}
	}
}


text:
layout: post
title:  "Build your own Hue Lights sensor"
date:   2018-02-08
comments: true
tags:
    - DIY
    - electronics
    - PIR
    - Hue
---
A few weeks ago I started playing with electronics. It was on a Hack Week at work, and we build a sensor for detecting when our pingpong table is free. You can read more about it in [this post][hackweek] I wrote.

I have never played with electronics before, and I got completely hooked! It's so fun to build stuff and see it working. After that Hack Week, I came out with a lot of ideas for projects.

As a first solo project, I decided to build something simple but useful. I have a set of Philips Hue lights at home. One of them is located in the hall, and I though it would be nice to turn it on automatically when someone enters home or is in the entrance getting ready to leave.

I rescued an old Raspberry Pi I bought in 2013 that has been  collecting dust since then. The only extra piece of hardware I needed for this was a PIR motion sensor.

A Passive Infrared Sensor (PIR sensor) is an electronic sensor that measures infrared (IR) light radiating from objects in its field of view. It is a very simple yet interesting sensor, since there are many variables that can affect its behaviour. This is a schema of a general PIR sensor.

![PIR Sensor schematics](/images/build_your_hue_sensor/PIR_Schematics.png)

If you're interested on the details, I _highly_ recommend you to read through this pages about [how PIR sensors work][PIR-working] (**DO IT!**).

For this project, just because I wanted to understand the different modes of the sensor, I decided to control the delay time via hardware.

To start testing, I connected the PIR sensor to the RPi and started observing the outputs. I decided that what I needed was "Repeatable trigger" mode. This is, whenever it detects movement, the delay time will restart. With this setting and slightly manipulating the time delay screw, the sensor will emit "True" whenever there is movement. It will do this until about one minute after the last movement is detected.

The connections to the Raspberry Pi are very simple. Depending on the model the GPIO pins may change, but you only need power, ground and a free digital pin to be configured as input.

The code running on the Pi only needs to read the sensor's input continuously and turn on/off the lights accordingly. Philips
Hue has a [really nice and simple API][HUE] that eases this task.

[Here][code] you can find the code I used in this project.

Also, if by any change you have access to a 3D printer, I designed a small box to hold and protect the sensor. Find it [here][thing].

#### Result
For being that simple, it's amazing how well it works :smile:. Here you can find a bunch of pictures and a video of the process. Hope this post is motivating, go and build!

![Box sensor](/images/build_your_hue_sensor/box_sensor.jpg)
![Whole setup](/images/build_your_hue_sensor/whole_setup.jpg)
![Sensor placed](/images/build_your_hue_sensor/placed.jpg)

<video controls="controls" width="100%" height="auto">
  <source type="video/mp4" src="/images/build_your_hue_sensor/working.mp4"></source>
  <source type="video/webm" src="/images/build_your_hue_sensor/working.mp4"></source>

Your browser does not support the video element.

</video>

[hackweek]: https://medium.com/izettle-engineering/hack-weeks-at-izettle-21217a12cec5
[PIR]: https://en.wikipedia.org/wiki/Passive_infrared_sensor
[PIR-working]: https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/how-pirs-work
[HUE]: https://www.developers.meethue.com/
[PIR_case]: https://www.thingiverse.com/thing:2766940
[code]: https://github.com/guillermo-carrasco/auto-hue
[thing]: https://www.thingiverse.com/thing:2766940

redpajama_set_name: RedPajamaGithub


text:
using std::atomic;
using std::lock_guard;
using std::string;
using std::thread;
using std::unordered_map;
using std::vector;

namespace kudu {
namespace consensus {

static constexpr const int64_t kInitialTerm = 1;

using LockTable = unordered_map<string, string>;

// Multithreaded stress tests for the cmeta manager.
class ConsensusMetadataManagerStressTest : public KuduTest {
 public:
  ConsensusMetadataManagerStressTest()
      : rng_(SeedRandom()),
        fs_manager_(env_, FsManagerOpts(GetTestPath("fs_root"))),
        cmeta_manager_(new ConsensusMetadataManager(&fs_manager_)) {
  }

  void SetUp() override {
    KuduTest::SetUp();
    ASSERT_OK(fs_manager_.CreateInitialFileSystemLayout());
    ASSERT_OK(fs_manager_.Open());

    // Initialize test configuration.
    config_.set_opid_index(kInvalidOpIdIndex);
    RaftPeerPB* peer = config_.add_peers();
    peer->set_permanent_uuid(fs_manager_.uuid());
    peer->set_member_type(RaftPeerPB::VOTER);
  }

 protected:
  enum OpType {
    kCreate,
    kLoad,
    kDelete,
    kNumOpTypes, // Must come last.
  };

  ThreadSafeRandom rng_;
  FsManager fs_manager_;
  scoped_refptr<ConsensusMetadataManager> cmeta_manager_;
  RaftConfigPB config_;

  // Lock used by tests.
  simple_spinlock lock_;
};

// Concurrency test to check whether TSAN will flag unsafe concurrent
// operations for simultaneous access to the cmeta manager by different threads
// on different tablet ids. For a given tablet id, a lock table is used as
// external synchronization to ensure exclusive access by a single thread.
TEST_F(ConsensusMetadataManagerStressTest, CreateLoadDeleteTSANTest) {
  static const int kNumTablets = 26;
  static const int kNumThreads = 8;
  static const int kNumOpsPerThread = 1000;

  // Set of tablets we are operating on.
  vector<string> tablet_ids;

  // Map of tablet_id -> cmeta existence.
  unordered_map<string, bool> tablet_cmeta_exists;

  // Each entry in 'lock_table' protects each value of
  // 'tablet_cmeta_exists[tablet_id]'. We never resize 'tablet_cmeta_exists'.
  LockTable lock_table;

  for (int i = 0; i < kNumTablets; i++) {
    string tablet_id = string(1, 'a' + i);
    // None of the cmetas have been created yet.
    InsertOrDie(&tablet_cmeta_exists, tablet_id, false);
    tablet_ids.push_back(std::move(tablet_id));
  }

  // Eventually exit if the test hangs.
  alarm(60);
  auto c = MakeScopedCleanup([&] { alarm(0); });

  atomic<int64_t> ops_performed(0);
  Barrier barrier(kNumThreads);
  vector<thread> threads;
  for (int thread_num = 0; thread_num < kNumThreads; thread_num++) {
    threads.emplace_back([&] {
      barrier.Wait();
      for (int op_num = 0; op_num < kNumOpsPerThread; op_num++) {
        const string& tablet_id = tablet_ids[rng_.Uniform(kNumTablets)];
        auto unlocker = MakeScopedCleanup([&] {
          lock_guard<simple_spinlock> l(lock_);
          CHECK(lock_table.erase(tablet_id));
        });
        // Acquire lock in lock table or bail.
        {
          // 'lock_' protects 'lock_table'.
          lock_guard<simple_spinlock> l(lock_);
          if (ContainsKey(lock_table, tablet_id)) {
            // Another thread has access to this tablet id. Bail.
            unlocker.cancel(); // Don't unlock what we didn't lock.
            continue;
          }
          InsertOrDie(&lock_table, tablet_id, "lock for test");
        }
        OpType type = static_cast<OpType>(rng_.Uniform(kNumOpTypes));
        switch (type) {
          case kCreate: {
            Status s = cmeta_manager_->Create(tablet_id, config_, kInitialTerm);
            if (tablet_cmeta_exists[tablet_id]) {
              CHECK(s.IsAlreadyPresent()) << s.ToString();
            } else {
              CHECK(s.ok()) << s.ToString();
              ops_performed.fetch_add(1, std::memory_order_relaxed);
            }
            tablet_cmeta_exists[tablet_id] = true;
            break;
          }
          case kLoad: {
            scoped_refptr<ConsensusMetadata> cmeta;
            Status s = cmeta_manager_->Load(tablet_id, &cmeta);
            if (tablet_cmeta_exists[tablet_id]) {
              CHECK(s.ok()) << s.ToString();
              ops_performed.fetch_add(1, std::memory_order_relaxed);
            } else {
              CHECK(s.IsNotFound()) << tablet_id << ": " << s.ToString();
            }
            // Load() does not change 'tablet_cmeta_exists' status.
            break;
          }
          case kDelete: {
            Status s = cmeta_manager_->Delete(tablet_id);
            if (tablet_cmeta_exists[tablet_id]) {
              CHECK(s.ok()) << s.ToString();
              ops_performed.fetch_add(1, std::memory_order_relaxed);
            } else {
              CHECK(s.IsNotFound()) << s.ToString();
            }
            tablet_cmeta_exists[tablet_id] = false;
            break;
          }
          default: LOG(FATAL) << type; break;
        }
      }
    });
  }

  for (int thread_num = 0; thread_num < kNumThreads; thread_num++) {
    threads[thread_num].join();
  }

  LOG(INFO) << "Ops performed: " << ops_performed.load(std::memory_order_relaxed);
}

} // namespace consensus
} // namespace kudu


text:
angular-admin-template
======================

This project aim to implement an admin template using express and angular framework. It's based on the AdminLTE project.


text:
from django.conf import settings

settings.SIGNALS_IMPORTED=True


text:
namespace remoting {

// Remoting host events reporter.
// Configured with the delegate for actual events delivery.
class HostEventReporterImpl : public HostEventReporter,
                              public HostStatusObserver {
 public:
  class Delegate {
   public:
    Delegate();
    Delegate(const Delegate& other) = delete;
    Delegate& operator=(const Delegate& other) = delete;
    virtual ~Delegate();

    // API to enqueue event. Must be implemented by subclass.
    virtual void EnqueueEvent(::ash::reporting::CRDRecord record) = 0;
  };

  HostEventReporterImpl(scoped_refptr<HostStatusMonitor> monitor,
                        std::unique_ptr<Delegate> delegate);
  HostEventReporterImpl(const HostEventReporterImpl& other) = delete;
  HostEventReporterImpl& operator=(const HostEventReporterImpl& other) = delete;
  ~HostEventReporterImpl() override;

  // HostStatusObserver implementation.  These methods will be called from the
  // network thread.
  void OnClientAccessDenied(const std::string& signaling_id) override;
  void OnClientAuthenticated(const std::string& signaling_id) override;
  void OnClientConnected(const std::string& signaling_id) override;
  void OnClientDisconnected(const std::string& signaling_id) override;
  void OnClientRouteChange(const std::string& signaling_id,
                           const std::string& channel_name,
                           const protocol::TransportRoute& route) override;
  void OnHostStarted(const std::string& owner_email) override;
  void OnHostShutdown() override;

 private:
  void ReportEvent(::ash::reporting::CRDRecord record);

  // Host user email.
  // Empty before the first call to ReportStart or after ReportStop.
  std::string host_user_;

  // Connection state (set piece by piece).
  std::string host_ip_;
  std::string client_ip_;
  std::string session_id_;

  // Event enqueueing delegate.
  std::unique_ptr<Delegate> delegate_;

  // Status monitor to observe.
  scoped_refptr<HostStatusMonitor> monitor_;
};

}  // namespace remoting

#endif  // REMOTING_HOST_CHROMEOS_HOST_EVENT_REPORTER_IMPL_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Xerces-C++: DOMDocumentType Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

Alphabetical List

Class List

Class Hierarchy

Class Members

DOMDocumentType Class Reference
Each DOMDocument has a doctype attribute whose value is either null or a DOMDocumentType object.
More...

Inheritance diagram for DOMDocumentType:

<map name="DOMDocumentType_map">
<area href="classDOMNode.html" alt="DOMNode" shape="rect" coords="0,0,126,24">
</map>

List of all members.

Public Member Functions

Destructor

virtual 	~DOMDocumentType ()

 	Destructor.

Functions introduced in DOM Level 1

virtual const XMLCh * 	getName () const =0

 	The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

virtual DOMNamedNodeMap * 	getEntities () const =0

 	A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

virtual DOMNamedNodeMap * 	getNotations () const =0

 	A DOMNamedNodeMap containing the notations declared in the DTD.

Functions introduced in DOM Level 2.

virtual const XMLCh * 	getPublicId () const =0

 	Get the public identifier of the external subset.

virtual const XMLCh * 	getSystemId () const =0

 	Get the system identifier of the external subset.

virtual const XMLCh * 	getInternalSubset () const =0

 	The internal subset as a string, or null if there is none.

Protected Member Functions

Hidden constructors

 	DOMDocumentType ()

Detailed Description

Each DOMDocument has a doctype attribute whose value is either null or a DOMDocumentType object.

The DOMDocumentType interface in the DOM Core provides an interface to the list of entities that are defined for the document, and little else because the effect of namespaces and the various XML schema efforts on DTD representation are not clearly understood as of this writing.

The DOM Level 2 doesn't support editing DOMDocumentType nodes.

See also the Document Object Model (DOM) Level 2 Core Specification.

Since:

DOM Level 1

Constructor & Destructor Documentation

          DOMDocumentType::DOMDocumentType
          (

           )
           [protected]

          virtual DOMDocumentType::~DOMDocumentType
          (

           )
           [virtual]

Destructor.

Member Function Documentation

          virtual const XMLCh* DOMDocumentType::getName
          (

           )
           const [pure virtual]

The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

Since:

DOM Level 1

          virtual DOMNamedNodeMap* DOMDocumentType::getEntities
          (

           )
           const [pure virtual]

A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

Parameter entities are not contained. Duplicates are discarded. For example in: <!DOCTYPE

 ex SYSTEM "ex.dtd" [ <!ENTITY foo "foo"> <!ENTITY bar

 "bar"> <!ENTITY bar "bar2"> <!ENTITY % baz "baz">

 ]> <ex/>

 the interface provides access to foo and the first declaration of bar but not the second declaration of bar or baz. Every node in this map also implements the DOMEntity interface.

The DOM Level 2 does not support editing entities, therefore entities cannot be altered in any way.

Since:

DOM Level 1

          virtual DOMNamedNodeMap* DOMDocumentType::getNotations
          (

           )
           const [pure virtual]

A DOMNamedNodeMap containing the notations declared in the DTD.

Duplicates are discarded. Every node in this map also implements the DOMNotation interface.

The DOM Level 2 does not support editing notations, therefore notations cannot be altered in any way.

Since:

DOM Level 1

          virtual const XMLCh* DOMDocumentType::getPublicId
          (

           )
           const [pure virtual]

Get the public identifier of the external subset.

Returns:

The public identifier of the external subset.

Since:

DOM Level 2

          virtual const XMLCh* DOMDocumentType::getSystemId
          (

           )
           const [pure virtual]

Get the system identifier of the external subset.

Returns:

The system identifier of the external subset.

Since:

DOM Level 2

          virtual const XMLCh* DOMDocumentType::getInternalSubset
          (

           )
           const [pure virtual]

The internal subset as a string, or null if there is none.

This is does not contain the delimiting square brackets.The actual content returned depends on how much information is available to the implementation. This may vary depending on various parameters, including the XML processor used to build the document.

Returns:

The internal subset as a string.

Since:

DOM Level 2

The documentation for this class was generated from the following file:

DOMDocumentType.hpp

<address style="text-align: right;">Generated on Wed Apr 21 17:55:49 2010 for Xerces-C++ by

 1.5.6 </address>


text:
package io.crate.analyze;

import io.crate.common.Booleans;
import org.elasticsearch.cluster.metadata.AutoExpandReplicas;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.settings.Settings;

import java.util.Objects;
import java.util.regex.Pattern;

public class NumberOfReplicas {

    public static final String NUMBER_OF_REPLICAS = IndexMetadata.SETTING_NUMBER_OF_REPLICAS;
    public static final String AUTO_EXPAND_REPLICAS = IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS;

    private static final Pattern EXPAND_REPLICA_PATTERN = Pattern.compile("\\d+\\-(all|\\d+)");
    private final String esSettingKey;
    private final String esSettingsValue;

    public NumberOfReplicas(Integer numReplicas) {
        this.esSettingKey = NUMBER_OF_REPLICAS;
        this.esSettingsValue = numReplicas.toString();
    }

    public NumberOfReplicas(String numReplicas) {
        assert numReplicas != null : "numReplicas must not be null";
        validateExpandReplicaSetting(numReplicas);

        this.esSettingKey = AUTO_EXPAND_REPLICAS;
        this.esSettingsValue = numReplicas;
    }

    private static void validateExpandReplicaSetting(String replicas) {
        if (!EXPAND_REPLICA_PATTERN.matcher(replicas).matches()) {
            throw new IllegalArgumentException("The \"number_of_replicas\" range \"" + replicas + "\" isn't valid");
        }
    }

    public String esSettingKey() {
        return esSettingKey;
    }

    public String esSettingValue() {
        return esSettingsValue;
    }

    public static String fromSettings(Settings settings) {
        String numberOfReplicas;
        String autoExpandReplicas = settings.get(AUTO_EXPAND_REPLICAS);
        if (autoExpandReplicas != null && !Booleans.isFalse(autoExpandReplicas)) {
            validateExpandReplicaSetting(autoExpandReplicas);
            numberOfReplicas = autoExpandReplicas;
        } else {
            numberOfReplicas = Objects.requireNonNullElse(settings.get(NUMBER_OF_REPLICAS), "1");
        }
        return numberOfReplicas;
    }

    public static int fromSettings(Settings settings, int dataNodeCount) {
        AutoExpandReplicas autoExpandReplicas = IndexMetadata.INDEX_AUTO_EXPAND_REPLICAS_SETTING.get(settings);
        if (autoExpandReplicas.isEnabled()) {
            final int min = autoExpandReplicas.getMinReplicas();
            final int max = autoExpandReplicas.getMaxReplicas(dataNodeCount);
            int numberOfReplicas = dataNodeCount - 1;
            if (numberOfReplicas < min) {
                return min;
            } else if (numberOfReplicas > max) {
                return max;
            }
        }
        return IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.get(settings);
    }
}


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "/Users/vitormakoto/Developer/SMAA-OPENGL/smaa-opengl/main.cpp" "/Users/vitormakoto/Developer/SMAA-OPENGL/smaa-opengl/cmake/CMakeFiles/smaa.dir/main.cpp.o"
  )
set(CMAKE_CXX_COMPILER_ID "Clang")

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
  "../src"
  "../external/include"
  "/usr/local/include"
  "/usr/local/Cellar/glfw3/3.1.1/include"
  )
set(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})


text:
import { async, ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';

import { ProjectsComponent } from './projects.component';
import { Post } from '../shared/classes/post';
import { ActivatedRoute } from '@angular/router';
import { PaginationConfig, PaginationModule } from 'ngx-bootstrap';
import { FormsModule } from '@angular/forms';
import { BlogPostsService } from '../shared/services/blog-posts.service';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

describe('ProjectsComponent', () => {
  let component: ProjectsComponent;
  let fixture: ComponentFixture<ProjectsComponent>;
  const mockRouter = {
    snapshot: {},
    queryParams: {
      subscribe: () => {
        return Observable.of({
          params: {
            page: 69
          }
        });
      }
    }
  };
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProjectsComponent],
      imports: [BrowserAnimationsModule, PaginationModule, FormsModule, RouterTestingModule],
      providers: [
        BlogPostsService,
        HttpClient,
        HttpHandler,
        PaginationConfig,
        { provide: ActivatedRoute, useValue: mockRouter }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ProjectsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should show jumbotrons for each blog post', fakeAsync(() => {

    component.projects = [
      new Post({
        title: 'TestArticle 1 Title',
        description: 'test article 1 despcription',
        author: 'test author1',
        image: { src: 'assets/images/woman-with-fidget-spinner.jpeg', name: 'woman with fidget spinner' },
        content: '
test content1
',
        postType: 'projectPost'
      }),
      new Post({
        title: 'TestArticle 2 Title',
        description: 'test article 2 despcription',
        author: 'test author2',
        image: { src: 'assets/images/woman-with-fidget-spinner.jpeg', name: 'woman with fidget spinner' },
        content: '
test content2
',
        postType: 'projectPost'
      }),
      new Post({
        title: 'TestArticle 3 Title',
        description: 'test article 3 despcription',
        author: 'test author3',
        image: { src: 'assets/images/woman-with-fidget-spinner.jpeg', name: 'woman with fidget spinner' },
        content: '
test content3
',
        postType: 'projectPost'
      })
    ];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const postDebugElements = fixture.debugElement.queryAll(By.css('.card'));

    expect(postDebugElements.length).toEqual(3);
    expect(postDebugElements[0].nativeElement.children[0].querySelector('h4').innerHTML).toEqual('TestArticle 1 Title');
    expect(postDebugElements[1].nativeElement.children[0].querySelector('h4').innerHTML).toEqual('TestArticle 2 Title');
    expect(postDebugElements[2].nativeElement.children[0].querySelector('h4').innerHTML).toEqual('TestArticle 3 Title');
  }));

  it('should have a method switchPage that sets the current page and calls route.navigate and scrolls to the top of the window', () => {
    const navigateSpy = spyOn((<any>component).router, 'navigate');
    const windowSpy = spyOn(window, 'scrollTo');

    component.switchPage({ page: 7 });
    expect(component.currentPage).toEqual(7);
    expect(navigateSpy).toHaveBeenCalled();
    expect(windowSpy).toHaveBeenCalledWith(0, 0);
  });
});


text:
set :sidekiq, -> { "#{fetch(:bundle_bin)} exec sidekiq" }

# ### sidekiqctl
# Sets the path to sidekiqctl.
set :sidekiqctl, -> { "#{fetch(:bundle_prefix)} sidekiqctl" }

# ### sidekiq_timeout
# Sets a upper limit of time a process is allowed to finish, before it is killed by sidekiqctl.
set :sidekiq_timeout, 11

# ### sidekiq_config
# Sets the path to the configuration file of sidekiq
set :sidekiq_config, -> { "#{fetch(:project_path)}/config/sidekiq.yml" }

# ### sidekiq_log
# Sets the path to the log file of sidekiq
#
# To disable logging set it to "/dev/null"
set :sidekiq_log, -> { "#{fetch(:project_path)}/log/sidekiq.log" }

# ### sidekiq_pid
# Sets the path to the pid file of a sidekiq worker
set :sidekiq_pid, -> { "#{fetch(:shared_path)}/pids/sidekiq.pid" }

# ### sidekiq_processes
# Sets the number of sidekiq processes launched
set :sidekiq_processes, 1

# ### sidekiq_concurrency
# Sets the number of sidekiq threads per process (overrides value in sidekiq.yml)
set :sidekiq_concurrency, nil

# ## Control Tasks
namespace :sidekiq do
  def for_each_process(&block)
    fetch(:sidekiq_processes).times do |idx|
      pid_file = if idx == 0
                   fetch(:sidekiq_pid)
                 else
                   "#{fetch(:sidekiq_pid)}-#{idx}"
                 end
      yield(pid_file, idx)
    end
  end

  # ### sidekiq:quiet
  desc "Quiet sidekiq (stop accepting new work)"
  task :quiet => :environment do
    comment 'Quiet sidekiq (stop accepting new work)'
    for_each_process do |pid_file, idx|
      command %{
        if [ -f #{pid_file} ] && kill -0 `cat #{pid_file}` > /dev/null 2>&1; then
          cd "#{fetch(:project_path)}"
          #{fetch(:sidekiqctl)} quiet #{pid_file}
        else
          echo 'Skip quiet command (no pid file found)'
        fi
      }.strip
    end
  end

  # ### sidekiq:stop
  desc "Stop sidekiq"
  task :stop => :environment do
    comment 'Stop sidekiq'
    for_each_process do |pid_file, idx|
      command %{
        if [ -f #{pid_file} ] && kill -0 `cat #{pid_file}`> /dev/null 2>&1; then
          cd #{fetch(:project_path)}
          #{fetch(:sidekiqctl)} stop #{pid_file} #{fetch(:sidekiq_timeout)}
        else
          echo 'Skip stopping sidekiq (no pid file found)'
        fi
      }.strip
    end
  end

  # ### sidekiq:start
  desc "Start sidekiq"
  task :start => :environment do
    comment 'Start sidekiq'
    for_each_process do |pid_file, idx|
      sidekiq_concurrency = fetch(:sidekiq_concurrency)
      concurrency_arg = if sidekiq_concurrency.nil?
                          ""
                        else
                          "-c #{sidekiq_concurrency}"
                        end
      in_path(fetch(:project_path)) do
        command %[#{fetch(:sidekiq)} -d -e #{fetch(:rails_env)} #{concurrency_arg} -C #{fetch(:sidekiq_config)} -i #{idx} -P #{pid_file} -L #{fetch(:sidekiq_log)}]
      end
    end
  end

  # ### sidekiq:restart
  desc "Restart sidekiq"
  task :restart do
    invoke :'sidekiq:stop'
    invoke :'sidekiq:start'
  end

  desc "Tail log from server"
  task :log => :environment do
    command %[tail -f #{sidekiq_log}]
  end
end


text:
<?php
namespace yiiunit\framework\web;

use yii\web\Request;
use yii\web\UrlManager;
use yiiunit\TestCase;

/**
 * @group web
 */
class UrlManagerTest extends TestCase
{
    protected function setUp()
    {
        parent::setUp();
        $this->mockApplication();
    }

    public function testCreateUrl()
    {
        // default setting with '/' as base url
        $manager = new UrlManager([
            'baseUrl' => '/',
            'scriptUrl' => '',
            'cache' => null,
        ]);
        $url = $manager->createUrl(['post/view']);
        $this->assertEquals('?r=post%2Fview', $url);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('?r=post%2Fview&id=1&title=sample+post', $url);

        // default setting with '/test/' as base url
        $manager = new UrlManager([
            'baseUrl' => '/test/',
            'scriptUrl' => '/test',
            'cache' => null,
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/test?r=post%2Fview&id=1&title=sample+post', $url);

        // pretty URL without rules
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'baseUrl' => '/',
            'scriptUrl' => '',
            'cache' => null,
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/post/view?id=1&title=sample+post', $url);
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'baseUrl' => '/test/',
            'scriptUrl' => '/test',
            'cache' => null,
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/test/post/view?id=1&title=sample+post', $url);
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'baseUrl' => '/test',
            'scriptUrl' => '/test/index.php',
            'cache' => null,
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/test/index.php/post/view?id=1&title=sample+post', $url);

        // test showScriptName
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'baseUrl' => '/test',
            'scriptUrl' => '/test/index.php',
            'showScriptName' => true,
            'cache' => null,
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/test/index.php/post/view?id=1&title=sample+post', $url);
        $url = $manager->createUrl(['/post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/test/index.php/post/view?id=1&title=sample+post', $url);
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'baseUrl' => '/test',
            'scriptUrl' => '/test/index.php',
            'showScriptName' => false,
            'cache' => null,
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/test/post/view?id=1&title=sample+post', $url);
        $url = $manager->createUrl(['/post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/test/post/view?id=1&title=sample+post', $url);

        // pretty URL with rules
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                [
                    'pattern' => 'post/<id>/<title>',
                    'route' => 'post/view',
                ],
            ],
            'baseUrl' => '/',
            'scriptUrl' => '',
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/post/1/sample+post', $url);
        $url = $manager->createUrl(['post/index', 'page' => 1]);
        $this->assertEquals('/post/index?page=1', $url);

        // rules with defaultAction
        $url = $manager->createUrl(['/post', 'page' => 1]);
        $this->assertEquals('/post?page=1', $url);

        // pretty URL with rules and suffix
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                [
                    'pattern' => 'post/<id>/<title>',
                    'route' => 'post/view',
                ],
            ],
            'baseUrl' => '/',
            'scriptUrl' => '',
            'suffix' => '.html',
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('/post/1/sample+post.html', $url);
        $url = $manager->createUrl(['post/index', 'page' => 1]);
        $this->assertEquals('/post/index.html?page=1', $url);

        // pretty URL with rules that have host info
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                [
                    'pattern' => 'post/<id>/<title>',
                    'route' => 'post/view',
                    'host' => 'http://<lang:en|fr>.example.com',
                ],
            ],
            'baseUrl' => '/test',
            'scriptUrl' => '/test',
        ]);
        $url = $manager->createUrl(['post/view', 'id' => 1, 'title' => 'sample post', 'lang' => 'en']);
        $this->assertEquals('http://en.example.com/test/post/1/sample+post', $url);
        $url = $manager->createUrl(['post/index', 'page' => 1]);
        $this->assertEquals('/test/post/index?page=1', $url);

        // create url with the same route but different params/defaults
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                [
                    'pattern' => '',
                    'route' => 'frontend/page/view',
                    'defaults' => ['slug' => 'index'],
                ],
                'page/<slug>' => 'frontend/page/view',
            ],
            'baseUrl' => '/test',
            'scriptUrl' => '/test',
        ]);
        $url = $manager->createUrl(['frontend/page/view', 'slug' => 'services']);
        $this->assertEquals('/test/page/services', $url);
        $url = $manager->createUrl(['frontend/page/view', 'slug' => 'index']);
        $this->assertEquals('/test/', $url);
    }

    /**
     * @depends testCreateUrl
     * @see https://github.com/yiisoft/yii2/issues/10935
     */
    public function testCreateUrlWithNullParams()
    {
        $manager = new UrlManager([
            'rules' => [
                '<param1>/<param2>' => 'site/index',
                '<param1>' => 'site/index',
            ],
            'enablePrettyUrl' => true,
            'scriptUrl' => '/test',

        ]);
        $this->assertEquals('/test/111', $manager->createUrl(['site/index', 'param1' => 111, 'param2' => null]));
        $this->assertEquals('/test/123', $manager->createUrl(['site/index', 'param1' => 123, 'param2' => null]));
        $this->assertEquals('/test/111/222', $manager->createUrl(['site/index', 'param1' => 111, 'param2' => 222]));
        $this->assertEquals('/test/112/222', $manager->createUrl(['site/index', 'param1' => 112, 'param2' => 222]));
    }

    /**
     * https://github.com/yiisoft/yii2/issues/6717
     */
    public function testCreateUrlWithEmptyPattern()
    {
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                '' => 'front/site/index',
            ],
            'baseUrl' => '/',
            'scriptUrl' => '',
        ]);
        $url = $manager->createUrl(['front/site/index']);
        $this->assertEquals('/', $url);
        $url = $manager->createUrl(['/front/site/index']);
        $this->assertEquals('/', $url);
        $url = $manager->createUrl(['front/site/index', 'page' => 1]);
        $this->assertEquals('/?page=1', $url);
        $url = $manager->createUrl(['/front/site/index', 'page' => 1]);
        $this->assertEquals('/?page=1', $url);

        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                '' => '/front/site/index',
            ],
            'baseUrl' => '/',
            'scriptUrl' => '',
        ]);
        $url = $manager->createUrl(['front/site/index']);
        $this->assertEquals('/', $url);
        $url = $manager->createUrl(['/front/site/index']);
        $this->assertEquals('/', $url);
        $url = $manager->createUrl(['front/site/index', 'page' => 1]);
        $this->assertEquals('/?page=1', $url);
        $url = $manager->createUrl(['/front/site/index', 'page' => 1]);
        $this->assertEquals('/?page=1', $url);
    }

    public function testCreateAbsoluteUrl()
    {
        $manager = new UrlManager([
            'baseUrl' => '/',
            'scriptUrl' => '',
            'hostInfo' => 'http://www.example.com',
            'cache' => null,
        ]);
        $url = $manager->createAbsoluteUrl(['post/view', 'id' => 1, 'title' => 'sample post']);
        $this->assertEquals('http://www.example.com?r=post%2Fview&id=1&title=sample+post', $url);

        $url = $manager->createAbsoluteUrl(['post/view', 'id' => 1, 'title' => 'sample post'], 'https');
        $this->assertEquals('https://www.example.com?r=post%2Fview&id=1&title=sample+post', $url);

        $manager->hostInfo = 'https://www.example.com';
        $url = $manager->createAbsoluteUrl(['post/view', 'id' => 1, 'title' => 'sample post'], 'http');
        $this->assertEquals('http://www.example.com?r=post%2Fview&id=1&title=sample+post', $url);
    }

    public function testCreateAbsoluteUrlWithSuffix()
    {
        $manager = new UrlManager([
            'baseUrl' => '/',
            'scriptUrl' => '',
            'hostInfo' => 'http://app.example.com',
            'cache' => null,

            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'suffix' => '/',
            'rules' => [
                'http://app.example.com/login' => 'site/login',
            ],
        ]);
        $url = $manager->createAbsoluteUrl(['site/login']);
        $this->assertEquals('http://app.example.com/login/', $url);
        $url = $manager->createUrl(['site/login']);
        $this->assertEquals('http://app.example.com/login/', $url);
    }

    public function testParseRequest()
    {
        $manager = new UrlManager(['cache' => null]);
        $request = new Request;

        // default setting without 'r' param
        unset($_GET['r']);
        $result = $manager->parseRequest($request);
        $this->assertEquals(['', []], $result);

        // default setting with 'r' param
        $_GET['r'] = 'site/index';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['site/index', []], $result);

        // default setting with 'r' param as an array
        $_GET['r'] = ['site/index'];
        $result = $manager->parseRequest($request);
        $this->assertEquals(['', []], $result);

        // pretty URL without rules
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
        ]);
        // empty pathinfo
        $request->pathInfo = '';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['', []], $result);
        // normal pathinfo
        $request->pathInfo = 'site/index';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['site/index', []], $result);
        // pathinfo with module
        $request->pathInfo = 'module/site/index';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['module/site/index', []], $result);
        // pathinfo with trailing slashes
        $request->pathInfo = '/module/site/index/';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['module/site/index/', []], $result);

        // pretty URL rules
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                [
                    'pattern' => 'post/<id>/<title>',
                    'route' => 'post/view',
                ],
            ],
        ]);
        // matching pathinfo
        $request->pathInfo = 'post/123/this+is+sample';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result);
        // trailing slash is significant
        $request->pathInfo = 'post/123/this+is+sample/';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/123/this+is+sample/', []], $result);
        // empty pathinfo
        $request->pathInfo = '';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['', []], $result);
        // normal pathinfo
        $request->pathInfo = 'site/index';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['site/index', []], $result);
        // pathinfo with module
        $request->pathInfo = 'module/site/index';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['module/site/index', []], $result);

        // pretty URL rules
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'suffix' => '.html',
            'cache' => null,
            'rules' => [
                [
                    'pattern' => 'post/<id>/<title>',
                    'route' => 'post/view',
                ],
            ],
        ]);
        // matching pathinfo
        $request->pathInfo = 'post/123/this+is+sample.html';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result);
        // matching pathinfo without suffix
        $request->pathInfo = 'post/123/this+is+sample';
        $result = $manager->parseRequest($request);
        $this->assertFalse($result);
        // empty pathinfo
        $request->pathInfo = '';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['', []], $result);
        // normal pathinfo
        $request->pathInfo = 'site/index.html';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['site/index', []], $result);
        // pathinfo without suffix
        $request->pathInfo = 'site/index';
        $result = $manager->parseRequest($request);
        $this->assertFalse($result);

        // strict parsing
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'suffix' => '.html',
            'cache' => null,
            'rules' => [
                [
                    'pattern' => 'post/<id>/<title>',
                    'route' => 'post/view',
                ],
            ],
        ]);
        // matching pathinfo
        $request->pathInfo = 'post/123/this+is+sample.html';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result);
        // unmatching pathinfo
        $request->pathInfo = 'site/index.html';
        $result = $manager->parseRequest($request);
        $this->assertFalse($result);
    }

    public function testParseRESTRequest()
    {
        $request = new Request;

        // pretty URL rules
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'cache' => null,
            'rules' => [
                'PUT,POST post/<id>/<title>' => 'post/create',
                'DELETE post/<id>' => 'post/delete',
                'post/<id>/<title>' => 'post/view',
                'POST/GET' => 'post/get',
            ],
        ]);
        // matching pathinfo GET request
        $_SERVER['REQUEST_METHOD'] = 'GET';
        $request->pathInfo = 'post/123/this+is+sample';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/view', ['id' => '123', 'title' => 'this+is+sample']], $result);
        // matching pathinfo PUT/POST request
        $_SERVER['REQUEST_METHOD'] = 'PUT';
        $request->pathInfo = 'post/123/this+is+sample';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/create', ['id' => '123', 'title' => 'this+is+sample']], $result);
        $_SERVER['REQUEST_METHOD'] = 'POST';
        $request->pathInfo = 'post/123/this+is+sample';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/create', ['id' => '123', 'title' => 'this+is+sample']], $result);

        // no wrong matching
        $_SERVER['REQUEST_METHOD'] = 'POST';
        $request->pathInfo = 'POST/GET';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/get', []], $result);

        // createUrl should ignore REST rules
        $this->mockApplication([
            'components' => [
                'request' => [
                    'hostInfo' => 'http://localhost/',
                    'baseUrl' => '/app'
                ]
            ]
        ], \yii\web\Application::className());
        $this->assertEquals('/app/post/delete?id=123', $manager->createUrl(['post/delete', 'id' => 123]));
        $this->destroyApplication();

        unset($_SERVER['REQUEST_METHOD']);
    }

    /**
     * Tests if hash-anchor present
     *
     * https://github.com/yiisoft/yii2/pull/9596
     */
    public function testHash()
    {
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'cache' => null,
            'rules' => [
                'http://example.com/testPage' => 'site/test',
            ],
            'hostInfo' => 'http://example.com',
            'scriptUrl' => '/index.php',
        ]);
        $url = $manager->createAbsoluteUrl(['site/test', '#' => 'testhash']);
        $this->assertEquals('http://example.com/index.php/testPage#testhash', $url);
    }

    /**
     * Tests if multislashes not accepted at the end of URL if PrettyUrl is enabled
     *
     * @see https://github.com/yiisoft/yii2/issues/10739
     */
    public function testMultiSlashesAtTheEnd()
    {
        $manager = new UrlManager([
            'enablePrettyUrl' => true,
        ]);

        $request = new Request;

        $request->pathInfo = 'post/multi/slash/';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/multi/slash/', []], $result);

        $request->pathInfo = 'post/multi/slash//';
        $result = $manager->parseRequest($request);
        $this->assertEquals(false, $result);

        $request->pathInfo = 'post/multi/slash////';
        $result = $manager->parseRequest($request);
        $this->assertEquals(false, $result);

        $manager = new UrlManager([
            'enablePrettyUrl' => true,
            'suffix' => '/'
        ]);

        $request->pathInfo = 'post/multi/slash/';
        $result = $manager->parseRequest($request);
        $this->assertEquals(['post/multi/slash', []], $result);

        $request->pathInfo = 'post/multi/slash//';
        $result = $manager->parseRequest($request);
        $this->assertEquals(false, $result);

        $request->pathInfo = 'post/multi/slash///////';
        $result = $manager->parseRequest($request);
        $this->assertEquals(false, $result);
    }
}


text:
from __future__ import unicode_literals
from django.core.files.base import File
from django.core.files.storage import default_storage
from django.db.models.fields.files import FileField as _FileField, FieldFile as _FieldFile
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy
from multifileinput.formfields import FileField as FileFormField
try:
    import json
except ImportError:
    from django.utils import simplejson as json
try:
    string_types = basestring
except NameError:
    string_types = str
try:
    callable = callable
except NameError:
    def callable(obj):
        return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)

class FileItem(_FieldFile):

    def __init__(self, instance, field, name):
        super(FileItem, self).__init__(instance, field, name)

    def delete(self, save=True):
        # Only close the file if it's already open, which we know by the
        # presence of self._file
        filename = self.name
        if hasattr(self, '_file'):
            self.close()
            del self.file
        self.storage.delete(self.name)
        self.name = None
        # Delete the filesize cache
        if hasattr(self, '_size'):
            del self._size
        self._committed = False
        if save:
            files = getattr(self.instance, self.field.name)
            files.remove([filename])
            self.instance.save()

    def save(self, name, content, save=True):
        filename = self.field.generate_filename(self.instance, name)
        self.name = self.storage.save(filename, content)
        # Update the filesize cache
        self._size = content.size
        self._committed = True
        if save:
            self.instance.save()
        return self.name

class FieldFiles(object):

    def __init__(self, descriptor, instance):
        self.descriptor = descriptor
        self.instance = instance
        self.clear()

    def clear(self):
        self._files = []
        self._files_remove = set() # set of file.name

    def append(self, f):
        fieldfile = self.descriptor.conv_to_file(f, self.instance)
        self._files.append(fieldfile)

    def extend(self, l):
        for f in l:
            self.append(f)

    def remove(self, f):
        if isinstance(f, string_types):
            self._files_remove.add(f)
        elif isinstance(f, File):
            self._files_remove.add(str(f))
        else:
            self._files_remove.update([str(item) for item in f if item])

    def remove_all(self):
        self._files_remove.update([str(item) for item in self._files if item])

    def should_remove(self, f):
        if str(f) in self._files_remove:
            return f._committed
        return False

    def __iter__(self):
        for f in self._files:
            if str(f) not in self._files_remove:
                yield f

    def __str__(self):
        return ", ".join([f.field.get_filename(f.name) for f in self])

class FieldFilesDescriptor(object):

    def __init__(self, field):
        self.field = field

    def __str__(self):
        return str(getattr(self, self.field.name))

    def __get__(self, instance=None, owner=None):
        if instance is None:
            raise AttributeError(
                "The '%s' attribute can only be accessed from %s instances."
                % (self.field.name, owner.__name__))
        return instance.__dict__[self.field.name]

    def __set__(self, instance, value):
        files = instance.__dict__.get(self.field.name)
        if files is None: # initialize
            files = instance.__dict__[self.field.name] = FieldFiles(self, instance)
        if files is value:
            return
        elif not value:
            files.remove_all()
            return
        elif isinstance(value, FieldFiles):
            files.remove(value._files_remove)
            files.extend(value)
            return
        elif isinstance(value, File):
            files.remove_all()
            files.append(value)
            return
        elif isinstance(value, string_types):
            try:
                value = json.loads(value)
                if not isinstance(value, string_types):
                    files.extend(value)
                else:
                    files.append(value)
            except ValueError:
                files.append(value)
            return
        elif isinstance(value, dict):
            files.remove(value.get("delete", ()))
            value = value.get("add", ())
            files.extend(value)
            return

    def conv_to_file(self, obj, instance):
        field = self.field
        file_class = field.attr_class
        if isinstance(obj, string_types):
            f = file_class(instance, field, obj)
            return f
        elif isinstance(obj, file_class):
            if not hasattr(obj, 'field'):
                obj.instance = instance
                obj.field = field
                obj.storage = field.storage
            return obj
        elif isinstance(obj, File):
            file_copy = file_class(instance, field, obj.name)
            file_copy.file = obj
            file_copy._committed = False
            return file_copy
        else:
            raise ValueError("Could not convert {0} to {1}".format(obj, file_class))

class FileField(_FileField):
    # The class to wrap instance attributes in. Accessing the file object off
    # the instance will always return an instance of attr_class.
    attr_class = FileItem

    # The descriptor to use for accessing the attribute off of the class.
    descriptor_class = FieldFilesDescriptor

    description = ugettext_lazy("Files")

    def get_internal_type(self):
        return "TextField"

    def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
        #TODO: アップロード可能なファイルの総数、トータルのサイズチェック、ファイルの有無チェック、ストレージからファイルを消すか
        for arg in ('primary_key', 'unique', 'choices'):
            if arg in kwargs:
                raise TypeError("'%s' is not a valid argument for %s." % (arg, self.__class__))
        self.storage = storage or default_storage
        self.upload_to = upload_to
        if callable(upload_to):
            self.generate_filename = upload_to
        kwargs['max_length'] = kwargs.get('max_length', 100)
        super(_FileField, self).__init__(verbose_name, name, **kwargs)

    def formfield(self, **kwargs):
        """
        Returns a django.forms.Field instance for this database Field.
        """
        defaults = {'max_length': self.max_length,
                    'required': not self.blank,
                    'label': capfirst(self.verbose_name),
                    'help_text': self.help_text}
        if self.has_default():
            if callable(self.default):
                defaults['initial'] = self.default()
            else:
                defaults['initial'] = self.default
        defaults.update(kwargs)
        return FileFormField(**defaults)

    def save_form_data(self, instance, data):
        setattr(instance, self.name, data)

    def get_prep_value(self, value):
        "Returns field's value prepared for saving into a database."
        if value:
            return json.dumps([str(f) for f in value])
        else:
            return None

    def pre_save(self, model_instance, add):
        "Returns field's value just before saving."
        new_files = []
        files = getattr(model_instance, self.name)
        for f in files._files:
            if not add and files.should_remove(f):
                f.delete(save=False)
            elif f:
                new_files.append(f)
        for f in new_files:
            if f and not f._committed:
                f.save(str(f), f, save=False)
        files.clear()
        files.extend(new_files)
        return files

    def south_field_triple(self):
        "Returns a suitable description of this field for South."
        from south.modelsinspector import introspector
        field_class = "django.db.models.fields.TextField"
        args, kwargs = introspector(self)
        return (field_class, args, kwargs)


text:
typedef enum {
    HWEmotionTabBarButtonTypeRecent,
    HWEmotionTabBarButtonTypeDefault,
    HWEmotionTabBarButtonTypeEmoji,
    HWEmotionTabBarButtonTypeLxh,
} HWEmotionTabBarButtonType;

@class HWEmotionTabBar;

@protocol HWEmotionTabBarDelegate <NSObject>
@optional
- (void)emotionTabBar:(HWEmotionTabBar *)tabBar didSelectButton:(HWEmotionTabBarButtonType)buttonType;
@end

@interface HWEmotionTabBar : UIView
@property (weak,nonatomic) id<HWEmotionTabBarDelegate> delegate;
@end


text:
// Enable OpenCL C++ exceptions
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cassert>

#include "poclu.h"

static char
kernelSourceCode[] =
"int putchar(int c);\n"
"kernel \n"
"void test_kernel(constant char *input,\n"
"                 __global char *output,\n"
"                 float a,\n"
"                 int b) {\n"
"    constant char* pos = input; \n"
"    while (*pos) {\n"
"        putchar (*pos);\n"
"        ++pos;\n"
"    }\n"
"#ifdef cl_TCE_ABSF\n"
"    clABSFTCE(input[0], output[0]); \n"
"#else\n"
"#error The machine should have ADDF in the ISA\n"
"#endif\n"
"    printf(\"%f %d\", a, b);\n"
"    output[0] = 'P'; \n"
"    output[1] = 'O'; \n"
"    output[2] = 'N'; \n"
"    output[3] = 'G'; \n"
"    output[4] = '\\0'; \n"
"}\n";

int
main(void)
{
    const size_t OUTPUT_SIZE = 5;
    const char *input = "PING\0";
    char output[OUTPUT_SIZE];
    float a = 23456.0f;
    int b = 2000001;

    try {
        std::vector<cl::Platform> platformList;

        // Pick platform
        cl::Platform::get(&platformList);

        // Pick first platform
        cl_context_properties cprops[] = {
            CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0};
        cl::Context context(CL_DEVICE_TYPE_GPU, cprops);

        // Query the set of devices attched to the context
        std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();

        assert (devices.size() == 1);

        cl::Device device = devices.at(0);

        assert (strncmp(device.getInfo<CL_DEVICE_NAME>().c_str(), "tta", 3)==0 );

        a = poclu_bswap_cl_float (device(), a);
        b = poclu_bswap_cl_int (device(), b);

        // Create and program from source
        cl::Program::Sources sources(1, std::make_pair(kernelSourceCode, 0));
        cl::Program program(context, sources);

        // Build program
        program.build(devices);

        cl::Buffer inputBuffer = cl::Buffer(
            context,
            CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
            strlen (input), (void *) &input[0]);

        // Create buffer for that uses the host ptr C
        cl::Buffer outputBuffer = cl::Buffer(
            context,
            CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
            OUTPUT_SIZE, (void *) &output[0]);

        // Create kernel object
        cl::Kernel kernel(program, "test_kernel");

        // Set kernel args
        kernel.setArg(0, inputBuffer);
        kernel.setArg(1, outputBuffer);
        kernel.setArg(2, a);
        kernel.setArg(3, b);

        // Create command queue
        cl::CommandQueue queue(context, devices[0], CL_QUEUE_PROFILING_ENABLE);

        cl::Event enqEvent;

        // Do the work
        queue.enqueueNDRangeKernel(
            kernel,
            cl::NullRange,
            cl::NDRange(1),
            cl::NullRange,
            NULL, &enqEvent);

        cl::Event mapEvent;
        (int *) queue.enqueueMapBuffer(
            outputBuffer,
            CL_TRUE, // block
            CL_MAP_READ,
            0, OUTPUT_SIZE, NULL, &mapEvent);

        if (std::string(output) == "PONG")
            std::cout << "OK\n";
        else
            std::cerr << "FAIL, received: " << output << "\n";

        cl::Event unmapEvent;
        // Finally release our hold on accessing the memory
        queue.enqueueUnmapMemObject(
            outputBuffer,
            (void *) &output[0],
            NULL,
            &unmapEvent);

        queue.finish();

        assert (enqEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);
        assert (mapEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);
        assert (unmapEvent.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>() == CL_COMPLETE);

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

#if 0
        std::cerr << "exec time: "
                  << enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() -
            enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() << std::endl;
#endif

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <=
            mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_SUBMIT>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>());

        assert (
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() <=
            unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (enqEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() <=
                mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

        assert (mapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() <=
                unmapEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>());

    }
    catch (cl::Error err) {
         std::cerr
             << "ERROR: "
             << err.what()
             << "("
             << err.err()
             << ")"
             << std::endl;

         return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}


text:
from flask import Blueprint, g, current_app, render_template, flash, redirect, request, url_for, jsonify, abort, Request, Markup
from flask.ext.login import current_user, login_required
from flask.ext.babel import gettext as _

#from app.utils import url_for_school
#from app.mod_school import get_school_context
from .models import Discussion, Comment
from .services import start_discussion, can_edit_comment
from .forms import AddDiscussionForm, AddCommentForm, EditCommentForm

# Blueprint definition
discussions = Blueprint('discussions', __name__, url_prefix='/discussions')

@discussions.route('/', methods=['GET'])
def list():
	""" Show a list of all discussions """
	if g.is_default_school:
		discussions = Discussion.objects.filter(published=True).order_by('-created')
	else:
		discussions = Discussion.objects.filter(schools=g.school, published=True).order_by('-created')
	return render_template('discussion/list.html',
		title=_('Discussions'),
		discussions=discussions)

@discussions.route('/<discussion_id>/proposals/<proposal_id>', methods=['GET'])
def detail(discussion_id, proposal_id):
	""" Show a single discussion, redirecting to the appropriate school if necessary """
	d = Discussion.objects.get_or_404(id=discussion_id)
	#context = get_school_context(d)
	#if not g.school==context:
	#	flash(_("You've been redirected to where the discussion was created."))
	#	return redirect(url_for_school('discussions.detail', school=context, id=d.id), code=301)
	#other_schools = [school for school in d.schools if not school==context]
	comments = Comment.objects.filter(discussion=d).order_by('created')
	# Passing some permissions related functions on to Jinja
	current_app.jinja_env.globals['can_edit_comment'] = can_edit_comment
	return render_template('discussion/detail.html',
		title = d.title,
		discussion = d,
		comments = comments, proposal_id=proposal_id)
		#other_schools = other_schools)

#@discussions.route('/create/proposals/<proposal_id>', methods=['GET','POST'])
#def create(proposal_id):
#	if current_user.is_anonymous():
#		flash(Markup(" You have to login before creating a discussion."), "info")
#		return redirect('/login?next=' + str(request.path))

#	""" Create a new discussion """
#	schools = g.all_schools
#	form = AddDiscussionForm()
#	if form.validate_on_submit():
#		d = start_discussion(request.form.get("text"), form=form)
#		return redirect(url_for('proposal.detail', discussion_id=d.id, proposal_id=proposal_id))
#	return render_template('discussion/create.html',
#		title=_('Start a discussion'),
#		form=form)

@discussions.route('/<discussion_id>/comment/proposals/<proposal_id>', methods=['GET','POST'])
def add_comment(discussion_id, proposal_id):
	if current_user.is_anonymous():
		flash(Markup(" You have to login before adding a comment."), "info")
		return redirect('/login?next=' + str(request.path))

	""" Add a comment to a discussion """
	d = Discussion.objects.get_or_404(id=discussion_id)
	form = AddCommentForm()
	if form.validate_on_submit():
		c = Comment(
			creator = current_user._get_current_object(),
			discussion = d)
		form.populate_obj(c)
		c.save()
		return redirect(url_for('discussions.detail', discussion_id=d.id, proposal_id=proposal_id))
	return render_template('discussion/add_comment.html',
		discussion = d,
        proposal_id = proposal_id,
		title = d.title,
		form = form)

@discussions.route('/<discussion_id>/comments/<comment_id>/edit/proposals/<proposal_id>', methods=['GET','POST'])
def edit_comment(discussion_id, comment_id, proposal_id):
	if current_user.is_anonymous():
		flash(Markup(" You have to login before editing a comment."), "info")
		return redirect('/login?next=' + str(request.path))

	""" Edit a comment of a discussion """
	d = Discussion.objects.get_or_404(id=discussion_id)
	c = Comment.objects.get_or_404(id=comment_id)
	form = EditCommentForm()

	# If the user is not the owner of the comment, throw a 403
	if current_user._get_current_object() != c.creator:
		abort(403)

	if form.validate_on_submit():
		c.edit_comment(newText=form.text.data)
		return redirect(url_for('discussions.detail', discussion_id=d.id, proposal_id=proposal_id))

	return render_template('discussion/edit_comment.html',
		discussion = d,
        proposal_id = proposal_id,
		title = d.title,
		comment = c,
        text = c.text,
        form = form)


text:
Add-PSSnapin Microsoft.SharePoint.PowerShell
Clear-Host

# create variables for new web application
$webAppName = "Wingtip Extranet"
$port = 443
$hostHeader = "extranet.wingtip.com"
$ssl = $true
$authProvider = New-SPAuthenticationProvider -UseBasicAuthentication
$url = "https://extranet.wingtip.com"
$appPoolName = "SharePoint - 80"
$dbServer = "WingtipServer"
$dbName = "WingtipExtranet_ContentDB"

# create new web application
Write-Host "Creating Web App..."
$webapp = New-SPWebApplication -Name $webAppName -Port $port -HostHeader $hostHeader -SecureSocketsLayer:$ssl -AuthenticationProvider $authProvider -URL $url -ApplicationPool $appPoolName -DatabaseServer $dbServer -DatabaseName $dbName
Write-Host "Wingtip Extranet Web App Created"
Write-Host

# create variables for root site collection
$siteUrl = "https://extranet.wingtip.com/"
$siteTitle = "Wingtip Extranet"
$siteOwner = "Wingtip\Administrator"
$siteTemplate = "STS#0"

# create root site collection
Write-Host "Creating Wingtip Extranet Root Site Collection..."
$site = New-SPSite -Url $siteUrl -Template $siteTemplate -OwnerAlias $siteOwner -Name $siteTitle
Write-Host "Wingtip Extranet Root Site Collection Created"
Write-Host

Write-Host "Script complete"
Write-Host


text:
using System;

namespace DesignPatternLib.Decorator
{
    public class Client
    {
        public static void Test()
        {
            // Create book
            var book = new Book("Worley", "Inside ASP.NET", 10);
            book.Display();
            // Create video
            var video = new Video("Spielberg", "Jaws", 23, 92);
            video.Display();
            // Make video borrowable, then borrow and display
            Console.WriteLine("\nMaking video borrowable:");
            var borrow = new Borrowable<Video>(video);
            borrow.BorrowItem("Customer #1");
            borrow.BorrowItem("Customer #2");
            borrow.Display();
            // Wait for user
            Console.ReadKey();
        }
    }
}


text:
package org.b3log.symphony.processor.advice.validate;

import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import org.b3log.latke.Keys;
import org.b3log.latke.model.User;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.advice.BeforeRequestProcessAdvice;
import org.b3log.latke.servlet.advice.RequestProcessAdviceException;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.Strings;
import org.json.JSONObject;

/**
 * Validates for user password update.
 *
 * @author Liang Ding
 * @version 1.0.0.1, Oct 29, 2012
 * @since 0.2.0
 */
@Named
@Singleton
public class UpdatePasswordValidation extends BeforeRequestProcessAdvice {

    /**
     * Language service.
     */
    @Inject
    private LangPropsService langPropsService;

    @Override
    public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args) throws RequestProcessAdviceException {
        final HttpServletRequest request = context.getRequest();

        JSONObject requestJSONObject;
        try {
            requestJSONObject = Requests.parseRequestJSONObject(request, context.getResponse());
            request.setAttribute(Keys.REQUEST, requestJSONObject);
        } catch (final Exception e) {
            throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, e.getMessage()));
        }

        final String oldPwd = requestJSONObject.optString(User.USER_PASSWORD);
        if (Strings.isEmptyOrNull(oldPwd)) {
            throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, langPropsService.get("emptyOldPwdLabel")));
        }

        final String pwd = requestJSONObject.optString(User.USER_PASSWORD);
        if (UserRegisterValidation.invalidUserPassword(pwd)) {
            throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, langPropsService.get("invalidPasswordLabel")));
        }
    }
}


text:
if jit then
	package.path = package.path ..
		";/usr/share/lua/5.1/?.lua;/usr/share/lua/5.1/?/init.lua"
	package.cpath = package.cpath ..
		";/usr/lib/x86_64-linux-gnu/lua/5.1/?.so;/usr/lib/lua/5.1/?.so;/usr/local/lib/lua/5.1/loadall.so"
end

-- Load the LFS module if needed (Windows has it built in).

if not lfs then
	lfs = require "lfs"
end

-- Bit library fallbacks. (LuaJIT vs Lua 5.2 incompatibilities.)

if not bit32 then
	bit32 =
	{
		bxor = bit.bxor,
		band = bit.band,
		bor = bit.bor,
		btest = function(a, b)
			return bit.band(a, b) ~= 0
		end
	}
end

-- Make sure that reads of undefined global variables fail. Note: this will
-- prevent us from storing nil in a global.

if DEBUG then
	local allowed =
	{
		X11_BLACK_COLOUR = true,
		X11_BOLD_MODIFIER = true,
		X11_BRIGHT_COLOUR = true,
		X11_DIM_COLOUR = true,
		X11_FONT = true,
		X11_ITALIC_MODIFIER = true,
		X11_NORMAL_COLOUR = true,
	}

	setmetatable(_G,
		{
			__index = function(self, k)
				if not allowed[k] then
					error("read from undefined local '"..k.."'")
				end
				return rawget(_G, k)
			end
		}
	)
end

-- Global definitions that the various source files need.

Cmd = {}