text:
package com.phoenixie.minigame;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ButtonGroup;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.phoenixie.minigame.utils.Queue;

public class MiniGame extends Game implements GestureListener {

	static final int CHIFFRE_MAX = 16;
	static final int CADRE_WIDTH = 6;
	static final int LINE_WIDTH = 3;
	static final int TABLE_WIDTH = 760;
	static final int FONT_SIZE = 48;

	static final int SCREEN_WIDTH = 800;
	static final int SCREEN_HEIGHT = 1280;
	static final float ASPECT_RATIO = (float) SCREEN_WIDTH
			/ (float) SCREEN_HEIGHT;

	static final int PHOTO_COUNT = 19;

	static final int BUTTON_UNDO = 0;
	static final int BUTTON_RESET = 1;
	static final int BUTTON_RESUME = 2;
	static final int BUTTON_SETTINGS = 3;

	static final int IMG_WIDTH = 128;
	static final int BUTTON_WIDTH = 240;
	static final int BUTTON_HEIGHT = 80;
	static final int BOTTOM_SPACE = 150;

	static final Color COLEUR_BACKGROUND = new Color(0.96875f, 0.9453125f,
			0.8515625f, 1);
	static final Color COLEUR_CADRE = new Color(0.77734375f, 0.68359375f,
			0.73828125f, 1);

	private OrthographicCamera camera;
	private SpriteBatch batch;
	private Skin skin;
	private BitmapFont font;

	private Texture chiffreImage;
	private TextureRegion[] chiffres;
	private Texture photoImage;
	private TextureRegion[] photos;
	private Texture pictureImage;
	private TextureRegion[] pictures;
	private int maxChiffre;

	private TextureRegion[] currImages;
	private ShapeRenderer renderer;
	private Rectangle viewport;

	private Texture buttonImage;

	private ImageButton buttonReset;
	private ImageButton buttonUndo;
	private ImageButton buttonSettings;
	private Stage stage;

	private CheckBox checkChiffres;
	private CheckBox checkPhotos;
	private CheckBox checkPictures;
	private CheckBox checkTable44;
	private CheckBox checkTable55;
	private CheckBox checkTable66;
	private Dialog dialogSettings;
	private Dialog dialogReset;
	private Dialog dialog2048;
	private Dialog dialog4096;
	private Dialog dialog8192;
	private Dialog dialog16384;
	private Dialog dialog32768;
	private Dialog dialog65536;

	private int boiteHorzCount = 4;
	private int boiteVertCount = 4;
	private int tableWidth = 0;
	private int tableHeight = 0;
	private int boiteWidth = IMG_WIDTH;

	enum Direction {
		UP, DOWN, LEFT, RIGHT
	}

	enum BoiteType {
		CHIFFRES, PHOTOS, PICTURES
	}

	private static class Pos {
		public int x;
		public int y;
	}

	private static class GameState {
		public int boiteHorzCount;
		public int boiteVertCount;
		public int gameCount;
		public long gameScore;
		public long gameTime;
		public int[][][] gameEtapes;
		public int[][] chiffreTable;
	}

	private static class Settings {
		public BoiteType boiteType = BoiteType.CHIFFRES;
		public int boiteHorzCount = 4;
		public int boiteVertCount = 4;
	};

	private Pos tableVertex;
	private Pos tableLeftBottom;
	private Pos tableRightTop;
	private Pos[][] boitesPos;

	private int[][] chiffreTable;
	private Queue etapeQueue;
	private int gameCount;
	private long gameScore;
	private long gameTime;
	private long gameStartTime;
	private int[][][] gameEtapeBuffer;
	private GameState gameState = new GameState();
	private boolean gameLoaded = false;
	private Settings settings = new Settings();
	private Kryo kryo;

	private Pos[] videBoites;
	private int videBoitesCount = 0;

	private static Random random = new Random(System.currentTimeMillis());

	@Override
	public void create() {
		// Gdx.graphics.setContinuousRendering(false);
		Gdx.graphics.requestRendering();
		Texture.setEnforcePotImages(false);

		stage = new Stage();
		stage.setViewport(SCREEN_WIDTH, SCREEN_HEIGHT, true);

		etapeQueue = new Queue();
		gameEtapeBuffer = new int[etapeQueue.capacity()][][];
		kryo = new Kryo();

		camera = new OrthographicCamera(SCREEN_WIDTH, SCREEN_HEIGHT);
		camera.position.set(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0);
		stage.setCamera(camera);

		batch = new SpriteBatch();
		skin = new Skin(Gdx.files.internal("data/uiskin.json"));
		font = new BitmapFont(Gdx.files.internal("data/fonts/fonts.fnt"),
				Gdx.files.internal("data/fonts/fonts.png"), false);
		renderer = new ShapeRenderer();

		chiffreImage = new Texture(Gdx.files.internal("data/chiffres.png"));
		chiffres = new TextureRegion[CHIFFRE_MAX];

		for (int i = 0; i < CHIFFRE_MAX; ++i) {
			chiffres[i] = new TextureRegion(chiffreImage, i * IMG_WIDTH, 0,
					IMG_WIDTH, IMG_WIDTH);
		}

		photoImage = new Texture(Gdx.files.internal("data/photos.png"));
		photos = new TextureRegion[PHOTO_COUNT];

		for (int i = 0; i < PHOTO_COUNT; ++i) {
			photos[i] = new TextureRegion(photoImage, i * IMG_WIDTH, 0,
					IMG_WIDTH, IMG_WIDTH);
		}

		pictureImage = new Texture(Gdx.files.internal("data/pics.png"));
		pictures = new TextureRegion[CHIFFRE_MAX];

		for (int i = 0; i < CHIFFRE_MAX; ++i) {
			pictures[i] = new TextureRegion(pictureImage, i * IMG_WIDTH, 0,
					IMG_WIDTH, IMG_WIDTH);
		}

		tableVertex = new Pos();
		tableVertex.x = (SCREEN_WIDTH - TABLE_WIDTH) / 2;
		tableVertex.y = BOTTOM_SPACE;
		tableRightTop = new Pos();

		Gdx.input.setInputProcessor(new InputMultiplexer(stage,
				new GestureDetector(0.0f, 0.0f, 0.0f, 5f, this) {
					private boolean wrongStart = false;

					@Override
					public boolean touchDown(int x, int y, int pointer,
							int button) {
						Vector3 touchPos = new Vector3(x, y, 0);
						camera.unproject(touchPos);

						if (touchPos.x < tableLeftBottom.x
								|| touchPos.x > tableRightTop.x) {
							wrongStart = true;
							return false;
						}
						if (touchPos.y < tableLeftBottom.y
								|| touchPos.y > tableRightTop.y) {
							wrongStart = true;
							return false;
						}

						wrongStart = false;
						return super.touchDown((float) x, (float) y, pointer,
								button);
					}

					@Override
					public boolean touchDragged(int x, int y, int pointer) {
						if (wrongStart) {
							return false;
						}
						return super
								.touchDragged((float) x, (float) y, pointer);
					}

					@Override
					public boolean touchUp(int x, int y, int pointer, int button) {
						if (wrongStart) {
							return false;
						}
						return super.touchUp((float) x, (float) y, pointer,
								button);
					}
				}));

		loadSettings();

		if (settings.boiteType == BoiteType.CHIFFRES) {
			currImages = chiffres;
		} else if (settings.boiteType == BoiteType.PHOTOS) {
			currImages = photos;
		} else if (settings.boiteType == BoiteType.PICTURES) {
			currImages = pictures;
		}

		changeTableSize(settings.boiteHorzCount);

		loadGame();

		drawButtons();

		createDialogs();

		if (gameLoaded) {
			resumeGame();
		} else {
			resetGame();
		}

		Timer.schedule(new Task() {

			@Override
			public void run() {
				Gdx.graphics.requestRendering();
			}

		}, 0f, 0.5f);
	}

	private void changeTableSize(int size) {
		boiteHorzCount = boiteVertCount = size;

		boitesPos = new Pos[boiteHorzCount][boiteVertCount];
		chiffreTable = new int[boiteHorzCount][boiteVertCount];
		videBoites = new Pos[boiteHorzCount * boiteVertCount];

		for (int i = 0; i < boiteHorzCount * boiteVertCount; ++i) {
			videBoites[i] = new Pos();
		}
		videBoitesCount = 0;

		tableWidth = TABLE_WIDTH;
		boiteWidth = (tableWidth - 2 * CADRE_WIDTH - (boiteHorzCount - 1)
				* LINE_WIDTH) / boiteHorzCount;
		tableHeight = boiteVertCount * boiteWidth + (boiteVertCount - 1)
				* LINE_WIDTH + 2 * CADRE_WIDTH;

		int yPos = tableVertex.y + CADRE_WIDTH;
		for (int j = 0; j < boiteVertCount; ++j) {
			int xPos = tableVertex.x + CADRE_WIDTH;
			for (int i = 0; i < boiteHorzCount; ++i) {
				boitesPos[i][boiteVertCount - 1 - j] = new Pos();
				boitesPos[i][boiteVertCount - 1 - j].x = xPos;
				boitesPos[i][boiteVertCount - 1 - j].y = yPos;
				xPos += boiteWidth + LINE_WIDTH;
			}
			yPos += boiteWidth + LINE_WIDTH;
		}

		tableLeftBottom = tableVertex;
		tableRightTop.x = tableVertex.x + tableWidth;
		tableRightTop.y = tableVertex.y + tableHeight;
	}

	private void saveSettings() {
		if (!Gdx.files.isLocalStorageAvailable()) {
			return;
		}

		FileHandle file = Gdx.files.local("settings");
		OutputStream ostream = file.write(false);
		Output output = new Output(ostream);

		kryo.writeObject(output, settings);
		output.close();
	}

	private void loadSettings() {
		if (!Gdx.files.isLocalStorageAvailable()) {
			return;
		}

		try {
			FileHandle file = Gdx.files.local("settings");
			InputStream istream = file.read();
			Input input = new Input(istream);
			settings = kryo.readObject(input, Settings.class);
			input.close();
		} catch (Exception e) {
//			e.printStackTrace();
			return;
		}
	}

	private void saveGame() {
		if (!Gdx.files.isLocalStorageAvailable()) {
			return;
		}

		int etapeCount = etapeQueue.dump(gameEtapeBuffer);

		FileHandle file = Gdx.files.local("gamedata");
		OutputStream ostream = file.write(false);
		Output output = new Output(ostream);

		gameState.boiteHorzCount = boiteHorzCount;
		gameState.boiteVertCount = boiteVertCount;
		gameState.gameCount = gameCount;
		gameState.gameScore = gameScore;
		gameState.gameTime = gameTime;
		gameState.chiffreTable = chiffreTable;
		gameState.gameEtapes = gameEtapeBuffer;

		kryo.writeObject(output, gameState);
		output.close();
	}

	private boolean loadGame() {
		gameLoaded = false;
		if (!Gdx.files.isLocalStorageAvailable()) {
			return false;
		}

		try {
			FileHandle file = Gdx.files.local("gamedata");
			InputStream istream = file.read();
			Input input = new Input(istream);
			gameState = kryo.readObject(input, GameState.class);
			input.close();

			if (gameState.gameCount == 0) {
				return false;
			}

			gameLoaded = true;
		} catch (Exception e) {
//			e.printStackTrace();
			return false;
		}

		return true;
	}

	private void resumeGame() {
		if (boiteHorzCount != gameState.boiteHorzCount) {
			changeTableSize(gameState.boiteHorzCount);
		}

		resetGame();

		gameCount = gameState.gameCount;
		gameScore = gameState.gameScore;
		gameTime = gameState.gameTime;
		chiffreTable = gameState.chiffreTable;

		for (int i = 0; i < boiteHorzCount; ++i) {
			for (int j = 0; j < boiteVertCount; ++j) {
				int cur = chiffreTable[i][j];
				if (maxChiffre < cur) {
					maxChiffre = cur;
				}
			}
		}

		for (int i = 0; i < gameState.gameEtapes.length; ++i) {
			if (gameState.gameEtapes[i] == null) {
				break;
			}
			etapeQueue.enqueue(gameState.gameEtapes[i]);
		}

		if (!etapeQueue.isEmpty()) {
			buttonUndo.setVisible(true);
			buttonReset.setVisible(true);
		}

		Gdx.graphics.requestRendering();

	}

	private void resetGame() {
		for (int j = 0; j < boiteVertCount; ++j) {
			for (int i = 0; i < boiteHorzCount; ++i) {
				chiffreTable[i][j] = -1;
			}
		}

		maxChiffre = 0;
		gameCount = 0;
		gameScore = 0;
		gameTime = 0;
		gameStartTime = System.currentTimeMillis();

		etapeQueue.clear();
		buttonUndo.setVisible(false);
		buttonReset.setVisible(false);

		generateChiffre();
		generateChiffre();

		shufflePhotos();
		shufflePictures();

		Gdx.graphics.requestRendering();
	}

	private void drawStat() {
		long currTime = System.currentTimeMillis();
		long delta = currTime - gameStartTime;

		gameTime += delta;
		gameStartTime = currTime;

		currTime = gameTime / 1000;

		int seconds = (int) (currTime % 60);
		currTime /= 60;
		int minutes = (int) (currTime % 60);
		int hours = (int) (currTime / 60);

		font.setColor(0f, 0f, 0f, 1f);
		font.draw(batch, "Points:   " + gameScore, 20, SCREEN_HEIGHT
				- FONT_SIZE - 30);
		font.draw(batch, "Temps:   " + hours + ":"
				+ (minutes < 10 ? "0" + minutes : minutes) + ":"
				+ (seconds < 10 ? "0" + seconds : seconds), 20, SCREEN_HEIGHT
				- FONT_SIZE - 100);
		font.draw(batch, "Tours:   " + gameCount, SCREEN_WIDTH / 2,
				SCREEN_HEIGHT - FONT_SIZE - 100);

	}

	private void drawCadre() {
		renderer.begin(ShapeType.FilledRectangle);
		renderer.setColor(COLEUR_CADRE);
		renderer.filledRect(tableVertex.x, tableVertex.y, tableWidth,
				CADRE_WIDTH);
		renderer.filledRect(tableVertex.x, tableVertex.y, CADRE_WIDTH,
				tableHeight);
		renderer.filledRect(tableVertex.x + tableWidth - CADRE_WIDTH,
				tableVertex.y, CADRE_WIDTH, tableHeight);
		renderer.filledRect(tableVertex.x, tableVertex.y + tableHeight
				- CADRE_WIDTH, tableWidth, CADRE_WIDTH);

		int linepos = CADRE_WIDTH + boiteWidth;
		for (int i = 0; i < boiteHorzCount - 1; ++i) {
			renderer.filledRect(tableVertex.x + linepos, tableVertex.y,
					LINE_WIDTH, tableHeight);
			linepos += LINE_WIDTH + boiteWidth;
		}
		linepos = CADRE_WIDTH + boiteWidth;
		for (int i = 0; i < boiteVertCount - 1; ++i) {
			renderer.filledRect(tableVertex.x, tableVertex.y + linepos,
					tableWidth, LINE_WIDTH);
			linepos += LINE_WIDTH + boiteWidth;
		}

		renderer.end();
	}

	private void drawButtons() {
		buttonImage = new Texture(Gdx.files.internal("data/buttons.png"));
		TextureRegion buttonUp = new TextureRegion(buttonImage, BUTTON_UNDO
				* BUTTON_WIDTH, 0, BUTTON_WIDTH, BUTTON_HEIGHT);
		TextureRegion buttonDown = new TextureRegion(buttonImage, BUTTON_UNDO
				* BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT);

		ImageButtonStyle style = new ImageButtonStyle();
		style.imageUp = new TextureRegionDrawable(buttonUp);
		style.imageDown = new TextureRegionDrawable(buttonDown);
		buttonUndo = new ImageButton(style);

		buttonUp = new TextureRegion(buttonImage, BUTTON_RESET * BUTTON_WIDTH,
				0, BUTTON_WIDTH, BUTTON_HEIGHT);
		buttonDown = new TextureRegion(buttonImage,
				BUTTON_RESET * BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_WIDTH,
				BUTTON_HEIGHT);

		style = new ImageButtonStyle();
		style.imageUp = new TextureRegionDrawable(buttonUp);
		style.imageDown = new TextureRegionDrawable(buttonDown);
		buttonReset = new ImageButton(style);

		buttonUp = new TextureRegion(buttonImage, BUTTON_SETTINGS
				* BUTTON_WIDTH, 0, BUTTON_WIDTH, BUTTON_HEIGHT);
		buttonDown = new TextureRegion(buttonImage, BUTTON_SETTINGS
				* BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT);

		style = new ImageButtonStyle();
		style.imageUp = new TextureRegionDrawable(buttonUp);
		style.imageDown = new TextureRegionDrawable(buttonDown);
		buttonSettings = new ImageButton(style);

		buttonUndo.setX(SCREEN_WIDTH - 20 - BUTTON_WIDTH);
		buttonUndo.setY(BOTTOM_SPACE + tableHeight + 40);
		buttonReset.setX(20);
		buttonReset.setY(BOTTOM_SPACE + tableHeight + 40);
		buttonSettings.setX(SCREEN_WIDTH - 20 - BUTTON_WIDTH);
		buttonSettings.setY(SCREEN_HEIGHT - 30 - BUTTON_HEIGHT);

		stage.addActor(buttonUndo);
		stage.addActor(buttonReset);
		stage.addActor(buttonSettings);

		buttonReset.addListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				dialogReset.show(stage);
			}

		});

		buttonUndo.addListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				int[][] load = (int[][]) etapeQueue.pop();
				if (load != null) {
					chiffreTable = load;
					Gdx.graphics.requestRendering();
					if (etapeQueue.isEmpty()) {
						buttonUndo.setVisible(false);
					}
				}
			}
		});

		buttonSettings.addListener(new ChangeListener() {

			@Override
			public void changed(ChangeEvent event, Actor actor) {
				showSettings();
			}

		});
	}

	private void createDialogs() {
		checkChiffres = new CheckBox("Chiffres", skin);
		checkPhotos = new CheckBox("Photos", skin);
		checkPictures = new CheckBox("Images", skin);

		checkChiffres.getCells().get(0).size(30, 30);
		checkPhotos.getCells().get(0).size(30, 30);
		checkPictures.getCells().get(0).size(30, 30);

		ButtonGroup buttonTable = new ButtonGroup(checkChiffres,
				checkPhotos, checkPictures);
		buttonTable.setMaxCheckCount(1);
		buttonTable.setMinCheckCount(1);
		buttonTable.setUncheckLast(true);

		checkTable44 = new CheckBox("4 X 4", skin);
		checkTable55 = new CheckBox("5 X 5", skin);
		checkTable66 = new CheckBox("6 X 6", skin);

		checkTable44.getCells().get(0).size(30, 30);
		checkTable55.getCells().get(0).size(30, 30);
		checkTable66.getCells().get(0).size(30, 30);

		ButtonGroup tableSize = new ButtonGroup(checkTable44, checkTable55, checkTable66);
		tableSize.setMaxCheckCount(1);
		tableSize.setMinCheckCount(1);
		tableSize.setUncheckLast(true);

		Dialog.fadeDuration = 0.2f;
		dialogSettings = new Dialog("Paramètres", skin, "dialog") {
			protected void result(Object object) {
				if (!(Boolean) object) {
					return;
				}

				if (checkChiffres.isChecked()) {
					if (settings.boiteType != BoiteType.CHIFFRES) {
						settings.boiteType = BoiteType.CHIFFRES;
						currImages = chiffres;
						Gdx.graphics.requestRendering();
					}
				} else if (checkPhotos.isChecked()) {
					if (settings.boiteType != BoiteType.PHOTOS) {
						settings.boiteType = BoiteType.PHOTOS;
						currImages = photos;
						Gdx.graphics.requestRendering();
					}
				} else if (checkPictures.isChecked()) {
					if (settings.boiteType != BoiteType.PICTURES) {
						settings.boiteType = BoiteType.PICTURES;
						currImages = pictures;
						Gdx.graphics.requestRendering();
					}
				}

				int tableSize = settings.boiteHorzCount;
				if (checkTable44.isChecked()) {
					tableSize = 4;
				} else if (checkTable55.isChecked()) {
					tableSize = 5;
				} else if (checkTable66.isChecked()) {
					tableSize = 6;
				}

				if (tableSize != settings.boiteHorzCount) {
					settings.boiteHorzCount = settings.boiteVertCount = tableSize;
					buttonReset.setVisible(true);
				}

				saveSettings();
			}
		};

		dialogSettings.center();
		dialogSettings.padTop(100).padBottom(30);

		Table table = dialogSettings.getContentTable();
		table.defaults().width(250);
		table.add(checkChiffres);
		table.add(checkPhotos);
		table.add(checkPictures);
		table.row().padTop(20);
		table.add(checkTable44);
		table.add(checkTable55);
		table.add(checkTable66);
		table.row();

		table = dialogSettings.getButtonTable();
		table.padTop(30);
		TextButton dbutton = new TextButton("OK", skin);
		table.add(dbutton).width(200f);
		dialogSettings.setObject(dbutton, true);
		dbutton = new TextButton("Annuler", skin);
		table.add(dbutton).width(200f);
		dialogSettings.setObject(dbutton, false);

		dialogSettings.invalidateHierarchy();
		dialogSettings.invalidate();
		dialogSettings.layout();

		dialogReset = new Dialog("", skin, "dialog") {
			protected void result (Object object) {
				Boolean v = (Boolean)object;

				if (v) {
					if (boiteHorzCount != settings.boiteHorzCount) {
						changeTableSize(settings.boiteHorzCount);
					}
					resetGame();
				}
			}
		}.text("Êtes-vous sûr de relancer le jeu?").button("Oui!", true).button("Non!", false).key(Keys.ENTER, true)
			.key(Keys.ESCAPE, false);

		dialog2048 = new Dialog("2048!", skin, "dialog").text("Très bien! Continuez!").button("OK", true);

		dialog4096 = new Dialog("4096!!", skin, "dialog").text("Excellent! Continuez!").button("OK", true);

		dialog8192 = new Dialog("8192!!", skin, "dialog").text("Intelligent! Continuez!").button("OK", true);

		dialog16384 = new Dialog("16384!!", skin, "dialog").text("Génial!! Continuez!").button("OK", true);

		dialog32768 = new Dialog("32768!!", skin, "dialog").text("Incroyable! Continuez!").button("OK", true);

		dialog65536 = new Dialog("65536!!", skin, "dialog")
			.text("Félicitation!\nVous avez obtenu le maximal point!!!").button("OK", true);
	}

	private void showSettings() {
		if (settings.boiteType == BoiteType.CHIFFRES) {
			checkChiffres.setChecked(true);
		} else if (settings.boiteType == BoiteType.PHOTOS) {
			checkPhotos.setChecked(true);
		} else {
			checkPictures.setChecked(true);
		}

		switch (settings.boiteHorzCount) {
		case 4: checkTable44.setChecked(true); break;
		case 5: checkTable55.setChecked(true); break;
		case 6: checkTable66.setChecked(true); break;
		}

		dialogSettings.show(stage);
	}

	@Override
	public void dispose() {
		chiffreImage.dispose();
		batch.dispose();
		renderer.dispose();
	}

	@Override
	public void render() {
		super.render();

		camera.update();
		camera.apply(Gdx.gl10);
		Gdx.gl.glViewport((int) viewport.x, (int) viewport.y,
				(int) viewport.width, (int) viewport.height);

		Gdx.gl.glClearColor(COLEUR_BACKGROUND.r, COLEUR_BACKGROUND.g,
				COLEUR_BACKGROUND.b, COLEUR_BACKGROUND.a);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

		batch.setProjectionMatrix(camera.combined);
		batch.begin();

		font.setColor(1f, 1f, 1f, 0.8f);
		for (int i = 0; i < boiteHorzCount; ++i) {
			for (int j = 0; j < boiteVertCount; ++j) {
				int cur = chiffreTable[i][j];
				if (cur == -1) {
					continue;
				}

				batch.draw(currImages[cur], boitesPos[i][j].x,
						boitesPos[i][j].y, boiteWidth, boiteWidth);
				if (currImages == photos || currImages == pictures) {
					font.draw(batch, "" + (cur + 1), boitesPos[i][j].x + 10,
							boitesPos[i][j].y + FONT_SIZE);
				}
			}
		}
		drawStat();

		batch.end();

		renderer.setProjectionMatrix(camera.combined);
		drawCadre();

		stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1f / 30f));
		stage.draw();

		if (Gdx.input.isKeyPressed(Keys.LEFT))
			move(Direction.LEFT);
		else if (Gdx.input.isKeyPressed(Keys.RIGHT))
			move(Direction.RIGHT);
		else if (Gdx.input.isKeyPressed(Keys.UP))
			move(Direction.UP);
		else if (Gdx.input.isKeyPressed(Keys.DOWN))
			move(Direction.DOWN);
	}

	@Override
	public void resize(int width, int height) {
		float aspectRatio = (float) width / (float) height;
		float scale = 1f;
		Vector2 crop = new Vector2(0f, 0f);

		if (aspectRatio > ASPECT_RATIO) {
			scale = (float) height / (float) SCREEN_HEIGHT;
			crop.x = (width - SCREEN_WIDTH * scale) / 2f;
		} else if (aspectRatio < ASPECT_RATIO) {
			scale = (float) width / (float) SCREEN_WIDTH;
			crop.y = (height - SCREEN_HEIGHT * scale) / 2f;
		} else {
			scale = (float) width / (float) SCREEN_WIDTH;
		}

		float w = (float) SCREEN_WIDTH * scale;
		float h = (float) SCREEN_HEIGHT * scale;
		viewport = new Rectangle(crop.x, crop.y, w, h);

	}

	@Override
	public void pause() {
	}

	@Override
	public void resume() {
		gameStartTime = System.currentTimeMillis();
	}

	private void shufflePhotos() {

		for (int i = 0; i < photos.length; i++) {
			int randomPosition = random.nextInt(photos.length);
			TextureRegion temp = photos[i];
			photos[i] = photos[randomPosition];
			photos[randomPosition] = temp;
		}

	}

	private void shufflePictures() {

		for (int i = 0; i < pictures.length; i++) {
			int randomPosition = random.nextInt(pictures.length);
			TextureRegion temp = pictures[i];
			pictures[i] = pictures[randomPosition];
			pictures[randomPosition] = temp;
		}

	}

	private void calVideBoites() {
		videBoitesCount = 0;
		for (int i = 0; i < boiteHorzCount; ++i) {
			for (int j = 0; j < boiteVertCount; ++j) {
				if (chiffreTable[i][j] == -1) {
					videBoites[videBoitesCount].x = i;
					videBoites[videBoitesCount].y = j;
					++videBoitesCount;
				}
			}
		}
	}

	private void generateChiffre() {
		calVideBoites();

		if (videBoitesCount == 0) {
			return;
		}

		int pos = random.nextInt(videBoitesCount);
		Pos boite = videBoites[pos];
		chiffreTable[boite.x][boite.y] = random.nextInt(20) == 0 ? 1 : 0; // 1 :
																			// 3
	}

	private void move(Direction direction) {
		int[][] bak = chiffreTable.clone();
		for (int i = 0; i < chiffreTable.length; ++i) {
			bak[i] = bak[i].clone();
		}

		int score = 0;
		if (direction == Direction.UP) {
			score = moveUp();
		} else if (direction == Direction.DOWN) {
			score = moveDown();
		} else if (direction == Direction.LEFT) {
			score = moveLeft();
		} else if (direction == Direction.RIGHT) {
			score = moveRight();
		}

		if (score >= 0) {
			++gameCount;
			gameScore += score;
			generateChiffre();
			etapeQueue.enqueue(bak);
			buttonUndo.setVisible(true);
			buttonReset.setVisible(true);
			saveGame();
		}
	}

	private void felicitation(int cur) {

		if (cur > maxChiffre) {
			switch (cur) {
			case 10: dialog2048.show(stage); break;
			case 11: dialog4096.show(stage); break;
			case 12: dialog8192.show(stage); break;
			case 13: dialog16384.show(stage); break;
			case 14: dialog32768.show(stage); break;
			case 15: dialog65536.show(stage); break;
			}
			maxChiffre = cur;
		}
	}

	private int moveRight() {
		boolean moved = false;
		int score = 0;

		for (int j = 0; j < boiteVertCount; ++j) {
			int gap = 0;
			boolean merged = false;

			if (chiffreTable[boiteHorzCount - 1][j] == -1) {
				gap = 1;
			}

			for (int i = boiteHorzCount - 1 - 1; i >= 0; --i) {
				if (chiffreTable[i][j] == -1) {
					++gap;
					continue;
				}

				int cur = chiffreTable[i][j];
				if (gap > 0) {
					chiffreTable[i + gap][j] = cur;
					chiffreTable[i][j] = -1;
					moved = true;
				}

				if (merged) {
					merged = false;
					continue;
				}

				int newi = i + gap;
				if (newi == boiteHorzCount - 1) {
					continue;
				}

				if (chiffreTable[newi + 1][j] == cur && chiffreTable[newi + 1][j] < CHIFFRE_MAX) {
					++chiffreTable[newi + 1][j];
					felicitation(chiffreTable[newi + 1][j]);
					chiffreTable[newi][j] = -1;
					++gap;
					moved = true;
					merged = true;
					score += (1 << (chiffreTable[newi + 1][j] + 1));
					felicitation(chiffreTable[newi + 1][j]);
				}

			}
		}
		if (!moved) {
			return -1;
		}
		return score;
	}

	private int moveLeft() {
		boolean moved = false;
		int score = 0;

		for (int j = 0; j < boiteVertCount; ++j) {
			int gap = 0;
			boolean merged = false;

			if (chiffreTable[0][j] == -1) {
				gap = 1;
			}
			for (int i = 1; i < boiteHorzCount; ++i) {
				if (chiffreTable[i][j] == -1) {
					++gap;
					continue;
				}

				int cur = chiffreTable[i][j];
				if (gap > 0) {
					chiffreTable[i - gap][j] = cur;
					chiffreTable[i][j] = -1;
					moved = true;
				}

				if (merged) {
					merged = false;
					continue;
				}

				int newi = i - gap;
				if (newi == 0) {
					continue;
				}

				if (chiffreTable[newi - 1][j] == cur && chiffreTable[newi - 1][j] < CHIFFRE_MAX) {
					++chiffreTable[newi - 1][j];
					chiffreTable[newi][j] = -1;
					++gap;
					moved = true;
					merged = true;
					score += (1 << (chiffreTable[newi - 1][j] + 1));
					felicitation(chiffreTable[newi - 1][j]);
				}
			}
		}
		if (!moved) {
			return -1;
		}
		return score;
	}

	private int moveDown() {
		boolean moved = false;
		int score = 0;

		for (int i = 0; i < boiteHorzCount; ++i) {
			int gap = 0;
			boolean merged = false;

			if (chiffreTable[i][boiteVertCount - 1] == -1) {
				gap = 1;
			}

			for (int j = boiteVertCount - 1 - 1; j >= 0; --j) {
				if (chiffreTable[i][j] == -1) {
					++gap;
					continue;
				}

				int cur = chiffreTable[i][j];
				if (gap > 0) {
					chiffreTable[i][j + gap] = cur;
					chiffreTable[i][j] = -1;
					moved = true;
				}

				if (merged) {
					merged = false;
					continue;
				}

				int newj = j + gap;
				if (newj == boiteVertCount - 1) {
					continue;
				}

				if (chiffreTable[i][newj + 1] == cur && chiffreTable[i][newj + 1] < CHIFFRE_MAX) {
					++chiffreTable[i][newj + 1];
					chiffreTable[i][newj] = -1;
					++gap;
					moved = true;
					merged = true;
					score += (1 << (chiffreTable[i][newj + 1] + 1));
					felicitation(chiffreTable[i][newj + 1]);
				}
			}
		}

		if (!moved) {
			return -1;
		}
		return score;
	}

	private int moveUp() {
		boolean moved = false;
		int score = 0;

		for (int i = 0; i < boiteHorzCount; ++i) {
			int gap = 0;
			boolean merged = false;

			if (chiffreTable[i][0] == -1) {
				gap = 1;
			}

			for (int j = 1; j < boiteVertCount; ++j) {
				if (chiffreTable[i][j] == -1) {
					++gap;
					continue;
				}

				int cur = chiffreTable[i][j];
				if (gap > 0) {
					chiffreTable[i][j - gap] = cur;
					chiffreTable[i][j] = -1;
					moved = true;
				}

				if (merged) {
					merged = false;
					continue;
				}

				int newj = j - gap;
				if (newj == 0) {
					continue;
				}

				if (chiffreTable[i][newj - 1] == cur && chiffreTable[i][newj - 1] < CHIFFRE_MAX) {
					++chiffreTable[i][newj - 1];
					chiffreTable[i][newj] = -1;
					++gap;
					moved = true;
					merged = true;
					score += (1 << (chiffreTable[i][newj - 1] + 1));
					felicitation(chiffreTable[i][newj - 1]);
				}
			}
		}

		if (!moved) {
			return -1;
		}
		return score;
	}

	@Override
	public boolean touchDown(float x, float y, int pointer, int button) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean tap(float x, float y, int count, int button) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean longPress(float x, float y) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean fling(float velocityX, float velocityY, int button) {
		float x = Math.abs(velocityX);
		float y = Math.abs(velocityY);
		int comp = Float.compare(x, y);

		if (comp > 0) {
			if (velocityX > 0.0) {
				move(Direction.RIGHT);
			} else if (velocityX < 0.0) {
				move(Direction.LEFT);
			} else {
				return false;
			}
		} else {
			if (velocityY > 0.0) {
				move(Direction.DOWN);
			} else if (velocityY < 0.0) {
				move(Direction.UP);
			} else {
				return false;
			}
		}

		return true;
	}

	@Override
	public boolean pan(float x, float y, float deltaX, float deltaY) {
		return false;
	}

	@Override
	public boolean zoom(float initialDistance, float distance) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
			Vector2 pointer1, Vector2 pointer2) {
		// TODO Auto-generated method stub
		return false;
	}
}


text:
package org.rocket.guice;

import com.google.inject.MembersInjector;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

import java.util.function.BiConsumer;

public final class GuiceDSL {
	private GuiceDSL() {}

	public static TypeListener listener(BiConsumer<TypeLiteral<?>, TypeEncounter<?>> fn) {
		return new TypeListener() {
			@Override
			public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
				fn.accept(type, encounter);
			}
		};
	}

	public static <T> MembersInjector<T> members(MembersInjector<T> fn) {
		return fn;
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var CSSProperty = require('CSSProperty');
var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');

var camelizeStyleName = require('fbjs/lib/camelizeStyleName');
var dangerousStyleValue = require('dangerousStyleValue');
var getComponentName = require('getComponentName');
var hyphenateStyleName = require('fbjs/lib/hyphenateStyleName');
var memoizeStringOnly = require('fbjs/lib/memoizeStringOnly');
var warning = require('fbjs/lib/warning');

if (__DEV__) {
  var {getCurrentFiberOwnerName} = require('ReactDebugCurrentFiber');
}

var processStyleName = memoizeStringOnly(function(styleName) {
  return hyphenateStyleName(styleName);
});

var hasShorthandPropertyBug = false;
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
  var tempStyle = document.createElement('div').style;
  try {
    // IE8 throws "Invalid argument." if resetting shorthand style properties.
    tempStyle.font = '';
  } catch (e) {
    hasShorthandPropertyBug = true;
  }
  // IE8 only supports accessing cssFloat (standard) as styleFloat
  if (document.documentElement.style.cssFloat === undefined) {
    styleFloatAccessor = 'styleFloat';
  }
}

if (__DEV__) {
  // 'msTransform' is correct, but the other prefixes should be capitalized
  var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;

  // style values shouldn't contain a semicolon
  var badStyleValueWithSemicolonPattern = /;\s*$/;

  var warnedStyleNames = {};
  var warnedStyleValues = {};
  var warnedForNaNValue = false;

  var warnHyphenatedStyleName = function(name, owner) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;
    warning(
      false,
      'Unsupported style property %s. Did you mean %s?%s',
      name,
      camelizeStyleName(name),
      checkRenderMessage(owner),
    );
  };

  var warnBadVendoredStyleName = function(name, owner) {
    if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
      return;
    }

    warnedStyleNames[name] = true;
    warning(
      false,
      'Unsupported vendor-prefixed style property %s. Did you mean %s?%s',
      name,
      name.charAt(0).toUpperCase() + name.slice(1),
      checkRenderMessage(owner),
    );
  };

  var warnStyleValueWithSemicolon = function(name, value, owner) {
    if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
      return;
    }

    warnedStyleValues[value] = true;
    warning(
      false,
      "Style property values shouldn't contain a semicolon.%s " +
        'Try "%s: %s" instead.',
      checkRenderMessage(owner),
      name,
      value.replace(badStyleValueWithSemicolonPattern, ''),
    );
  };

  var warnStyleValueIsNaN = function(name, value, owner) {
    if (warnedForNaNValue) {
      return;
    }

    warnedForNaNValue = true;
    warning(
      false,
      '`NaN` is an invalid value for the `%s` css style property.%s',
      name,
      checkRenderMessage(owner),
    );
  };

  var checkRenderMessage = function(owner) {
    var ownerName;
    if (owner != null) {
      // Stack passes the owner manually all the way to CSSPropertyOperations.
      ownerName = getComponentName(owner);
    } else {
      // Fiber doesn't pass it but uses ReactDebugCurrentFiber to track it.
      // It is only enabled in development and tracks host components too.
      ownerName = getCurrentFiberOwnerName();
      // TODO: also report the stack.
    }
    if (ownerName) {
      return '\n\nCheck the render method of `' + ownerName + '`.';
    }
    return '';
  };

  /**
   * @param {string} name
   * @param {*} value
   * @param {ReactDOMComponent} component
   */
  var warnValidStyle = function(name, value, component) {
    var owner;
    if (component) {
      owner = component._currentElement._owner;
    }
    if (name.indexOf('-') > -1) {
      warnHyphenatedStyleName(name, owner);
    } else if (badVendoredStyleNamePattern.test(name)) {
      warnBadVendoredStyleName(name, owner);
    } else if (badStyleValueWithSemicolonPattern.test(value)) {
      warnStyleValueWithSemicolon(name, value, owner);
    }

    if (typeof value === 'number' && isNaN(value)) {
      warnStyleValueIsNaN(name, value, owner);
    }
  };
}

/**
 * Operations for dealing with CSS properties.
 */
var CSSPropertyOperations = {
  /**
   * Serializes a mapping of style properties for use as inline styles:
   *
   *   > createMarkupForStyles({width: '200px', height: 0})
   *   "width:200px;height:0;"
   *
   * Undefined values are ignored so that declarative programming is easier.
   * The result should be HTML-escaped before insertion into the DOM.
   *
   * @param {object} styles
   * @param {ReactDOMComponent} component
   * @return {?string}
   */
  createMarkupForStyles: function(styles, component) {
    var serialized = '';
    for (var styleName in styles) {
      if (!styles.hasOwnProperty(styleName)) {
        continue;
      }
      var styleValue = styles[styleName];
      if (__DEV__) {
        warnValidStyle(styleName, styleValue, component);
      }
      if (styleValue != null) {
        serialized += processStyleName(styleName) + ':';
        serialized += dangerousStyleValue(styleName, styleValue, component) +
          ';';
      }
    }
    return serialized || null;
  },

  /**
   * Sets the value for multiple styles on a node.  If a value is specified as
   * '' (empty string), the corresponding style property will be unset.
   *
   * @param {DOMElement} node
   * @param {object} styles
   * @param {ReactDOMComponent} component
   */
  setValueForStyles: function(node, styles, component) {
    var style = node.style;
    for (var styleName in styles) {
      if (!styles.hasOwnProperty(styleName)) {
        continue;
      }
      if (__DEV__) {
        warnValidStyle(styleName, styles[styleName], component);
      }
      var styleValue = dangerousStyleValue(
        styleName,
        styles[styleName],
        component,
      );
      if (styleName === 'float' || styleName === 'cssFloat') {
        styleName = styleFloatAccessor;
      }
      if (styleValue) {
        style[styleName] = styleValue;
      } else {
        var expansion = hasShorthandPropertyBug &&
          CSSProperty.shorthandPropertyExpansions[styleName];
        if (expansion) {
          // Shorthand property that IE8 won't like unsetting, so unset each
          // component to placate it
          for (var individualStyleName in expansion) {
            style[individualStyleName] = '';
          }
        } else {
          style[styleName] = '';
        }
      }
    }
  },
};

module.exports = CSSPropertyOperations;


text:
package com.netflix.spinnaker.halyard.config.model.v1.providers.dcos;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.netflix.spinnaker.halyard.config.model.v1.node.*;
import com.netflix.spinnaker.halyard.config.model.v1.providers.containers.ContainerAccount;
import com.netflix.spinnaker.halyard.config.model.v1.providers.dockerRegistry.DockerRegistryProvider;
import com.netflix.spinnaker.halyard.config.problem.v1.ConfigProblemSetBuilder;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
@JsonIgnoreProperties({"providerVersion"})
public class DCOSAccount extends ContainerAccount {
  private List<ClusterCredential> clusters;

  @Override
  public NodeIterator getChildren() {
    return NodeIteratorFactory.makeListIterator(
        clusters.stream().map(c -> (Node) c).collect(Collectors.toList()));
  }

  public void removeCredential(String name, String uid) {
    clusters.removeIf(c -> c.getName().equals(name) && c.getUid().equals(uid));
  }

  protected List<String> dockerRegistriesOptions(ConfigProblemSetBuilder psBuilder) {
    DeploymentConfiguration context = parentOfType(DeploymentConfiguration.class);
    DockerRegistryProvider dockerRegistryProvider = context.getProviders().getDockerRegistry();

    if (dockerRegistryProvider != null) {
      return dockerRegistryProvider.getAccounts().stream()
          .map(Account::getName)
          .collect(Collectors.toList());
    } else {
      return null;
    }
  }

  @Data
  @EqualsAndHashCode(callSuper = false)
  public static class ClusterCredential extends Node implements Cloneable {
    private final String name;
    private final String uid;
    @Secret private final String password;
    @LocalFile @SecretFile private final String serviceKeyFile;

    @Override
    public String getNodeName() {
      return name;
    }

    @Override
    public NodeIterator getChildren() {
      return NodeIteratorFactory.makeEmptyIterator();
    }
  }
}


text:
<?php

/**
 * This example shows how to get the language for all
 * languages written in native letters
 *
 * So en = english de = deutsch da = dánsk and so on
 */

/**
 * @see Zend_Locale
 */
require_once 'Zend/Locale.php';

$list = Zend_Locale::getTranslationList('language');

foreach($list as $language => $content) {
    try {
        $lang = Zend_Locale::getTranslation($language, 'language', $language);
        print "\n<br>[".$language."] ".$lang;
    } catch (Exception $e) {
        // no output
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_t58_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mcodegeeks.tutorial.T58_AudioCapture.T58MainActivity">

    <TextView
        android:id="@+id/titleView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/t58_title"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="20dp" />

</RelativeLayout>


text:
#import "OBACoordinateBounds.h"

@implementation OBACoordinateBounds

- (id) init {
    self = [super init];
    if( self ) {
        _empty = YES;
    }
    return self;
}

- (id) initWithBounds:(OBACoordinateBounds*)bounds {
    self = [super init];
    if (self) {
        _empty = bounds.empty;
        _minLatitude = bounds.minLatitude;
        _maxLatitude = bounds.maxLatitude;
        _minLongitude = bounds.minLongitude;
        _maxLongitude = bounds.maxLongitude;
    }
    return self;
}

- (id) initWithRegion:(MKCoordinateRegion)region {
    self = [super init];
    if( self ) {
        _empty = YES;
        [self addRegion:region];
    }
    return self;
}

- (id) initWithCoder:(NSCoder*)coder {
    self = [super init];
    if( self ) {
        _empty = [coder decodeBoolForKey:@"empty"];
        _minLatitude = [coder decodeDoubleForKey:@"minLatitude"];
        _maxLatitude = [coder decodeDoubleForKey:@"maxLatitude"];
        _minLongitude = [coder decodeDoubleForKey:@"minLongitude"];
        _maxLongitude = [coder decodeDoubleForKey:@"maxLongitude"];
    }
    return self;
}

+ (id) bounds {
    return [[OBACoordinateBounds alloc] init];
}

- (MKCoordinateRegion) region {
    return MKCoordinateRegionMake([self center],[self span]);
}

- (CLLocationCoordinate2D) center {
    CLLocationCoordinate2D center = {0.0,0.0};
    if( ! _empty ) {
        center.latitude = (_minLatitude + _maxLatitude)/2;
        center.longitude = (_minLongitude + _maxLongitude)/2;
    }
    return center;
}

- (MKCoordinateSpan) span {
    MKCoordinateSpan span = MKCoordinateSpanMake(0.0,0.0);
    if( ! _empty ) {
        span.latitudeDelta = _maxLatitude - _minLatitude;
        span.longitudeDelta = _maxLongitude - _minLongitude;
    }
    return span;
}

- (void) addRegion:(MKCoordinateRegion)region {
    CLLocationCoordinate2D c = region.center;
    MKCoordinateSpan span = region.span;
    [self addLat:c.latitude-span.latitudeDelta/2 lon:c.longitude-span.longitudeDelta/2];
    [self addLat:c.latitude+span.latitudeDelta/2 lon:c.longitude+span.longitudeDelta/2];
}

- (void) addLocations:(NSArray*)locations {
    for( CLLocation * location in locations)
        [self addLocation:location];
}

- (void) addLocation:(CLLocation*)location {
    [self addCoordinate:location.coordinate];
}

- (void) addCoordinate:(CLLocationCoordinate2D)coordinate {
    [self addLat:coordinate.latitude lon:coordinate.longitude];
}

- (void) addLat:(double)lat lon:(double)lon {
    if( _empty ) {
        _empty = NO;

        _minLatitude = lat;
        _maxLatitude = lat;
        _minLongitude = lon;
        _maxLongitude = lon;
    }
    else {
        _minLatitude = MIN(_minLatitude,lat);
        _maxLatitude = MAX(_maxLatitude,lat);
        _minLongitude = MIN(_minLongitude,lon);
        _maxLongitude = MAX(_maxLongitude,lon);
    }
}

- (void) expandByRatio:(double)ratio {
    if( _empty )
        return;
    double latDelta = (_maxLatitude - _minLatitude) * ratio / 2;
    double lonDelta = (_maxLongitude - _minLongitude) * ratio / 2;
    _maxLatitude += latDelta;
    _minLatitude -= latDelta;
    _maxLongitude += lonDelta;
    _minLongitude -= lonDelta;
}

- (NSString*) description {
    return [NSString stringWithFormat:@"%f %f %f %f",_minLatitude,_minLongitude,_maxLatitude,_maxLongitude];
}

#pragma mark NSCoder Methods

- (void) encodeWithCoder: (NSCoder *)coder {
    [coder encodeBool:_empty forKey:@"empty"];
    [coder encodeDouble:_minLatitude forKey:@"minLatitude"];
    [coder encodeDouble:_maxLatitude forKey:@"maxLatitude"];
    [coder encodeDouble:_minLongitude forKey:@"minLongitude"];
    [coder encodeDouble:_maxLongitude forKey:@"maxLongitude"];
}

@end


text:
package dxat.appserver.manager;

import java.util.List;
import java.util.Map.Entry;

import dxat.appserver.manager.database.Create;
import dxat.appserver.manager.database.Delete;
import dxat.appserver.manager.database.Update;
import dxat.appserver.manager.exceptions.OrgNotFoundException;
import dxat.appserver.manager.exceptions.TerminalAlreadyExistsException;
import dxat.appserver.manager.exceptions.TerminalNotFoundException;
import dxat.appserver.manager.pojos.OrgTerminal;
import dxat.appserver.topology.pojos.Terminal;
import dxat.appserver.topology.pojos.TerminalCollection;

public class OrgTerminalManager {
	private static OrgTerminalManager instance;
	public OrgManager orgManager;
	private Create dbcreate;
	public Update dbupdate;
	public Delete dbdelete;

	private OrgTerminalManager(){
		//TODO initialize!
		dbupdate = new Update();
		dbcreate = new Create();
		dbdelete = new Delete();
		orgManager = OrgManager.getInstance();

	}
	public static OrgTerminalManager getInstance(){
		if(instance == null)
			instance = new OrgTerminalManager();
		return instance;
	}
	public List<OrgTerminal> getAllOrgTerminals(String orgId){
		//TODO
		return null;
	}

	public OrgTerminal getOrgTerminal(String orgId, String terminalId){
		//TODO
		return null;
	}
	public void deleteOrgTerminal(String orgId, String terminalId){
		//TODO
	}

	//ADD/PUT HM
	public OrgTerminal putOrgTerminal(OrgTerminal terminal){
		orgManager.getTerminals().put(terminal.getIdentifier(), terminal);
		return terminal;
	}

	//ALSO CALLED FROM TOPO RESOURCE PUT
	//CREATE TERMINAL TO DB IF ASSIGNING ORG FROM MANAGER
	//UPDATE  HM AND CREATE(only if assigned orgId) DB
	public OrgTerminal tryCreateOrgTerminal(String orgId, OrgTerminal terminal){
		OrgTerminal oterminal = new OrgTerminal();
		oterminal.setActive(true);
		oterminal.setIdentifier(Integer.toString(terminal.getMac().hashCode()));
		oterminal.setIpAddress(terminal.getIpAddress());
		oterminal.setPortApiID(terminal.getPortApiID());
		oterminal.setAssigned(true);
		oterminal.setAssignedOrgId(orgId);
		oterminal.setDescription(terminal.getDescription());
		oterminal.setHostName(terminal.getHostName());
		oterminal.setIfaceSpeed(terminal.getIfaceSpeed());
		oterminal.setMac(terminal.getMac());

		if(orgId!=null){
			try {
				orgManager.getTerminals().put(oterminal.getIdentifier(), oterminal);
				orgManager.getOrg(orgId).getTerminals().put(oterminal.getIdentifier(), oterminal);
				dbcreate.createTerminal(oterminal, orgId);
				return oterminal;
			} catch (TerminalAlreadyExistsException | OrgNotFoundException e) {
				e.printStackTrace();
			}
		}
//		else{
//
//			//TODO CHECK IF NEED TO EXIST THIS ELSE OPTION (should never enter here)
//
//			try {
//				dbupdate.updateTerminal(terminal, terminal.getAssignedOrgId());
//				return terminal;
//			} catch (TerminalNotFoundException | OrgNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		return null;
	}

	//UPDATE ORG TERMINALS FROM TOPO TERMINALS
	public void updateOrgTerminals(TerminalCollection allTTerminals) {
		boolean updated;
		boolean found;
		String idFound = null;
		for(Terminal tterminal : allTTerminals.getTerminals()){
			OrgTerminal newterminal = new OrgTerminal();
			OrgTerminal oterminal = new OrgTerminal();

			//TODO CHECK NUMBER OF TTERMINALS
			System.out.println("SIZE OF T.TERMINALS COLLECTION : "+allTTerminals.getTerminals().size());

			if(!tterminal.getPortAPId().equals("00:00:00:00:00:00:00:00:0") && !tterminal.getIpv4().equals("0.0.0.0")){
				updated = false;
				found = false;
				if(!orgManager.getTerminals().isEmpty()){
					for(Entry<String, OrgTerminal> allOTerminals : orgManager.getTerminals().entrySet()){
						oterminal = allOTerminals.getValue();

						if(oterminal.getMac().equals(tterminal.getMac())){
							found = true;
							idFound = Integer.toString(tterminal.getTerminalId().hashCode());
							break;
						}
					}
					if(found){
						found = false;
						if(!orgManager.getTerminals().get(idFound).getIdentifier().equals(Integer.toString(tterminal.getTerminalId().hashCode()))){
							orgManager.getTerminals().get(idFound).setIdentifier(Integer.toString(tterminal.getTerminalId().hashCode()));
							System.out.println("[TERMINAL TOPOLOGY TO MANAGER] INCONGRUENCE! (but... could be the first check of this terminal! ;) )");
							System.out.println("------------> matching of mac but not of ids -> setting id O.Term. from topo");
						}
						//update HM and DB with updated oterminal
						//FALTA XEQUEJAR SI TÉ ASSIGNED ORG AQUÍ!!!
						if(orgManager.getTerminals().get(idFound).getAssignedOrgId()==null){
							System.out.println("UPDATING TERMINAL HM: "+Integer.toString(tterminal.getTerminalId().hashCode()));

							//ONLY ADD HM
							//update oterminal
							updated = true;
							oterminal.setActive(true);
							oterminal.setIdentifier(Integer.toString(tterminal.getMac().hashCode()));
							oterminal.setIpAddress(tterminal.getIpv4());
							oterminal.setPortApiID(tterminal.getPortAPId());
							oterminal.setAssigned(true);
							oterminal.setAssignedOrgId(null);
							oterminal.setDescription(orgManager.getTerminals().get(idFound).getDescription());
							oterminal.setHostName(orgManager.getTerminals().get(idFound).getHostName());
							oterminal.setIfaceSpeed(orgManager.getTerminals().get(idFound).getIfaceSpeed());
							oterminal.setMac(tterminal.getMac());
//							orgManager.getTerminals().get(idFound).setActive(true);
//							orgManager.getTerminals().get(idFound).setIdentifier(tterminal.getTerminalId());
//							orgManager.getTerminals().get(idFound).setIpAddress(tterminal.getIpv4());
//							orgManager.getTerminals().get(idFound).setPortApiID(tterminal.getPortAPId());
							putOrgTerminal(oterminal);
						}else{
							System.out.println("UPDATING ORG TERMINAL HM AND DB: "+Integer.toString(tterminal.getTerminalId().hashCode()));
							//update oterminal
							//CHECK IF TERMINAL IN ORG
							updated = true;
							oterminal.setActive(true);
							oterminal.setIdentifier(Integer.toString(tterminal.getMac().hashCode()));
							oterminal.setIpAddress(tterminal.getIpv4());
							oterminal.setPortApiID(tterminal.getPortAPId());
							oterminal.setAssigned(true);
							oterminal.setAssignedOrgId(orgManager.getTerminals().get(idFound).getAssignedOrgId());
							oterminal.setDescription(orgManager.getTerminals().get(idFound).getDescription());
							oterminal.setHostName(orgManager.getTerminals().get(idFound).getHostName());
							oterminal.setIfaceSpeed(orgManager.getTerminals().get(idFound).getIfaceSpeed());
							oterminal.setMac(tterminal.getMac());
//							orgManager.getTerminals().get(idFound).setActive(true);
//							orgManager.getTerminals().get(idFound).setIdentifier(tterminal.getTerminalId());
//							orgManager.getTerminals().get(idFound).setIpAddress(tterminal.getIpv4());
//							orgManager.getTerminals().get(idFound).setPortApiID(tterminal.getPortAPId());
							try {
								dbupdate.updateTerminal(oterminal, oterminal.getAssignedOrgId());
								orgManager.getOrg(oterminal.getAssignedOrgId()).getTerminals().put(oterminal.getIdentifier(), oterminal);
								orgManager.getTerminals().put(oterminal.getIdentifier(), oterminal);
							} catch (TerminalNotFoundException
									| OrgNotFoundException e) {
								e.printStackTrace();
							}
						}
					}
					if(!updated){
						System.out.println("NEW TERMINAL: "+tterminal.getTerminalId());
						updated = false;
						//PUSH OTERMINAL - orgId = null - setActive -
						newterminal.setActive(true);
						newterminal.setAssigned(false);
						newterminal.setDescription("new terminal from topology");
						newterminal.setIdentifier(Integer.toString(tterminal.getMac().hashCode()));
						newterminal.setPortApiID(tterminal.getPortAPId());
						newterminal.setHostName("not set");
						newterminal.setIfaceSpeed(0);
						newterminal.setIpAddress(tterminal.getIpv4());
						newterminal.setMac(tterminal.getMac());
						newterminal.setAssignedOrgId(null);
						putOrgTerminal(newterminal);
					}
				}else{
					//PUSH FIRST OTERMINAL - orgId = null - setActive -
					System.out.println("FIRST TERMINAL: "+tterminal.getTerminalId());
					newterminal.setActive(true);
					newterminal.setAssigned(false);
					newterminal.setDescription("new terminal from topology");
					newterminal.setIdentifier(Integer.toString(tterminal.getMac().hashCode()));
					newterminal.setPortApiID(tterminal.getPortAPId());
					newterminal.setHostName("not set");
					newterminal.setIfaceSpeed(0);
					newterminal.setIpAddress(tterminal.getIpv4());
					newterminal.setMac(tterminal.getMac());
					newterminal.setAssignedOrgId(null);
					putOrgTerminal(newterminal);
				}
			}
		}
	}
}


text:
var expect = require('chai').expect
  , zephyr = require('zephyr')();

describe('Zephyr:', function() {

  it('should add instance method', function(done) {
    zephyr.plugin([require('../fixture/instance-plugin')]);
    var z = zephyr();
    expect(z.callback).to.be.a('function');
    z.callback(done);
  });

});


text:
package org.wso2.carbon.usage.agent.util;

import java.io.IOException;
import java.io.Writer;

/**
 * this class is used to wrap Writer object
 */
public class MonitoredWriter extends Writer {
    Writer writer;
    long totalWritten;

    public MonitoredWriter(Writer writer) {
        this.writer = writer;
        totalWritten = 0;
    }

    public void write(char cbuf[], int off, int len) throws IOException {
        totalWritten += (len - off);
        writer.write(cbuf, off, len);
    }

    public void flush() throws IOException {
        writer.flush();
    }

    public void close() throws IOException {
        writer.close();
    }

    public long getTotalWritten() {
        return totalWritten;
    }
}


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <stdint.h>
#include <fixedmath.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>

#include "up_arch.h"

#include "chip/imxrt_wdog.h"
#include "imxrt_config.h"
#include "imxrt_log.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/
#define LOG_BUF_LENGTH 1024
#define LAST_LOG_BUF_LENGTH 32
/* Configuration ************************************************************/

/****************************************************************************
 * Private Data
 ****************************************************************************/
uint8_t log_buffer[LOG_BUF_LENGTH];
uint8_t last_log_buffer[LAST_LOG_BUF_LENGTH];

uint32_t current_log_length = 0;

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: imxrt_log_write_kernelbuffer
 *
 * Description:
 *   Save the log when booting
 *
 ****************************************************************************/

void imxrt_log_write_kernelbuffer(const uint8_t *log_string, const uint32_t log_length)
{
	memset(last_log_buffer, 0, LAST_LOG_BUF_LENGTH);

	if (log_length > LAST_LOG_BUF_LENGTH - 1) {
		memcpy(last_log_buffer, log_string, LAST_LOG_BUF_LENGTH-1);
	} else {
		memcpy(last_log_buffer, log_string, log_length);
	}

	if (current_log_length + log_length > LOG_BUF_LENGTH - 1) {
		current_log_length = 0;
		return;
	}

	memcpy(&log_buffer[current_log_length], log_string, log_length);
	current_log_length += log_length;
	log_buffer[current_log_length] = '\n';
	current_log_length += 1;
}

/****************************************************************************
 * Name: imxrt_log_print_kernelbuffer
 *
 * Description:
 *   Called when kernel log can be printed
 *
 ****************************************************************************/

void imxrt_log_print_kernelbuffer(void)
{
	printf("\n");
	printf("#### LAST LOG ########\n");
	printf("%s", last_log_buffer);
	printf("\n");
	printf("#### TOTAL LOG #######\n");
	printf("%s", log_buffer);
	printf("\n");
}


text:
package org.strykeforce.swerve;

import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveDriveOdometry;
import edu.wpi.first.math.kinematics.SwerveModuleState;

/** The default odometry strategy that wraps a {@code SwerveDriveOdometry}. */
public class KinematicOdometryStrategy implements OdometryStrategy {

  private final SwerveDriveOdometry odometry;

  public KinematicOdometryStrategy(
      SwerveDriveKinematics kinematics, Rotation2d gyroAngle, Pose2d initialPose) {
    this.odometry = new SwerveDriveOdometry(kinematics, gyroAngle, initialPose);
  }

  public KinematicOdometryStrategy(SwerveDriveKinematics kinematics, Rotation2d gyroAngle) {
    this(kinematics, gyroAngle, new Pose2d());
  }

  @Override
  public Pose2d getPoseMeters() {
    return odometry.getPoseMeters();
  }

  @Override
  public void resetPosition(Pose2d pose, Rotation2d gyroAngle) {
    odometry.resetPosition(pose, gyroAngle);
  }

  @Override
  public Pose2d update(Rotation2d gyroAngle, SwerveModuleState... moduleStates) {
    return odometry.update(gyroAngle, moduleStates);
  }

  @Override
  public Pose2d updateWithTime(
      double currentTimeSeconds, Rotation2d gyroAngle, SwerveModuleState... moduleStates) {
    return odometry.updateWithTime(currentTimeSeconds, gyroAngle, moduleStates);
  }
}


text:
s3fs $S3BUCKET:$S3PATH /data/Packages -o iam_role=$AWS_IAM_ROLE,allow_other,rw

mkdir /tmp/$TOMCAT
CATALINA_TMPDIR=/tmp/$TOMCAT
CATALINA_HOME=/usr/share/$TOMCAT
CATALINA_BASE=/var/lib/$TOMCAT
TOMCAT7_SECURITY=no
export CATALINA_TMPDIR CATALINA_HOME CATALINA_BASE TOMCAT7_SECURITY NUGET_HOME
/usr/share/$TOMCAT/bin/catalina.sh run


text:
package com.example.leandro.appcar.control.persistence;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.leandro.appcar.control.SQLiteConnector;
import com.example.leandro.appcar.control.Util;
import com.example.leandro.appcar.control.rest.CarroJSON;
import com.example.leandro.appcar.control.server.ConnectorSocket;
import com.example.leandro.appcar.model.Carro;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CarroDao {

    private SQLiteConnector connector;
    private Context context;

    public CarroDao(Context context) {
        this.connector = new SQLiteConnector(context);
        this.context = context;
    }

    public long save(Carro carro) {
        long i;
        SQLiteDatabase db = connector.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("cod", carro.getCod());
        values.put("marca", carro.getMarca());
        values.put("modelo", carro.getModelo());
        values.put("cor", carro.getCor());
        values.put("ano", carro.getAno());
        values.put("chassi", carro.getChassi());
        values.put("km", carro.getKm());
        values.put("placa", carro.getPlaca());
        values.put("obs", carro.getObs());
        values.put("dono_codigo", carro.getDono());

            i = db.insert("carro", null, values);

        db.close();
        return i;
    }

    public void remove(Carro carro) {
        SQLiteDatabase db = connector.getWritableDatabase();
        db.delete("carro", "cod = ?", new String[]{String.valueOf(carro.getCod())});
        db.close();
    }

    public List<Carro> getAll() {
        SQLiteDatabase db = connector.getReadableDatabase();
        List<Carro> carros = new ArrayList<>();
        Cursor cursor = db.query("carro", null, null, null, null, null, null);

        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    do {
                        Carro carro = new Carro();
                        carro.setCod(cursor.getInt(cursor.getColumnIndex("cod")));
                        carro.setMarca((cursor.getString(cursor.getColumnIndex("marca"))));
                        carro.setModelo((cursor.getString(cursor.getColumnIndex("modelo"))));
                        carro.setCor((cursor.getString(cursor.getColumnIndex("cor"))));
                        carro.setAno((cursor.getString(cursor.getColumnIndex("ano"))));
                        carro.setChassi((cursor.getString(cursor.getColumnIndex("chassi"))));
                        carro.setKm((cursor.getString(cursor.getColumnIndex("km"))));
                        carro.setPlaca((cursor.getString(cursor.getColumnIndex("placa"))));
                        carro.setObs((cursor.getString(cursor.getColumnIndex("obs"))));
                        carro.setDono(cursor.getInt(cursor.getColumnIndex("dono_codigo")));
                        carros.add(carro);
                    } while (cursor.moveToNext());
                }
            } finally {
                cursor.close();
            }
        }
        db.close();
        return carros;
    }

    public Carro get(int id) {
        SQLiteDatabase db = connector.getReadableDatabase();

        Cursor cursor = db.query("Carro", null, "cod=?", new String[]{String.valueOf(id)}, null, null, null, null);
        Carro carro = new Carro();
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    carro.setCod(cursor.getInt(cursor.getColumnIndex("cod")));
                    carro.setMarca((cursor.getString(cursor.getColumnIndex("marca"))));
                    carro.setModelo((cursor.getString(cursor.getColumnIndex("modelo"))));
                    carro.setCor((cursor.getString(cursor.getColumnIndex("cor"))));
                    carro.setAno((cursor.getString(cursor.getColumnIndex("ano"))));
                    carro.setChassi((cursor.getString(cursor.getColumnIndex("chassi"))));
                    carro.setKm((cursor.getString(cursor.getColumnIndex("km"))));
                    carro.setPlaca((cursor.getString(cursor.getColumnIndex("placa"))));
                    carro.setObs((cursor.getString(cursor.getColumnIndex("obs"))));
                    carro.setDono(cursor.getInt(cursor.getColumnIndex("dono_codigo")));
                }
            } finally {
                cursor.close();
            }
        }
        db.close();
        return carro;

    }

    public void truncate() {
        SQLiteDatabase db = connector.getWritableDatabase();
        Cursor cursor = db.query("carro", null, null, null, null, null, null);
        if (cursor.getCount() > 0) {
            db.delete("carro", null, null);
        }
        db.close();
    }

    public void populateSocket() {
        this.truncate();
        try {
            JSONArray array = new JSONObject(new ConnectorSocket().execute(Util.geraJSON("get_Carro_All")).get()).getJSONObject("return").getJSONArray("carro");
            for (int i = 0; i < array.length(); i++) {
                System.out.println(array.getJSONObject(i));
                this.save(CarroJSON.getCarroJSON(array.getJSONObject(i)));
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}


text:
import json

from django.core.management.base import BaseCommand

from rest_framework_swagger.urlparser import UrlParser
from rest_framework_swagger import SWAGGER_SETTINGS
from rest_framework_swagger.docgenerator import DocumentationGenerator

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--path',
                    action='store',
                    default=None)
        parser.add_argument('--urlconf',
                    action='store',
                    default=None)

    def handle(self, path=None, urlconf=None, *args, **options):
        if path is None:
            data = self.get_resource_listing(urlconf=urlconf)
        else:
            data = self.get_api_declaration(path, urlconf=urlconf)
        print json.dumps(data, indent=2, sort_keys=True)

    def get_resource_listing(self, urlconf):
        apis = self.get_apis(urlconf=urlconf)
        data = {
            'apiVersion': SWAGGER_SETTINGS.get('api_version', ''),
            'swaggerVersion': '1.2',
            'apis': apis,
            'info': SWAGGER_SETTINGS.get('info', {
                # 'contact': '',
                'description': '',
                'license': '',
                'licenseUrl': '',
                'termsOfServiceUrl': '',
                'title': '',
            }),
        }
        return data

    def get_apis(self, urlconf):
        apis = []
        resources = self.get_resources(urlconf=urlconf)

        for path in resources:
            apis.append({
                'path': "/%s" % path,
            })
        return apis

    def get_resources(self, urlconf):
        urlparser = UrlParser()
        apis = urlparser.get_apis(exclude_namespaces=SWAGGER_SETTINGS.get('exclude_namespaces'), urlconf=urlconf)
        resources = urlparser.get_top_level_apis(apis)
        return resources

    def get_api_declaration(self, path, urlconf):
        api_full_uri = SWAGGER_SETTINGS.get('api_full_uri')

        apis = self.get_api_for_resource(path, urlconf=urlconf)
        generator = DocumentationGenerator()

        return {
            'apiVersion': SWAGGER_SETTINGS.get('api_version', ''),
            'swaggerVersion': '1.2',
            'basePath': api_full_uri.rstrip('/'),
            'resourcePath': '/' + path,
            'apis': generator.generate(apis),
            'models': generator.get_models(apis),
        }

    def get_api_for_resource(self, filter_path, urlconf):
        urlparser = UrlParser()
        return urlparser.get_apis(filter_path=filter_path, urlconf=urlconf)


text:
#include <boost/lexical_cast.hpp>

#include "Wt/Ext/TextEdit"
#include "Wt/WTextArea"

#include "DomElement.h"

namespace Wt {

  namespace Ext {

TextEdit::TextEdit(WContainerWidget *parent)
  : FormField(parent),
    linkDefaultLocation_("http://"),
    alignments_(true),
    colors_(true),
    font_(true),
    format_(true),
    links_(true),
    lists_(true),
    sourceEdit_(true)
{
  //extjs: textedit doesn't stand a parent with display: none
  setHideWithOffsets(true);

  textArea_ = new WTextArea();
  addOrphan(textArea_);
}

TextEdit::TextEdit(const WT_USTRING& text, WContainerWidget *parent)
  : FormField(parent),
    linkDefaultLocation_("http://"),
    alignments_(true),
    colors_(true),
    font_(true),
    format_(true),
    links_(true),
    lists_(true),
    sourceEdit_(true)
{
  //extjs: textedit doesn't stand a parent with display: none
  setHideWithOffsets(true);

  textArea_ = new WTextArea();
  addOrphan(textArea_);

  textArea_->setText(text);
}

WFormWidget *TextEdit::formWidget() const
{
  return textArea_;
}

void TextEdit::setLinkDefault(const WString& text, const WString& location)
{
  linkDefaultText_ = text;
  linkDefaultLocation_ = location;
}

void TextEdit::setEnableAlignments(bool enable)
{
  alignments_ = enable;
}

void TextEdit::setEnableColors(bool enable)
{
  colors_ = enable;
}

void TextEdit::setEnableFont(bool enable)
{
  font_ = enable;
}

void TextEdit::setEnableFormat(bool enable)
{
  format_ = enable;
}

void TextEdit::setEnableLinks(bool enable)
{
  links_ = enable;
}

void TextEdit::setEnableLists(bool enable)
{
  lists_ = enable;
}

void TextEdit::setEnableSourceEdit(bool enable)
{
  sourceEdit_ = enable;
}

void TextEdit::setText(const WT_USTRING& text)
{
  textArea_->setText(text);
  if (isRendered())
    addUpdateJS(elVar() + ".setValue(" + WWebWidget::jsStringLiteral(text)
		+ ");");
}

const WT_USTRING& TextEdit::text() const
{
  return textArea_->text();
}

WValidator::State TextEdit::validate()
{
  if (validator()) {
    return validator()->validate(textArea_->text()).state();
  } else
    return WValidator::Valid;
}

void TextEdit::resize(const WLength& width, const WLength& height)
{
  textArea_->resize(width, height);
}

void TextEdit::useAsTableViewEditor()
{
  textArea_->setFormObject(false);
}

std::string TextEdit::createJS(DomElement *inContainer)
{
  std::stringstream result;
  result << elVar() << " = new Ext.form.HtmlEditor(" << configStruct() << ");";

  applyToWidget(textArea_, result, inContainer);

  return result.str();
}

void TextEdit::createConfig(std::ostream& config)
{
  if (!linkDefaultText_.empty())
    config << ",createLinkText:" << linkDefaultText_.jsStringLiteral();
  config << ",defaultLinkValue:" << linkDefaultLocation_.jsStringLiteral();
  if (alignments_ != true)
    config << ",enableAlignments:false";
  if (colors_ != true)
    config << ",enableColors:false";
  if (font_ != true)
    config << ",enableFont:false";
  if (format_ != true)
    config << ",enableFormat:false";
  if (colors_ != true)
    config << ",enableLinks:false";
  if (font_ != true)
    config << ",enableLists:false";
  if (format_ != true)
    config << ",enableSourceEdit:false";

  FormField::createConfig(config);
}

  }
}