text:
import { Component } from "react";
import { connect } from "react-redux";

import { give as giveActions } from "../../../../data/store";

import Primary from "./Primary";
import Layout from "./Layout";

export const withRedux = connect(null, giveActions);

type ISubFund = {
  accounts: Object[],
  changeAmount: Function,
  changeFund: Function,
  fundId: number,
  id: number,
  preFill: Function,
  primary: boolean,
  amount: number,
};

class SubFund extends Component {
  props: ISubFund;

  state = { active: false }

  componentWillMount() {
    if (this.props.amount) this.setState({ active: true });
  }

  changeAmount = amount => this.props.changeAmount(amount, this.props.fundId)
  changeFund = fund => {
    this.setState({ active: !!fund });
    return this.props.changeFund(Number(fund), this.props.id);
  }

  render() {
    const props = {
      accounts: this.props.accounts,
      active: this.state.active,
      changeAmount: this.changeAmount,
      fundId: this.props.fundId,
      preFill: this.props.preFill,
      changeFund: this.changeFund,
      selectVal: this.props.fundId,
    };

    if (this.props.primary) return <Primary {...props} />;
    return <Layout {...props} />;
  }
}

export default withRedux(SubFund);

export {
  SubFund as SubFundWithoutData,
};


text:
<!--L
  Copyright Duke Comprehensive Cancer Center

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/catrip/LICENSE.txt for details.
L-->

<ns1:gov.nih.nci.cagrid.cqlquery.CQLQuery xmlns:ns1="http://CQL.caBIG/1/gov.nih.nci.cagrid.CQLQuery">
 <ns1:Target name="gov.nih.nhlbi.icbl.qbt.datamodel.pubchem.Substance">
      <ns1:ReturnAttributes>
       		<ns1:ReturnAttribute>idVersion</ns1:ReturnAttribute>
      </ns1:ReturnAttributes>
 </ns1:Target>
</ns1:gov.nih.nci.cagrid.cqlquery.CQLQuery>

redpajama_set_name: RedPajamaGithub


text:
package simpledesign.section5StateVsBehavior;

public class Location {

	public Location(int x, int y, Cell cell) {
   }

}


text:
from SimpleGP import lstsqGP
from sklearn import cross_validation
import numpy as np

class Cl(lstsqGP):
    def eval(self, *args, **kwargs):
        return super(Cl, self).eval(*args, **kwargs)

fpt = open('data/iris.npy', 'rb')
X = np.load(fpt)
cl = np.load(fpt)
fpt.close()

pr = np.empty_like(cl)
for ts, vs in cross_validation.KFold(cl.shape[0], n_folds=5, shuffle=True):
    gp = Cl.run_cl(X[ts], cl[ts], verbose=True, test=X[vs],
                   generations=50)
    pr[vs] = gp.predict_test_set(gp.best).round().astype(np.int)
print (pr == cl).sum() / float(cl.shape[0])


text:
import numeral from 'numeral'

export const isPositive = (value) => value >= 0
export const getFormattedVolume = (volume) => numeral(volume).format('0.0a').toUpperCase()
export const getFormattedBTCPrice = (price) => price === 1 ? 1 : numeral(price).format('0,0.000000')
export const getFormattedCurrencyPrice = (price) => numeral(price).format('0,0.0000')
export const getFormattedCurrencyPriceShort = (price) => numeral(price).format('0,0.00')

export const getFormattedPercentage = (value) => {
  const formattedValue = numeral(value / 100).format('0.00%')
  if (isPositive(value)) return `+${formattedValue}`
  else return formattedValue
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml;
using System.Text;
using System.Windows.Forms;

namespace Rawr.Moonkin
{
    public partial class CalculationOptionsPanelMoonkin : CalculationOptionsPanelBase
    {
        public CalculationOptionsPanelMoonkin()
        {
            InitializeComponent();
        }

        // Load the options into the form
        protected override void LoadCalculationOptions()
        {
			if (Character.CalculationOptions == null)
				Character.CalculationOptions = new CalculationOptionsMoonkin();

			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
            cmbTargetLevel.SelectedItem = calcOpts.TargetLevel.ToString();
			txtLatency.Text = calcOpts.Latency.ToString();
            txtFightLength.Text = calcOpts.FightLength.ToString();
            chkInnervate.Checked = calcOpts.Innervate;
            //chkManaPots.Checked = calcOpts.ManaPots;
            //cmbPotType.SelectedItem = calcOpts.ManaPotType;
            //cmbPotType.Enabled = chkManaPots.Checked;
            txtInnervateDelay.Text = calcOpts.InnervateDelay.ToString();
            txtInnervateDelay.Enabled = chkInnervate.Checked;
            trkReplenishmentUptime.Value = (int)(calcOpts.ReplenishmentUptime * 100);
            trkTreantLifespan.Value = (int)(calcOpts.TreantLifespan * 100);
            cmbUserRotation.SelectedItem = calcOpts.UserRotation;
            chkPtrMode.Checked = calcOpts.PTRMode;
        }

        private void cmbTargetLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
			calcOpts.TargetLevel = int.Parse(cmbTargetLevel.SelectedItem.ToString());
            Character.OnCalculationsInvalidated();
        }

        private void txtLatency_TextChanged(object sender, EventArgs e)
        {
			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
			calcOpts.Latency = float.Parse(txtLatency.Text);
            Character.OnCalculationsInvalidated();
        }

        private void txtFightLength_Leave(object sender, EventArgs e)
        {
			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
			calcOpts.FightLength = float.Parse(txtFightLength.Text);
            Character.OnCalculationsInvalidated();
        }

        private void chkInnervate_CheckedChanged(object sender, EventArgs e)
        {
			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
			calcOpts.Innervate = chkInnervate.Checked;
            txtInnervateDelay.Enabled = chkInnervate.Checked;
            Character.OnCalculationsInvalidated();
        }

        /*private void chkManaPots_CheckedChanged(object sender, EventArgs e)
        {
			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
			calcOpts.ManaPots = chkManaPots.Checked;
            cmbPotType.Enabled = chkManaPots.Checked;
            Character.OnCalculationsInvalidated();
        }

        private void cmbPotType_SelectedIndexChanged(object sender, EventArgs e)
        {
			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
			calcOpts.ManaPotType = cmbPotType.SelectedItem.ToString();
            Character.OnCalculationsInvalidated();
        }*/

        private void txtInnervateDelay_Leave(object sender, EventArgs e)
        {
			CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
			calcOpts.InnervateDelay = float.Parse(txtInnervateDelay.Text);
            Character.OnCalculationsInvalidated();
        }

        private void trkReplenishmentUptime_ValueChanged(object sender, EventArgs e)
        {
            CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
            calcOpts.ReplenishmentUptime = trkReplenishmentUptime.Value / 100.0f;
            lblUptimeValue.Text = trkReplenishmentUptime.Value.ToString();
            Character.OnCalculationsInvalidated();
        }

        private void trkTreantLifespan_ValueChanged(object sender, EventArgs e)
        {
            CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
            calcOpts.TreantLifespan = trkTreantLifespan.Value / 100.0f;
            lblLifespanValue.Text = trkTreantLifespan.Value.ToString();
            Character.OnCalculationsInvalidated();
        }

        private void cmbUserRotation_SelectedIndexChanged(object sender, EventArgs e)
        {
            CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
            calcOpts.UserRotation = cmbUserRotation.SelectedItem.ToString();
            Character.OnCalculationsInvalidated();
        }

        private void chkPtrMode_CheckedChanged(object sender, EventArgs e)
        {
            CalculationOptionsMoonkin calcOpts = Character.CalculationOptions as CalculationOptionsMoonkin;
            calcOpts.PTRMode = chkPtrMode.Checked;
            Character.OnCalculationsInvalidated();
        }
    }
}


text:
package io.github.sislivros.controller;

import io.github.sislivros.entidades.Usuario;
import io.github.sislivros.model.QueryUsuario;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Controla o acesso aos perfis de usuarios
 * @author Victor, Wensttay
 */
@WebServlet(name = "grupos", urlPatterns = {"/grupos"})
public class GruposController  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        buildRequest(request);
        RequestDispatcher rd = request.getRequestDispatcher("/grupos.jsp?email="+request.getParameter("email"));
        rd.forward(request, response);

    }

    private void buildRequest(HttpServletRequest request){

        QueryUsuario query = new QueryUsuario();

        Usuario donoPerfil = query.buscarEmail(request.getParameter("email"));

        request.setAttribute("donoPerfil", donoPerfil);
        request.setAttribute("grupos", query.buscarGrupos(donoPerfil.getId()));
    }
}


text:
StatsClient = StatsClient or class({})
ModuleRequire(..., "data")

Events:Register("activate", function ()
	PlayerTables:CreateTable("stats_client", {}, AllPlayersInterval)
	PlayerTables:CreateTable("stats_team_rating", {}, AllPlayersInterval)
	CustomGameEventManager:RegisterListener("stats_client_add_guide", Dynamic_Wrap(StatsClient, "AddGuide"))
	CustomGameEventManager:RegisterListener("stats_client_vote_guide", Dynamic_Wrap(StatsClient, "VoteGuide"))
end)

function StatsClient:FetchPreGameData()
	local data = {
		matchid = tostring(GameRules:GetMatchID()),
		players = {},
	}
	for i = 0, DOTA_MAX_TEAM_PLAYERS-1 do
		if PlayerResource:IsValidPlayerID(i) and not PlayerResource:IsPlayerAbandoned(i) then
			data.players[i] = PlayerResource:GetRealSteamID(i)
		end
	end

	StatsClient:Send("fetchPreGameMatchData", data, function(response)
		for playerId, data in pairs(response) do
			playerId = tonumber(playerId)

			PLAYER_DATA[playerId].serverData = data
			PLAYER_DATA[playerId].Inventory = data.inventory or {}
			local isBanned = Options:IsEquals("EnableBans") and data.isBanned == true
			PLAYER_DATA[playerId].isBanned = isBanned

			local clientData = table.deepcopy(data)
			clientData.TBDRating = nil
			PlayerTables:SetTableValue("stats_client", playerId, clientData)

			if isBanned then
				PlayerResource:MakePlayerAbandoned(playerId)
			end
		end
	end, math.huge)
end

function StatsClient:CalculateAverageRating()
	local teamRatings = {}

	for playerId, data in pairs(PLAYER_DATA) do
		local team = PlayerResource:GetTeam(playerId)
		if data.serverData and not PlayerResource:IsBanned(playerId) then
			teamRatings[team] = teamRatings[team] or {}
			table.insert(teamRatings[team], data.serverData.Rating or (2500 + (data.serverData.TBDRating or 0)))
		end
	end

	for team, values in pairs(teamRatings) do
		PlayerTables:SetTableValue("stats_team_rating", team, math.round(table.average(values)))
	end
end

function StatsClient:AssignTeams(callback)
	local data = {
		size = Teams.Data[DOTA_TEAM_GOODGUYS].count,
		players = {},
	}
	for i = 0, DOTA_MAX_TEAM_PLAYERS - 1 do
		if PlayerResource:IsValidPlayerID(i) then
			table.insert(data.players, { id = i, steamid = PlayerResource:GetRealSteamID(i) })
		end
	end

	StatsClient:Send("assignTeams", data, callback, false, nil, function(response)
		GameMode:BreakSetup(response.error and ("Server error: " .. response.error) or "Unknown server error")
	end)
end

function StatsClient:OnGameEnd(winner)
	local status, nextCall = xpcall(function()
		if GameMode.Broken then
			PlayerTables:CreateTable("stats_game_result", {error = GameMode.Broken}, AllPlayersInterval)
			return
		end
		if not IsInToolsMode() and StatsClient.GameEndScheduled then return end
		StatsClient.GameEndScheduled = true
		local time = GameRules:GetDOTATime(false, true)
		local matchID = tostring(GameRules:GetMatchID())
		if (GameRules:IsCheatMode() and not StatsClient.Debug) or time < 0 then
			return
		end
		local data = {
			version = ARENA_VERSION,
			matchID = matchID,
			mapName = GetMapName(),
			players = {},
			killGoal = KILLS_TO_END_GAME_FOR_TEAM,
			teamsInfo = {},
			version = ARENA_VERSION,
			duration = math.floor(time),
			flags = {
				isRanked = Options:IsEquals("EnableRatingAffection")
			}
		}

		for i = DOTA_TEAM_FIRST, DOTA_TEAM_CUSTOM_MAX do
			if GetTeamAllPlayerCount(i) > 0 then
				data.teamsInfo[tostring(i)] = {
					duelsWon = (Duel.TimesTeamWins[i] or 0),
					isGameWinner = i == winner,
					score = Teams:GetScore(i),
				}
			end
		end

		for i = 0, DOTA_MAX_TEAM_PLAYERS-1 do
			if PlayerResource:IsValidPlayerID(i) then
				local hero = PlayerResource:GetSelectedHeroEntity(i)
				local playerInfo = {
					abandoned = PlayerResource:IsPlayerAbandoned(i),
					steamid = PlayerResource:GetRealSteamID(i),

					heroDamage = PlayerResource:GetPlayerStat(i, "heroDamage"),
					bossDamage = PlayerResource:GetPlayerStat(i, "bossDamage"),
					heroHealing = PlayerResource:GetHealing(i),
					duelsPlayed = PlayerResource:GetPlayerStat(i, "Duels_Played"),
					duelsWon = PlayerResource:GetPlayerStat(i, "Duels_Won"),
					kills = PlayerResource:GetKills(i),
					deaths = PlayerResource:GetDeaths(i),
					assists = PlayerResource:GetAssists(i),
					lasthits = PlayerResource:GetLastHits(i),
					heroName = HeroSelection:GetSelectedHeroName(i) or "",
					bonus_str = 0,
					bonus_agi = 0,
					bonus_int = 0,

					team = tonumber(PlayerResource:GetTeam(i)),
					level = 0,
					items = {}
				}
				if IsValidEntity(hero) then
					playerInfo.level = hero:GetLevel()
					if hero.Additional_str then playerInfo.bonus_str = hero.Additional_str end
					if hero.Additional_agi then playerInfo.bonus_agi = hero.Additional_agi end
					if hero.Additional_int then playerInfo.bonus_int = hero.Additional_int end
					for item_slot = DOTA_ITEM_SLOT_1, DOTA_STASH_SLOT_6 do
						local item = hero:GetItemInSlot(item_slot)
						if item then
							playerInfo.items[item_slot] = {
								name = item:GetAbilityName(),
								charges = item:GetCurrentCharges()
							}
						end
					end
					if playerInfo.heroName == "" then playerInfo.heroName = hero:GetFullName() end
				end
				playerInfo.netWorth = Gold:GetGold(i)
				for slot, item in pairs(playerInfo.items) do
					playerInfo.netWorth = playerInfo.netWorth + GetTrueItemCost(item.name)
				end
				data.players[i] = playerInfo
			end
		end
		PrintTable(data)

		local clientData = {players = {}}

		StatsClient:Send("endMatch", data, function(response)
			if not response.players then
				local err = response.error and ("Server error: " .. response.error) or "Unknown server error"
				PlayerTables:CreateTable("stats_game_result", { error = err }, AllPlayersInterval)
			else
				for playerId, receivedData in pairs(response.players) do
					playerId = tonumber(playerId)
					local sentData = data.players[playerId]
					clientData.players[playerId] = {
						hero = sentData.heroName,
						heroDamage = sentData.heroDamage,
						bossDamage = sentData.bossDamage,
						heroHealing = sentData.heroHealing,

						netWorth = sentData.netWorth,
						bonus_str = sentData.bonus_str,
						bonus_agi = sentData.bonus_agi,
						bonus_int = sentData.bonus_int,
						items = sentData.items,

						ratingNew = receivedData.ratingNew,
						ratingOld = receivedData.ratingOld,
						ratingGamesRemaining = receivedData.ratingGamesRemaining or 10,
						experienceNew = receivedData.experienceNew or 0,
						experienceOld = receivedData.experienceOld or 0,
					}
				end
				PlayerTables:CreateTable("stats_game_result", clientData, AllPlayersInterval)
			end
		end, math.huge, nil, true)
	end, function(msg)
		return msg..'\n'..debug.traceback()..'\n'
	end)
	if not status then
		PlayerTables:CreateTable("stats_game_result", {error = nextCall}, AllPlayersInterval)
	end
end

function StatsClient:HandleError(err)
	if err and type(err) == "string" then
		StatsClient:Send("HandleError", {
			version = ARENA_VERSION,
			text = err
		})
	end
end

--Guides
function StatsClient:AddGuide(data)
	local playerId = data.PlayerID
	local hero = HeroSelection:GetSelectedHeroName(playerId)
	local steamID = PlayerResource:GetRealSteamID(playerId)
	if #data.title < 4 or #data.description < 4 then
		return
	end
	if #data.title > 60 or #data.description > 250 or table.count(data.items) == 0 then
		return
	end
	if not NPC_HEROES_CUSTOM[hero] or NPC_HEROES_CUSTOM[hero].Enabled == 0 then
		return
	end
	for _,group in ipairs(data.items) do
		if type(group.title) ~= "string" or #group.title > 20 then
			return
		end
		for _,item in ipairs(group.content) do
			if not KeyValues.ItemKV[item] then
				error("Invalid item", item)
			end
		end
	end

	if data.youtube ~= nil and (type(data.youtube) ~= "string" or #data.youtube == 0) then
		data.youtube = nil
	end

	StatsClient:Send("AddGuide", {
		title = data.title,
		description = data.description,
		steamID = steamID,
		hero = hero,
		items = data.items,
		youtube = data.youtube,
		version = ARENA_VERSION,
	}, function(response)
		if response.insertedId then
			CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(playerId), "stats_client_add_guide_success", {insertedId = response.insertedId})
		else
			Containers:DisplayError(playerId, response.error)
		end
	end)
end

function StatsClient:VoteGuide(data)
	StatsClient:Send("VoteGuide", {
		steamID = PlayerResource:GetRealSteamID(data.PlayerID),
		id = data.id or "",
		vote = type(data.vote) == "number" and data.vote or 0
	})
end

local AUTH_KEY = GetDedicatedServerKey("1")
function StatsClient:Send(path, data, callback, retryCount, protocol, onerror, _currentRetry)
	if type(retryCount) == "boolean" then
		retryCount = retryCount and math.huge or 0
	elseif not retryCount then
		retryCount = 0
	end

	local request = CreateHTTPRequestScriptVM(protocol or "POST", self.ServerAddress .. path .. (protocol == "GET" and StatsClient:EncodeParams(data) or ""))
	request:SetHTTPRequestHeaderValue("Auth-Key", AUTH_KEY)
	request:SetHTTPRequestGetOrPostParameter("data", json.encode(data))
	request:Send(function(response)
		if response.StatusCode ~= 200 or not response.Body then
			local currentRetry = (_currentRetry or 0) + 1
			if not StatsClient.Debug and currentRetry < retryCount then
				Timers:CreateTimer(self.RetryDelay, function()
					StatsClient:Send(path, data, callback, retryCount, protocol, onerror, currentRetry)
				end)
			elseif onerror then
				if onerror == true then onerror = callback end

				local resp = json.decode(response.Body)
				if type(resp) ~= "table" then resp = {} end
				onerror(resp, response.StatusCode)
			end
		else
			local obj, pos, err = json.decode(response.Body)
			if obj and callback then
				callback(obj)
			end
		end
	end)
end

function StatsClient:EncodeParams(params)
	if type(params) ~= "table" or next(params) == nil then return "" end
	local str = "/?"
	for k,v in pairs(params) do
		k = k:gsub("([^%w ])", function(c) return string.format("%%%02X", string.byte(c)) end):gsub(" ", "+")
		v = v:gsub("([^%w ])", function(c) return string.format("%%%02X", string.byte(c)) end):gsub(" ", "+")
		str = str + k + "=" + v
	end
	return str
end


text:
SimpleForms
===========

This package is made specially to facilitate creation of forms and to make a code simpler for perception.


text: Installed Memory


text:
/**
 * @file scene_graph.h
 * @brief Defines SceneGraph.
 */

#pragma once

#include "std/ogle_std.inc"
#include "entity/entity.h"

namespace ogle {

/**
 * @brief Tracks all Entities in scene.
 *
 * It is assumed that the SceneGraph is a tree, with no cycles.
 */
class SceneGraph {
 public:
  /**
   * @brief Default Constructor.
   */
  SceneGraph();

  /// Entity at root of graph. All other Entities are beneath it.
  std::unique_ptr<Entity> root_;
};

}  // namespace ogle


text:
from setuptools import setup

def get_version(filename="nvd3.py", varname="__version__"):
    glb = {}
    with open(filename) as fp:
        for line in fp:
            if varname in line:
                exec(line, glb)
                break
    return glb[varname]

def readfile(filename):
    with open(filename) as fp:
        return fp.read()

setup(name="nvd3_py",
      version=get_version(),
      description="Build NVD3 charts from python",
      long_description=readfile("README.rst"),
      keywords="chart, charts, graph, nvd3, d3, html, javascript",
      author="Marco Giusti",
      author_email="marco.giusti@posteo.de",
      url="https://github.com/marcogiusti/nvd3_py",
      license="MIT",
      test_suite="test_nvd3",
      py_modules=["nvd3"],
      packages=["django_nvd3", "django_nvd3.templatetags"],
      extra_require = {
          "Django": ["Django"]
      },
      classifiers=[
          "Development Status :: 1 - Planning",
          "Intended Audience :: Developers",
          "License :: OSI Approved :: MIT License",
          "Operating System :: OS Independent",
          "Programming Language :: Python",
          "Programming Language :: Python :: 2",
          "Programming Language :: Python :: 2.7",
      ],
)


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Show Dircatinos</title>

	<this style="font-weight: 600;">The Royal Commission of Yanbu Colleges & Institutes Libraries & Learing Resources</this>

	MEMBERSHIP FORM

	 Signup For New Memebership

	Confirm Membership


text:
Angular Toasty
=================
**Angular Toasty** is a simple standalone AngularJS module with extensive features that provides growl-style alerts and messages for your app.

#### Demo

[Check it out!](http://invertase.github.io/angular-toasty/example/)

#### Current Features
* 3 Themes (Default, Material Design & Bootstrap 3)
* Global/Individual timeouts
* Shaking Toasts
* Toaster sound
* onAdd, onRemove & onClick event handlers
* Event broadcasting
* Positioning
* HTML allowed

#### Installation
###### Install from Bower:

```HTML
bower install angular-toasty
```
###### Add dependancies to HTML (AngularJS required)

```HTML
<link href="./bower_components/angular-toasty/dist/angular-toasty.min.css" rel="stylesheet" />

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="./bower_components/angular-toasty/dist/angular-toasty.min.js"></script>
```

###### Add the toasty module to your Angular app:

```javascript
angular.module('app', ['angular-toasty']);
```

###### Add the toasty directive:

```HTML
		<toasty></toasty>
	</body>
</html>
```

###### Inject and use the toasty service in your controllers:

```javascript
angular.module('app').controller('UserCtrl', ['$scope', 'toasty', function($scope, toasty) {
	$scope.addUser = function(user) {
		// ...
		// Add user
		// ...
		toasty.success({
			title: 'User added!',
			msg: user.firstName + ' has been added!'
		});
}]);
```

> Each toast must have at least a title or message.

#### Configuration

The default toasty config:

```
* limit: 5, // {int} Maximum number of toasties to show at once
showClose: true, // {bool} Whether to show the 'X' icon to close the toasty
clickToClose: false, // {bool} Whether clicking the toasty closes it
* position: 'bottom-right', // {string:bottom-right,bottom-left,top-right,top-left} The window position where the toast pops up
timeout: 5000, // {int} How long (in miliseconds) the toasty shows before it's removed. Set to false to disable.
sound: true, // {bool} Whether to play a sound when a toast is added
html: false, // {bool} Whether HTML is allowed in toasts
shake: false, // {bool} Whether to shake the toasts
theme: 'default' // {string} What theme to use; default, material or bootstrap
```
> Config items marked with * cannot be overridden at an individual level

##### Global Overrides

To globally override the above config, simply inject the toastyProvider into your app at config:

```javascript
angular.module('app').config(['toastyConfigProvider', function(toastyConfigProvider) {
	toastyConfigProvider.setConfig({
		sound: false,
		shake: true
	});
}]);
```

> You can also get the global config at any time by calling `toasty.getGlobalConfig()`!

##### Individual Overrides

To override the global config for individual toasts, simply pass them into the creation object:

```javascript
toasty({
	title: 'Ping!',
	msg: '<a href="http://google.com">Take me to Google!</a>',
	showClose: false,
	clickToClose: true,
	timeout: 10000,
	sound: false,
	html: true,
	shake: true,
	theme: 'bootstrap'
});
```

#### Features

##### Clearing/Removing

You can easily clear/remove a toast from the view by calling the `clear` method. To remove all at once, just call the method with no ID.

```
toasty.clear(); // Clear all
toasty.clear(id); // Remove a single toast by it's ID
```

##### Toast Types

There's multiple types of toast to use:

```javascript
toasty(); // Default
toasty.info();
toasty.success();
toasty.wait();
toasty.error();
toasty.warning();
```

To create a "quick toast", just pass a string or integer to the function instead:

```javascript
toasty('Quick Toast!');
toasty.success('Quick Success Toast!');
```

##### Event Handlers & Broadcasting

You can easily hook into individual toast item events by calling a functions:

```javascript
toasty({
	title: 'New Toast!',
	onAdd: function() {
		console.log('Toasty ' + this.id + ' has been added!', this);
	},
	onRemove: function() {
		console.log('Toasty ' + this.id + ' has been removed!', this);
	},
	onClick: function() {
		console.log('Toasty ' + this.id + ' has been clicked!', this);
	}
});
```

Toasty also broadcasts on events which can be hooked into:

```javascript
// When a new toast is added
$rootScope.$on('toasty-added', function(event, toast) { console.log(toast) });
// When a toast is clicked
$rootScope.$on('toasty-clicked', function(event, toast) { console.log(toast) });
// When a toast is cleared/removed
$rootScope.$on('toasty-cleared', function(event, toast) { console.log(toast) });
```

#### Contributing

Please see the [contributing guidelines](https://github.com/invertase/angular-toasty/blob/master/CONTRIBUTING.md).


text:
===========================
fastchunking Python library
===========================

.. image:: https://travis-ci.org/netleibi/fastchunking.svg?branch=master
    :target: https://travis-ci.org/netleibi/fastchunking

.. image:: https://badge.fury.io/py/fastchunking.svg
    :target: https://badge.fury.io/py/fastchunking

.. image:: https://readthedocs.org/projects/fastchunking/badge/?version=latest
    :target: http://fastchunking.readthedocs.io/en/latest/?badge=latest
    :alt: Documentation Status

What it is
----------

`fastchunking` is a Python library that contains efficient and easy-to-use implementations of string chunking
algorithms.

It has been developed as part of the work [LS17]_ at CISPA, Saarland University.

Installation
------------

::

    $ pip install fastchunking

.. note:: For performance reasons, parts of this library are implemented in C++. Installation from a source
    distribution, thus, requires availability of a correctly configured C++ compiler.

Usage and Overview
------------------

`fastchunking` provides efficient implementations for different string chunking algorithms, e.g., static chunking (SC)
and content-defined chunking (CDC).

Static Chunking (SC)
^^^^^^^^^^^^^^^^^^^^

Static chunking splits a message into fixed-size chunks.

Let us consider a random example message that shall be chunked:
    >>> import os
    >>> message = os.urandom(1024*1024)

Static chunking is trivial when chunking a single message:
    >>> import fastchunking
    >>> sc = fastchunking.SC()
    >>> chunker = sc.create_chunker(chunk_size=4096)
    >>> chunker.next_chunk_boundaries(message)
    [4096, 8192, 12288, ...]

A large message can also be chunked in fragments, though:
    >>> chunker = sc.create_chunker(chunk_size=4096)
    >>> chunker.next_chunk_boundaries(message[:10240])
    [4096, 8192]
    >>> chunker.next_chunk_boundaries(message[10240:])
    [2048, 6144, 10240, ...]

Content-Defined Chunking (CDC)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

`fastchunking` supports content-defined chunking, i.e., chunking of messages into fragments of variable lengths.

Currently, a chunking strategy based on Rabin-Karp rolling hashes is supported.

As a rolling hash computation on plain-Python strings is incredibly slow with any interpreter, most of the computation
is performed by a C++ extension which is based on the `ngramhashing` library by Daniel Lemire, see:
https://github.com/lemire/rollinghashcpp

Let us consider a random message that should be chunked:
    >>> import os
    >>> message = os.urandom(1024*1024)

When using static chunking, we have to specify a rolling hash window size (here: 48 bytes) and an optional seed value
that affects the pseudo-random distribution of the generated chunk boundaries.

Despite that, usage is similar to static chunking:
    >>> import fastchunking
    >>> cdc = fastchunking.RabinKarpCDC(window_size=48, seed=0)
    >>> chunker = cdc.create_chunker(chunk_size=4096)
    >>> chunker.next_chunk_boundaries(message)
    [7475, 10451, 12253, 13880, 15329, 19808, ...]

Chunking in fragments is straightforward:
    >>> chunker = cdc.create_chunker(chunk_size=4096)
    >>> chunker.next_chunk_boundaries(message[:10240])
    [7475]
    >>> chunker.next_chunk_boundaries(message[10240:])
    [211, 2013, 3640, 5089, 9568, ...]

Multi-Level Chunking (ML-\*)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Multiple chunkers of the same type (but with different chunk sizes) can be efficiently used in parallel, e.g., to
perform multi-level chunking [LS17]_.

Again, let us consider a random message that should be chunked:
    >>> import os
    >>> message = os.urandom(1024*1024)

Usage of multi-level-chunking, e.g., ML-CDC, is easy:
    >>> import fastchunking
    >>> cdc = fastchunking.RabinKarpCDC(window_size=48, seed=0)
    >>> chunk_sizes = [1024, 2048, 4096]
    >>> chunker = cdc.create_multilevel_chunker(chunk_sizes)
    >>> chunker.next_chunk_boundaries_with_levels(message)
    [(1049, 2), (1511, 1), (1893, 2), (2880, 1), (2886, 0), (3701, 0), (4617, 0), (5809, 2), (5843, 0), ...]

The second value in each tuple indicates the highest chunk size that leads to a boundary. Here, the first boundary is a
boundary created by the chunker with index 2, i.e., the chunker with 4096 bytes target chunk size.

.. note::
Only the highest index is output if multiple chunkers yield the same boundary.

.. warning::
Chunk sizes have to be passed in correct order, i.e., from lowest to highest value.

Performance
-----------

Computation costs for `static chunking` are barely measurable: As chunking does not depend on the actual message but
only its length, computation costs are essentially limited to a single :code:`xrange` call.

`Content-defined chunking`, however, is expensive: The algorithm has to compute hash values for rolling hash window
contents at `every` byte position of the message that is to be chunked. To minimize costs, fastchunking works as
follows:

    1. The message (fragment) is passed in its entirety to the C++ extension.
    2. Chunking is performed within the C++ extension.
    3. The resulting list of chunk boundaries is communicated back to Python and converted into a Python list.

Based on a 100 MiB random content, the author measured the following throughput on an Intel Core i7-4770K in a single,
non-representative test run using Python 3.5 (Windows x86-64):

    =========== ==========
    chunk size  throughput
    =========== ==========
    64 bytes    118 MiB/s
    128 bytes   153 MiB/s
    256 bytes   187 MiB/s
    512 bytes   206 MiB/s
    1024 bytes  221 MiB/s
    2048 bytes  226 MiB/s
    4096 bytes  231 MiB/s
    8192 bytes  234 MiB/s
    16384 bytes 233 MiB/s
    32768 bytes 234 MiB/s
    =========== ==========

Testing
-------

`fastchunking` uses tox for testing, so simply run:

::

    $ tox

References:
    .. [LS17] Dominik Leibenger and Christoph Sorge (2017). sec-cs: Getting the Most out of Untrusted Cloud Storage. In
        Proceedings of the 42nd IEEE Conference on Local Computer Networks (LCN 2017), 2017. (Preprint:
        `arXiv:1606.03368 <http://arxiv.org/abs/1606.03368>`_)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Aaron Barfoot | Software Developer</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

    <link href="css/creative.min.css" rel="stylesheet">

    <link href="css/main.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Aaron Barfoot | Software Developer

                        About

                        Technologies

                        Portfolio

                        GitHub

                        Resume

                        Contact

Aaron Barfoot

                Full-Stack Software Developer

Hello, I'm Aaron

                        Ever since I was a child, I have been captivated by computers and the ability of technology to influence people's lives for the better.

                        After graduating from the University of Tennessee in 2014, I went to work at Celebration Concert Tours International (CCT), a group tour operator and event coordinator located in Franklin, TN. At CCT, I organized events which allowed me to travel the world as well as gain full-time experience in a fast paced office environment.

                        My time at CCT helped spark my interest in learning software development as a trade. I got a taste of the process through serving as the product owner and admin for a new website as well as an online trip registration and payment system for CCT. This experience helped me see that software development is something I want to do for the rest of my life.

                        I enjoy solving complex problems while collaborating with others to design the best solution possible. I believe that communication, empathy, pragmatism, and continuous learning are crucial traits in a good software developer. I do my best to practice each of these daily.

Download My Resume

Technologies Used

AngularJS

Bootstrap

Bower

Browserfy

CSS3

Django/Django REST framework

Firebase

Git

GitHub

Gulp

Grunt

HTML5

Ionic

JavaScript

jQuery

Materialize

NPM

Python

Sass

SQLite

 *Also familiar working with GitHub Project Management Tools, Google Analytics, Test Driven Development, Python Unittest Framework, MailChimp Admin, OpenCart Admin, WordPress Admin, Authorize.net Admin, and Microsoft Office 365 Admin

Portfolio

FlightCrew

FlightCrew is an AngularJS application created to give users the ability to track a set of flights for a group of people coming into a town for an event and display updated flight data as it becomes available via the FlightStats API. FlightCrew is intended to be used by a company such as a tour-operator or event-manager who needs a way to schedule charter bus pickups for a very large amount of people arriving on many different airlines and into multiple airports. FlightCrew was built using AngularJS, Firebase, the FlightStats API, and is styled using Materialize.

View Live Project

View GitHub Repo

TravelPack

TravelPack is a Django web application built to sell pre-packaged trips for couples who do not have time to plan their own travel itineraries. Users can search for and purchase trips, as well as add trips to their wishlist and post trip reviews. TravelPack was built using Python, Django, SQLite, and is styled with Bootstrap.

View GitHub Repo

Live Project Coming Soon!

Contact Aaron

Looking for a Software Developer? Contact Aaron today!

github.com/barfootaaron

linkedin.com/in/aaron-barfoot

barfootaaron@yahoo.com

(615) 957-1153

© 2017 Aaron Barfoot


text:
<?php

namespace ReRouter;

class Share implements \ReRouter\Interfaces\Share
{
	public $items = array();

	public function __set($key, $value)
	{
		$this->items[$key] = $value;
	}

	public function __get($key)
	{
		return $this->items[$key];
	}

	public function load(array $shares)
	{
		$this->items = $shares;
	}
}


text:
var Replay = require('@pirxpilot/replay');
Replay.fixtures = __dirname;

// default replay mode is 'replay'
// change it by setting REPLAY environment variable:
// REPLAY=record make


text:
package org.apereo.portal.portlet.container.cache;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertArrayEquals;

import com.google.common.base.Function;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.output.NullOutputStream;
import org.junit.Test;
/** Tests for {@link LimitingTeeOutputStream}. */
public class LimitingTeeOutputStreamTest {

    @Test
    public void testControl() throws IOException {
        final byte[] content = "
Simple content
".getBytes();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        LimitingTeeOutputStream stream =
                new LimitingTeeOutputStream(
                        content.length, NullOutputStream.NULL_OUTPUT_STREAM, byteStream);
        stream.write(content);

        assertFalse(stream.isLimitReached());
        assertArrayEquals(content, byteStream.toByteArray());
    }

    @Test
    public void testContentExceedsThreshold() throws IOException {
        final byte[] content = "
Simple content
".getBytes();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        LimitingTeeOutputStream stream =
                new LimitingTeeOutputStream(
                        content.length - 1, NullOutputStream.NULL_OUTPUT_STREAM, byteStream);
        stream.write(content);

        assertTrue(stream.isLimitReached());
        assertArrayEquals(new byte[0], byteStream.toByteArray());
        // try to write more and see no results
        stream.write("a".getBytes());
        assertArrayEquals(new byte[0], byteStream.toByteArray());
    }

    @Test
    public void testContentExceedsClearBuffer() throws IOException {
        final byte[] content = "
Simple content
".getBytes();
        final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        LimitingTeeOutputStream stream =
                new LimitingTeeOutputStream(
                        content.length - 1,
                        NullOutputStream.NULL_OUTPUT_STREAM,
                        byteStream,
                        new Function<LimitingTeeOutputStream, Object>() {
                            @Override
                            public Object apply(LimitingTeeOutputStream input) {
                                byteStream.reset();
                                return null;
                            }
                        });
        // write the first few chars
        stream.write(content, 0, 5);
        // verify content successfully buffered
        assertFalse(stream.isLimitReached());
        final byte[] subContent = Arrays.copyOf(content, 5);
        assertArrayEquals(subContent, byteStream.toByteArray());

        // now write the remainder
        stream.write(content, 5, content.length);

        assertTrue(stream.isLimitReached());
        assertArrayEquals(new byte[0], byteStream.toByteArray());
        // try to write more and see no results
        stream.write("a".getBytes());
        assertArrayEquals(new byte[0], byteStream.toByteArray());
    }

    @Test
    public void testContentExceedsResetBuffer() throws IOException {
        final byte[] content = "
Simple content
".getBytes();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        LimitingTeeOutputStream stream =
                new LimitingTeeOutputStream(
                        content.length - 1, NullOutputStream.NULL_OUTPUT_STREAM, byteStream);
        stream.write(content);

        assertTrue(stream.isLimitReached());
        assertArrayEquals(new byte[0], byteStream.toByteArray());

        stream.resetByteCount();

        // try to write more and see results
        stream.write("a".getBytes());
        assertArrayEquals("a".getBytes(), byteStream.toByteArray());
    }
}


text:
layout: post
title: "Hello World"
categories: Diary
tags: Diary
---
* content
{:toc}

Hello World!

What is the coder's worst nightmare?

1. Code works perfectly after the first try. The starts are not even aligned today.

2. Favorite coffee shop is closed.

3. Client from hell.

4. Hey, I have an awesome idea that can change the world, you can code it for me, and I'll give you 30% of the company.

5. This is the computer genius I told you about.

Note: It is from [Quora](https://www.quora.com/What-is-a-coders-worst-nightmare/answer/Aladin-Bensassi).


text:
package client

import (
	"fmt"
	"net/url"

	"github.com/docker/docker/engine"
	flag "github.com/docker/docker/pkg/mflag"
	"github.com/docker/docker/utils"
)

func (cli *DockerCli) CmdLogs(args ...string) error {
	var (
		cmd    = cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container", true)
		follow = cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
		times  = cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps")
		tail   = cmd.String([]string{"-tail"}, "all", "Number of lines to show from the end of the logs")
	)
	cmd.Require(flag.Exact, 1)

	utils.ParseFlags(cmd, args, true)

	name := cmd.Arg(0)

	stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
	if err != nil {
		return err
	}

	env := engine.Env{}
	if err := env.Decode(stream); err != nil {
		return err
	}

	if env.GetSubEnv("HostConfig").GetSubEnv("LogConfig").Get("Type") != "json-file" {
		return fmt.Errorf("\"logs\" command is supported only for \"json-file\" logging driver")
	}

	v := url.Values{}
	v.Set("stdout", "1")
	v.Set("stderr", "1")

	if *times {
		v.Set("timestamps", "1")
	}

	if *follow {
		v.Set("follow", "1")
	}
	v.Set("tail", *tail)

	return cli.streamHelper("GET", "/containers/"+name+"/logs?"+v.Encode(), env.GetSubEnv("Config").GetBool("Tty"), nil, cli.out, cli.err, nil)
}


text:
var hull = require('hull.js');
var twgl = require('twgl.js');

var Drawable = require('./Drawable');
var ShaderManager = require('./ShaderManager');

class RenderWebGL {
    /**
     * Create a renderer for drawing Scratch sprites to a canvas using WebGL.
     * Coordinates will default to Scratch 2.0 values if unspecified.
     * The stage's "native" size will be calculated from the these coordinates.
     * For example, the defaults result in a native size of 480x360.
     * Queries such as "touching color?" will always execute at the native size.
     * @see setStageSize
     * @see resize
     * @param {canvas} canvas The canvas to draw onto.
     * @param {int} [xLeft=-240] The x-coordinate of the left edge.
     * @param {int} [xRight=240] The x-coordinate of the right edge.
     * @param {int} [yBottom=-180] The y-coordinate of the bottom edge.
     * @param {int} [yTop=180] The y-coordinate of the top edge.
     * @constructor
     */
    constructor(canvas, xLeft, xRight, yBottom, yTop) {
        // TODO: remove?
        twgl.setDefaults({crossOrigin: true});

        this._gl = twgl.getWebGLContext(canvas, {alpha: false, stencil: true});
        this._drawables = [];
        this._projection = twgl.m4.identity();

        this._createGeometry();

        this.setBackgroundColor(1, 1, 1);
        this.setStageSize(
            xLeft || -240, xRight || 240, yBottom || -180, yTop || 180);
        this.resize(this._nativeSize[0], this._nativeSize[1]);
        this._createQueryBuffers();

        var gl = this._gl;
        gl.disable(gl.DEPTH_TEST);
        gl.enable(gl.BLEND); // TODO: disable when no partial transparency?
        gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE);
        this._shaderManager = new ShaderManager(gl);
    }
}

module.exports = RenderWebGL;

/**
 * Maximum touch size for a picking check.
 * TODO: Figure out a reasonable max size. Maybe this should be configurable?
 * @type {int[]}
 */
RenderWebGL.MAX_TOUCH_SIZE = [3, 3];

/**
 * "touching {color}?" or "{color} touching {color}?" tests will be true if the
 * target is touching a color whose components are each within this tolerance of
 * the corresponding component of the query color.
 * @type {int} between 0 (exact matches only) and 255 (match anything).
 */
RenderWebGL.TOLERANCE_TOUCHING_COLOR = 2;

/********
 * Functions called only locally: these are not available from a worker.
 ********/

/**
 * Set the physical size of the stage in device-independent pixels.
 * This will be multiplied by the device's pixel ratio on high-DPI displays.
 * @param {int} pixelsWide The desired width in device-independent pixels.
 * @param {int} pixelsTall The desired height in device-independent pixels.
 */
RenderWebGL.prototype.resize = function (pixelsWide, pixelsTall) {
    var pixelRatio = window.devicePixelRatio || 1;
    this._gl.canvas.width = pixelsWide * pixelRatio;
    this._gl.canvas.height = pixelsTall * pixelRatio;
};

/**
 * Set the background color for the stage. The stage will be cleared with this
 * color each frame.
 * @param {number} red The red component for the background.
 * @param {number} green The green component for the background.
 * @param {number} blue The blue component for the background.
 */
RenderWebGL.prototype.setBackgroundColor = function(red, green, blue) {
    this._backgroundColor = [red, green, blue, 1];
};

/**
 * Tell the renderer to draw various debug information to the provided canvas
 * during certain operations.
 * @param {canvas} canvas The canvas to use for debug output.
 */
RenderWebGL.prototype.setDebugCanvas = function (canvas) {
    this._debugCanvas = canvas;
};

/**
 * Set logical size of the stage in Scratch units.
 * @param {int} xLeft The left edge's x-coordinate. Scratch 2 uses -240.
 * @param {int} xRight The right edge's x-coordinate. Scratch 2 uses 240.
 * @param {int} yBottom The bottom edge's y-coordinate. Scratch 2 uses -180.
 * @param {int} yTop The top edge's y-coordinate. Scratch 2 uses 180.
 */
RenderWebGL.prototype.setStageSize = function (xLeft, xRight, yBottom, yTop) {
    this._xLeft = xLeft;
    this._xRight = xRight;
    this._yBottom = yBottom;
    this._yTop = yTop;
    this._nativeSize = [Math.abs(xRight - xLeft), Math.abs(yBottom - yTop)];
    this._projection = twgl.m4.ortho(xLeft, xRight, yBottom, yTop, -1, 1);
};

/**
 * Create a new Drawable and add it to the scene.
 * @returns {int} The ID of the new Drawable.
 */
RenderWebGL.prototype.createDrawable = function () {
    var drawable = new Drawable(this._gl);
    var drawableID = drawable.getID();
    this._drawables.push(drawableID);
    return drawableID;
};

/**
 * Destroy a Drawable, removing it from the scene.
 * @param {int} drawableID The ID of the Drawable to remove.
 * @returns {Boolean} True iff the drawable was found and removed.
 */
RenderWebGL.prototype.destroyDrawable = function (drawableID) {
    var index = this._drawables.indexOf(drawableID);
    if (index >= 0) {
        Drawable.getDrawableByID(drawableID).dispose();
        this._drawables.splice(index, 1);
        return true;
    }
    return false;
};

/**
 * Set a drawable's order in the drawable list (effectively, z/layer).
 * Can be used to move drawables to absolute positions in the list,
 * or relative to their current positions.
 * "go back N layers": setDrawableOrder(id, -N, true, 1); (assuming stage at 0).
 * "go to back": setDrawableOrder(id, 1); (assuming stage at 0).
 * "go to front": setDrawableOrder(id, Infinity);
 * @param {int} drawableID ID of Drawable to reorder.
 * @param {Number} order New absolute order or relative order adjusment.
 * @param {Boolean=} opt_isRelative If set, `order` refers to a relative change.
 * @param {Number=} opt_min If set, order constrained to be at least `opt_min`.
 * @return {?Number} New order if changed, or null.
 */
RenderWebGL.prototype.setDrawableOrder = function (
    drawableID, order, opt_isRelative, opt_min) {
    var oldIndex = this._drawables.indexOf(drawableID);
    if (oldIndex >= 0) {
        // Remove drawable from the list.
        var drawable = this._drawables.splice(oldIndex, 1)[0];
        // Determine new index.
        var newIndex = order;
        if (opt_isRelative) {
            newIndex += oldIndex;
        }
        if (opt_min) {
            newIndex = Math.max(newIndex, opt_min);
        }
        newIndex = Math.max(newIndex, 0);
        // Insert at new index.
        this._drawables.splice(newIndex, 0, drawable);
        return this._drawables.indexOf(drawable);
    }
    return null;
};

/**
 * Draw all current drawables and present the frame on the canvas.
 */
RenderWebGL.prototype.draw = function () {
    var gl = this._gl;

    twgl.bindFramebufferInfo(gl, null);
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    gl.clearColor.apply(gl, this._backgroundColor);
    gl.clear(gl.COLOR_BUFFER_BIT);

    this._drawThese(
        this._drawables, ShaderManager.DRAW_MODE.default, this._projection);
};

/**
 * Get the precise bounds for a Drawable.
 * @param {int} drawableID ID of Drawable to get bounds for.
 * @return {Object} Bounds for a tight box around the Drawable.
 */
RenderWebGL.prototype.getBounds = function (drawableID) {
    const drawable = Drawable.getDrawableByID(drawableID);
    // Tell the Drawable about its updated convex hull, if necessary.
    if (drawable.needsConvexHullPoints()) {
        const points = this._getConvexHullPointsForDrawable(drawableID);
        drawable.setConvexHullPoints(points);
    }
    let bounds = drawable.getBounds();
    // In debug mode, draw the bounds.
    if (this._debugCanvas) {
        let gl = this._gl;
        this._debugCanvas.width = gl.canvas.width;
        this._debugCanvas.height = gl.canvas.height;
        let context = this._debugCanvas.getContext('2d');
        context.drawImage(gl.canvas, 0, 0);
        context.strokeStyle = '#FF0000';
        let pr = window.devicePixelRatio;
        context.strokeRect(
            pr * (bounds.left + this._nativeSize[0]/2),
            pr * (-bounds.top + this._nativeSize[1]/2),
            pr * (bounds.right - bounds.left),
            pr * (-bounds.bottom + bounds.top)
        );
    }
    return bounds;
};

/**
 * Get the current skin (costume) size of a Drawable.
 * @param {int} drawableID The ID of the Drawable to measure.
 * @return {Array.<number>} Skin size, width and height.
 */
RenderWebGL.prototype.getSkinSize = function (drawableID) {
    const drawable = Drawable.getDrawableByID(drawableID);
    return drawable.getSkinSize();
};

/**
 * Check if a particular Drawable is touching a particular color.
 * @param {int} drawableID The ID of the Drawable to check.
 * @param {int[]} color3b Test if the Drawable is touching this color.
 * @param {int[]} [mask3b] Optionally mask the check to this part of Drawable.
 * @returns {Boolean} True iff the Drawable is touching the color.
 */
RenderWebGL.prototype.isTouchingColor = function(drawableID, color3b, mask3b) {
    const gl = this._gl;
    twgl.bindFramebufferInfo(gl, this._queryBufferInfo);

    let bounds = this._touchingBounds(drawableID);
    if (!bounds) {
        return;
    }
    let candidateIDs = this._filterCandidatesTouching(
        drawableID, this._drawables, bounds);
    if (!candidateIDs) {
        return;
    }

    // Limit size of viewport to the bounds around the target Drawable,
    // and create the projection matrix for the draw.
    gl.viewport(0, 0, bounds.width, bounds.height);
    const projection = twgl.m4.ortho(
        bounds.left, bounds.right, bounds.bottom, bounds.top, -1, 1);

    gl.clearColor.apply(gl, this._backgroundColor);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);

    var extraUniforms;
    if (mask3b) {
        extraUniforms = {
            u_colorMask: [mask3b[0] / 255, mask3b[1] / 255, mask3b[2] / 255],
            u_colorMaskTolerance: RenderWebGL.TOLERANCE_TOUCHING_COLOR / 255
        };
    }

    try {
        gl.enable(gl.STENCIL_TEST);
        gl.stencilFunc(gl.ALWAYS, 1, 1);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
        gl.colorMask(false, false, false, false);
        this._drawThese(
            [drawableID],
            mask3b ?
                ShaderManager.DRAW_MODE.colorMask :
                ShaderManager.DRAW_MODE.silhouette,
            projection,
            undefined,
            extraUniforms);

        gl.stencilFunc(gl.EQUAL, 1, 1);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
        gl.colorMask(true, true, true, true);

        this._drawThese(
            candidateIDs, ShaderManager.DRAW_MODE.default, projection,
            function (testID) {
                return testID != drawableID;
            });
    }
    finally {
        gl.colorMask(true, true, true, true);
        gl.disable(gl.STENCIL_TEST);
    }

    var pixels = new Buffer(bounds.width * bounds.height * 4);
    gl.readPixels(
        0, 0, bounds.width, bounds.height,
        gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    if (this._debugCanvas) {
        this._debugCanvas.width = bounds.width;
        this._debugCanvas.height = bounds.height;
        var context = this._debugCanvas.getContext('2d');
        var imageData = context.getImageData(
            0, 0, bounds.width, bounds.height);
        for (var i = 0, bytes = pixels.length; i < bytes; ++i) {
            imageData.data[i] = pixels[i];
        }
        context.putImageData(imageData, 0, 0);
    }

    for (var pixelBase = 0; pixelBase < pixels.length; pixelBase += 4) {
        var pixelDistanceR = Math.abs(pixels[pixelBase] - color3b[0]);
        var pixelDistanceG = Math.abs(pixels[pixelBase + 1] - color3b[1]);
        var pixelDistanceB = Math.abs(pixels[pixelBase + 2] - color3b[2]);

        if (pixelDistanceR <= RenderWebGL.TOLERANCE_TOUCHING_COLOR &&
            pixelDistanceG <= RenderWebGL.TOLERANCE_TOUCHING_COLOR &&
            pixelDistanceB <= RenderWebGL.TOLERANCE_TOUCHING_COLOR) {
            return true;
        }
    }

    return false;
};

/**
 * Check if a particular Drawable is touching any in a set of Drawables.
 * @param {int} drawableID The ID of the Drawable to check.
 * @param {int[]} candidateIDs The Drawable IDs to check, otherwise all.
 * @returns {Boolean} True iff the Drawable is touching one of candidateIDs.
 */
RenderWebGL.prototype.isTouchingDrawables = function(drawableID, candidateIDs) {
    candidateIDs = candidateIDs || this._drawables;

    const gl = this._gl;

    twgl.bindFramebufferInfo(gl, this._queryBufferInfo);

    let bounds = this._touchingBounds(drawableID);
    if (!bounds) {
        return;
    }
    candidateIDs = this._filterCandidatesTouching(
        drawableID, candidateIDs, bounds);
    if (!candidateIDs) {
        return;
    }

    // Limit size of viewport to the bounds around the target Drawable,
    // and create the projection matrix for the draw.
    gl.viewport(0, 0, bounds.width, bounds.height);
    const projection = twgl.m4.ortho(
        bounds.left, bounds.right, bounds.bottom, bounds.top, -1, 1);

    const noneColor = Drawable.color4fFromID(Drawable.NONE);
    gl.clearColor.apply(gl, noneColor);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);

    try {
        gl.enable(gl.STENCIL_TEST);
        gl.stencilFunc(gl.ALWAYS, 1, 1);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
        gl.colorMask(false, false, false, false);
        this._drawThese(
            [drawableID], ShaderManager.DRAW_MODE.silhouette, projection
        );

        gl.stencilFunc(gl.EQUAL, 1, 1);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
        gl.colorMask(true, true, true, true);

        this._drawThese(
            candidateIDs, ShaderManager.DRAW_MODE.silhouette, projection,
            function (testID) {
                return testID != drawableID;
            }
        );
    } finally {
        gl.colorMask(true, true, true, true);
        gl.disable(gl.STENCIL_TEST);
    }

    let pixels = new Buffer(bounds.width * bounds.height * 4);
    gl.readPixels(
        0, 0, bounds.width, bounds.height,
        gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    if (this._debugCanvas) {
        this._debugCanvas.width = bounds.width;
        this._debugCanvas.height = bounds.height;
        const context = this._debugCanvas.getContext('2d');
        let imageData = context.getImageData(
            0, 0, bounds.width, bounds.height);
        for (let i = 0, bytes = pixels.length; i < bytes; ++i) {
            imageData.data[i] = pixels[i];
        }
        context.putImageData(imageData, 0, 0);
    }

    for (let pixelBase = 0; pixelBase < pixels.length; pixelBase += 4) {
        let pixelID = Drawable.color4bToID(
            pixels[pixelBase],
            pixels[pixelBase + 1],
            pixels[pixelBase + 2],
            pixels[pixelBase + 3]);
        if (pixelID > Drawable.NONE) {
            return true;
        }
    }

    return false;
};

/**
 * Detect which sprite, if any, is at the given location.
 * @param {int} centerX The client x coordinate of the picking location.
 * @param {int} centerY The client y coordinate of the picking location.
 * @param {int} touchWidth The client width of the touch event (optional).
 * @param {int} touchHeight The client height of the touch event (optional).
 * @param {int[]} candidateIDs The Drawable IDs to pick from, otherwise all.
 * @returns {int} The ID of the topmost Drawable under the picking location, or
 * Drawable.NONE if there is no Drawable at that location.
 */
RenderWebGL.prototype.pick = function (
    centerX, centerY, touchWidth, touchHeight, candidateIDs) {
    var gl = this._gl;

    touchWidth = touchWidth || 1;
    touchHeight = touchHeight || 1;
    candidateIDs = candidateIDs || this._drawables;

    var clientToGLX = gl.canvas.width / gl.canvas.clientWidth;
    var clientToGLY = gl.canvas.height / gl.canvas.clientHeight;

    centerX *= clientToGLX;
    centerY *= clientToGLY;
    touchWidth *= clientToGLX;
    touchHeight *= clientToGLY;

    touchWidth =
        Math.max(1, Math.min(touchWidth, RenderWebGL.MAX_TOUCH_SIZE[0]));
    touchHeight =
        Math.max(1, Math.min(touchHeight, RenderWebGL.MAX_TOUCH_SIZE[1]));

    var pixelLeft = Math.floor(centerX - Math.floor(touchWidth / 2) + 0.5);
    var pixelRight = Math.floor(centerX + Math.ceil(touchWidth / 2) + 0.5);
    var pixelTop = Math.floor(centerY - Math.floor(touchHeight / 2) + 0.5);
    var pixelBottom = Math.floor(centerY + Math.ceil(touchHeight / 2) + 0.5);

    twgl.bindFramebufferInfo(gl, this._pickBufferInfo);
    gl.viewport(0, 0, touchWidth, touchHeight);

    var noneColor = Drawable.color4fFromID(Drawable.NONE);
    gl.clearColor.apply(gl, noneColor);
    gl.clear(gl.COLOR_BUFFER_BIT);

    var widthPerPixel = (this._xRight - this._xLeft) / this._gl.canvas.width;
    var heightPerPixel = (this._yBottom - this._yTop) / this._gl.canvas.height;

    var pickLeft = this._xLeft + pixelLeft * widthPerPixel;
    var pickRight = this._xLeft + pixelRight * widthPerPixel;
    var pickTop = this._yTop + pixelTop * heightPerPixel;
    var pickBottom = this._yTop + pixelBottom * heightPerPixel;

    var projection = twgl.m4.ortho(
        pickLeft, pickRight, pickTop, pickBottom, -1, 1);

    this._drawThese(
        candidateIDs, ShaderManager.DRAW_MODE.silhouette, projection);

    var pixels = new Buffer(touchWidth * touchHeight * 4);
    gl.readPixels(
        0, 0, touchWidth, touchHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    if (this._debugCanvas) {
        this._debugCanvas.width = touchWidth;
        this._debugCanvas.height = touchHeight;
        var context = this._debugCanvas.getContext('2d');
        var imageData = context.getImageData(0, 0, touchWidth, touchHeight);
        for (var i = 0, bytes = pixels.length; i < bytes; ++i) {
            imageData.data[i] = pixels[i];
        }
        context.putImageData(imageData, 0, 0);
    }

    var hits = {};
    for (var pixelBase = 0; pixelBase < pixels.length; pixelBase += 4) {
        var pixelID = Drawable.color4bToID(
            pixels[pixelBase],
            pixels[pixelBase + 1],
            pixels[pixelBase + 2],
            pixels[pixelBase + 3]);
        hits[pixelID] = (hits[pixelID] || 0) + 1;
    }

    // Bias toward selecting anything over nothing
    hits[Drawable.NONE] = 0;

    var hit = Drawable.NONE;
    for (var hitID in hits) {
        if (hits.hasOwnProperty(hitID) && (hits[hitID] > hits[hit])) {
            hit = hitID;
        }
    }

    return hit | 0;
};

/**
 * Get the candidate bounding box for a touching query.
 * @param {int} drawableID ID for drawable of query.
 * @return {?Rectangle} Rectangle bounds for touching query, or null.
 */
RenderWebGL.prototype._touchingBounds = function (drawableID) {
    const drawable = Drawable.getDrawableByID(drawableID);
    const bounds = drawable.getFastBounds();

    // Limit queries to the stage size.
    bounds.clamp(this._xLeft, this._xRight, this._yBottom, this._yTop);

    // Use integer coordinates for queries - weird things happen
    // when you provide float width/heights to gl.viewport and projection.
    bounds.snapToInt();

    if (bounds.width == 0 || bounds.height == 0) {
        // No space to query.
        return null;
    }
    return bounds;
};

/**
 * Filter a list of candidates for a touching query into only those that
 * could possibly intersect the given bounds.
 * @param {int} drawableID ID for drawable of query.
 * @param {Array.<int>} candidateIDs Candidates for touching query.
 * @param {Rectangle} Bounds to limit candidates to.
 * @return {?Array.<int>} Filtered candidateIDs, or null if none.
 */
RenderWebGL.prototype._filterCandidatesTouching = function (
    drawableID, candidateIDs, bounds) {
    // Filter candidates by rough bounding box intersection.
    // Do this before _drawThese, so we can prevent any GL operations
    // and readback by returning early.
    candidateIDs = candidateIDs.filter(function (testID) {
        if (testID == drawableID) return false;
        // Only draw items which could possibly overlap target Drawable.
        let candidate = Drawable.getDrawableByID(testID);
        let candidateBounds = candidate.getFastBounds();
        return bounds.intersects(candidateBounds);
    });
    if (candidateIDs.length == 0) {
        // No possible intersections based on bounding boxes.
        return null;
    }
    return candidateIDs;
};

/**
* Update the position, direction, scale, or effect properties of this Drawable.
* @param {int} drawableID The ID of the Drawable to update.
* @param {Object.<string,*>} properties The new property values to set.
 */
RenderWebGL.prototype.updateDrawableProperties = function (
        drawableID, properties) {
    var drawable = Drawable.getDrawableByID(drawableID);
    drawable.updateProperties(properties);
};

/********
 * Truly internal functions: these support the functions above.
 ********/

/**
 * Build geometry (vertex and index) buffers.
 * @private
 */
RenderWebGL.prototype._createGeometry = function () {
    var quad = {
        a_position: {
            numComponents: 2,
            data: [
                -0.5, -0.5,
                0.5, -0.5,
                -0.5, 0.5,
                -0.5, 0.5,
                0.5, -0.5,
                0.5, 0.5
            ]
        },
        a_texCoord: {
            numComponents: 2,
            data: [
                1, 0,
                0, 0,
                1, 1,
                1, 1,
                0, 0,
                0, 1
            ]
        }
    };
    this._bufferInfo = twgl.createBufferInfoFromArrays(this._gl, quad);
};

/**
 * Create the frame buffers used for queries such as picking and color-touching.
 * These buffers are fixed in size regardless of the size of the main render
 * target. The fixed size allows (more) consistent behavior across devices and
 * presentation modes.
 * @private
 */
RenderWebGL.prototype._createQueryBuffers = function () {
    var gl = this._gl;
    var attachments = [
        {format: gl.RGBA },
        {format: gl.DEPTH_STENCIL }
    ];

    this._pickBufferInfo = twgl.createFramebufferInfo(
        gl, attachments,
        RenderWebGL.MAX_TOUCH_SIZE[0], RenderWebGL.MAX_TOUCH_SIZE[1]);

    // TODO: should we create this on demand to save memory?
    // A 480x360 32-bpp buffer is 675 KiB.
    this._queryBufferInfo = twgl.createFramebufferInfo(
        gl, attachments, this._nativeSize[0], this._nativeSize[1]);
};

/**
 * Draw all Drawables, with the possible exception of
 * @param {int[]} drawables The Drawable IDs to draw, possibly this._drawables.
 * @param {ShaderManager.DRAW_MODE} drawMode Draw normally, silhouette, etc.
 * @param {module:twgl/m4.Mat4} projection The projection matrix to use.
 * @param {Drawable~idFilterFunc} [filter] An optional filter function.
 * @param {Object.<string,*>} [extraUniforms] Extra uniforms for the shaders.
 * @private
 */
RenderWebGL.prototype._drawThese = function(
    drawables, drawMode, projection, filter, extraUniforms) {

    var gl = this._gl;
    var currentShader = null;

    var numDrawables = drawables.length;
    for (var drawableIndex = 0; drawableIndex < numDrawables; ++drawableIndex) {
        var drawableID = drawables[drawableIndex];

        // If we have a filter, check whether the ID fails
        if (filter && !filter(drawableID)) continue;

        var drawable = Drawable.getDrawableByID(drawableID);
        // TODO: check if drawable is inside the viewport before anything else

        // Hidden drawables (e.g., by a "hide" block) are never drawn.
        if (!drawable.getVisible()) continue;

        var effectBits = drawable.getEnabledEffects();
        var newShader = this._shaderManager.getShader(drawMode, effectBits);
        if (currentShader != newShader) {
            currentShader = newShader;
            gl.useProgram(currentShader.program);
            twgl.setBuffersAndAttributes(gl, currentShader, this._bufferInfo);
            twgl.setUniforms(currentShader, {u_projectionMatrix: projection});
            twgl.setUniforms(currentShader, {u_fudge: window.fudge || 0});
        }

        twgl.setUniforms(currentShader, drawable.getUniforms());

        // Apply extra uniforms after the Drawable's, to allow overwriting.
        if (extraUniforms) {
            twgl.setUniforms(currentShader, extraUniforms);
        }

        twgl.drawBufferInfo(gl, gl.TRIANGLES, this._bufferInfo);
    }
};

/**
 * Get the convex hull points for a particular Drawable.
 * To do this, draw the Drawable unrotated, unscaled, and untranslated.
 * Read back the pixels and find all boundary points.
 * Finally, apply a convex hull algorithm to simplify the set.
 * @param {int} drawablesID The Drawable IDs calculate convex hull for.
 * @return {Array.<Array.<number>>} points Convex hull points, as [[x, y], ...]
 */
RenderWebGL.prototype._getConvexHullPointsForDrawable = function (drawableID) {
    const drawable = Drawable.getDrawableByID(drawableID);
    const [width, height] = drawable._uniforms.u_skinSize;
    // No points in the hull if invisible or size is 0.
    if (!drawable.getVisible() || width == 0 || height == 0) {
        return [];
    }

    // Only draw to the size of the untransformed drawable.
    const gl = this._gl;
    twgl.bindFramebufferInfo(gl, this._queryBufferInfo);
    gl.viewport(0, 0, width, height);

    // Clear the canvas with Drawable.NONE.
    const noneColor = Drawable.color4fFromID(Drawable.NONE);
    gl.clearColor.apply(gl, noneColor);
    gl.clear(gl.COLOR_BUFFER_BIT);

    // Overwrite the model matrix to be unrotated, unscaled, untranslated.
    let modelMatrix = twgl.m4.identity();
    twgl.m4.rotateZ(modelMatrix, Math.PI, modelMatrix);
    twgl.m4.scale(modelMatrix, [width, height], modelMatrix);

    const projection = twgl.m4.ortho(
        -0.5 * width, 0.5 * width,
        -0.5 * height, 0.5 * height,
        -1, 1
    );

    this._drawThese([drawableID],
        ShaderManager.DRAW_MODE.silhouette,
        projection,
        undefined,
        {u_modelMatrix: modelMatrix}
    );

    const pixels = new Buffer(width * height * 4);
    gl.readPixels(
        0, 0, width, height,
        gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    // Known boundary points on left/right edges of pixels.
    let boundaryPoints = [];

    /**
     * Helper method to look up a pixel.
     * @param {int} x X coordinate of the pixel in `pixels`.
     * @param {int} y Y coordinate of the pixel in `pixels`.
     * @return Known ID at that pixel, or Drawable.NONE.
     */
    const _getPixel = function (x, y) {
        var pixelBase = ((width * y) + x) * 4;
        return Drawable.color4bToID(
            pixels[pixelBase],
            pixels[pixelBase + 1],
            pixels[pixelBase + 2],
            pixels[pixelBase + 3]);
    };
    for (let y = 0; y <= height; y++) {
        // Scan from left.
        for (let x = 0; x < width; x++) {
            if (_getPixel(x, y) > Drawable.NONE) {
                boundaryPoints.push([x, y]);
                break;
            }
        }
        // Scan from right.
        for (let x = width - 1; x >= 0; x--) {
            if (_getPixel(x, y) > Drawable.NONE) {
                boundaryPoints.push([x, y]);
                break;
            }
        }
    }
    // Simplify boundary points using convex hull.
    return hull(boundaryPoints, Infinity);
};


text:
-- phpMyAdmin SQL Dump
-- version 3.4.10.1deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 07, 2015 at 07:10 AM
-- Server version: 5.5.38
-- PHP Version: 5.5.16-1+deb.sury.org~precise+1

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `slack-lens`
--

-- --------------------------------------------------------

--
-- Table structure for table `channels`
--

CREATE TABLE IF NOT EXISTS `channels` (
  `id` varchar(64) NOT NULL,
  `name` varchar(64) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `creator` varchar(64) NOT NULL,
  `is_archived` tinyint(1) NOT NULL DEFAULT '0',
  `topic` text NOT NULL,
  `purpose` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `channel_user`
--

CREATE TABLE IF NOT EXISTS `channel_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `channel_id` varchar(64) NOT NULL,
  `user_id` varchar(64) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` varchar(64) NOT NULL,
  `name` varchar(64) NOT NULL,
  `deleted` tinyint(1) NOT NULL DEFAULT '0',
  `color` varchar(6) NOT NULL DEFAULT '000000',
  `profile` text NOT NULL,
  `is_admin` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
package io.strimzi.operator.cluster.model;

import io.strimzi.api.kafka.model.AbstractConnectorSpec;
import io.strimzi.operator.common.Reconciliation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Class for handling KafkaConnector configuration passed by the user
 */
public class KafkaConnectorConfiguration extends AbstractConfiguration {
    private static final List<String> FORBIDDEN_PREFIXES;
    private static final List<String> FORBIDDEN_PREFIX_EXCEPTIONS;
    private static final Map<String, String> DEFAULTS;

    static {
        FORBIDDEN_PREFIXES = AbstractConfiguration.splitPrefixesToList(AbstractConnectorSpec.FORBIDDEN_PARAMETERS);
        FORBIDDEN_PREFIX_EXCEPTIONS = List.of();
        DEFAULTS = new HashMap<>(0);
    }

    /**
     * Constructor used to instantiate this class from JsonObject. Should be used to create configuration from
     * ConfigMap / CRD.
     *
     * @param reconciliation  The reconciliation
     * @param jsonOptions     Json object with configuration options as key ad value pairs.
     */
    public KafkaConnectorConfiguration(Reconciliation reconciliation, Iterable<Map.Entry<String, Object>> jsonOptions) {
        super(reconciliation, jsonOptions, FORBIDDEN_PREFIXES, FORBIDDEN_PREFIX_EXCEPTIONS, DEFAULTS);
    }
}


text:
/* */
"use strict";
var Observable_1 = require('../../Observable');
var publishBehavior_1 = require('../../operator/publishBehavior');
Observable_1.Observable.prototype.publishBehavior = publishBehavior_1.publishBehavior;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Writ. 7: 1315 (1924)

#### Original name
Polyporus pectunculus Lloyd

### Remarks
null


text:
package gce

import (
	"fmt"
	"math/rand"
	"regexp"
	"strings"

	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider"

	gce "google.golang.org/api/compute/v1"
	apiv1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/autoscaler/cluster-autoscaler/utils/gpu"
	kubeletapis "k8s.io/kubernetes/pkg/kubelet/apis"

	"github.com/ghodss/yaml"
	"github.com/golang/glog"
)

const (
	mbPerGB           = 1000
	millicoresPerCore = 1000
)

// builds templates for gce cloud provider
type templateBuilder struct {
	projectId string
}

func (t *templateBuilder) getAcceleratorCount(accelerators []*gce.AcceleratorConfig) int64 {
	count := int64(0)
	for _, accelerator := range accelerators {
		if strings.HasPrefix(accelerator.AcceleratorType, "nvidia-") {
			count += accelerator.AcceleratorCount
		}
	}
	return count
}

func (t *templateBuilder) buildCapacity(machineType string, accelerators []*gce.AcceleratorConfig, zone string, cpu int64, mem int64) (apiv1.ResourceList, error) {
	capacity := apiv1.ResourceList{}
	// TODO: get a real value.
	capacity[apiv1.ResourcePods] = *resource.NewQuantity(110, resource.DecimalSI)
	capacity[apiv1.ResourceCPU] = *resource.NewQuantity(cpu, resource.DecimalSI)
	capacity[apiv1.ResourceMemory] = *resource.NewQuantity(mem, resource.DecimalSI)

	if accelerators != nil && len(accelerators) > 0 {
		capacity[gpu.ResourceNvidiaGPU] = *resource.NewQuantity(t.getAcceleratorCount(accelerators), resource.DecimalSI)
	}

	return capacity, nil
}

// buildAllocatableFromKubeEnv builds node allocatable based on capacity of the node and
// value of kubeEnv.
// KubeEnv is a multi-line string containing entries in the form of
// <RESOURCE_NAME>:<string>. One of the resources it contains is a list of
// kubelet arguments from which we can extract the resources reserved by
// the kubelet for its operation. Allocated resources are capacity minus reserved.
// If we fail to extract the reserved resources from kubeEnv (e.g it is in a
// wrong format or does not contain kubelet arguments), we return an error.
func (t *templateBuilder) buildAllocatableFromKubeEnv(capacity apiv1.ResourceList, kubeEnv string) (apiv1.ResourceList, error) {
	kubeReserved, err := extractKubeReservedFromKubeEnv(kubeEnv)
	if err != nil {
		return nil, err
	}
	reserved, err := parseKubeReserved(kubeReserved)
	if err != nil {
		return nil, err
	}
	return t.getAllocatable(capacity, reserved), nil
}

// buildAllocatableFromCapacity builds node allocatable based only on node capacity.
// Calculates reserved as a ratio of capacity. See calculateReserved for more details
func (t *templateBuilder) buildAllocatableFromCapacity(capacity apiv1.ResourceList) apiv1.ResourceList {
	memoryReserved := memoryReservedMB(capacity.Memory().Value() / (1024 * 1024))
	cpuReserved := cpuReservedMillicores(capacity.Cpu().MilliValue())
	reserved := apiv1.ResourceList{}
	reserved[apiv1.ResourceCPU] = *resource.NewMilliQuantity(cpuReserved, resource.DecimalSI)
	reserved[apiv1.ResourceMemory] = *resource.NewQuantity(memoryReserved*1024*1024, resource.BinarySI)
	return t.getAllocatable(capacity, reserved)
}

func (t *templateBuilder) getAllocatable(capacity, reserved apiv1.ResourceList) apiv1.ResourceList {
	allocatable := apiv1.ResourceList{}
	for key, value := range capacity {
		quantity := *value.Copy()
		if reservedQuantity, found := reserved[key]; found {
			quantity.Sub(reservedQuantity)
		}
		allocatable[key] = quantity
	}
	return allocatable
}

func (t *templateBuilder) buildNodeFromTemplate(mig *Mig, template *gce.InstanceTemplate, cpu int64, mem int64) (*apiv1.Node, error) {

	if template.Properties == nil {
		return nil, fmt.Errorf("instance template %s has no properties", template.Name)
	}

	node := apiv1.Node{}
	nodeName := fmt.Sprintf("%s-template-%d", template.Name, rand.Int63())

	node.ObjectMeta = metav1.ObjectMeta{
		Name:     nodeName,
		SelfLink: fmt.Sprintf("/api/v1/nodes/%s", nodeName),
		Labels:   map[string]string{},
	}

	capacity, err := t.buildCapacity(template.Properties.MachineType, template.Properties.GuestAccelerators, mig.GceRef.Zone, cpu, mem)
	if err != nil {
		return nil, err
	}
	node.Status = apiv1.NodeStatus{
		Capacity: capacity,
	}

	var nodeAllocatable apiv1.ResourceList
	// KubeEnv labels & taints
	if template.Properties.Metadata == nil {
		return nil, fmt.Errorf("instance template %s has no metadata", template.Name)
	}
	for _, item := range template.Properties.Metadata.Items {
		if item.Key == "kube-env" {
			if item.Value == nil {
				return nil, fmt.Errorf("no kube-env content in metadata")
			}
			// Extract labels
			kubeEnvLabels, err := extractLabelsFromKubeEnv(*item.Value)
			if err != nil {
				return nil, err
			}
			node.Labels = cloudprovider.JoinStringMaps(node.Labels, kubeEnvLabels)
			// Extract taints
			kubeEnvTaints, err := extractTaintsFromKubeEnv(*item.Value)
			if err != nil {
				return nil, err
			}
			node.Spec.Taints = append(node.Spec.Taints, kubeEnvTaints...)

			if allocatable, err := t.buildAllocatableFromKubeEnv(node.Status.Capacity, *item.Value); err == nil {
				nodeAllocatable = allocatable
			}
		}
	}
	if nodeAllocatable == nil {
		glog.Warningf("could not extract kube-reserved from kubeEnv for mig %q, setting allocatable to capacity.", mig.Name)
		node.Status.Allocatable = node.Status.Capacity
	} else {
		node.Status.Allocatable = nodeAllocatable
	}
	// GenericLabels
	labels, err := buildGenericLabels(mig.GceRef, template.Properties.MachineType, nodeName)
	if err != nil {
		return nil, err
	}
	node.Labels = cloudprovider.JoinStringMaps(node.Labels, labels)

	// Ready status
	node.Status.Conditions = cloudprovider.BuildReadyConditions()
	return &node, nil
}

func (t *templateBuilder) buildNodeFromAutoprovisioningSpec(mig *Mig, cpu int64, mem int64) (*apiv1.Node, error) {
	if mig.spec == nil {
		return nil, fmt.Errorf("no spec in mig %s", mig.Name)
	}

	node := apiv1.Node{}
	nodeName := fmt.Sprintf("%s-autoprovisioned-template-%d", mig.Name, rand.Int63())

	node.ObjectMeta = metav1.ObjectMeta{
		Name:     nodeName,
		SelfLink: fmt.Sprintf("/api/v1/nodes/%s", nodeName),
		Labels:   map[string]string{},
	}

	capacity, err := t.buildCapacity(mig.spec.machineType, nil, mig.GceRef.Zone, cpu, mem)
	if err != nil {
		return nil, err
	}

	if gpuRequest, found := mig.spec.extraResources[gpu.ResourceNvidiaGPU]; found {
		capacity[gpu.ResourceNvidiaGPU] = gpuRequest.DeepCopy()
	}

	node.Status = apiv1.NodeStatus{
		Capacity:    capacity,
		Allocatable: t.buildAllocatableFromCapacity(capacity),
	}

	labels, err := buildLabelsForAutoprovisionedMig(mig, nodeName)
	if err != nil {
		return nil, err
	}
	node.Labels = labels

	node.Spec.Taints = mig.spec.taints

	// Ready status
	node.Status.Conditions = cloudprovider.BuildReadyConditions()
	return &node, nil
}

func buildLabelsForAutoprovisionedMig(mig *Mig, nodeName string) (map[string]string, error) {
	// GenericLabels
	labels, err := buildGenericLabels(mig.GceRef, mig.spec.machineType, nodeName)
	if err != nil {
		return nil, err
	}
	if mig.spec.labels != nil {
		for k, v := range mig.spec.labels {
			if existingValue, found := labels[k]; found {
				if v != existingValue {
					return map[string]string{}, fmt.Errorf("conflict in labels requested: %s=%s  present: %s=%s",
						k, v, k, existingValue)
				}
			} else {
				labels[k] = v
			}
		}
	}
	return labels, nil
}

func buildGenericLabels(ref GceRef, machineType string, nodeName string) (map[string]string, error) {
	result := make(map[string]string)

	// TODO: extract it somehow
	result[kubeletapis.LabelArch] = cloudprovider.DefaultArch
	result[kubeletapis.LabelOS] = cloudprovider.DefaultOS

	result[kubeletapis.LabelInstanceType] = machineType
	ix := strings.LastIndex(ref.Zone, "-")
	if ix == -1 {
		return nil, fmt.Errorf("unexpected zone: %s", ref.Zone)
	}
	result[kubeletapis.LabelZoneRegion] = ref.Zone[:ix]
	result[kubeletapis.LabelZoneFailureDomain] = ref.Zone
	result[kubeletapis.LabelHostname] = nodeName
	return result, nil
}

func parseKubeReserved(kubeReserved string) (apiv1.ResourceList, error) {
	resourcesMap, err := parseKeyValueListToMap(kubeReserved)
	if err != nil {
		return nil, fmt.Errorf("failed to extract kube-reserved from kube-env: %q", err)
	}
	reservedResources := apiv1.ResourceList{}
	for name, quantity := range resourcesMap {
		switch apiv1.ResourceName(name) {
		case apiv1.ResourceCPU, apiv1.ResourceMemory, apiv1.ResourceEphemeralStorage:
			if q, err := resource.ParseQuantity(quantity); err == nil && q.Sign() >= 0 {
				reservedResources[apiv1.ResourceName(name)] = q
			}
		default:
			glog.Warningf("ignoring resource from kube-reserved: %q", name)
		}
	}
	return reservedResources, nil
}

func extractLabelsFromKubeEnv(kubeEnv string) (map[string]string, error) {
	// In v1.10+, labels are only exposed for the autoscaler via AUTOSCALER_ENV_VARS
	// see kubernetes/kubernetes#61119. We try AUTOSCALER_ENV_VARS first, then
	// fall back to the old way.
	labels, err := extractAutoscalerVarFromKubeEnv(kubeEnv, "node_labels")
	if err != nil {
		glog.Errorf("node_labels not found via AUTOSCALER_ENV_VARS due to error, will try NODE_LABELS: %v", err)
		labels, err = extractFromKubeEnv(kubeEnv, "NODE_LABELS")
		if err != nil {
			return nil, err
		}
	}
	return parseKeyValueListToMap(labels)
}

func extractTaintsFromKubeEnv(kubeEnv string) ([]apiv1.Taint, error) {
	// In v1.10+, taints are only exposed for the autoscaler via AUTOSCALER_ENV_VARS
	// see kubernetes/kubernetes#61119. We try AUTOSCALER_ENV_VARS first, then
	// fall back to the old way.
	taints, err := extractAutoscalerVarFromKubeEnv(kubeEnv, "node_taints")
	if err != nil {
		glog.Errorf("node_taints not found via AUTOSCALER_ENV_VARS due to error, will try NODE_TAINTS: %v", err)
		taints, err = extractFromKubeEnv(kubeEnv, "NODE_TAINTS")
		if err != nil {
			return nil, err
		}
	}
	taintMap, err := parseKeyValueListToMap(taints)
	if err != nil {
		return nil, err
	}
	return buildTaints(taintMap)
}

func extractKubeReservedFromKubeEnv(kubeEnv string) (string, error) {
	// In v1.10+, kube-reserved is only exposed for the autoscaler via AUTOSCALER_ENV_VARS
	// see kubernetes/kubernetes#61119. We try AUTOSCALER_ENV_VARS first, then
	// fall back to the old way.
	kubeReserved, err := extractAutoscalerVarFromKubeEnv(kubeEnv, "kube_reserved")
	if err != nil {
		glog.Errorf("kube_reserved not found via AUTOSCALER_ENV_VARS due to error, will try kube-reserved in KUBELET_TEST_ARGS: %v", err)
		kubeletArgs, err := extractFromKubeEnv(kubeEnv, "KUBELET_TEST_ARGS")
		if err != nil {
			return "", err
		}
		resourcesRegexp := regexp.MustCompile(`--kube-reserved=([^ ]+)`)

		matches := resourcesRegexp.FindStringSubmatch(kubeletArgs)
		if len(matches) > 1 {
			return matches[1], nil
		}
		return "", fmt.Errorf("kube-reserved not in kubelet args in kube-env: %q", kubeletArgs)
	}
	return kubeReserved, nil
}

func extractAutoscalerVarFromKubeEnv(kubeEnv, name string) (string, error) {
	const autoscalerVars = "AUTOSCALER_ENV_VARS"
	autoscalerVals, err := extractFromKubeEnv(kubeEnv, autoscalerVars)
	if err != nil {
		return "", err
	}
	for _, val := range strings.Split(autoscalerVals, ";") {
		val = strings.Trim(val, " ")
		items := strings.SplitN(val, "=", 2)
		if len(items) != 2 {
			return "", fmt.Errorf("malformed autoscaler var: %s", val)
		}
		if strings.Trim(items[0], " ") == name {
			return strings.Trim(items[1], " \"'"), nil
		}
	}
	return "", fmt.Errorf("var %s not found in %s: %v", name, autoscalerVars, autoscalerVals)
}

func extractFromKubeEnv(kubeEnv, resource string) (string, error) {
	kubeEnvMap := make(map[string]string)
	err := yaml.Unmarshal([]byte(kubeEnv), &kubeEnvMap)
	if err != nil {
		return "", fmt.Errorf("Error unmarshalling kubeEnv: %v", err)
	}
	return kubeEnvMap[resource], nil
}

func parseKeyValueListToMap(kvList string) (map[string]string, error) {
	result := make(map[string]string)
	if len(kvList) == 0 {
		return result, nil
	}
	for _, keyValue := range strings.Split(kvList, ",") {
		kvItems := strings.SplitN(keyValue, "=", 2)
		if len(kvItems) != 2 {
			return nil, fmt.Errorf("error while parsing key-value list, val: %s", keyValue)
		}
		result[kvItems[0]] = kvItems[1]
	}
	return result, nil
}

func buildTaints(kubeEnvTaints map[string]string) ([]apiv1.Taint, error) {
	taints := make([]apiv1.Taint, 0)
	for key, value := range kubeEnvTaints {
		values := strings.SplitN(value, ":", 2)
		if len(values) != 2 {
			return nil, fmt.Errorf("error while parsing node taint value and effect: %s", value)
		}
		taints = append(taints, apiv1.Taint{
			Key:    key,
			Value:  values[0],
			Effect: apiv1.TaintEffect(values[1]),
		})
	}
	return taints, nil
}

type allocatableBracket struct {
	threshold            int64
	marginalReservedRate float64
}

func memoryReservedMB(memoryCapacityMB int64) int64 {
	if memoryCapacityMB <= 1*mbPerGB {
		// do not set any memory reserved for nodes with less than 1 Gb of capacity
		return 0
	}
	return calculateReserved(memoryCapacityMB, []allocatableBracket{
		{
			threshold:            0,
			marginalReservedRate: 0.25,
		},
		{
			threshold:            4 * mbPerGB,
			marginalReservedRate: 0.2,
		},
		{
			threshold:            8 * mbPerGB,
			marginalReservedRate: 0.1,
		},
		{
			threshold:            16 * mbPerGB,
			marginalReservedRate: 0.06,
		},
		{
			threshold:            128 * mbPerGB,
			marginalReservedRate: 0.02,
		},
	})
}

func cpuReservedMillicores(cpuCapacityMillicores int64) int64 {
	return calculateReserved(cpuCapacityMillicores, []allocatableBracket{
		{
			threshold:            0,
			marginalReservedRate: 0.06,
		},
		{
			threshold:            1 * millicoresPerCore,
			marginalReservedRate: 0.01,
		},
		{
			threshold:            2 * millicoresPerCore,
			marginalReservedRate: 0.005,
		},
		{
			threshold:            4 * millicoresPerCore,
			marginalReservedRate: 0.0025,
		},
	})
}

// calculateReserved calculates reserved using capacity and a series of
// brackets as follows:  the marginalReservedRate applies to all capacity
// greater than the bracket, but less than the next bracket.  For example, if
// the first bracket is threshold: 0, rate:0.1, and the second bracket has
// threshold: 100, rate: 0.4, a capacity of 100 results in a reserved of
// 100*0.1 = 10, but a capacity of 200 results in a reserved of
// 10 + (200-100)*.4 = 50.  Using brackets with marginal rates ensures that as
// capacity increases, reserved always increases, and never decreases.
func calculateReserved(capacity int64, brackets []allocatableBracket) int64 {
	var reserved float64
	for i, bracket := range brackets {
		c := capacity
		if i < len(brackets)-1 && brackets[i+1].threshold < capacity {
			c = brackets[i+1].threshold
		}
		additionalReserved := float64(c-bracket.threshold) * bracket.marginalReservedRate
		if additionalReserved > 0 {
			reserved += additionalReserved
		}
	}
	return int64(reserved)
}


text:
#ifndef QT3DCORE_QNODEID_H
#define QT3DCORE_QNODEID_H

#include <Qt3DCore/qt3dcore_global.h>
#include <QDebug>
#include <QtCore/QHashFunctions>

QT_BEGIN_NAMESPACE

namespace Qt3DCore {

class QNodeId
{
    Q_DECL_CONSTEXPR explicit QNodeId(quint64 i) Q_DECL_NOTHROW
        : m_id(i)
    {}
public:
    Q_DECL_CONSTEXPR QNodeId() Q_DECL_NOTHROW
        : m_id(0)
    {}

    QT3DCORESHARED_EXPORT static QNodeId createId() Q_DECL_NOTHROW;

    Q_DECL_CONSTEXPR bool isNull() const Q_DECL_NOTHROW
    {
        return m_id == 0;
    }

    Q_DECL_CONSTEXPR bool operator ==(QNodeId other) const Q_DECL_NOTHROW
    {
        return other.m_id == m_id;
    }

    Q_DECL_CONSTEXPR bool operator !=(QNodeId other) const Q_DECL_NOTHROW
    {
        return !operator ==(other);
    }

    Q_DECL_CONSTEXPR bool operator <(QNodeId other) const Q_DECL_NOTHROW
    {
        return m_id < other.m_id;
    }

    Q_DECL_CONSTEXPR bool operator >(QNodeId other) const Q_DECL_NOTHROW
    {
        return m_id > other.m_id;
    }

    Q_DECL_CONSTEXPR quint64 id() const Q_DECL_NOTHROW
    {
        return m_id;
    }

    Q_DECL_CONSTEXPR operator bool() const Q_DECL_NOTHROW
    {
        return m_id != 0;
    }

private:
    quint64 m_id;
};
QT3D_DECLARE_TYPEINFO(Qt3DCore, QNodeId, Q_PRIMITIVE_TYPE)

typedef QVector<QNodeId> QNodeIdVector;

#ifndef QT_NO_DEBUG_STREAM
QT3DCORESHARED_EXPORT QDebug operator<<(QDebug d, QNodeId id);
#endif

inline Q_DECL_CONSTEXPR uint qHash(QNodeId id, uint seed = 0) Q_DECL_NOTHROW
{
    using QT_PREPEND_NAMESPACE(qHash);
    return qHash(id.id(), seed);
}

} // Qt3DCore

QT_END_NAMESPACE

Q_DECLARE_METATYPE(Qt3DCore::QNodeId) // LCOV_EXCL_LINE

#endif // QT3DCORE_QNODEID_H


text:
Building:
```shell
cabal configure
cabal install --only-dependencies
cabal build
```
Running:
```shell
cabal configure
cabal install --only-dependencies
cabal run
```

## With `stack`

Building:
```shell
stack build
```
Running:
```shell
stack exec htetris
```

# Screenshots
![](https://cloud.githubusercontent.com/assets/2439255/12403317/7e641ca0-be33-11e5-8d98-8b2afffe3720.png)
![](https://cloud.githubusercontent.com/assets/2439255/12403413/f6a1c0fa-be33-11e5-8770-41fb4a468b41.png)


text:
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(

Hello there! How are you?
,
	document.getElementById('root')
);