text:
<?php
namespace Bee\MVC\Session;

use Exception;
use PDO;

class PDOHandler implements IHandler {

	const DEFAUlT_SESSION_TABLE_NAME = 'BEE_SESSIONS';

	/**
	 * Enter description here...
	 *
	 * @var PDO
	 */
	private $pdoConnection;

	/**
	 * Enter description here...
	 *
	 * @var String
	 */
	private $sessionTableName = self::DEFAUlT_SESSION_TABLE_NAME;

	/**
	 * Enter description here...
	 *
	 * @return PDO
	 */
	public final function getPdoConnection() {
		return $this->pdoConnection;
	}

	/**
	 * Enter description here...
	 *
	 * @param PDO $pdoConnection
	 * @return void
	 */
	public final function setPdoConnection(PDO $pdoConnection) {
		$this->pdoConnection = $pdoConnection;
	}

	/**
	 * Enter description here...
	 *
	 * @return String
	 */
	public final function getSessionTableName() {
		return $this->sessionTableName;
	}

	/**
	 * Enter description here...
	 *
	 * @param String $sessionTableName
	 * @return void
	 */
	public final function setSessionTableName($sessionTableName) {
		$this->sessionTableName = $sessionTableName;
	}

	public function read($sessionId) {
		$stmt = $this->pdoConnection->prepare('SELECT value FROM ' . $this->sessionTableName . ' WHERE id = :sessionId');
		$stmt->execute(array(':sessionId' => $sessionId));
		$result = $stmt->fetchColumn();
		if($result !== false) {
			return $result;
		}
		throw new Exception('PDOHandler::read() : No session with ID ' . $sessionId . ' found in database');
	}

	public function write($sessionId, $sessionData) {
		$params = array(':sessionId' => $sessionId, ':sessionTime' => time(), ':value' => $sessionData);

		$stmt = $this->pdoConnection->prepare('UPDATE ' . $this->sessionTableName . ' SET session_time = :sessionTime, value = :value WHERE id = :sessionId');
		$stmt->execute($params);
		if($stmt->rowCount() > 0) {
			return true;
		}

		$stmt = $this->pdoConnection->prepare('INSERT INTO ' . $this->sessionTableName . ' (id, session_time, session_start, value) VALUES (:sessionId, :sessionTime, :sessionTime, :value)');
		$stmt->execute($params);
		if($stmt->rowCount() > 0) {
			return true;
		}

		throw new Exception('PDOHandler::write() : Could not insert record for session with ID ' . $sessionId . ' ... very strange!');
	}

	public function destroy($sessionId) {
		$stmt = $this->pdoConnection->prepare('DELETE FROM ' . $this->sessionTableName . ' WHERE id = :sessionId');
		$stmt->execute(array(':sessionId' => $sessionId));
		if($stmt->rowCount() > 0) {
			return true;
		}
		throw new Exception('PDOHandler::destroy() : No session with ID ' . $sessionId . ' found in database');
	}

	public function gc($ttl) {
		$stmt = $this->pdoConnection->prepare('DELETE FROM ' . $this->sessionTableName . ' WHERE session_time < :sessionTime');
		$stmt->execute(array(':sessionTime' => time() - $ttl));
		return true;
	}
}


text:
#ifndef EVENT1_EVENT_H_INCLUDED_
#define EVENT1_EVENT_H_INCLUDED_

/** @file event.h

  A library for writing event-driven network servers.

  The <event.h> header is deprecated in Libevent 2.0 and later; please
  use <event2/event.h> instead.  Depending on what functionality you
  need, you may also want to include more of the other event2/
  headers.
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <event2/event-config.h>
#ifdef EVENT__HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef EVENT__HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef EVENT__HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdarg.h>

/* For int types. */
#include "evutil.h"

#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#endif

#include "event2/event_struct.h"
#include "event2/event.h"
#include "event2/event_compat.h"
#include "event2/buffer.h"
#include "event2/buffer_compat.h"
#include "event2/bufferevent.h"
#include "event2/bufferevent_struct.h"
#include "event2/bufferevent_compat.h"
#include "event2/tag.h"
#include "event2/tag_compat.h"

#ifdef __cplusplus
}
#endif

#endif /* EVENT1_EVENT_H_INCLUDED_ */

redpajama_set_name: RedPajamaGithub


text:
mini-route file compression handler.

Example:
```javascript
var http = require('http');
var MiniRoute = require('mini-route');
var miniCompress = require('mini-compress');

var server = http.createServer();
var router = new MiniRoute(server);

router.get('/', function(req, res) {
  miniCompress(req, 'some data to compress', function(err, compressed) {
    res.end(compressed);
  });
});

server.listen(8080);
```

This can also be used with Express:
```javascript
var miniFile = require('mini-file');
var app = require('express')();

app.get('/', function(req, res) {
  miniCompress(req, 'some data to compress', function(err, compressed) {
    res.end(compressed);
  });
});

app.listen(8080);
```


text:
/* globals isSetNotNull, RocketChatFileEmojiCustomInstance */
Meteor.startup(function() {
	let storeType = 'GridFS';

	if (RocketChat.settings.get('EmojiUpload_Storage_Type')) {
		storeType = RocketChat.settings.get('EmojiUpload_Storage_Type');
	}

	const RocketChatStore = RocketChatFile[storeType];

	if (!isSetNotNull(() => RocketChatStore)) {
		throw new Error(`Invalid RocketChatStore type [${storeType}]`);
	}

	console.log(`Using ${storeType} for custom emoji storage`.green);

	let path = '~/uploads';
	if (isSetNotNull(() => RocketChat.settings.get('EmojiUpload_FileSystemPath'))) {
		if (RocketChat.settings.get('EmojiUpload_FileSystemPath').trim() !== '') {
			path = RocketChat.settings.get('EmojiUpload_FileSystemPath');
		}
	}

	this.RocketChatFileEmojiCustomInstance = new RocketChatStore({
		name: 'custom_emoji',
		absolutePath: path
	});

	return WebApp.connectHandlers.use('/emoji-custom/', Meteor.bindEnvironment(function(req, res/*, next*/) {
		const params =
			{emoji: decodeURIComponent(req.url.replace(/^\//, '').replace(/\?.*$/, ''))};

		if (_.isEmpty(params.emoji)) {
			res.writeHead(403);
			res.write('Forbidden');
			res.end();
			return;
		}

		const file = RocketChatFileEmojiCustomInstance.getFileWithReadStream(encodeURIComponent(params.emoji));

		res.setHeader('Content-Disposition', 'inline');

		if (!isSetNotNull(() => file)) {
			//use code from username initials renderer until file upload is complete
			res.setHeader('Content-Type', 'image/svg+xml');
			res.setHeader('Cache-Control', 'public, max-age=0');
			res.setHeader('Expires', '-1');
			res.setHeader('Last-Modified', 'Thu, 01 Jan 2015 00:00:00 GMT');

			const reqModifiedHeader = req.headers['if-modified-since'];
			if (reqModifiedHeader != null) {
				if (reqModifiedHeader === 'Thu, 01 Jan 2015 00:00:00 GMT') {
					res.writeHead(304);
					res.end();
					return;
				}
			}

			const color = '#000';
			const initials = '?';

			const svg = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" width="50" height="50" style="width: 50px; height: 50px; background-color: ${color};">
	<text text-anchor="middle" y="50%" x="50%" dy="0.36em" pointer-events="auto" fill="#ffffff" font-family="Helvetica, Arial, Lucida Grande, sans-serif" style="font-weight: 400; font-size: 28px;">
		${initials}
	</text>
</svg>`;

			res.write(svg);
			res.end();
			return;
		}

		let fileUploadDate = undefined;
		if (isSetNotNull(() => file.uploadDate)) {
			fileUploadDate = file.uploadDate.toUTCString();
		}

		const reqModifiedHeader = req.headers['if-modified-since'];
		if (isSetNotNull(() => reqModifiedHeader)) {
			if (reqModifiedHeader === fileUploadDate) {
				res.setHeader('Last-Modified', reqModifiedHeader);
				res.writeHead(304);
				res.end();
				return;
			}
		}

		res.setHeader('Cache-Control', 'public, max-age=0');
		res.setHeader('Expires', '-1');
		if (isSetNotNull(() => fileUploadDate)) {
			res.setHeader('Last-Modified', fileUploadDate);
		} else {
			res.setHeader('Last-Modified', new Date().toUTCString());
		}
		if (/^svg$/i.test(params.emoji.split('.').pop())) {
			res.setHeader('Content-Type', 'image/svg+xml');
		} else {
			res.setHeader('Content-Type', 'image/jpeg');
		}
		res.setHeader('Content-Length', file.length);

		file.readStream.pipe(res);
	}));
});


text:
"""TemplateEntity utility class."""
from __future__ import annotations

import logging
from typing import Any, Callable

import voluptuous as vol

from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import EVENT_HOMEASSISTANT_START, CoreState, callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import (
    Event,
    TrackTemplate,
    TrackTemplateResult,
    async_track_template_result,
)
from homeassistant.helpers.template import Template, result_as_boolean

_LOGGER = logging.getLogger(__name__)

class _TemplateAttribute:
    """Attribute value linked to template result."""

    def __init__(
        self,
        entity: Entity,
        attribute: str,
        template: Template,
        validator: Callable[[Any], Any] = None,
        on_update: Callable[[Any], None] | None = None,
        none_on_template_error: bool | None = False,
    ):
        """Template attribute."""
        self._entity = entity
        self._attribute = attribute
        self.template = template
        self.validator = validator
        self.on_update = on_update
        self.async_update = None
        self.none_on_template_error = none_on_template_error

    @callback
    def async_setup(self):
        """Config update path for the attribute."""
        if self.on_update:
            return

        if not hasattr(self._entity, self._attribute):
            raise AttributeError(f"Attribute '{self._attribute}' does not exist.")

        self.on_update = self._default_update

    @callback
    def _default_update(self, result):
        attr_result = None if isinstance(result, TemplateError) else result
        setattr(self._entity, self._attribute, attr_result)

    @callback
    def handle_result(
        self,
        event: Event | None,
        template: Template,
        last_result: str | None | TemplateError,
        result: str | TemplateError,
    ) -> None:
        """Handle a template result event callback."""
        if isinstance(result, TemplateError):
            _LOGGER.error(
                "TemplateError('%s') "
                "while processing template '%s' "
                "for attribute '%s' in entity '%s'",
                result,
                self.template,
                self._attribute,
                self._entity.entity_id,
            )
            if self.none_on_template_error:
                self._default_update(result)
            else:
                self.on_update(result)
            return

        if not self.validator:
            self.on_update(result)
            return

        try:
            validated = self.validator(result)
        except vol.Invalid as ex:
            _LOGGER.error(
                "Error validating template result '%s' "
                "from template '%s' "
                "for attribute '%s' in entity %s "
                "validation message '%s'",
                result,
                self.template,
                self._attribute,
                self._entity.entity_id,
                ex.msg,
            )
            self.on_update(None)
            return

        self.on_update(validated)
        return

class TemplateEntity(Entity):
    """Entity that uses templates to calculate attributes."""

    def __init__(
        self,
        *,
        availability_template=None,
        icon_template=None,
        entity_picture_template=None,
        attribute_templates=None,
    ):
        """Template Entity."""
        self._template_attrs = {}
        self._async_update = None
        self._attribute_templates = attribute_templates
        self._attributes = {}
        self._availability_template = availability_template
        self._available = True
        self._icon_template = icon_template
        self._entity_picture_template = entity_picture_template
        self._icon = None
        self._entity_picture = None
        self._self_ref_update_count = 0

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @callback
    def _update_available(self, result):
        if isinstance(result, TemplateError):
            self._available = True
            return

        self._available = result_as_boolean(result)

    @callback
    def _update_state(self, result):
        if self._availability_template:
            return

        self._available = not isinstance(result, TemplateError)

    @property
    def available(self) -> bool:
        """Return if the device is available."""
        return self._available

    @property
    def icon(self):
        """Return the icon to use in the frontend, if any."""
        return self._icon

    @property
    def entity_picture(self):
        """Return the entity_picture to use in the frontend, if any."""
        return self._entity_picture

    @property
    def extra_state_attributes(self):
        """Return the state attributes."""
        return self._attributes

    @callback
    def _add_attribute_template(self, attribute_key, attribute_template):
        """Create a template tracker for the attribute."""

        def _update_attribute(result):
            attr_result = None if isinstance(result, TemplateError) else result
            self._attributes[attribute_key] = attr_result

        self.add_template_attribute(
            attribute_key, attribute_template, None, _update_attribute
        )

    def add_template_attribute(
        self,
        attribute: str,
        template: Template,
        validator: Callable[[Any], Any] = None,
        on_update: Callable[[Any], None] | None = None,
        none_on_template_error: bool = False,
    ) -> None:
        """
        Call in the constructor to add a template linked to a attribute.

        Parameters
        ----------
        attribute
            The name of the attribute to link to. This attribute must exist
            unless a custom on_update method is supplied.
        template
            The template to calculate.
        validator
            Validator function to parse the result and ensure it's valid.
        on_update
            Called to store the template result rather than storing it
            the supplied attribute. Passed the result of the validator, or None
            if the template or validator resulted in an error.

        """
        attribute = _TemplateAttribute(
            self, attribute, template, validator, on_update, none_on_template_error
        )
        self._template_attrs.setdefault(template, [])
        self._template_attrs[template].append(attribute)

    @callback
    def _handle_results(
        self,
        event: Event | None,
        updates: list[TrackTemplateResult],
    ) -> None:
        """Call back the results to the attributes."""
        if event:
            self.async_set_context(event.context)

        entity_id = event and event.data.get(ATTR_ENTITY_ID)

        if entity_id and entity_id == self.entity_id:
            self._self_ref_update_count += 1
        else:
            self._self_ref_update_count = 0

        if self._self_ref_update_count > len(self._template_attrs):
            for update in updates:
                _LOGGER.warning(
                    "Template loop detected while processing event: %s, skipping template render for Template[%s]",
                    event,
                    update.template.template,
                )
            return

        for update in updates:
            for attr in self._template_attrs[update.template]:
                attr.handle_result(
                    event, update.template, update.last_result, update.result
                )

        self.async_write_ha_state()

    async def _async_template_startup(self, *_) -> None:
        template_var_tups = []
        for template, attributes in self._template_attrs.items():
            template_var_tups.append(TrackTemplate(template, None))
            for attribute in attributes:
                attribute.async_setup()

        result_info = async_track_template_result(
            self.hass, template_var_tups, self._handle_results
        )
        self.async_on_remove(result_info.async_remove)
        self._async_update = result_info.async_refresh
        result_info.async_refresh()

    async def async_added_to_hass(self) -> None:
        """Run when entity about to be added to hass."""
        if self._availability_template is not None:
            self.add_template_attribute(
                "_available", self._availability_template, None, self._update_available
            )
        if self._attribute_templates is not None:
            for key, value in self._attribute_templates.items():
                self._add_attribute_template(key, value)
        if self._icon_template is not None:
            self.add_template_attribute(
                "_icon", self._icon_template, vol.Or(cv.whitespace, cv.icon)
            )
        if self._entity_picture_template is not None:
            self.add_template_attribute(
                "_entity_picture", self._entity_picture_template
            )
        if self.hass.state == CoreState.running:
            await self._async_template_startup()
            return

        self.hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_START, self._async_template_startup
        )

    async def async_update(self) -> None:
        """Call for forced update."""
        self._async_update()


text:
set -eu

# Ensure that this is being run inside a CI container
if [ "${CI}" != "true" ]
then
  (>&2 echo "This script is designed to run inside a CI container only.")
  (>&2 echo "Aborting.")
  exit 1
fi

: "${ZEPHIR_PARSER_VERSION:=master}"

# Install psr extension
(>&1 echo "Install psr extension...")
printf "\\n" | pecl install --force psr 1> /dev/null

# Install Zephir Parser
(>&1 echo "Install Zephir Parser...")
git clone -b "$ZEPHIR_PARSER_VERSION" --depth 1 -q https://github.com/phalcon/php-zephir-parser
cd php-zephir-parser
# shellcheck disable=SC2091
$(phpenv which phpize) 1> /dev/null
./configure --silent --with-php-config="$(phpenv which php-config)" --enable-zephir_parser 1> /dev/null
make --silent -j"$(getconf _NPROCESSORS_ONLN)" 1> /dev/null
make --silent install 1> /dev/null
echo 'extension="zephir_parser.so"' > "$(phpenv root)/versions/$(phpenv version-name)/etc/conf.d/zephir_parser.ini"

# Install Box
if [[ "$BUILD_PHAR" -eq "1" ]] && [[ "$(command -v box 2>/dev/null || true)" = "" ]]
then
  (>&1 echo "Install Box...")
  wget \
    "https://github.com/humbug/box/releases/download/${BOX_VERSION}/box.phar" \
    --quiet \
    -O "${HOME}/bin/box"

  chmod +x "${HOME}/bin/box"
  box --version
fi


text:
import React from 'react';
import styles from './DiamondProgress.m.scss';

interface Props {
  /** 0-1 progress for the outer ring */
  progress: number;
  /** Level to display */
  level?: number;
  /** The icon to use */
  icon: string;
  /** The small transparent icon overlay for ritual vendors */
  icon2?: string;
  className?: string;
}

/**
 * A circle-shaped progress bar (from faction icons).
 */
export default function CircleProgress({ progress, level, icon, icon2, className }: Props) {
  const style = {
    strokeDashoffset: 121.622368 - 121.622368 * progress,
  };

  return (

      <svg viewBox="0 0 48 48">
        <image xlinkHref={icon} width="48" height="48" />
        <image xlinkHref={icon2} x="6" y="6" width="36" height="36" />
        {progress > 0 && (
          <circle
            strokeDasharray="121.622368"
            style={style}
            fillOpacity="0"
            stroke="#FFF"
            strokeWidth="3"
            cx="24"
            cy="24"
            r="21"
            strokeLinecap="butt"
            transform="rotate(-90 24 24)"
          />
        )}
      </svg>
      {level !== undefined &&
{level}
}

  );
}


text:
from openstack import exceptions
from openstack.identity.v3 import project

from osc_lib.i18n import _

def add_project_owner_option_to_parser(parser):
    """Register project and project domain options.

    :param parser: argparse.Argument parser object.
    """
    parser.add_argument(
        '--project',
        metavar='<project>',
        help=_("Owner's project (name or ID)")
    )
    parser.add_argument(
        '--project-domain',
        metavar='<project-domain>',
        help=_('Domain the project belongs to (name or ID). '
               'This can be used in case collisions between project names '
               'exist.'),
    )

def find_project(sdk_connection, name_or_id, domain_name_or_id=None):
    """Find a project by its name name or ID.

    If Forbidden to find the resource (a common case if the user does not have
    permission), then return the resource by creating a local instance of
    openstack.identity.v3.Project resource.

    :param sdk_connection: Connection object of OpenStack SDK.
    :type sdk_connection: `openstack.connection.Connection`
    :param name_or_id: Name or ID of the project
    :type name_or_id: string
    :param domain_name_or_id: Domain name or ID of the project.
        This can be used when there are multiple projects with a same name.
    :returns: the project object found
    :rtype: `openstack.identity.v3.project.Project`

    """
    try:
        if domain_name_or_id:
            domain = sdk_connection.identity.find_domain(domain_name_or_id,
                                                         ignore_missing=False)
            domain_id = domain.id
        else:
            domain_id = None
        return sdk_connection.identity.find_project(name_or_id,
                                                    ignore_missing=False,
                                                    domain_id=domain_id)
    # NOTE: OpenStack SDK raises HttpException for 403 response code.
    # There is no specific exception class at now, so we need to catch
    # HttpException and check the status code.
    except exceptions.HttpException as e:
        if e.status_code == 403:
            return project.Project(id=name_or_id, name=name_or_id)
        raise


text:
import { TestBed, inject } from '@angular/core/testing';

import { AnswersService } from './answers.service';

describe('AnswersService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AnswersService]
    });
  });

  it('should be created', inject([AnswersService], (service: AnswersService) => {
    expect(service).toBeTruthy();
  }));
});


text:
import { User } from './../core/models/user';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { UserService } from '../core/services/user.service';

@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
    model: User;
    loading = false;
    returnUrl: string = '/';

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private userService: UserService) {
        this.model = new User();
    }

    ngOnInit() {
        // reset login status
        // this.userService.logout();
    }

    login() {
        this.loading = true;

        this.userService.login(this.model.email, this.model.password)
            .subscribe(
            data => {
                this.router.navigateByUrl(this.returnUrl);
                location.reload();
            },
            error => {
                this.loading = false;
            });
    }
}


text:
package ca.ualberta.cmput301w14t08.geochan.managers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import ca.ualberta.cmput301w14t08.geochan.helpers.GsonHelper;
import ca.ualberta.cmput301w14t08.geochan.models.Comment;
import ca.ualberta.cmput301w14t08.geochan.models.ThreadComment;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Class responsible for managing local saving of threadsList, threads, and
 * comments. As well as managing and saving the queues of comments and
 * threadComments which are to be posted when internet connection is acquired.
 *
 * @author Artem Chikin
 *
 */
public class CacheManager {
	private static CacheManager instance = null;
	private Context context;
	private Gson offlineGson;
	private Gson onlineGson;
	private static final String EXTENSION = ".sav";
	// File for saving ThreadList
	private static final String FILENAME = "threads.sav";
	private static final String IMAGE = "IMG";
	// File for the Queue of Comments to post
	private static final String FILENAME2 = "commentq.sav";
	// File for the Queue of ChreadComments to post
	private static final String FILENAME3 = "threadq.sav";
	private ArrayList<Comment> commentQueue;
	private ArrayList<ThreadComment> threadCommentQueue;

	/**
	 * Initializes the CacheManager fields, private because of the Singleton
	 * pattern.
	 *
	 * @param context The Context the CacheManager is running in.
	 */
	private CacheManager(Context context) {
		this.context = context;
		this.offlineGson = GsonHelper.getOfflineGson();
		// thread Gson is same as online - all the data except for the comments.
		this.onlineGson = GsonHelper.getOnlineGson();
		commentQueue = deserializeCommentQueue();
		threadCommentQueue = deserializeThreadCommentQueue();
	}

	/**
	 * Adds a comment to the Queue of comments to post when Internet connection
	 * is acquired. Serializes the queue.
	 *
	 * @param comment The Comment to be added to the queue.
	 */
	public void addCommentToQueue(Comment comment) {
		commentQueue.add(comment);
		serializeCommentQueue();
	}

	/**
	 * Adds a threadComment to the Queue of threadComments to post when Internet
	 * connection is acquired. Serializes the queue.
	 *
	 * @param thread The ThreadComment to be added to the queue.
	 */
	public void addThreadCommentToQueue(ThreadComment thread) {
		threadCommentQueue.add(thread);
		serializeThreadCommentQueue();
	}

	/**
	 * Using the ThreadManager, posts all the comments and threadComments in the
	 * queue, called once internet connection is acquired.
	 */
	public void postAll() {
		for (Comment comment : commentQueue) {
			ThreadManager.startPost(comment, null, comment.getLocation(), null,
					false);
			commentQueue.remove(comment);
		}
		for (ThreadComment threadComment : threadCommentQueue) {
			Comment bodyComment = threadComment.getBodyComment();
			ThreadManager.startPost(bodyComment, threadComment.getTitle(),
					bodyComment.getLocation(), null, false);
			threadCommentQueue.remove(threadComment);
		}
		serializeCommentQueue();
		serializeThreadCommentQueue();
	}

	public static CacheManager getInstance() {
		return instance;
	}

	public static void generateInstance(Context context) {
		instance = new CacheManager(context);
	}

	public ArrayList<Comment> getCommentQueue() {
		return commentQueue;
	}

	public void setCommentQueue(ArrayList<Comment> commentQueue) {
		this.commentQueue = commentQueue;
	}

	public ArrayList<ThreadComment> getThreadCommentQueue() {
		return threadCommentQueue;
	}

	public void setThreadCommentQueue(
			ArrayList<ThreadComment> threadCommentQueue) {
		this.threadCommentQueue = threadCommentQueue;
	}

	/**
	 * Serializes the comment queue to JSON.
	 */
	public void serializeCommentQueue() {
		try {
			String json = offlineGson.toJson(getCommentQueue());
			FileOutputStream f = context.openFileOutput(FILENAME2,
					Context.MODE_PRIVATE);
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(f));
			w.write(json);
			w.close();
			f.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Deserializes the comment queue from JSON.
	 * @return An ArrayList of the deserialized Comments.
	 */
	public ArrayList<Comment> deserializeCommentQueue() {
		ArrayList<Comment> list = new ArrayList<Comment>();
		try {
			FileInputStream f = context.openFileInput(FILENAME2);
			BufferedReader r = new BufferedReader(new InputStreamReader(f));
			String json = "";
			String temp = "";
			temp = r.readLine();
			while (temp != null) {
				json = json + temp;
				temp = r.readLine();
			}
			r.close();
			f.close();
			Type type = new TypeToken<ArrayList<Comment>>() {
			}.getType();
			list = onlineGson.fromJson(json, type);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * Serializes the ThreadComment queue to JSON.
	 */
	public void serializeThreadCommentQueue() {
		try {
			String json = offlineGson.toJson(getThreadCommentQueue());
			FileOutputStream f = context.openFileOutput(FILENAME3,
					Context.MODE_PRIVATE);
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(f));
			w.write(json);
			w.close();
			f.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Deserializes the ThreadComment queue from JSON.
	 * @return An ArrayList of the deserialized ThreadComments.
	 */
	public ArrayList<ThreadComment> deserializeThreadCommentQueue() {
		ArrayList<ThreadComment> list = new ArrayList<ThreadComment>();
		try {
			FileInputStream f = context.openFileInput(FILENAME3);
			BufferedReader r = new BufferedReader(new InputStreamReader(f));
			String json = "";
			String temp = "";
			temp = r.readLine();
			while (temp != null) {
				json = json + temp;
				temp = r.readLine();
			}
			r.close();
			f.close();
			Type type = new TypeToken<ArrayList<ThreadComment>>() {
			}.getType();
			list = onlineGson.fromJson(json, type);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * Serializes a Bitmap into JSON and stores it in the cache.
	 * @param image The Bitmap to be serialized.
	 * @param id The ID of the image being serialized.
	 */
	public void serializeImage(Bitmap image, String id) {
		try {
			String json = onlineGson.toJson(image);
			FileOutputStream f = context.openFileOutput(IMAGE + id + EXTENSION,
					Context.MODE_PRIVATE);
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(f));
			w.write(json);
			w.close();
			f.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Deserializes an image from the cache and returns it.
	 * @param id The ID of the comment to retrieve.
	 * @return The deserialized Bitmap.
	 */
	public Bitmap deserializeImage(String id) {
		Bitmap image = null;
		try {
			FileInputStream f = context.openFileInput(IMAGE + id + EXTENSION);
			BufferedReader r = new BufferedReader(new InputStreamReader(f));
			String json = "";
			String temp = "";
			temp = r.readLine();
			while (temp != null) {
				json = json + temp;
				temp = r.readLine();
			}
			r.close();
			f.close();
			image = onlineGson.fromJson(json, Bitmap.class);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}

	/**
	 * Serialize the list of threads with all the data with the exception of all
	 * the comment children of the Thread body comment.
	 *
	 * @param list The ArrayList of ThreadComments to serialize.
	 */
	public void serializeThreadList(ArrayList<ThreadComment> list) {
		try {
			String json = onlineGson.toJson(list);
			FileOutputStream f = context.openFileOutput(FILENAME,
					Context.MODE_PRIVATE);
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(f));
			w.write(json);
			w.close();
			f.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Deserialize a list of ThreadComment objects without comments.
	 *
	 * @return The ArrayList of ThreadComments.
	 */
	public ArrayList<ThreadComment> deserializeThreadList() {
		ArrayList<ThreadComment> list = new ArrayList<ThreadComment>();
		try {
			FileInputStream f = context.openFileInput(FILENAME);
			BufferedReader r = new BufferedReader(new InputStreamReader(f));
			String json = "";
			String temp = "";
			temp = r.readLine();
			while (temp != null) {
				json = json + temp;
				temp = r.readLine();
			}
			r.close();
			f.close();
			Type type = new TypeToken<ArrayList<ThreadComment>>() {
			}.getType();
			list = onlineGson.fromJson(json, type);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * Serialize ThreadComment object into a file with the file's name being
	 * ThreadComment's id.
	 *
	 * @param thread The ThreadComment to serialize.
	 */
	public void serializeThreadCommentById(ThreadComment thread) {
		try {
			String json = offlineGson.toJson(thread);
			FileOutputStream f = context.openFileOutput(thread.getId()
					+ EXTENSION, Context.MODE_PRIVATE);
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(f));
			w.write(json);
			w.close();
			f.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Retrieve ThreadComment object by id and return the children of its body
	 * comment. This is done because we already have ThreadComment object and
	 * its BodyComment from the ThreadComment Deserializers. This deserializer
	 * runs when a thread is opened and we need to retrieve comments only from
	 * the cache.
	 *
	 * @param id The id of the ThreadComment to deserialize.
	 * @return An ArrayList of the ThreadComment's body comment's children.
	 */
	public ArrayList<Comment> deserializeThreadCommentById(String id) {
		ThreadComment thread = null;
		try {
			FileInputStream f = context.openFileInput(id + EXTENSION);
			BufferedReader r = new BufferedReader(new InputStreamReader(f));
			String json = "";
			String temp = "";
			temp = r.readLine();
			while (temp != null) {
				json = json + temp;
				temp = r.readLine();
			}
			r.close();
			f.close();
			thread = offlineGson.fromJson(json, ThreadComment.class);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (thread != null) {
			return thread.getBodyComment().getChildren();
		} else {
			return null;
		}
	}
}


text:
package org.optaplanner.persistence.jaxb.api.score.buildin.bendablebigdecimal;

import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.junit.Test;
import org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore;
import org.optaplanner.persistence.jaxb.api.score.AbstractScoreJaxbXmlAdapterTest;

public class BendableBigDecimalScoreJaxbXmlAdapterTest extends AbstractScoreJaxbXmlAdapterTest {

    @Test
    public void serializeAndDeserialize() {
        assertSerializeAndDeserialize(null, new TestBendableBigDecimalScoreWrapper(null));
        BendableBigDecimalScore score = BendableBigDecimalScore.valueOf(
                new BigDecimal[]{new BigDecimal("1000.0001"), new BigDecimal("200.0020")}, new BigDecimal[]{new BigDecimal("34.4300")});
        assertSerializeAndDeserialize(score, new TestBendableBigDecimalScoreWrapper(score));
        score = BendableBigDecimalScore.valueOfUninitialized(-7,
                new BigDecimal[]{new BigDecimal("1000.0001"), new BigDecimal("200.0020")}, new BigDecimal[]{new BigDecimal("34.4300")});
        assertSerializeAndDeserialize(score, new TestBendableBigDecimalScoreWrapper(score));
    }

    @XmlRootElement
    public static class TestBendableBigDecimalScoreWrapper extends TestScoreWrapper<BendableBigDecimalScore> {

        @XmlJavaTypeAdapter(BendableBigDecimalScoreJaxbXmlAdapter.class)
        private BendableBigDecimalScore score;

        @SuppressWarnings("unused")
        private TestBendableBigDecimalScoreWrapper() {
        }

        public TestBendableBigDecimalScoreWrapper(BendableBigDecimalScore score) {
            this.score = score;
        }

        @Override
        public BendableBigDecimalScore getScore() {
            return score;
        }

    }

}


text:
package controllers

import scala.concurrent._
import ExecutionContext.Implicits.global

import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.ws._
import play.api.mvc._
import play.api.libs._
import play.api.libs.iteratee._
import play.Play
import java.net.URLEncoder
import models._
import play.api.i18n.Messages
import play.api.libs.oauth.OAuth
import play.api.libs.json.JsString
import scala.Some
import play.api.libs.oauth.ServiceInfo
import play.api.libs.oauth.RequestToken
import play.api.libs.oauth.OAuthCalculator
import play.api.libs.oauth.ConsumerKey
import akka.util.Timeout
import java.util.concurrent.TimeUnit
import play.api.libs.concurrent.Akka
import akka.actor.{ActorRef, Props, Actor}

/**
 * Tweet wall, using new Twitter Stream API.
 *
 * Original version created by Nicolas Martignole (@nmartignole) march 2014
 * Actor support added by Mathieu Ancelin (@TrevorReznik)
 */
object Tweetwall extends Controller  {

  val cfg = Play.application.configuration

  val KEY = ConsumerKey(cfg.getString("twitter.consumerKey"), cfg.getString("twitter.consumerSecret"))

  val tweetActor = Akka.system(play.api.Play.current).actorOf(Props[TweetsBroadcaster])
  implicit val timeout = Timeout(1, TimeUnit.SECONDS)

  val TWITTER = OAuth(ServiceInfo(
    "https://api.twitter.com/oauth/request_token",
    "https://api.twitter.com/oauth/access_token",
    "https://api.twitter.com/oauth/authorize", KEY),
    use10a = false)

  // Check if we have a valid Twitter token session, else authenticate
  def index = Action {
    implicit request =>
      request.session.get("token").map {
        token: String =>
          Ok(views.html.Tweetwall.showWall())
      }.getOrElse {
        Redirect(routes.Tweetwall.authenticate)
      }
  }

  // Twitter OAuth
  def authenticate = Action {
    implicit request =>
      request.queryString.get("oauth_verifier").flatMap(_.headOption).map {
        verifier =>
          val tokenPair = sessionTokenPair(request).get
          // We got the verifier; now get the access token, store it and back to index
          TWITTER.retrieveAccessToken(tokenPair, verifier) match {
            case Right(t) => {
              // We received the unauthorized tokens in the OAuth object - store it before we proceed
              Redirect(routes.Tweetwall.index).withSession("token" -> t.token, "secret" -> t.secret)
            }
            case Left(e) => throw e
          }
      }.getOrElse(
          TWITTER.retrieveRequestToken(routes.Tweetwall.authenticate.absoluteURL()) match {
            case Right(t) => {
              // We received the unauthorized tokens in the OAuth object - store it before we proceed
              Redirect(TWITTER.redirectUrl(t.token)).withSession("token" -> t.token, "secret" -> t.secret)
            }
            case Left(e) => throw e
          })
  }

  // Starts to watch tweets
  def watchTweets(keywords: String) = Action.async {
    implicit request =>
      import akka.pattern.ask
      (tweetActor ? WallRequest(keywords, request)).mapTo[WallResponse].map {
        response =>
          Ok.feed(response.enumerator &> Enumeratee.map[Array[Byte]](Json.parse) &> EventSource()).as("text/event-stream")
      }
  }

  def sessionTokenPair(implicit request: RequestHeader): Option[RequestToken] = {
    for {
      token <- request.session.get("token")
      secret <- request.session.get("secret")
    } yield {
      RequestToken(token, secret)
    }
  }

  // Loads the list of best talks. This part relies on an external simple web service built by Xebia.
  def watchBestTalks() = Action {
    implicit request =>
      import scala.concurrent.duration._

      //val url: String = routes.SchedullingController.giveMeBestTalks.absoluteURL()
      val url: String = "http://kouign-amann-cloud.devoxxfr-kouign-amann.cloudbees.net/most-popular"

      def futureIDs: Future[Option[JsValue]] = WS.url(url).get().map {
        response =>
          response.status match {
            case 200 => Some(Json.parse(response.body))
            case other => None
          }
      }

      val bestProposalIDs: Enumerator[JsValue] = Enumerator.generateM[JsValue] {
        futureIDs.flatMap(r => play.api.libs.concurrent.Promise.timeout(r, 30 seconds))
      }

      val jsIDstoProposal: Enumeratee[JsValue, JsValue] = Enumeratee.map {
        jsValue =>

          val ids = jsValue.as[List[String]]

          val proposals = Proposal.loadAndParseProposals(ids.toSet).values.toSeq

          val jsonObject = Json.toJson(
            proposals.map {
              proposal =>
                Json.toJson(
                  Map(
                    "id" -> JsString(proposal.id),
                    "title" -> JsString(proposal.title),
                    "speakers" -> JsString(proposal.allSpeakers.map(s => s.cleanName).mkString(", ")),
                    "gravatars" -> Json.toJson(proposal.allSpeakersGravatar),
                    "track" -> JsString(Messages(proposal.track.label))
                  )
                )
            }
          )
          Json.toJson(jsonObject)
      }

      Ok.feed(bestProposalIDs &> jsIDstoProposal &> EventSource()).as("text/event-stream")
  }

  // Loads the next talks,
  def loadNextTalks() = Action {
    implicit request =>
      import scala.concurrent.duration._
      import play.api.libs.concurrent.Promise

      val nextTalks: Enumerator[Seq[Slot]] = Enumerator.generateM[Seq[Slot]] {
        // 1) For production
        //  play.api.libs.concurrent.Promise.timeout(ScheduleConfiguration.loadNextTalks(), 20 seconds)
        // 2) For demo
        Promise.timeout(ScheduleConfiguration.loadRandomTalks(), 20 seconds)
      }

      val proposalsToJSON: Enumeratee[Seq[Slot], JsValue] = Enumeratee.map {
        slots =>
          val jsonObject = Json.toJson(
            slots.map {
              slot =>
                slot match {
                  case s if slot.proposal.isDefined => {
                    val proposal = slot.proposal.get
                    Json.toJson(
                      Map(
                        "id" -> JsString(proposal.id),
                        "title" -> JsString(proposal.title),
                        "speakers" -> JsString(proposal.allSpeakers.map(s => s.cleanName).mkString(", ")),
                        "room" -> JsString(slot.room.name),
                        "track" -> JsString(Messages(proposal.track.label)),
                        "from" -> JsString(slot.from.toString("HH:mm")),
                        "to" -> JsString(slot.to.toString("HH:mm"))
                      )
                    )
                  }
                  case s if slot.break.isDefined => {
                    val zeBreak = slot.break.get
                    Json.toJson(
                      Map(
                        "id" -> JsString(zeBreak.id),
                        "title" -> JsString(zeBreak.nameFR),
                        "room" -> JsString(zeBreak.room.name),
                        "track" -> JsString(""),
                        "speakers" -> JsString(""),
                        "from" -> JsString(slot.from.toString("HH:mm")),
                        "to" -> JsString(slot.from.toString("HH:mm"))
                      )
                    )
                  }
                }
            }
          )
          Json.toJson(jsonObject)
      }

      Ok.feed(nextTalks &> proposalsToJSON &> EventSource()).as("text/event-stream")
  }

}

case class WallRequest(keywords: String, request: RequestHeader)

case class WallResponse(enumerator: Enumerator[Array[Byte]])

case class ResetConnection()

class TweetsBroadcaster extends Actor {

  import context.become

  val (enumerator, channel) = Concurrent.broadcast[Array[Byte]]

  def streamIt(keywords: String, request: RequestHeader, myself: ActorRef) {
    WS.url(s"https://stream.twitter.com/1.1/statuses/filter.json?stall_warnings=true&filter_level=none&language=fr,en&track=" + URLEncoder.encode(keywords, "UTF-8"))
      .withRequestTimeout(-1) // else we close the stream
      .sign(OAuthCalculator(Tweetwall.KEY, Tweetwall.sessionTokenPair(request).get))
      .withHeaders("Connection" -> "keep-alive") // not sure we really need this
      .postAndRetrieveStream("")(_ => Iteratee.foreach[Array[Byte]](bytes => channel.push(bytes))).flatMap(_.run).onComplete {
      case _ => myself ! ResetConnection()
    }
  }

  def beforeAuth: Receive = {
    case WallRequest(keywords, request) => {
      val myself = self
      sender ! WallResponse(enumerator)
      become(afterAuth)
      streamIt(keywords, request, myself)
    }
    case _ =>
  }

  def afterAuth: Receive = {
    case WallRequest(keywords, request) => sender ! WallResponse(enumerator)
    case ResetConnection() => become(beforeAuth)
    case _ =>
  }

  def receive = beforeAuth
}


text:
#include <gussoundutil/timer.h>

#if GUSLIB_FLAG_MULTITHREAD
#pragma message("Timer: Multithreaded synchronization enabled!")
#else
#pragma message("Timer: Multithreaded synchronization disabled!")
#endif

#include <sstream>

#ifdef _WINDOWS
#include <windows.h>
#include <mmsystem.h>	//	(Requires winmm.lib added to the link options.)
#pragma comment(lib,"winmm.lib")

#else
#include <time.h>

#endif //_WINDOWS

namespace guslib
{
	AbstractTimer::AbstractTimer()
		: latestTime(0)
	{
	}

	AbstractTimer::~AbstractTimer()
	{
	}

	void AbstractTimer::reset()
	{
		// call to abstract function. this must not be called in the abstract class' constructor.
		latestTime = getCurrentTimeUnits();
	}

	TimeUnits AbstractTimer::elapsed()
	{
		TimeUnits curr = getCurrentTimeUnits();
		TimeUnits tu = curr - latestTime;
		return tu;
	}

	TimeUnits AbstractTimer::renew()
	{
		TimeUnits curr = getCurrentTimeUnits();
		TimeUnits tu = curr - latestTime;
		latestTime = curr;
		return tu;
	}

	// --------------------- the windows timer --------------------------

#ifdef _WINDOWS

	WinTimer::WinTimer()
	{
		reset();
	}

	WinTimer::~WinTimer()
	{
	}

	TimeUnits WinTimer::getCurrentTimeUnits() const
	{
		return timeGetTime();
	}

	TimeUnits WinTimer::getTimeSinceMidnight () const
	{
		TimeUnits returnValue (0);

#ifdef _WINDOWS
		SYSTEMTIME localTime;
		GetLocalTime (&localTime);

		returnValue = localTime.wHour;
		returnValue = returnValue * 60 + localTime.wMinute;
		returnValue = returnValue * 60 + localTime.wSecond;
		returnValue = returnValue * 1000 + localTime.wMilliseconds;
#else
		struct tm *newtime;

		time_t long_time;

		time( &long_time );
		newtime = localtime( &long_time ); // Convert to local time.

		returnValue = newtime->tm_hour;
		returnValue = returnValue * 60 + newtime->tm_min;
		returnValue = returnValue * 60 + newtime->tm_sec;
		returnValue = returnValue * 1000 + 0; // no millis
		delete newtime;
#endif
		return returnValue;
	}

#endif

	// ------------------------- app clock ---------------------------

	ApplicationClockUtil::ApplicationClockUtil ()
		: Timer ()
	{
		initialTime_ = getCurrentTimeUnits();
	}

	ApplicationClockUtil::~ApplicationClockUtil ()
	{
	}

	std::string ApplicationClockUtil::getTimeAsString () const
	{
		TimeUnits temp (getTimeFromStart ());
		std::string returnValue;

		int nMillis = temp % 1000;
		temp = (temp - nMillis) / 1000;

		int nSec = temp % 60;
		temp = (temp - nSec) / 60;

		int nMin = temp % 60;
		temp = (temp - nMin) / 60;

		int nHour = temp % 24;
		temp = (temp - nHour) / 24;

		std::stringstream ss;
		ss << nHour << ":" << nMin << ":" << nSec << "." << nMillis;
		returnValue = ss.str ();

		return returnValue;
	}

	TimeUnits ApplicationClockUtil::getTimeFromStart () const
	{
		TimeUnits curr = getCurrentTimeUnits();
		TimeUnits tu = curr - initialTime_;
		return tu;
	}

	// ------------------------- sys clock ---------------------------

	SystemClockUtil::SystemClockUtil ()
	{
		initialTime_ = getTimeSinceMidnight ();

		TimeUnits timeSinceStartup = getCurrentTimeUnits ();

		// since we will always get the time based on the time since the startup, we must change this initial time.
		// so that it has an offset.
		initialTime_ = timeSinceStartup - initialTime_;
	}

	TimeUnits SystemClockUtil::getTimeFromStart () const
	{
		TimeUnits curr = getCurrentTimeUnits();
		TimeUnits tu = curr - initialTime_;
		return tu;
	}

}


text:
This folder contains some of the source code for the
[Android codelab](https://codelabs.developers.google.com/?cat=Android)


text:
package com.wubinet.dao;

import com.wubinet.model.Node;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface NodeRepository extends MongoRepository<Node, String> {

}


text:
<?php

namespace BlueBear\GameChessBundle\Event\Listener;

use BlueBear\CoreBundle\Entity\Map\MapItem;
use BlueBear\CoreBundle\Manager\MapItemManager;
use BlueBear\EngineBundle\Event\EngineEvent;
use BlueBear\EngineBundle\Event\Request\MapItemClickRequest;
use BlueBear\EngineBundle\Event\Response\MapUpdateResponse;
use BlueBear\EngineBundle\Factory\EntityTypeFactory;
use BlueBear\GameChessBundle\Entity\Piece;
use BlueBear\GameChessBundle\Event\ChessContextUtilities;
use Doctrine\Common\Collections\Collection;

abstract class PieceEventListener
{
    /** @var ChessContextUtilities */
    protected $contextUtilities;

    /** @var MapItemManager */
    protected $mapItemManager;

    /** @var EntityTypeFactory */
    protected $entityTypeFactory; // Temporary

    /** @var MapItem[]|Collection */
    protected $mapItems = [];

    /** @var Piece */
    protected $piece;

    /**
     * @return array
     */
    abstract protected function findMoves();

    public function __construct(
        ChessContextUtilities $contextUtilities,
        MapItemManager $mapItemManager,
        EntityTypeFactory $entityTypeFactory
    ) {
        $this->contextUtilities = $contextUtilities;
        $this->mapItemManager = $mapItemManager;
        $this->entityTypeFactory = $entityTypeFactory; // Temporary
    }

    /**
     * @param EngineEvent $engineEvent
     *
     * @throws \Exception
     */
    public function onSelect(EngineEvent $engineEvent)
    {
        /**
         * @var MapItemClickRequest $request
         * @var MapUpdateResponse   $response
         */
        $request = $engineEvent->getRequest();
        $response = $engineEvent->getResponse();
        $context = $engineEvent->getContext();
        $this->contextUtilities->setContext($context);
        $this->piece = $this->contextUtilities->findTarget($request->target);
        if (!$this->piece) {
            throw new \Exception('No valid target found');
        }

        // Select current piece
        $this->mapItems = [
            $this->contextUtilities->selectPiece($this->piece),
        ];

        $this->addPossibleActions();

        $response->setData($this->mapItems);
        $response->name = EngineEvent::EDITOR_MAP_UPDATE;
    }

    /**
     * @param EngineEvent $engineEvent
     *
     * @throws \Exception
     */
    public function onMove(EngineEvent $engineEvent)
    {
        /**
         * @var MapItemClickRequest $request
         * @var MapUpdateResponse   $response
         */
        $request = $engineEvent->getRequest();
        $response = $engineEvent->getResponse();
        $context = $engineEvent->getContext();
        $this->contextUtilities->setContext($context);
        $this->piece = $this->contextUtilities->findTarget($request->source);
        if (!$this->piece) {
            throw new \Exception('No valid source found');
        }

        $x = $request->target->position->x;
        $y = $request->target->position->y;
        $this->isAllowedMovement($x, $y); // Will throw exception if not allowed

        $removed = [];
        $toCapture = $this->contextUtilities->findTarget($request->target);
        if ($toCapture) {
            $removed[] = $toCapture->getMapItem();
            $this->mapItemManager->delete($toCapture->getMapItem());
        }

        $mapItem = $this->piece->getMapItem();

        // Gros fix dégueulasse:
        $entitiesBehaviors = $this->entityTypeFactory->getEntityBehaviors();
        $behaviors = $this->piece->getBehaviors();
        // adding entity listeners for each behaviors from configuration
        foreach ($behaviors as $behavior) {
            if (!array_key_exists($behavior, $entitiesBehaviors)) {
                throw new \Exception('Invalid behavior : '.$behavior);
            }
            $mapItem->addListener(
                'click',
                [
                    'name' => $entitiesBehaviors[$behavior]->getListener(),
                ]
            );
        }
        // Fin du gros fix dégueulasse

        $mapItem->setPath([['x' => $x, 'y' => $y]]);
        $response->setData([clone $mapItem], $removed);
        $response->name = EngineEvent::EDITOR_MAP_UPDATE;

        $mapItem->setX($x);
        $mapItem->setY($y);
        $this->mapItemManager->save($mapItem);
    }

    /**
     * Check all possible actions for legal moves
     */
    protected function addPossibleActions()
    {
        foreach ($this->findMoves() as $position) {
            $this->handlePossibleAction($position['x'], $position['y']);
        }
    }

    /**
     * @param int $x
     * @param int $y
     *
     * @return string
     */
    protected function handlePossibleAction($x, $y)
    {
        if (!$this->isAllowedMovement($x, $y)) {
            return ChessContextUtilities::BLOCKED;
        }

        return $this->contextUtilities->handlePossibleAction($this->piece, $x, $y, $this->mapItems);
    }

    /**
     * @param int $x
     * @param int $y
     *
     * @return string
     */
    protected function handlePossibleCapture($x, $y)
    {
        if (!$this->isAllowedMovement($x, $y)) {
            return ChessContextUtilities::BLOCKED;
        }

        return $this->contextUtilities->handlePossibleCapture($this->piece, $x, $y, $this->mapItems);
    }

    /**
     * @param int $x
     * @param int $y
     *
     * @return string
     */
    protected function handlePossibleMovement($x, $y)
    {
        if (!$this->isAllowedMovement($x, $y)) {
            return ChessContextUtilities::BLOCKED;
        }

        return $this->contextUtilities->handlePossibleMovement($this->piece, $x, $y, $this->mapItems);
    }

    /**
     * @param int $x
     * @param int $y
     *
     * @return bool
     */
    protected function isAllowedMovement($x, $y)
    {
        foreach ($this->findMoves() as $move) {
            if ($move['x'] == $x && $move['y'] == $y) {
                // More checks with ChessContextUtilities
                return true;
            }
        }

        return false;
    }

    /**
     * Method is declared here because it's used by both rook and queen
     *
     * @param array $moves
     *
     * @return array
     */
    protected function findRookMoves(array &$moves = [])
    {
        $this->contextUtilities->findPath($this->piece, 1, 0, $moves);
        $this->contextUtilities->findPath($this->piece, -1, 0, $moves);
        $this->contextUtilities->findPath($this->piece, 0, 1, $moves);
        $this->contextUtilities->findPath($this->piece, 0, -1, $moves);

        return $moves;
    }

    /**
     * Method is declared here because it's used by both bishop and queen
     *
     * @param array $moves
     *
     * @return array
     */
    protected function findBishopMoves(array &$moves = [])
    {
        $this->contextUtilities->findPath($this->piece, 1, 1, $moves);
        $this->contextUtilities->findPath($this->piece, 1, -1, $moves);
        $this->contextUtilities->findPath($this->piece, -1, 1, $moves);
        $this->contextUtilities->findPath($this->piece, -1, -1, $moves);

        return $moves;
    }
}


text:
"""
The entropy triangle, from [Valverde-Albacete, Francisco Jose, and Carmen
Pelaez-Moreno. "The Multivariate Entropy Triangle and Applications." Hybrid
Artificial Intelligent Systems. Springer International Publishing, 2016.
647-658].
"""
from abc import ABCMeta, abstractmethod

from six import with_metaclass

from ..distribution import BaseDistribution
from ..distconst import product_distribution, uniform_like
from ..multivariate import (entropy, residual_entropy, dual_total_correlation,
                            total_correlation)

__all__ = [
    'EntropyTriangle',
    'EntropyTriangle2',
]

class BaseEntropyTriangle(with_metaclass(ABCMeta, object)):
    """
    BaseEntropyTriangle

    Static Attributes
    -----------------
    left_label : str
        The label for the bottom axis when plotting.
    right_label : str
        The label for the right axis when plotting.
    bottom_label : str
        The label for the bottom axis when plotting.

    Attributes
    ----------
    dists : [Distribution]
    points : list of tuples

    Methods
    -------
    draw
        Plot the entropy triangle.
    """

    left_label = r"$\operatorname{R}[\mathrm{dist}]$"
    right_label = r"$\operatorname{T}[\mathrm{dist}] + \operatorname{B}[\mathrm{dist}]$"
    bottom_label = r"$\Delta \operatorname{H}_{\Pi_\overline{X}}$"

    def __init__(self, dists):
        """
        Initialize the entropy triangle.

        Parameters
        ----------
        dists : [Distribution] or Distribution
            The list of distributions to plot on the entropy triangle. If a
            single distribution is provided, it alone will be computed.
        """
        if isinstance(dists, BaseDistribution):
            self.dists = [dists]
        else:
            self.dists = dists
        self.points = [self._compute_point(dist) for dist in self.dists]

    @staticmethod
    @abstractmethod
    def _compute_point(dist):
        """
        Compute the three normalized axis.

        Parameters
        ----------
        dist : Distribution
            The distribution to compute values for.
        """
        pass

    def draw(self, ax=None, setup=True, marker='o', color='k'): # pragma: no cover
        """
        Plot the entropy triangle.

        Parameters
        ----------
        ax : Axis or None
            The matplotlib axis to plot on. If none is provided, one will be
            constructed.
        setup : bool
            If true, labels, tick marks, gridlines, and a boundary will be added
            to the plot. Defaults to True.
        marker : str
            The matplotlib marker shape to use.
        color : str
            The color of marker to use.
        """
        import ternary

        if ax is None:
            fig, ax = ternary.figure()
            fig.set_size_inches(10, 8)
        else:
            ax = ternary.TernaryAxesSubplot(ax=ax)

        if setup:
            ax.boundary()
            ax.gridlines(multiple=0.1)

            fontsize = 20
            ax.set_title("Entropy Triangle", fontsize=fontsize)
            ax.left_axis_label(self.left_label, fontsize=fontsize)
            ax.right_axis_label(self.right_label, fontsize=fontsize)
            ax.bottom_axis_label(self.bottom_label, fontsize=fontsize)

            ax.ticks(axis='lbr', multiple=0.1, linewidth=1)
            ax.clear_matplotlib_ticks()

        ax.scatter(self.points, marker=marker, color=color)
        ax._redraw_labels()

        return ax

class EntropyTriangle(BaseEntropyTriangle):
    """
    Construct the Multivariate Entropy Triangle, as defined in
    [Valverde-Albacete, Francisco Jose, and Carmen Pelaez-Moreno. "The
    Multivariate Entropy Triangle and Applications." Hybrid Artificial
    Intelligent Systems. Springer International Publishing, 2016. 647-658]
    """

    left_label = r"$\operatorname{R}[\mathrm{dist}]$"
    right_label = r"$\operatorname{T}[\mathrm{dist}] + \operatorname{B}[\mathrm{dist}]$"
    bottom_label = r"$\Delta \operatorname{H}_{\Pi_\overline{X}}$"

    @staticmethod
    def _compute_point(dist):
        """
        Compute the deviation from uniformity, dependence, and independence of a
        distribution.

        Parameters
        ----------
        dist : Distribution
            The distribution to compute values for.
        """
        H_U = entropy(uniform_like(dist))
        H_P = entropy(product_distribution(dist))

        Delta = H_U - H_P
        VI = residual_entropy(dist)
        M = H_P - VI

        return (Delta/H_U, M/H_U, VI/H_U)

class EntropyTriangle2(BaseEntropyTriangle):
    """
    Construct a variation on the Entropy Triangle, comparing the amount of
    independence in the distribution (residual entropy) to two types of
    dependence (total correlation and dual total correlation).
    """

    left_label = r"$\operatorname{B}[\mathrm{dist}]$"
    right_label = r"$\operatorname{T}[\mathrm{dist}]$"
    bottom_label = r"$\operatorname{R}[\mathrm{dist}]$"

    @staticmethod
    def _compute_point(dist):
        """
        Compute the residual entropy, total correlation, and dual total
        correlation for the distribution, and normalize them.

        Parameters
        ----------
        dist : Distribution
            The distribution to compute values for.
        """

        R = residual_entropy(dist)
        B = dual_total_correlation(dist)
        T = total_correlation(dist)
        total = R + B + T

        return (R/total, T/total, B/total)


text:
package org.locationtech.geomesa.hbase.spark

import com.typesafe.scalalogging.LazyLogging
import org.apache.spark.sql.{DataFrame, SQLContext, SQLTypes, SparkSession}
import org.geotools.data.{Query, Transaction}
import org.geotools.factory.CommonFactoryFinder
import org.junit.runner.RunWith
import org.locationtech.geomesa.hbase.data.HBaseDataStoreFactory
import org.locationtech.geomesa.hbase.data.HBaseDataStoreParams._
import org.locationtech.geomesa.spark.SparkSQLTestUtils
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

import scala.collection.JavaConversions._

@RunWith(classOf[JUnitRunner])
class HBaseSparkProviderIntegrationTest extends Specification with LazyLogging {

  sequential

  // START HBASE INSTANCE MANUALLY
  lazy val sftName: String = "chicago"

  def spec: String = SparkSQLTestUtils.ChiSpec

  private val ff = CommonFactoryFinder.getFilterFactory2

  def dtgField: Option[String] = Some("dtg")

  lazy val dsParams = Map(BigTableNameParam.getName -> "test_sft")
  lazy val dsf = new HBaseDataStoreFactory()
  lazy val ds = dsf.createDataStore(dsParams)

  var spark: SparkSession = null
  var sc: SQLContext = null

  var df: DataFrame = null

  lazy val params = dsParams

  "HBase Spark Data Tests" should {
      // before
      "start spark" >> {
        skipped("integration")
        spark = SparkSQLTestUtils.createSparkSession()
        sc = spark.sqlContext
        SQLTypes.init(sc)
        SparkSQLTestUtils.ingestChicago(ds)

        df = spark.read
          .format("geomesa")
          .options(params.map { case (k, v) => k -> v.toString })
          .option("geomesa.feature", "chicago")
          .load()

        logger.debug(df.schema.treeString)
        df.createOrReplaceTempView("chicago")
        true
      }

      "select by secondary indexed attribute" >> {
        skipped("integration")
        val cases = df.select("case_number").where("case_number = 1").collect().map(_.getInt(0))
        cases.length mustEqual 1
      }

      "complex st_buffer" >> {
        skipped("integration")
        val buf = sc.sql("select st_asText(st_bufferPoint(geom,10)) from chicago where case_number = 1").collect().head.getString(0)
        sc.sql(
          s"""
             |select *
             |from chicago
             |where
             |  st_contains(st_geomFromWKT('$buf'), geom)
                        """.stripMargin
        ).collect().length must beEqualTo(1)
      }

      "write data and properly index" >> {
        skipped("integration")
        val subset = sc.sql("select case_number,geom,dtg from chicago")
        subset.write.format("geomesa")
          .options(params.map { case (k, v) => k -> v.toString })
          .option("geomesa.feature", "chicago2")
          .save()

        val sft = ds.getSchema("chicago2")
        val enabledIndexes = sft.getUserData.get("geomesa.indices").asInstanceOf[String]
        enabledIndexes.indexOf("z3") must be greaterThan -1
      }

      "handle reuse __fid__ on write if available" >> {
        skipped("integration")
        val subset = sc.sql("select __fid__,case_number,geom,dtg from chicago")
        subset.write.format("geomesa")
          .options(params.map { case (k, v) => k -> v.toString })
          .option("geomesa.feature", "fidOnWrite")
          .save()

        import org.locationtech.geomesa.utils.geotools.Conversions._
        val filter = ff.equals(ff.property("case_number"), ff.literal(1))
        val queryOrig = new Query("chicago", filter)
        val origResults = ds.getFeatureReader(queryOrig, Transaction.AUTO_COMMIT).toIterator.toList

        val query = new Query("fidOnWrite", filter)
        val results = ds.getFeatureReader(query, Transaction.AUTO_COMMIT).toIterator.toList

        results.head.getID must be equalTo origResults.head.getID
      }

  }

}