text:
#include "polycode/ide/PolycodeMeshEditor.h"

extern UIGlobalMenu *globalMenu;

PolycodeMeshEditor::PolycodeMeshEditor(Core *core, ResourcePool *pool) : PolycodeEditor(core, pool, true), localResourcePool(core, "", pool) {

	previewScene = new Scene(core, Scene::SCENE_3D);
	renderTexture = new SceneRenderTexture(512, 512, false);

	ownsChildren = true;

	previewScene->clearColor.setColor(0.2, 0.2, 0.2, 1.0);
	previewScene->useClearColor = true;

//	previewScene->ambientColor.setColor(0.0, 0.0, 0.0, 1.0);

	Number customFalloff = 0.006;
	mainLight = new SceneLight(SceneLight::POINT_LIGHT, 999999, customFalloff, customFalloff, customFalloff);
	previewScene->addChild(mainLight);

	secondLight = new SceneLight(SceneLight::POINT_LIGHT, 999999, customFalloff, customFalloff, customFalloff);
	previewScene->addChild(secondLight);

	mainLight->setPosition(9999, 9999, 9999);
	secondLight->setPosition(-9999, -9999, -9999);

	previewShape = new UIRect(core, pool, 256, 256);
	previewShape->setAnchorPoint(-1.0, -1.0, 0.0);
	previewShape->setTexture(renderTexture->getTargetTexture());
	addChild(previewShape);

	previewBase = new Entity();
	previewScene->addChild(previewBase);

	previewMesh = NULL;
	trackballCamera = new TrackballCamera(core->getInput(), previewScene->getDefaultCamera(), previewShape);
	trackballCamera->getTargetCamera()->setClippingPlanes(0.1, 1000.0);
	//trackballCamera->getTargetCamera()->setPosition(0.0, 0.0, 50.);
	trackballCamera->setOrbitingCenter(Vector3(0.0, 0.0, 0.0));
}

void PolycodeMeshEditor::Activate() {
	previewScene->enabled = true;
	renderTexture->enabled = true;
}

void PolycodeMeshEditor::Deactivate() {
	previewScene->enabled = false;
	renderTexture->enabled = false;

}

void PolycodeMeshEditor::Render(GPUDrawBuffer *buffer) {
	renderTexture->Render(buffer->renderFrame, previewScene, previewScene->getDefaultCamera());
}

void PolycodeMeshEditor::handleEvent(Event *event) {
}

PolycodeMeshEditor::~PolycodeMeshEditor() {
	resourcePool->removeAllHandlersForListener(this);
	previewScene->rootEntity.setOwnsChildrenRecursive(true);
	delete previewScene;
	delete renderTexture;
	delete trackballCamera;
}

bool PolycodeMeshEditor::openFile(OSFileEntry filePath) {
	previewMesh = new SceneMesh(&localResourcePool, filePath.fullPath);
	previewBase->addChild(previewMesh);
	previewMesh->setMaterial(resourcePool->getMaterial("Default"));
	PolycodeEditor::openFile(filePath);
	trackballCamera->setCameraDistance(previewMesh->getMesh()->getRadius() * 3.0);
	trackballCamera->setCameraPosition(trackballCamera->getOribitingCenter()+Vector3(0.0, 0.0, trackballCamera->getCameraDistance()));
	return true;
}

void PolycodeMeshEditor::Resize(int x, int y) {

	renderTexture->resizeRenderTexture(x, y-30);
	previewShape->setTexture(renderTexture->getTargetTexture());
	previewShape->Resize(x, y-30);
	previewShape->setPosition(0, 30);
	PolycodeEditor::Resize(x,y);
}


text:
package ca.dal.cs.scavenger;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ViewChallenge extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_challenge);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tests\Unit\Models;

use App\Repositories\TagRepository;
use App\Models\Space;
use App\Models\Spending;
use App\Models\Tag;
use Tests\TestCase;

class TagTest extends TestCase
{
    public function testMostExpensiveTags()
    {
        $space = Space::factory()->create();

        $repository = new TagRepository();

        // No tags existing
        $this->assertEmpty($repository->getMostExpensiveTags($space->id));

        $tag = Tag::factory()->create([
            'space_id' => $space->id
        ]);

        // After creating tag
        $this->assertNotEmpty($repository->getMostExpensiveTags($space->id));
        $this->assertEquals(0, $repository->getMostExpensiveTags($space->id)[0]->amount);

        // After creating spending for said tag
        Spending::factory()->create([
            'space_id' => $space->id,
            'tag_id' => $tag->id,
            'amount' => 1025
        ]);

        $this->assertEquals(1025, $repository->getMostExpensiveTags($space->id)[0]->amount);

        // TODO TEST YEAR, MONTH AND LIMIT
    }
}


text:
package com.google.code.axonguice.commandhandling;

import com.google.code.axonguice.AxonGuiceTestBase;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.junit.Assert;
import org.junit.Test;

import javax.inject.Inject;
import javax.inject.Provider;

/**
 * @author Alexey Krylov
 * @since 06.02.13
 */
public class SingletonCommandGatewayTest extends AxonGuiceTestBase {

    /*===========================================[ INSTANCE VARIABLES ]===========*/

    @Inject
    private Provider<CommandGateway> commandGatewayProvider;

    /*===========================================[ CLASS METHODS ]================*/

    @Test
    public void testCommandGatewayIsSingleton() {
        CommandGateway instance = injector.getInstance(CommandGateway.class);
        CommandGateway instance1 = injector.getInstance(CommandGateway.class);
        Assert.assertEquals(instance, instance1);
        Assert.assertEquals(commandGatewayProvider.get(), commandGatewayProvider.get());
    }
}


text:
import React, { PureComponent } from 'react';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { Posts } from '../../lib/collections/posts';
import { postGetPageUrl } from '../../lib/collections/posts/helpers';
import { Comments } from '../../lib/collections/comments'
import Users from '../../lib/collections/users/collection';
import { Link } from '../../lib/reactRouterWrapper'
import { styles } from '../admin/AdminHome';
import classNames from 'classnames';

const DateDisplay = ({column, document}) => {
  return
{document[column.name] && <Components.FormatDate date={document[column.name]}/>}

}

const PostDisplay = ({column, document}) => {
  const post = document.post || document
  return <Link rel="nofollow" to={postGetPageUrl(post) + "#" + document._id }>{ post.title }</Link>
}

const UserDisplay = ({column, document}) => {
  const user = document.user || document
  return

    <Components.UsersName user={user} nofollow />

}

const DeletedByUserDisplay = ({column, document}) => {
  const user = document.deletedByUser || document.user || document
  return

    <Components.UsersName user={user} nofollow />

}

const BannedUsersDisplay = ({column, document}) => {
  const bannedUsers = document[column.name]
  return

    { bannedUsers.map((userId) =>

      <Components.UsersNameWrapper documentId={userId} nofollow />

)}

}

const deletedCommentColumns = [
  {
    name: 'user',
    component: UserDisplay,
  },
  {
    name: 'post',
    component: PostDisplay,
  },
  {
    name: 'deletedByUser',
    component: DeletedByUserDisplay,
  },
  {
    name: 'deletedDate',
    label: 'Deleted Date',
    component: DateDisplay,
  },
  {
    name:'deletedPublic',
    label:'Deleted Public'
  },
  {
    name:'deletedReason',
    label:'Reason'
  },
]

const usersBannedFromPostsColumns = [
  {
    name: 'user',
    component: UserDisplay,
  },
  {
    name: '_id',
    label: 'Post',
    component: PostDisplay,
  },
  {
    name:'bannedUserIds',
    label:'Banned Users',
    component: BannedUsersDisplay
  },
]

const usersBannedFromUsersColumns = [
  {
    name: '_id',
    component: UserDisplay,
  },
  {
    name:'bannedUserIds',
    label:'Banned Users',
    component: BannedUsersDisplay
  },
]

class ModerationLog extends PureComponent<any> {

  constructor(props) {
    super(props);
  }

  render() {
    const { classes } = this.props;
    const { SingleColumnSection } = Components;
    return (
      <SingleColumnSection className={classes.adminHomeOrModerationLogPage}>

Moderation Log

Deleted Comments

          <Components.Datatable
            collection={Comments}
            columns={deletedCommentColumns}
            options={{
              fragmentName: 'DeletedCommentsModerationLog',
              terms: {view: "allCommentsDeleted"},
              limit: 10,
            }}
            showEdit={false}
          />

Users Banned From Posts

          <Components.Datatable
            collection={Posts}
            columns={usersBannedFromPostsColumns}
            options={{
              fragmentName: 'UsersBannedFromPostsModerationLog',
              terms: {view: "postsWithBannedUsers"},
              limit: 10,
            }}
            showEdit={false}
            showNew={false}
          />

Users Banned From Users

          <Components.Datatable
            collection={Users}
            columns={usersBannedFromUsersColumns}
            options={{
              fragmentName: 'UsersBannedFromUsersModerationLog',
              terms: {view: "usersWithBannedUsers"},
              limit: 10,
            }}
            showEdit={false}
            showNew={false}
          />

      </SingleColumnSection>
    )
  }
}

const ModerationLogComponent = registerComponent('ModerationLog', ModerationLog, {styles});

declare global {
  interface ComponentTypes {
    ModerationLog: typeof ModerationLogComponent
  }
}


text:
layout: post
title: 一些软件安装的备忘录
categories: [Configuration]
tags: [Memo, Ubuntu]
description: "一个简单的备忘录,记录一些常用的Ubuntu软件安装方法以及一些不需要记住的东西。"
fullview: false
comments: true
---
# Ubuntu 常用软件配置

## Ubuntu shutter 截图快捷键设置

    shutter -s

## Ubuntu 屏幕防蓝光

    redshift

## Ubuntu wps 中文字体解决

下载字体包解压

cp所有字体文件到/usr/share/fonts路径下

生成字体索引信息

    sudo mkfontscale
    sudo mkfontdir

更新字体缓存

    sudo fc-cache

## Ubuntu Terminator 图标修复

默认Ubuntu 使用 Unity 桌面,Terminator使用Gonme驱动所以修改后才能使图标固定在启动栏

    gsettings set org.gnome.desktop.default-applications.terminal exec 'terminator'

## Git 全局代理设置

    git config --global http.proxy http://127.0.0.1:1080
    git config --global https.proxy http://127.0.0.1:1080

如果使用 socks5 则使用如下配置:

    git config --global http.proxy socks5://127.0.0.1:1080
    git config --global https.proxy socks5://127.0.0.1:1080

如果不想使用全局代理则使用如下配置取消代理:

    git config --global --unset http.proxy
    git config --global --unset https.proxy

进阶:如果使用下列方法代理github速度感人

    git config --global http.https://github.com.proxy socks5://127.0.0.1:1080

## 设置系统目录为英文

默认的中文目录非常不方便,可以只设置系统目录为英文

    export LANG=en_US
    xdg-user-dirs-gtk-update
    export LANG=zh-CN

## 安装 Google Chrome

    wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
    sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
    sudo apt update
    sudo apt install google-chrome-xxxxx

# Ubuntu 非常用软件配置

## Ubuntu 安装 WhatWeb(fix bug)

在安装whatweb之后发现报错:

    /usr/bin/whatweb: /usr/lib/ruby/vendor_ruby/rchardet/universaldetector.rb:39: invalid multibyte escape: /[\x80-\xFF]/ (SyntaxError)

运行环境:

    Ubuntu 16.04
    ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]

问题解决:

    sudo vi /usr/lib/ruby/vendor_ruby/rchardet/universaldetector.rb

在文件第一行加入

    # encoding: US-ASCII

Bug fix 启动正常,但是仍然报错

    /usr/share/whatweb/lib/tld.rb:85: warning: key "2nd_level_registration" is duplicated and overwritten on line 85
    /usr/share/whatweb/lib/tld.rb:93: warning: key "2nd_level_registration" is duplicated and overwritten on line 93
    /usr/share/whatweb/lib/tld.rb:95: warning: key "2nd_level_registration" is duplicated and overwritten on line 95

## Ubuntu 安装 Metasploit

    curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && \
    chmod 755 msfinstall && \
    ./msfinstall

## Ubuntu 安装 exploit-db

Frist step: get exploit-db in github

    git clone https://github.com/offensive-security/exploit-database.git /opt/exploit-database

Next:link

    ln -sf /opt/exploit-database/searchsploit /usr/local/bin/searchsploit


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSPY v5 rel. 4 U (http://www.xmlspy.com) by Walter Hamscher (Standard Advantage) -->
<!-- XBRL 2.1 Tests -->
<!-- Copyright 2003 XBRL International. All Rights Reserved. -->
<?xml-stylesheet type="text/xsl" href="../../testcase.xsl"?>
<testcase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Linkbase References" description="Section 5 Taxonomies" outpath="out" owner="geoff@galexy.net" xsi:noNamespaceSchemaLocation="../lib/test.xsd" minimal="true">
	<variation id="V-01" name="LinkbaseRefCounterExample">
		<description>
		201.01 The LinkbaseRef elements MUST hold the URI of
		Linkbases.  In this case the URI's do not resolve to
		XML documents.
		</description>
		<data>
			<xsd readMeFirst="true">201-01-LinkbaseRefCounterExample.xsd</xsd>
		</data>
		<result expected="invalid"/>
	</variation>
	<variation id="V-02" name="LinkbaseRef">
		<description>
		201.02 The LinkbaseRef elements hold the URI of
		Linkbases.  In this case the URI's actually resolve to
		documents that contain the right kinds of XBRL linkbases.
		</description>
		<!-- done: populate linkbaseRef.xsd with five pointers -->
		<data>
			<xsd readMeFirst="true">201-02-LinkbaseRef.xsd</xsd>
			<linkbase readMeFirst="false">LinkbaseRef-label.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-reference.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-calculation.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-presentation.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-definition.xml</linkbase>
		</data>
		<result expected="valid"/>
	</variation>
	<variation id="V-03" name="LinkbaseRefXMLBase">
		<description>
		201.03 XML Base must be used to process the URI of a
		LinkbaseRef.  In this case the schema use the xml base
		attribute to get the linkbase to be picked up from the
		base directory instead of the current directory.
		</description>
		<data>
			<xsd readMeFirst="true">201-03-LinkbaseRefXMLBase.xsd</xsd>
			<linkbase readMeFirst="false">base/201-03-LinkbaseRefXMLBase-label.xml</linkbase>
		</data>
		<result expected="valid"/>
	</variation>
	<variation id="V-04" name="LinkbaseRefLabelCounterExample">
		<description>
		201.04 The LinkbaseRef XLink role attribute value must
		match the linkbase found at its target.  In this case
		it does not.  The role indicates a label linkbase and
		the actual linkbase is a reference linkbase.
		</description>
		<data>
			<xsd readMeFirst="true">201-04-LinkbaseRefLabelCounterExample.xsd</xsd>
			<linkbase readMeFirst="false">LinkbaseRef-reference.xml</linkbase>
		</data>
		<result expected="invalid"/>
	</variation>
	<variation id="V-05" name="LinkbaseRefReferenceCounterExample">
		<description>
		201.05 The LinkbaseRef element role must match the
		linkbase found at its target.  In this case
		it does not.  The role indicates a reference linkbase and
		the actual linkbase is a label linkbase.
		</description>
		<data>
			<xsd readMeFirst="true">201-05-LinkbaseRefReferenceCounterExample.xsd</xsd>
			<linkbase readMeFirst="false">LinkbaseRef-label.xml</linkbase>
		</data>
		<result expected="invalid"/>
	</variation>
	<variation id="V-06" name="LinkbaseRefDefinitionCounterExample">
		<description>
		201.06 The LinkbaseRef element role must match the
		linkbase found at its target.  In this case a
		calculation linkbase is indicated and a definition
		linkbase is provided.
		</description>
		<data>
			<xsd readMeFirst="true">201-06-LinkbaseRefDefinitionCounterExample.xsd</xsd>
			<linkbase readMeFirst="false">LinkbaseRef-definition.xml</linkbase>
		</data>
		<result expected="invalid"/>
	</variation>
	<variation id="V-07" name="LinkbaseRefPresentationCounterExample">
		<description>
		201.07 The LinkbaseRef element role must match the
		linkbase found at its target.  In this case a
		definition linkbase is indicated and a presentation
		linkbase is provided.
		</description>
		<data>
			<xsd readMeFirst="true">201-07-LinkbaseRefPresentationCounterExample.xsd</xsd>
			<linkbase readMeFirst="false">LinkbaseRef-presentation.xml</linkbase>
		</data>
		<result expected="invalid"/>
	</variation>
	<variation id="V-08" name="LinkbaseRefCalculationCounterExample">
		<description>
		201.08 The LinkbaseRef element role must match the
		linkbase found at its target.  In this case a
		presentation linkbase is indicated and a calculation
		linkbase is provided.
		</description>
		<data>
			<xsd readMeFirst="true">201-08-LinkbaseRefCalculationCounterExample.xsd</xsd>
			<linkbase readMeFirst="false">LinkbaseRef-calculation.xml</linkbase>
		</data>
		<result expected="invalid"/>
	</variation>
	<variation id="V-09" name="LinkbaseRefMultipleExample">
		<description>
		201.09 There can be any number of LinkbaseRef elements
		having the same role but the role must always match
		the target.
		</description>
		<data>
			<xsd readMeFirst="true">201-09-LinkbaseRefMultipleExample.xsd</xsd>
			<linkbase readMeFirst="false">LinkbaseRef-presentation.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-2-presentation.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-3-calculation.xml</linkbase>
		</data>
		<result expected="valid"/>
	</variation>
	<variation id="V-10" name="InvalidRefInSecondAppinfo">
		<description>
		201.10 The LinkbaseRef element in the second appinfo section holds
    the URI of a reference linkbase, but uses a role that should only
    point to label Linkbases.
  	</description>
		<!-- done: populate linkbaseRef.xsd with five pointers -->
		<data>
			<xsd readMeFirst="true">201-10-InvalidLinbaseRefInSecondAppinfo.xsd</xsd>
			<linkbase readMeFirst="false">201-02-LinkbaseRef.xsd</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-label.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-reference.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-calculation.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-presentation.xml</linkbase>
			<linkbase readMeFirst="false">LinkbaseRef-definition.xml</linkbase>
		</data>
		<result expected="invalid"/>
	</variation>
</testcase>


text:
<?php

namespace Zend\ServiceManager\Factory;

use Interop\Container\ContainerInterface;

/**
 * Interface for an abstract factory.
 *
 * An abstract factory extends the factory interface, but also has an
 * additional "canCreate" method, which is called to check if the abstract
 * factory has the ability to create an instance for the given service. You
 * should limit the number of abstract factories to ensure good performance.
 * Starting from ServiceManager v3, remember that you can also attach multiple
 * names to the same factory, which reduces the need for abstract factories.
 */
interface AbstractFactoryInterface extends FactoryInterface
{
    /**
     * Can the factory create an instance for the service?
     *
     * @param  ContainerInterface $container
     * @param  string $requestedName
     * @return bool
     */
    public function canCreate(ContainerInterface $container, $requestedName);
}


text:
.class public Lo/ĵ$If;
.super Lo/ĸ$ˊ;
.source ""

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lo/ĵ;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "If"
.end annotation

# instance fields
.field ʻ:Z

.field public ˊ:Z
    .annotation runtime Landroid/view/ViewDebug$ExportedProperty;
    .end annotation
.end field

.field public ˋ:I
    .annotation runtime Landroid/view/ViewDebug$ExportedProperty;
    .end annotation
.end field

.field public ˎ:I
    .annotation runtime Landroid/view/ViewDebug$ExportedProperty;
    .end annotation
.end field

.field public ˏ:Z
    .annotation runtime Landroid/view/ViewDebug$ExportedProperty;
    .end annotation
.end field

.field public ᐝ:Z
    .annotation runtime Landroid/view/ViewDebug$ExportedProperty;
    .end annotation
.end field

# direct methods
.method public constructor <init>(II)V
    .locals 1

    .line 800
    invoke-direct {p0, p1, p2}, Lo/ĸ$ˊ;-><init>(II)V

    .line 801
    const/4 v0, 0x0

    iput-boolean v0, p0, Lo/ĵ$If;->ˊ:Z

    .line 802
    return-void
.end method

.method constructor <init>(IIZ)V
    .locals 0

    .line 805
    invoke-direct {p0, p1, p2}, Lo/ĸ$ˊ;-><init>(II)V

    .line 806
    iput-boolean p3, p0, Lo/ĵ$If;->ˊ:Z

    .line 807
    return-void
.end method

.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
    .locals 0

    .line 787
    invoke-direct {p0, p1, p2}, Lo/ĸ$ˊ;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V

    .line 788
    return-void
.end method

.method public constructor <init>(Landroid/view/ViewGroup$LayoutParams;)V
    .locals 0

    .line 791
    invoke-direct {p0, p1}, Lo/ĸ$ˊ;-><init>(Landroid/view/ViewGroup$LayoutParams;)V

    .line 792
    return-void
.end method

.method public constructor <init>(Lo/ĵ$If;)V
    .locals 1

    .line 795
    invoke-direct {p0, p1}, Lo/ĸ$ˊ;-><init>(Landroid/view/ViewGroup$LayoutParams;)V

    .line 796
    iget-boolean v0, p1, Lo/ĵ$If;->ˊ:Z

    iput-boolean v0, p0, Lo/ĵ$If;->ˊ:Z

    .line 797
    return-void
.end method


text:
"""
tokeniser.py

Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""

from exabgp.util import coroutine
from exabgp.configuration.engine.location import Location
from exabgp.configuration.engine.raised import Raised

# convert special caracters

@coroutine.join
def unescape (s):
	start = 0
	while start < len(s):
		pos = s.find('\\', start)
		if pos == -1:
			yield s[start:]
			break
		yield s[start:pos]
		pos += 1
		esc = s[pos]
		if esc == 'b':
			yield '\b'
		elif esc == 'f':
			yield '\f'
		elif esc == 'n':
			yield '\n'
		elif esc == 'r':
			yield '\r'
		elif esc == 't':
			yield '\t'
		elif esc == 'u':
			yield chr(int(s[pos + 1:pos + 5], 16))
			pos += 4
		else:
			yield esc
		start = pos + 1

# A coroutine which return the producer token, or string if quoted from the stream

@coroutine.each
def tokens (stream):
	spaces = [' ','\t','\r','\n']
	strings = ['"', "'"]
	syntax = [',','[',']','{','}']
	comment = ['#',]
	nb_lines = 0
	for line in stream:
		nb_lines += 1
		nb_chars = 0
		quoted = ''
		word = ''
		for char in line:
			if char in comment:
				if quoted:
					word += char
					nb_chars += 1
				else:
					if word:
						yield nb_lines,nb_chars,line,char
						word = ''
					break

			elif char in syntax:
				if quoted:
					word += char
				else:
					if word:
						yield nb_lines,nb_chars-len(word),line,word
						word = ''
					yield nb_lines,nb_chars,line,char
				nb_chars += 1

			elif char in spaces:
				if quoted:
					word += char
				elif word:
					yield nb_lines,nb_chars-len(word),line,word
					word = ''
				nb_chars += 1

			elif char in strings:
				word += char
				if quoted == char:
					quoted = ''
					yield nb_lines,nb_chars-len(word),line,word
					word = ''
				else:
					quoted = char
				nb_chars += 1

			else:
				word += char
				nb_chars += 1

# ==================================================================== Tokeniser
# Return the producer token from the configuration

class Tokeniser (Location):
	def __init__ (self,name,stream):
		super(Tokeniser,self).__init__()
		self.name = name                  # A unique name for this tokenier, so we can have multiple
		self.tokeniser = tokens(stream)   # A corouting giving us the producer toker
		self._rewind = []                 # Should we want to rewind, the list of to pop first

	def __call__ (self):
		if self._rewind:
			return self._rewind.pop()
		token = self.content(self.tokeniser)
		return token

	# XXX: FIXME: line and position only work if we only rewind one element
	def rewind (self,token):
		self._rewind.append(token)

	def content (self,producer):
		try:
			while True:
				self.idx_line,self.idx_column,self.line,token = producer()
				if token == '[':
					returned = []
					for token in self.iterate_list(producer):
						returned.append((self.idx_line,self.idx_column,self.line,token))
					return returned
				elif token[0] in ('"',"'"):
					return unescape(token[1:-1])
				else:
					return token
		except ValueError:
			raise Raised(Location(self.idx_line,self.idx_column,self.line),'Could not parse %s' % str(token))
		except StopIteration:
			return None

	def iterate_list (self,producer):
		token = self.content(producer)
		while token and token != ']':
			yield token
			token = self.content(producer)


text:
from ggplot import aes, geom_step, ggplot
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from bokeh import mpl
from bokeh.plotting import output_file, show

df = pd.DataFrame({
    "x": range(100),
    "y": np.random.choice([-1, 1], 100)
})
df.y = df.y.cumsum()

g = ggplot(aes(x='x', y='y'), data=df) + geom_step()
g.make()

plt.title("Step ggplot-based plot in Bokeh.")

output_file("ggplot_step.html", title="ggplot_step.py example")

show(mpl.to_bokeh())


text: pip install requests==2.6.1


text:
package stmt

import (
	"github.com/sqlabble/sqlabble/keyword"
	"github.com/sqlabble/sqlabble/token"
	"github.com/sqlabble/sqlabble/tokenizer"
)

type Select struct {
	prev     Prever
	distinct bool
	columns  []ValOrColOrAliasOrFuncOrSubOrFormula
}

func NewSelect(columns ...ValOrColOrAliasOrFuncOrSubOrFormula) Select {
	return Select{
		distinct: false,
		columns:  columns,
	}
}

func NewSelectDistinct(columns ...ValOrColOrAliasOrFuncOrSubOrFormula) Select {
	return Select{
		distinct: true,
		columns:  columns,
	}
}

func (s Select) From(t JoinerOrAlias) From {
	f := NewFrom(t)
	f.prev = s
	return f
}

func (s Select) nodeize() (tokenizer.Tokenizer, []interface{}) {
	return nodeizePrevs(s)
}

func (s Select) nodeizeSelf() (tokenizer.Tokenizer, []interface{}) {
	tokenizers := make(tokenizer.Tokenizers, len(s.columns))
	values := []interface{}{}
	for i, c := range s.columns {
		var vals []interface{}
		tokenizers[i], vals = c.nodeize()
		values = append(values, vals...)
	}
	tokens := token.NewTokens(token.Word(keyword.Select))
	if s.distinct {
		tokens = tokens.Append(
			token.Word(keyword.Distinct),
		)
	}
	return tokenizer.NewContainer(
		tokenizer.NewLine(tokens...),
	).SetMiddle(
		tokenizers.Prefix(token.Comma),
	), values
}

func (s Select) previous() Prever {
	return s.prev
}


text:
/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
 */

#if defined(GTK_DISABLE_SINGLE_INCLUDES) && !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION)
#error "Only <gtk/gtk.h> can be included directly."
#endif

#ifndef __GTK_RANGE_H__
#define __GTK_RANGE_H__

#include <gtk/gtkadjustment.h>
#include <gtk/gtkwidget.h>

G_BEGIN_DECLS

#define GTK_TYPE_RANGE            (gtk_range_get_type ())
#define GTK_RANGE(obj)            (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_RANGE, GtkRange))
#define GTK_RANGE_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_RANGE, GtkRangeClass))
#define GTK_IS_RANGE(obj)         (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_RANGE))
#define GTK_IS_RANGE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_RANGE))
#define GTK_RANGE_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_RANGE, GtkRangeClass))

/* These two are private/opaque types, ignore */
typedef struct _GtkRangeLayout    GtkRangeLayout;
typedef struct _GtkRangeStepTimer GtkRangeStepTimer;

typedef struct _GtkRange        GtkRange;
typedef struct _GtkRangeClass   GtkRangeClass;

struct _GtkRange
{
  GtkWidget widget;

  GtkAdjustment *GSEAL (adjustment);
  GtkUpdateType GSEAL (update_policy);
  guint GSEAL (inverted) : 1;

  /*< protected >*/

  guint GSEAL (flippable) : 1;

  /* Steppers are: < > ---- < >
   *               a b      c d
   */

  guint GSEAL (has_stepper_a) : 1;
  guint GSEAL (has_stepper_b) : 1;
  guint GSEAL (has_stepper_c) : 1;
  guint GSEAL (has_stepper_d) : 1;

  guint GSEAL (need_recalc) : 1;

  guint GSEAL (slider_size_fixed) : 1;

  gint GSEAL (min_slider_size);

  GtkOrientation GSEAL (orientation);

  /* Area of entire stepper + trough assembly in widget->window coords */
  GdkRectangle GSEAL (range_rect);
  /* Slider range along the long dimension, in widget->window coords */
  gint GSEAL (slider_start);
  gint GSEAL (slider_end);

  /* Round off value to this many digits, -1 for no rounding */
  gint GSEAL (round_digits);

  /*< private >*/
  guint GSEAL (trough_click_forward) : 1;  /* trough click was on the forward side of slider */
  guint GSEAL (update_pending) : 1;        /* need to emit value_changed */
  GtkRangeLayout *GSEAL (layout);
  GtkRangeStepTimer *GSEAL (timer);
  gint GSEAL (slide_initial_slider_position);
  gint GSEAL (slide_initial_coordinate);
  guint GSEAL (update_timeout_id);
  GdkWindow *GSEAL (event_window);
};

struct _GtkRangeClass
{
  GtkWidgetClass parent_class;

  /* what detail to pass to GTK drawing functions */
  gchar *slider_detail;
  gchar *stepper_detail;

  void (* value_changed)    (GtkRange     *range);
  void (* adjust_bounds)    (GtkRange     *range,
                             gdouble	   new_value);

  /* action signals for keybindings */
  void (* move_slider)      (GtkRange     *range,
                             GtkScrollType scroll);

  /* Virtual functions */
  void (* get_range_border) (GtkRange     *range,
                             GtkBorder    *border_);

  gboolean (* change_value) (GtkRange     *range,
                             GtkScrollType scroll,
                             gdouble       new_value);

  /* Padding for future expansion */
  void (*_gtk_reserved1) (void);
  void (*_gtk_reserved2) (void);
  void (*_gtk_reserved3) (void);
};

GType              gtk_range_get_type                      (void) G_GNUC_CONST;

void               gtk_range_set_update_policy             (GtkRange      *range,
                                                            GtkUpdateType  policy);
GtkUpdateType      gtk_range_get_update_policy             (GtkRange      *range);

void               gtk_range_set_adjustment                (GtkRange      *range,
                                                            GtkAdjustment *adjustment);
GtkAdjustment*     gtk_range_get_adjustment                (GtkRange      *range);

void               gtk_range_set_inverted                  (GtkRange      *range,
                                                            gboolean       setting);
gboolean           gtk_range_get_inverted                  (GtkRange      *range);

void               gtk_range_set_flippable                 (GtkRange      *range,
                                                            gboolean       flippable);
gboolean           gtk_range_get_flippable                 (GtkRange      *range);

void               gtk_range_set_slider_size_fixed         (GtkRange      *range,
                                                            gboolean       size_fixed);
gboolean           gtk_range_get_slider_size_fixed         (GtkRange      *range);

void               gtk_range_set_min_slider_size           (GtkRange      *range,
                                                            gboolean       min_size);
gint               gtk_range_get_min_slider_size           (GtkRange      *range);

void               gtk_range_get_range_rect                (GtkRange      *range,
                                                            GdkRectangle  *range_rect);
void               gtk_range_get_slider_range              (GtkRange      *range,
                                                            gint          *slider_start,
                                                            gint          *slider_end);

void               gtk_range_set_lower_stepper_sensitivity (GtkRange      *range,
                                                            GtkSensitivityType sensitivity);
GtkSensitivityType gtk_range_get_lower_stepper_sensitivity (GtkRange      *range);
void               gtk_range_set_upper_stepper_sensitivity (GtkRange      *range,
                                                            GtkSensitivityType sensitivity);
GtkSensitivityType gtk_range_get_upper_stepper_sensitivity (GtkRange      *range);

void               gtk_range_set_increments                (GtkRange      *range,
                                                            gdouble        step,
                                                            gdouble        page);
void               gtk_range_set_range                     (GtkRange      *range,
                                                            gdouble        min,
                                                            gdouble        max);
void               gtk_range_set_value                     (GtkRange      *range,
                                                            gdouble        value);
gdouble            gtk_range_get_value                     (GtkRange      *range);

void               gtk_range_set_show_fill_level           (GtkRange      *range,
                                                            gboolean       show_fill_level);
gboolean           gtk_range_get_show_fill_level           (GtkRange      *range);
void               gtk_range_set_restrict_to_fill_level    (GtkRange      *range,
                                                            gboolean       restrict_to_fill_level);
gboolean           gtk_range_get_restrict_to_fill_level    (GtkRange      *range);
void               gtk_range_set_fill_level                (GtkRange      *range,
                                                            gdouble        fill_level);
gdouble            gtk_range_get_fill_level                (GtkRange      *range);

/* internal API */
gdouble            _gtk_range_get_wheel_delta              (GtkRange      *range,
                                                            GdkScrollDirection direction);

void               _gtk_range_set_stop_values              (GtkRange      *range,
                                                            gdouble       *values,
                                                            gint           n_values);
gint               _gtk_range_get_stop_positions           (GtkRange      *range,
                                                            gint         **values);

G_END_DECLS

#endif /* __GTK_RANGE_H__ */


text: FPMGSB website


text:
/* The API controller
	Exports 3 methods:
		* post - Creates a new thread
		* list - Returns a list of threads
		* show - Displays a thread and its posts
*/

var Thread = require('../models/thread.js');
var Post = require('../models/post.js');

exports.demo = function(req, res) {
	new Thread({
		title: 'You don\'t know JS',
		author: 'Great'
	}).save();
}

exports.post = function(req, res) {
	new Thread({title: req.body.title, author: req.body.author}).save();
}

exports.list = function(req, res) {
	Thread.find(function(err, threads) {
		res.send(threads);
	});
}

// first locates a thread by title, then locates the replies by thread ID.
exports.show = (function(req, res) {
	Thread.findOne({title: req.params.title}, function(error, thread) {
		var posts = Post.find({thread: thread._id}, function(error, posts) {
			res.send([{thread: thread, posts: posts}]);
		});
	})
});


text:
#ifndef DOM_CAMERA_GONKNATIVEWINDOWCLIENT_H
#define DOM_CAMERA_GONKNATIVEWINDOWCLIENT_H

#include <ui/egl/android_natives.h>

#include "GonkNativeWindow.h"

namespace android {

class GonkNativeWindowClient : public EGLNativeBase<ANativeWindow, GonkNativeWindowClient, RefBase>
{
public:
    GonkNativeWindowClient(const sp<GonkNativeWindow>& window);
    ~GonkNativeWindowClient(); // this class cannot be overloaded

private:
    void init();

    // ANativeWindow hooks
    static int hook_cancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer);
    static int hook_dequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer);
    static int hook_lockBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer);
    static int hook_perform(ANativeWindow* window, int operation, ...);
    static int hook_query(const ANativeWindow* window, int what, int* value);
    static int hook_queueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer);
    static int hook_setSwapInterval(ANativeWindow* window, int interval);

    int dispatchConnect(va_list args);
    int dispatchDisconnect(va_list args);
    int dispatchSetBufferCount(va_list args);
    int dispatchSetBuffersGeometry(va_list args);
    int dispatchSetBuffersDimensions(va_list args);
    int dispatchSetBuffersFormat(va_list args);
    int dispatchSetBuffersTimestamp(va_list args);
    int dispatchSetUsage(va_list args);

protected:
    virtual int cancelBuffer(ANativeWindowBuffer* buffer);
    virtual int dequeueBuffer(ANativeWindowBuffer** buffer);
    virtual int lockBuffer(ANativeWindowBuffer* buffer);
    virtual int perform(int operation, va_list args);
    virtual int query(int what, int* value) const;
    virtual int queueBuffer(ANativeWindowBuffer* buffer);
    virtual int setSwapInterval(int interval);

    virtual int connect(int api);
    virtual int disconnect(int api);
    virtual int setBufferCount(int bufferCount);
    virtual int setBuffersDimensions(int w, int h);
    virtual int setBuffersFormat(int format);
    virtual int setBuffersTimestamp(int64_t timestamp);
    virtual int setUsage(uint32_t reqUsage);

    int getNumberOfArgsForOperation(int operation);

    enum { MIN_UNDEQUEUED_BUFFERS = GonkNativeWindow::MIN_UNDEQUEUED_BUFFERS };
    enum { NUM_BUFFER_SLOTS = GonkNativeWindow::NUM_BUFFER_SLOTS };
    enum { DEFAULT_FORMAT = PIXEL_FORMAT_RGBA_8888 };
    enum { NATIVE_WINDOW_SET_BUFFERS_SIZE = 0x10000000 };

private:
    void freeAllBuffers();
    int getSlotFromBufferLocked(android_native_buffer_t* buffer) const;

    sp<GonkNativeWindow> mNativeWindow;

    // mSlots stores the buffers that have been allocated for each buffer slot.
    // It is initialized to null pointers, and gets filled in with the result of
    // ISurfaceTexture::requestBuffer when the client dequeues a buffer from a
    // slot that has not yet been used. The buffer allocated to a slot will also
    // be replaced if the requested buffer usage or geometry differs from that
    // of the buffer allocated to a slot.
    sp<GraphicBuffer> mSlots[NUM_BUFFER_SLOTS];

    // mReqWidth is the buffer width that will be requested at the next dequeue
    // operation. It is initialized to 1.
    uint32_t mReqWidth;

    // mReqHeight is the buffer height that will be requested at the next deuque
    // operation. It is initialized to 1.
    uint32_t mReqHeight;

    // mReqFormat is the buffer pixel format that will be requested at the next
    // deuque operation. It is initialized to PIXEL_FORMAT_RGBA_8888.
    uint32_t mReqFormat;

    // mReqUsage is the set of buffer usage flags that will be requested
    // at the next deuque operation. It is initialized to 0.
    uint32_t mReqUsage;

    // mTimestamp is the timestamp that will be used for the next buffer queue
    // operation. It defaults to NATIVE_WINDOW_TIMESTAMP_AUTO, which means that
    // a timestamp is auto-generated when queueBuffer is called.
    int64_t mTimestamp;

    // mDefaultWidth is default width of the window, regardless of the
    // native_window_set_buffers_dimensions call
    uint32_t mDefaultWidth;

    // mDefaultHeight is default width of the window, regardless of the
    // native_window_set_buffers_dimensions call
    uint32_t mDefaultHeight;

    // mTransformHint is the transform probably applied to buffers of this
    // window. this is only a hint, actual transform may differ.
    uint32_t mTransformHint;

    // mMutex is the mutex used to prevent concurrent access to the member
    // variables of GonkNativeWindow objects. It must be locked whenever the
    // member variables are accessed.
    mutable Mutex mMutex;

    bool                        mConnectedToCpu;
};

}; // namespace android

#endif // DOM_CAMERA_GONKNATIVEWINDOWCLIENT_H


text:
#include "hand.h"

VOID
CoreNotifyProtocolEntry (
  IN PROTOCOL_ENTRY   *ProtEntry
  )
/*++

Routine Description:

  Signal event for every protocol in protocol entry.

Arguments:

  ProtEntry     - Protocol entry

Returns:

--*/
{
  PROTOCOL_NOTIFY     *ProtNotify;
  EFI_LIST_ENTRY      *Link;

  ASSERT_LOCKED (&gProtocolDatabaseLock);

  for (Link=ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) {
    ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE);
    CoreSignalEvent (ProtNotify->Event);
  }
}

PROTOCOL_INTERFACE *
CoreRemoveInterfaceFromProtocol (
  IN IHANDLE        *Handle,
  IN EFI_GUID       *Protocol,
  IN VOID           *Interface
  )
/*++

Routine Description:

  Removes Protocol from the protocol list (but not the handle list).

Arguments:

  Handle -  The handle to remove protocol on.

  Protocol  -  GUID of the protocol to be moved

  Interface - The interface of the protocol

Returns:

  Protocol Entry

--*/
{
  PROTOCOL_INTERFACE  *Prot;
  PROTOCOL_NOTIFY     *ProtNotify;
  PROTOCOL_ENTRY      *ProtEntry;
  EFI_LIST_ENTRY      *Link;

  ASSERT_LOCKED (&gProtocolDatabaseLock);

  Prot = CoreFindProtocolInterface (Handle, Protocol, Interface);
  if (Prot != NULL) {

    ProtEntry = Prot->Protocol;

    //
    // If there's a protocol notify location pointing to this entry, back it up one
    //

    for(Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) {
      ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE);

      if (ProtNotify->Position == &Prot->ByProtocol) {
        ProtNotify->Position = Prot->ByProtocol.BackLink;
      }
    }

    //
    // Remove the protocol interface entry
    //

    RemoveEntryList (&Prot->ByProtocol);
  }

  return Prot;
}

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreRegisterProtocolNotify (
  IN EFI_GUID       *Protocol,
  IN EFI_EVENT      Event,
  OUT  VOID           **Registration
  )
/*++

Routine Description:

  Add a new protocol notification record for the request protocol.

Arguments:

  Protocol      - The requested protocol to add the notify registration

  Event         - The event to signal

  Registration  - Returns the registration record

Returns:

  EFI_INVALID_PARAMETER       - Invalid parameter

  EFI_SUCCESS                 - Successfully returned the registration record that has been added

--*/
{
  PROTOCOL_ENTRY      *ProtEntry;
  PROTOCOL_NOTIFY     *ProtNotify;
  EFI_STATUS        Status;

  if ((Protocol == NULL) || (Event == NULL) || (Registration == NULL))  {
    return EFI_INVALID_PARAMETER;
  }

  CoreAcquireProtocolLock ();

  ProtNotify = NULL;

  //
  // Get the protocol entry to add the notification too
  //

  ProtEntry = CoreFindProtocolEntry (Protocol, TRUE);
  if (ProtEntry != NULL) {

    //
    // Allocate a new notification record
    //

    ProtNotify = CoreAllocateBootServicesPool (sizeof(PROTOCOL_NOTIFY));

    if (ProtNotify != NULL) {

      ProtNotify->Signature = PROTOCOL_NOTIFY_SIGNATURE;
      ProtNotify->Protocol = ProtEntry;
      ProtNotify->Event = Event;
      //
      // start at the begining
      //
      ProtNotify->Position = &ProtEntry->Protocols;

      InsertTailList (&ProtEntry->Notify, &ProtNotify->Link);
    }
  }

  CoreReleaseProtocolLock ();

  //
  // Done.  If we have a protocol notify entry, then return it.
  // Otherwise, we must have run out of resources trying to add one
  //

  Status = EFI_OUT_OF_RESOURCES;
  if (ProtNotify != NULL) {
    *Registration = ProtNotify;
    Status = EFI_SUCCESS;
  }

  return Status;
}

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreReinstallProtocolInterface (
  IN EFI_HANDLE     UserHandle,
  IN EFI_GUID       *Protocol,
  IN VOID           *OldInterface,
  IN VOID           *NewInterface
  )
/*++

Routine Description:

  Reinstall a protocol interface on a device handle.  The OldInterface for Protocol is replaced by the NewInterface.

Arguments:

  UserHandle    - Handle on which the interface is to be reinstalled
  Protocol      - The numeric ID of the interface
  OldInterface  - A pointer to the old interface
  NewInterface  - A pointer to the new interface

Returns:

  Status code.

  On EFI_SUCCESS            The protocol interface was installed
  On EFI_NOT_FOUND          The OldInterface on the handle was not found
  On EFI_INVALID_PARAMETER  One of the parameters has an invalid value

--*/
{
  EFI_STATUS                Status;
  IHANDLE                   *Handle;
  PROTOCOL_INTERFACE        *Prot;
  PROTOCOL_ENTRY            *ProtEntry;

  Status = CoreValidateHandle (UserHandle);
  if (EFI_ERROR (Status)) {
    return Status;
  }

  if (Protocol == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Handle = (IHANDLE *) UserHandle;

  //
  // Lock the protocol database
  //
  CoreAcquireProtocolLock ();

  //
  // Check that Protocol exists on UserHandle, and Interface matches the interface in the database
  //
  Prot = CoreFindProtocolInterface (UserHandle, Protocol, OldInterface);
  if (Prot == NULL) {
    CoreReleaseProtocolLock ();
    return EFI_NOT_FOUND;
  }

  //
  // Attempt to disconnect all drivers that are using the protocol interface that is about to be reinstalled
  //
  Status = CoreDisconnectControllersUsingProtocolInterface (
             UserHandle,
             Prot
             );
  if (EFI_ERROR (Status)) {
    //
    // One or more drivers refused to release, so return the error
    //
    CoreReleaseProtocolLock ();
    return Status;
  }

  //
  // Remove the protocol interface from the protocol
  //
  Prot = CoreRemoveInterfaceFromProtocol (Handle, Protocol, OldInterface);

  if (Prot == NULL) {
    CoreReleaseProtocolLock ();
    return EFI_NOT_FOUND;
  }

  ProtEntry = Prot->Protocol;

  //
  // Update the interface on the protocol
  //
  Prot->Interface = NewInterface;

  //
  // Add this protocol interface to the tail of the
  // protocol entry
  //
  InsertTailList (&ProtEntry->Protocols, &Prot->ByProtocol);

  //
  // Update the Key to show that the handle has been created/modified
  //
  gHandleDatabaseKey++;
  Handle->Key = gHandleDatabaseKey;

  //
  // Release the lock and connect all drivers to UserHandle
  //
  CoreReleaseProtocolLock ();
  Status = CoreConnectController (
                  UserHandle,
                  NULL,
                  NULL,
                  TRUE
                  );
  CoreAcquireProtocolLock ();

  //
  // Notify the notification list for this protocol
  //
  CoreNotifyProtocolEntry (ProtEntry);

  CoreReleaseProtocolLock ();

  return EFI_SUCCESS;
}


text:
package com.meyouhealth.myhandroid;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class MYHBaseActivity extends AppCompatActivity {

    // extending classes can override this function with their page name
    protected String getTrackPath() {
        return getClass().getSimpleName();
    }

    protected AtomicBoolean mIsRunning = new AtomicBoolean(false);
    private Context mContext;

    @Override
    protected void onPause() {
        super.onPause();
        mIsRunning.set(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mContext = this;
        mIsRunning.set(true);
    }

    public synchronized boolean isRunning() {
        return mIsRunning.get();
    }
}


text:
<?php
namespace Logs;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\MvcEvent;
use Zend\EventManager\GlobalEventManager;
use Monolog\Logger;
use Zend\EventManager\Event;
use Zend\Json\Encoder;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/../../src/' . __NAMESPACE__
                )
            )
        );
    }

    public function getConfig()
    {
        return include __DIR__ . "/../../config/module.config.php";
    }

    public function onBootstrap(MvcEvent $e)
    {
        $serviceLocator = $e->getApplication()->getServiceManager();
        GlobalEventManager::attach(EVENT_LOG_ERROR, function (Event $event) use($serviceLocator)
        {
            $message = Encoder::encode($event->getParams());
            $serviceLocator->get('LogMongodbService')->addRecord(Logger::ERROR, $message, array());
            return true;
        });

        GlobalEventManager::attach(EVENT_LOG_DEBUG, function (Event $event) use($serviceLocator)
        {
        	$message = Encoder::encode($event->getParams());
        	$serviceLocator->get('LogMongodbService')->addRecord(Logger::DEBUG, $message, array());
        	return true;
        });
    }
}


text:
<?php namespace FHIR\Resources\Infrastructure\Profile;

use FHIR\Common\AbstractFHIRObject;
use FHIR\Elements\Primitive\FHIRString;
use FHIR\Elements\Primitive\FHIRUri;
use FHIR\Elements\Simple\FHIRId;

/**
 * Class FHIRProfileMapping
 * @package FHIR\Resources\Infrastructure\Profile
 */
class FHIRProfileMapping extends AbstractFHIRObject
{
    /** @var FHIRId */
    protected $identity = null;

    /** @var FHIRUri */
    protected $uri = null;

    /** @var FHIRString */
    protected $name = null;

    /** @var FHIRString */
    protected $comments = null;

    /**
     * @return FHIRId
     */
    public function getIdentity()
    {
        return $this->identity;
    }

    /**
     * @param FHIRId $identity
     */
    public function setIdentity(FHIRId $identity)
    {
        $this->identity = $identity;
    }

    /**
     * @return FHIRUri
     */
    public function getUri()
    {
        return $this->uri;
    }

    /**
     * @param FHIRUri $uri
     */
    public function setUri(FHIRUri $uri)
    {
        $this->uri = $uri;
    }

    /**
     * @return FHIRString
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param FHIRString $name
     */
    public function setName(FHIRString $name)
    {
        $this->name = $name;
    }

    /**
     * @return FHIRString
     */
    public function getComments()
    {
        return $this->comments;
    }

    /**
     * @param FHIRString $comments
     */
    public function setComments(FHIRString $comments)
    {
        $this->comments = $comments;
    }
}


text:
function isTouchDevice(){
  return 'ontouchstart' in window // works on most browsers
        || 'onmsgesturechange' in window; // works on ie10
}

function objToArray(obj){
  if(Array.isArray(obj))
    return obj;
  return Object.keys(obj).map(function(key){return obj[key]});
}

//actual code
function redactData(str){
  var illegalWords = [
    {word:"pa2c_tesA", replace:"plasmid"}
  ]

  illegalWords.forEach(function(word){
    var replaceWith = word.replace || "[REDACTED]"
    str = str.replace(word.word, replaceWith)
  });
  return JSON.parse(str)
}

function awake(){
  //load journals
  var manifest = ["charlotte.json"]
  var count = 0;
  var journals = Array(manifest.length)
  var failedToLoad = 0;
  function loadManifest(data){
    //console.log(arguments)
    journals[count] = data
    count++;
    if(count == manifest.length - failedToLoad){
      start(journals);
    }
  }

  manifest.forEach(function(file){
    $.ajax({
      type:"GET",
      contentType:"application/json",
      url:"../Journal/" + file + "?action=raw&ctype=text/javascript",
      success:function(data){
          loadManifest(redactData(JSON.stringify(data)));
      },
      error:function(e){
        failedToLoad++;
        console.log("Failed to load a journal", e)
      }

    })

  })
}

function start(journals){
  console.log(journals)
  var options = {
    container: document.getElementById("cy"),
    //elements
    //style
    layout:{name:'grid'},
    ready:function(evt){
      graphReady(evt)
    },
    zoom:1,
    pan:{x:0,y:0},
    minZoom:1e-50,
    maxZoom:1e50,
    zoomingEnabled:true,
    userZoomingEnabled:true,
    panningEnabled:true,
    userPanningEnabled:true,
    boxSelectionEnabled:true,
    selectionType:(isTouchDevice?'additive':'single'),
    touchTapThreshold:8,
    desktopTapThreshold:4,
    autolock:false,
    autoungrabify:false,
    autounselectify:false,

    //rendering options
    headless:false,
    styleEnabled:true,
    hideEdgesOnViewport:false,
    hideLabelsOnViewport:false,
    textureOnViewport:false,
    motionBlur:true,
    motionBlurOpacity:.2,
    wheelSensitivity:1,
    pixelRatio:1,
    initrender:function(evt){
      graphRenderReady(evt);
    },
    renderer:{}
  };
  //convert journals into graph for Cyoscape
  var elements = journalsToGraph(journals); //{nodes:[], edges:[]}
  //console.log(elements)
  options.elements = elements;

  this.cy = cytoscape(options);
}

function journalsToGraph(journals){
  //journals are organized into an array of events that happend on a given day.
  var nodes = {};
  var edges = {};
  var jns = journals[0] //journals = [Array(9)]

  nodeCount = 0;
  edgeCount = 0;

  for(var d = 0; d < jns.length; d++){
    var journal = jns[d];
    //console.log(journal)
    var date = Date.parse(journal["when"]);
    var exps = journal["what"];

    //get an experiment
    for(var i = 0; i < exps.length; i++){
      var exp = exps[i];
      var node = {};
      node.data = {};
      //check for fields.
      if(exp.hasOwnProperty('id')){
        node.data.id = exp['id'];
      }else {
        continue;
      }

      nodeCount++;

      //from
      if(exp.hasOwnProperty('from')){
        var sources = Array.isArray(exp['from'])? exp['from'] : [exp['from']];
        sources.forEach(function(id){
          edges[id+"_"+node.data.id] = {
            data:{
              id:id+"_"+node.data.id,
              source:id,
              target:node.data.id
            }
          }
          console.log(id+"_"+node.data.id)
          edgeCount++;
        });

      }

      //add to nodes list
      nodes[node.data.id] = node;
      console.log(node, node.data.id)
    }

  }
  return {nodes:objToArray(nodes), edges:objToArray(edges) }
}

function graphRenderReady(evt){
  //grab screenshot
}

function graphReady(evt){
  console.log("Graph Ready", evt)
}

$(document).ready(function(){
  awake();
});

cytoscape({
  container: document.getElementById('cy'),
  elements:[
    {
      group:'nodes',

      data:{
        id:'n1',
        parent:'nparent',
        weight: 100
      },

      //scratchpad data
      scratch:{
        foo:'bar'
      },

      position:{
        x:100, y:100
      },

      selected: false,

      selectable: true,

      locked: false,

      grabbable:true,

      classes:'foo bar',

      style:{'background-color':'red'},

    },

    {
      group: 'nodes',
      data:{
        id:'n2'
      },
      renderedPosition:{x:200, y:200}
    },

    {
      group: 'nodes',
      data:{id:'n3', parent:'nparent'},
      position:{x:123, y:234}
    },
    { // edge e1
      group: 'edges',
      data: {
        id: 'e1',
        source: 'n1', // the source node id (edge comes from this node)
        target: 'n2'  // the target node id (edge goes to this node)
      }
    }
  ],

  layout: {
   name: 'preset'
 },

 // so we can see the ids
 style: [
   {
     selector: 'node',
     style: {
       'content': 'data(id)'
     }
   }
 ]
});


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]
### Added|Changed|Deprecated|Removed|Fixed|Security
Nothing so far

## 3.0.2 - 2022-08-04
### Added
- Prevent segfaults and exceptions due to debugging info

## 3.0.1 - 2021-11-18
### Changed
- Replaced PSR-0 autoloading in favor of PSR-4.
- Added upgrade guide for migrating itertools from 2.x to 3.0

## 3.0.0 - 2021-10-21
### Added
- Added support for php 8.
- Added support for Twig 3.
### Changed
- The argument to `iterable()` is no longer required, instead,
  an empty iterator is made when no arguments are given.
- The first argument of `->reduce()` is now a required closure.
### Removed
- Removed support for php 5.
- Removed support for Twig 1.
- Removed everything marked deprecated in the previous major release.
- Removed the option to enable or disable the legacy Twig filters and functions.

## 2.15.0 - 2021-04-08
### Added
- Support for changing the name in Twig
- Enable or disable the legacy Twig filters and functions

When the `zicht/framework-extra-bundle` is used to load the Twig extension,
the following allows you to configure these properties.

  ```yaml
  zicht_framework_extra:
    itertools:
        twig_name: it                   # use `it` (default)
        twig_enable_legacy_api: true    # enable legacy api (default)
  ```

## 2.14.0 - 2021-03-25
### Changed
- Marked many functions as deprecated, i.e. `filters\match` is now available as `Filters::match`.
  This is in preparation of the 3.0 release that will be compatible with php 8, which ships with a
  global `match` statement of its own.

  ```php
  // Deprecated
  // function from filters.php, mappings.php, and reductions.php
  use function Zicht\Iterable\reductions\join;
  iterable(['a', 'b', 'c'])->reduce(join(' - '));

  // New style
  use Zicht\Itertools\util\Reductions;
  iterable(['a', 'b', 'c'])->reduce(Reductions::join(' - '));
  ```

- Marked many twig filters and functions as deprecated, i.e. `[1, 2, 3]|filter` is now available as
  `[1, 2, 3]|it.filter` or `it([1, 2, 3]).filter`.
  This is because twig has been adding filters that use the same names as itertools does.

  ```twig
  {# Deprecated #}
  {{ entries|group_by('key') }}

  {# Everything was replaced by `it` #}
  {{ entries|it.groupBy('key') }}
  ```

## 2.13.0 - 2020-05-22
### Added
- Added `constant` mapping helper.

## 2.12.3 - 2020-02-14
### Fixed
- Small code improvement on how `before` and `after` convert ISO date strings.

## 2.12.2 - 2020-01-31
### Fixed
- The `before` and `after` filter helpers will now convert ISO date string when the expected
  value is a `DateTimeInterface`.

## 2.12.1 - 2020-01-08
### Fixed
- Linter fixes.

## 2.12.0 - 2020-01-08
### Added
- Added `cache` and `string` mapping helper.
- Added `before` and `after` filter helpers.

## 2.11.0 - 2019-04-29
### Added
- Added `CollapseIterator` usable from php or twig.

## 2.10.14 - 2019-04-23
### Fixed
- The `select` mapper now accepts either an array or an object as its first parameter,
  when an object is given then`select` will create an array with objects, when an array is
  given then `select` will create an array with arrays, as before.

## 2.10.13 - 2018-12-07
### Fixed
- Update `composer.lock`.
- Update code to conform with `zicht/standards-php` 3.4.0.

## 2.10.12 - 2018-11-12
### Fixed
- `ChainTrait`, `MapTrait`, and `ZipTrait` would indicate that they throw `\ReflectionException`,
  while this never happens.  This caused other code to give unnecessary warnings.

## 2.10.11 - 2018-11-07
### Fixed
- Changed the auto loader to only include the src directory.

## 2.10.10 - 2018-07-02
### Added
- Support for Twig v2.

## 2.10.9 - 2018-06-14
### Fixed
- The `values`, `toArray`, and `items` traits will now work recursively.
  This is useful when you have a nested iterator and also iterate over
  those iterators in a nested way (php does not properly support this).

  In the below example, the `.values` is used to created a *nested* array, i.e.
  both the `GroupByIterator` and the nested `GroupedIterator` are replaced by an
  array, this allows multiple iterations to occur at the same time.

  ```twig
    {% for grouped in items|group_by('EventId')|sorted('first.EventDateTime').values %}
       {% set first_item = grouped|first %}
       ...
    {% endfor %}
  ```

## 2.10.8 - 2017-12-14
### Added
- Added mappers `json_encode` and `json_decode`.

## 2.10.7 - 2017-11-09
### Fixed
- Reducing using `min` or `max` now supports `\DateTime` instances.

## 2.10.6 - 2017-08-31
### Fixed
- Added missing `$sort` parameter to the `group_by` twig filter extension.

## 2.10.5 - 2017-08-04
### Added
- Added a new filter helper `filters\match`.

## 2.10.4 - 2017-07-31
### Changed
- Calling `values()` on `GroupByIterator` will return the `values()` of every
  item in the group, instead of the `GroupedIterator` instances.

## 2.10.3 - 2017-06-30
### Added
- Added `$discardEmptyContainer` parameter to `mappings/select`.

## 2.10.2 - 2017-06-22
### Added
- Added `not` filter to `filters.php`
### Deprecated
- We should no longer use `not_in(...)` and instead use `not(in(...))`.

## 2.10.1 - 2017-06-21
### Added
- Added `$strategy` parameter to `mappings/select`.
- Added `$discardNull` parameter to `mappings/select`.

## 2.10.0 - 2017-06-01
### Added
- DifferenceTrait, this allows a call like $a->difference($b).
- IntersectionTrait, this allows a call like $a->intersection($b).
- first_key and FirstTrait::firstKey, allowing to get the key of the first element in the iterable.
- last_key and LastTrait::lastKey, allowing to get the key of the last element in the iterable.
### Changed
- Interface definitions for every trait, allowing for optimizations by not having to convert certain
  instances when it is known to be of the correct type already.
- InfiniteIterableInterface and InfiniteIterableTrait: these represent all Interfaces and traits
  that apply to an infinite iterable.
- FiniteIterableInterface and FiniteIterableTrait: these represent all Interfaces and traits
  that apply to a finite iterable.

## 2.9.0 - 2017-04-04
### Added
- $strategy will use twig strategy when getting values, i.e.
  1. array keys
  2. object public property
  3. object public method
  4. object public method with 'get' prefixed [NEW]
  5. object public method with 'is' prefixed [NEW]
  6. object public method with 'has' prefixed [NEW]
  7. object public method __get
  8. otherwise, returns null

## 2.8.26 - 2017-02-27
### Changed
- $strategy can always be null, string, or \Closure

## 2.8.25 - 2017-02-16
### Added
- ZipIterator now provided keys(), values(), and items()
### Changes
- Propagate key property for filters
- Remove usage of Foo::class

  Foo::class was introduced in php 5.5.  We do not need, but it is nice
  to be, compatible with older php versions.
### Fixed
- Fixes bug in KeyValuePair

## 2.8.24 - 2017-01-11
### Added
- Adds mappings/lower and mappings/upper
### Changes
- Move get_mapping and get_reduction to the twig extension

## 2.8.23 - 2016-12-20
### Added
- Adds chain reduction
- Adds type mapping
- Adds parent::key() in callback
### Changed
- Made reductions\chain behavior stateless

  Before reductions\chain is released, I feel this change is needed to
  ensure that the reduction is stateless.

  This also fixes cases where the data list that is being iterated over
  is only a single element long.  This would result in that single
  element being returned (as per reduce behavior).  While we expect a
  ChainIterator as the reduce result.
### Fixed
- Fixes bug in slice combined with infinite iterator
- Fixes bug in filters in and not_in
- Fixes bug in get_reduction

## 2.8.21 - 2016-11-24
### Added
- Adds the GetterTrait to the GroupByIterator

## 2.8.20 - 2016-11-24
### Added
- Adds {Items|Keys|Values}Trait classes
### Fixes
- select with flatten enabled now behaves as follows:

  The select function will, when flatten is enabled, return an array with
  all values of the iterable.  This can now be done using
  iterable->values().

  Moreover, the select function did not properly handle iterables that had
  duplicate keys (because of the iterator_to_array implementation).  This
  is fixed properly when using the iterable->values() call.

## 2.8.19 - 2016-11-16
### Added
- Adds $STRICT to filters\in and filters\not_in
- Adds filters\equals
### Fixed
- Fixes GetterTrait: instanceof Trait always returns false

## 2.8.18 - 2016-11-09
### Added
- Adds key and select mapping
- Adds a random mapping used to sort items randomly
### Changed
- Optimize SortedIterator: we only need to call the value getter once
  per element in the iterable.  Before, the value getter was called
  multiple times per element

## 2.8.17 - 2016-11-02
### Changed
- Use __get method to retrieve value

## 2.8.16 - 2016-10-03
### Added
- Adds function iterable

## 2.8.15 - 2016-09-26
### Added
- Adds in and not_in filters

## 2.8.14 - 2016-09-05
### Fixed
- Compatability fix for PHP 5.4

  Note: Prior to PHP 5.5, empty() only supports variables; anything else
  will result in a parse error. In other words, the following will not
  work: empty(trim($name)). Instead, use trim($name) == false.

## 2.8.13 - 2016-09-01
### Added
- Add length

## 2.8.12 - 2016-09-01
### Added
- Adds reversed filter to twig extension

## 2.8.11 - 2016-08-31
### Added
- Provide filter closures with key and value
### Changed
- null now results in the identity function, which has the same result.
- Renamed $keyStrategy to $strategy

## 2.8.10 - 2016-08-29
### Fixed
- Fixes filter argument order.

## 2.8.9 - 2016-08-29
### Fixed
- Fixes reduce trait arguments

## 2.8.8 - 2016-08-23
### Changed
- Move util classes to functions

  The Conversions, Mappings, and Reductions classes were effectively
  namespaces.  These have been removed in favor of using actual
  namespaces.

## 2.8.7 - 2016-08-23
### Changed
- Split all traits into separate files

## 2.8.6 - 2016-08-19
### Added
- Adds chaining trait to UniqueIterator

## 2.8.5 - 2016-08-11
### Added
- GroupbyIterator should be able to chain
- Sorted should allow array access

## 2.8.4 - 2016-08-08
### Added
- Gives ArrayAccess to ChainIterator

## 2.8.3 - 2016-08-04
### Changed
- Move mixedToClosure to Conversions class

## 2.8.2 - 2016-08-01
### Added
- Add Mapppings util class and twig functions
### Changed
- Move conversions to Conversions util class

## 2.8.1 - 2016-06-30
### Added
### Changed
- rename KeyCallback to MapBy
### Fixed
- bugfix for ReversedIterator

## 2.8.0 - 2016-06-30
### Added
- add twig extension file

## 2.7.1 - 2016-06-29
### Added
- Adds chaining trait

## 2.7.0 - 2016-06-28
### Added
- dev branch for itertool chaining
- move method first

## 2.6.0 - 2016-06-23
### Added
- adds function first
### Changed
- move the reduction closures to their own Reductions class

## 2.5.3 - 2016-06-23
### Fixed
- fixes a bug where AccumulateIterator would call current on its inner iterator while this inner iterator was not valid

## 2.5.2 - 2016-06-22
### Fixed
- fixes bug where UniqueFilter would report an incorrect length

## 2.5.1 - 2016-06-15
### Added
- MapIterator now allows ArrayAccess

## 2.5.0 - 2016-06-15
### Changed
- the SortedIterator and GroupbyIterator now call their closure with both value and key

## 2.4.0 - 2016-05-31
### Changed
- interperate null as an empty list

## 2.3.1 - 2016-05-20
### Added
- adds traits for countable and __debugInfo
- add SliceIterator
### Changed
- When mixedToValueGetter gets null it will return a closure that behaves as an identity function
- move ArrayAccess methods to ArrayAccessTrait
### Fixed
- UniqueIterator should forget the items it has seen on rewind

## 2.3.0 - 2016-05-11
### Added
- adds the reduce operator
- adds __debugInfo magic method to all applicable iterators
- adds unique and uniqueBy
- adds any and all
- implemented countable in to the SortedIterator
### Changed
- adds functionality for keeping keys while iterating
- the closure is no longer required for the filter iterator
- the MapIterator will now keep the keys of the input iterator
- MapIterator now provides both iterator keys and values to the callbacks
### Fixed
- added temp var to support 5.4
- fixes key strategy for sorted and groupby
- fix iterator inception

## 2.0
The primary goal of version 2.0 was a different way of handling
keys in a sequence.  Version 1.0 handled sequences as Python would, i.e.
a sequence of values.  However, php iterators have both a value and
a key assigned to every item in the sequence, version 2.0 takes
this into account.

## 1.5.0 - 2016-02-10
### Added
- adds FilterIterator::toArray()
- adds Countable interface to FilterIterator
- adds toArray to groupby iterator
- implemented array access
### Changed
- renamed 'keyCallback' to 'mapBy', added 'select()' and internally renamed 'mixedToKeyStrategy' to 'mixedToValueGetter'

## 1.4.3 - 2015-11-03
### Added
- adds a few toArray methods

## 1.4.2 - 2015-11-03
### Added
- implements Countable interface for MapIterator

## 1.4.0 - 2015-10-30
### Added
- adds ArrayAccess to GroupedIterator
- adds support for doctrine PersistentCollection
- adds couting to ChainIterator
### Changed
- consider any doctrine collection to be iterable

## 1.3.0 - 2015-08-28
### Added
- adds revered
- adds stable sorting (i.e. items with the same sorting value retain their order)
### Changed
- rename SortIterator to SortedIterator

## 1.2.0 - 2015-08-28
### Changed
- groupby now also sorts by default

## 1.0
The 1.0 version was short lived, it had one big flaw that was fixed in
2.0.  1.0 has not been, and should not be, used in production code.


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

<project default="build" name="airpackage"
	xmlns:if="ant:if"
	xmlns:unless="ant:unless">

	<import file="../build_common.xml" />

	<property name="version.release" value="${version_release_major}.${version_release_minor}.${version_release_build}" if:set="version_release_major" />
	<property name="version.release" value="${version_major}.${version_minor}.${version_build}" />
	<property name="version" value="${version_major}.${version_minor}.${version_build}" />
	<lower name="project.namelower" value="${project.name}" />

	<dirname property="airpackage.basedir" file="${ant.file.airpackage}" />

	<tstamp>
		<format property="publish_date" pattern="yyyy-MM-dd" locale="en,UK" />
	</tstamp>

	<target name="clean" >
		<antcall target="clean_variant" >
			<param name="variant.basedir" value="${airpackage.basedir}" />
		</antcall>
		<foreach target="clean_variant" param="variant.basedir" inheritall="true" >
			<path>
				<dirset dir="${airpackage.basedir}">
					<include name="variants/*"/>
				</dirset>
			</path>
		</foreach>
	</target>

	<target name="clean_variant" >
		<delete includeemptydirs="true" failonerror="false">
			<fileset dir="${variant.basedir}">
				<include name="**/build/**" />
				<include name="**/*.airpackage" />
			</fileset>
		</delete>
		<!-- delete all platform/android/subdirectories but not platform/android/AndroidManifest.xml -->
		<if>
			<available file="${variant.basedir}/platforms/android" type="dir" />
			<then>
				<for param="androidDir" >
					<path>
						<dirset dir="${variant.basedir}/platforms/android" >
							<include name="*"/>
						</dirset>
					</path>
					<sequential>
						<delete includeEmptyDirs="true" failonerror="false" dir="@{androidDir}" />
					</sequential>
				</for>
			</then>
		</if>
	</target>

	<target name="copy_template" >
		<copy todir="${airpackage.sourcedir}/${output.dir}" overwrite="true" >
			<fileset dir="${common.basedir}/${airpackage.tmpl}">
				<!-- Exclude these as they are just templates for manual integration -->
				<exclude name="assets/**" />
				<exclude name="platforms/**" />
			</fileset>
			<filterchain>
				<tokenfilter>
					<replacestring from="@NAME@" to="${airpackage.name}"/>
					<replacestring from="@NAMELOWER@" to="${project.namelower}"/>
					<replacestring from="@DESCRIPTION@" to="${airpackage.description}"/>
					<replacestring from="@GITHUB_REPO@" to="${github.repo}"/>
					<replacestring from="@VERSION@" to="${version}"/>
					<replacestring from="@VERSIONRELEASE@" to="${version.release}"/>
					<replacestring from="@EXTENSIONID@" to="${output.name}"/>
					<replacestring from="@PACKAGE@" to="${package.name}"/>
					<replacestring from="@ANDROIDPACKAGE@" to="${package.name}"/>
					<replacestring from="@DATE@" to="${publish_date}"/>
					<replacestring from="@VARIANT@" to="${airpackage.variant}"/>
				</tokenfilter>
			</filterchain>
		</copy>
	</target>

	<target name="copy" >

		<!-- See if variant ane dir exists, else copy normal ane -->
		<if>
			<available file="${common.basedir}/${output.dir}/${airpackage.variant}"/>
			<then>
				<copy todir="${airpackage.sourcedir}/${output.dir}/ane" flatten="true" overwrite="true" >
					<fileset dir="${common.basedir}/${output.dir}/${airpackage.variant}">
						<include name="*.ane" />
					</fileset>
				</copy>
				<copy todir="${airpackage.sourcedir}/${output.dir}/assets/ios" overwrite="true" >
					<fileset dir="${common.basedir}/${output.dir}/${airpackage.variant}">
						<include name="Frameworks/**" />
					</fileset>
				</copy>
			</then>
			<else>
				<copy todir="${airpackage.sourcedir}/${output.dir}/ane" flatten="true" overwrite="true" >
					<fileset dir="${common.basedir}/${output.dir}">
						<include name="*.ane" />
					</fileset>
				</copy>
				<copy todir="${airpackage.sourcedir}/${output.dir}/assets/ios" overwrite="true" >
					<fileset dir="${common.basedir}/${output.dir}">
						<include name="Frameworks/**" />
					</fileset>
				</copy>
			</else>
		</if>

		<copy todir="${airpackage.sourcedir}/${output.dir}" overwrite="true" failonerror="false">
			<fileset dir="${common.basedir}/../..">
				<include name="CHANGELOG.md" />
				<include name="README.md" />
			</fileset>
			<filterchain>
				<tokenfilter>
					<replacestring from="![](images/hero.png)" to=""/>
					<replacestring from="![](images/promo.png)" to=""/>
				</tokenfilter>
			</filterchain>
		</copy>
		<copy todir="${airpackage.sourcedir}/${output.dir}" overwrite="true" failonerror="false">
			<fileset dir="${common.basedir}">
				<include name="CHANGELOG.md" />
				<include name="README.md" />
			</fileset>
			<filterchain>
				<tokenfilter>
					<replacestring from="![](images/hero.png)" to=""/>
					<replacestring from="![](images/promo.png)" to=""/>
				</tokenfilter>
			</filterchain>
		</copy>
		<copy todir="${airpackage.sourcedir}/${output.dir}" overwrite="true" >
			<fileset dir="${airpackage.sourcedir}">
				<include name="package.json" />
				<include name="CHANGELOG.md" />
				<include name="README.md" />
				<include name="assets/**" />
				<include name="platforms/**" />
			</fileset>
			<filterchain>
				<tokenfilter>
					<replacestring from="@NAME@" to="${airpackage.name}"/>
					<replacestring from="@NAMELOWER@" to="${project.namelower}"/>
					<replacestring from="@DESCRIPTION@" to="${airpackage.description}"/>
					<replacestring from="@GITHUB_REPO@" to="${github.repo}"/>
					<replacestring from="@VERSION@" to="${version}"/>
					<replacestring from="@VERSIONRELEASE@" to="${version.release}"/>
					<replacestring from="@EXTENSIONID@" to="${output.name}"/>
					<replacestring from="@PACKAGE@" to="${package.name}"/>
					<replacestring from="@ANDROIDPACKAGE@" to="${package.name}"/>
					<replacestring from="@DATE@" to="${publish_date}"/>
					<replacestring from="@VARIANT@" to="${airpackage.variant}"/>
				</tokenfilter>
			</filterchain>
		</copy>
	</target>

	<target name="build_android" >

		<fileset dir="${common.basedir}/${android.dir}/externals/" erroronmissingdir="false" id="filesetexternals" >
			<include name="*.aar" />
		</fileset>
		<fileset dir="${common.basedir}/${android.dir}/libs/${airpackage.variant}" erroronmissingdir="false" id="filesetvariant">
			<include name="*.aar" />
		</fileset>
		<fileset dir="${common.basedir}/${android.dir}/dependencies" erroronmissingdir="false" id="filesetdependencies">
			<include name="*.aar" />
		</fileset>
		<foreach target="explode_aar" param="explode_aar_file">
			<param name="airpackage.sourcedir" value="${airpackage.sourcedir}" />
			<param name="airpackage.variant" value="${airpackage.variant}" />
			<path>
				<union>
					<resources refid="filesetexternals" />
					<resources refid="filesetvariant" />
					<resources refid="filesetdependencies" />
				</union>
			</path>
		</foreach>

	</target>

	<target name="explode_aar">
		<basename property="explode_aar_name" file="${explode_aar_file}" suffix=".aar" />
		<echo message="explode ${explode_aar_file} ${explode_aar_name}" />

		<mkdir dir="${airpackage.basedir}/${output.tmpdir}/${explode_aar_name}" />
		<unzip src="${explode_aar_file}" dest="${airpackage.basedir}/${output.tmpdir}/${explode_aar_name}" overwrite="true"/>
		<copy overwrite="true" failonerror="false" quiet="true" todir="${airpackage.sourcedir}/${output.dir}/platforms/android/${explode_aar_name}" >
			<fileset dir="${airpackage.basedir}/${output.tmpdir}/${explode_aar_name}" >
				<include name="AndroidManifest.xml" />
			</fileset>
		</copy>
		<copy overwrite="true" failonerror="false" quiet="true" todir="${airpackage.sourcedir}/${output.dir}/assets/android" >
			<fileset dir="${airpackage.basedir}/${output.tmpdir}/${explode_aar_name}/assets" >
				<include name="*" />
			</fileset>
		</copy>
		<delete dir="${airpackage.basedir}/${output.tmpdir}" />
	</target>

	<!-- BUILD -->

	<target name="build" depends="clean" >
		<antcall target="build_android" >
			<param name="airpackage.sourcedir" value="${airpackage.basedir}" />
			<param name="airpackage.variant" value="" />
		</antcall>

		<antcall target="copy_template" >
			<param name="airpackage.sourcedir" value="${airpackage.basedir}" />
			<param name="airpackage.variant" value="" />
		</antcall>
		<antcall target="copy" >
			<param name="airpackage.sourcedir" value="${airpackage.basedir}" />
			<param name="airpackage.variant" value="" />
		</antcall>
		<exec executable="apm" dir="${airpackage.basedir}">
			<arg line="build build" />
		</exec>

		<!-- Build variants -->
		<antcall target="build_variants" />

	</target>

	<target name="build_variants" >
		<foreach target="build_variant" param="variant.basedir" inheritall="true" >
			<path>
				<dirset dir="${airpackage.basedir}">
					<include name="variants/*"/>
				</dirset>
			</path>
		</foreach>
	</target>

	<target name="build_variant" >
		<basename property="variant.name" file="${variant.basedir}"/>

		<echo message="BUILD VARIANT: ${variant.name}" />

		<antcall target="build_android" >
			<param name="airpackage.sourcedir" value="${variant.basedir}" />
			<param name="airpackage.variant" value="${variant.name}" />
		</antcall>

		<antcall target="copy_template" >
			<param name="airpackage.sourcedir" value="${variant.basedir}" />
			<param name="airpackage.variant" value="${variant.name}" />
		</antcall>
		<antcall target="copy" >
			<param name="airpackage.sourcedir" value="${variant.basedir}" />
			<param name="airpackage.variant" value="${variant.name}" />
		</antcall>
		<exec executable="apm" dir="${variant.basedir}">
			<arg line="build build" />
		</exec>

	</target>

	<!-- DEPLOY -->

	<target name="deploy" depends="build">
		<foreach target="deploy_package" param="packagefile" inheritall="true">
			<path>
				<fileset dir="${airpackage.basedir}">
					<include name="**/**/*.airpackage"/>
				</fileset>
			</path>
		</foreach>
	</target>

	<target name="deploy_package" >
		<echo message="deploying to ${github.repo} v${version.release} ${packagefile}" />
		<!-- Upload to github release -->
		<exec executable="gh" failonerror="true">
			<arg line="-R ${github.repo} release upload v${version.release}" />
			<arg line="${packagefile}" />
			<arg line="--clobber" />
		</exec>
		<!-- Publish to apm repository -->
		<exec executable="apm">
			<arg line="publish ${packagefile}" />
		</exec>
	</target>

</project>


text:
/*	$NetBSD: hexdump.c,v 1.18 2012/07/06 09:06:43 wiz Exp $	*/

/*
 * Copyright (c) 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif

#include <sys/cdefs.h>
#if !defined(lint)
__COPYRIGHT("@(#) Copyright (c) 1989, 1993\
 The Regents of the University of California.  All rights reserved.");
#if 0
static char sccsid[] = "@(#)hexdump.c	8.1 (Berkeley) 6/6/93";
#else
__RCSID("$NetBSD: hexdump.c,v 1.18 2012/07/06 09:06:43 wiz Exp $");
#endif
#endif /* not lint */

#include <sys/types.h>

#include <errno.h>
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "hexdump.h"

FS *fshead;				/* head of format strings */
int blocksize;				/* data block size */
int exitval;				/* final exit value */
int length = -1;			/* max bytes to read */
static int isod = 0;

int
main(int argc, char *argv[])
{
	FS *tfs;
	char *p;

	setlocale(LC_ALL, "");

	isod = 0;
	p = strrchr(argv[0], 'o');
	if (p != NULL && strcmp(p, "od") == 0)
		isod = 1;

	if (isod)
		odsyntax(argc, &argv);
	else
		hexsyntax(argc, &argv);

	/* figure out the data block size */
	for (blocksize = 0, tfs = fshead; tfs; tfs = tfs->nextfs) {
		tfs->bcnt = size(tfs);
		if (blocksize < tfs->bcnt)
			blocksize = tfs->bcnt;
	}
	/* rewrite the rules, do syntax checking */
	for (tfs = fshead; tfs; tfs = tfs->nextfs)
		rewrite(tfs);

	(void)next(argv);
	display();
	exit(exitval);
}

void
usage(void)
{
	const char *pname = getprogname();

	(void)fprintf(stderr, "usage: %s ", pname);
	if (isod)
		(void)fprintf(stderr, "[-aBbcDdeFfHhIiLlOovXx] [-A base] "
		    "[-j skip] [-N length] [-t type_string] [[+]offset[.][Bb]] "
		    "[file ...]\n");
	else
		(void)fprintf(stderr, "[-bCcdovx] [-e format_string] [-f format_file] "
		    "[-n length] [-s skip] [file ...]\n");
	exit(1);
}


text:
#ifndef _DLGCERTIFICATESTORESHOWCERTIFICATEPARAMETERSPUBLIC_H_
#define _DLGCERTIFICATESTORESHOWCERTIFICATEPARAMETERSPUBLIC_H_

#include <afxwin.h>
#include <afxcmn.h>
#include <resource.h>

class CDlgCertificateStoreShowCertificateParametersPublic : public CDialog {
	enum { IDD = IDD_CERTIFICATE_STORE_SHOW_CERTIFICATE_PARAMETERS_PUBLIC };
public:
	CDlgCertificateStoreShowCertificateParametersPublic(CWnd *_parent = 0);
	virtual ~CDlgCertificateStoreShowCertificateParametersPublic();
protected:
	virtual BOOL OnInitDialog();
	virtual void DoDataExchange(CDataExchange *_pDX);
protected:
	afx_msg void clickedButtonClose();
protected:
	CString m_editPublicParameters;
public:
	void setPublicParameters(const CString &_publicParameters) { m_editPublicParameters = _publicParameters; }

	DECLARE_MESSAGE_MAP()
};

#endif


text:
import findLastIndex from '..'

describe('findLastIndex', () => {
  it('returns -1 on an empty list', () => {
    expect(findLastIndex(x => true, [])).toBe(-1)
  })

  it('returns -1 when no elements satisfy the predicate', () => {
    expect(findLastIndex(x => false, [1, 2, 3])).toBe(-1)
  })

  it('finds the last element that satisfies the predicate using element', () => {
    expect(findLastIndex(e => e === 1, [1, 2, 1])).toBe(2)
  })

  it('finds the last element that satisfies the predicate using index', () => {
    expect(findLastIndex((e, i) => i === 1, [1, 2, 1])).toBe(1)
  })

  it('finds the last element that satisfies the predicate using list', () => {
    expect(findLastIndex((e, i, l) => e === l[1], [1, 2, 1])).toBe(1)
  })

  it('is curried', () => {
    expect(findLastIndex(x => x === 1)([1, 2, 1])).toBe(2)
  })
})


text:
import * as types from '../constants/ActionTypes'

export function createWindow() {
  return { type: types.CREATE }
}

export function destroyWindow(id) {
  return { type: types.DESTROY, id }
}


text:
class QSurfaceFormat;
class QOpenGLContext;

class WindowQt : public QWindow
{
public:
    WindowQt();
    WindowQt(const QSurfaceFormat & format);
    virtual ~WindowQt();

    virtual void resizeEvent(QResizeEvent * event) override;
    virtual void exposeEvent(QExposeEvent * event) override;
    bool event(QEvent * event);

    virtual void enterEvent(QEvent * event);
    virtual void leaveEvent(QEvent * event);

    void makeCurrent();
    void doneCurrent();

    QOpenGLContext * context();

    void updateGL();

protected:
    QScopedPointer<QOpenGLContext> m_context;

    bool m_updatePending;
    bool m_initialized;

    void initialize();
    void resize(QResizeEvent * event);
    void paint();

    virtual void initializeGL();
    virtual void resizeGL(QResizeEvent * event);
    virtual void paintGL();
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.senac.sp.agendadecontatos.exceptions;

/**
 *
 * @author Antonio Grosse
 */
public class ContatoException extends Exception {

    /**
     * Construtor de exceções que permite informar uma mensagem *
     */
    public ContatoException(String message) {
        super(message);
    }

}


text:
package org.socraticgrid.hl7.services.orders.xmladapter;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MessageTypeAdapter extends XmlAdapter<Object, Object> {

	@Override
	public Object unmarshal(Object v) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object marshal(Object v) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
package com.google.cloud.bigtable.hbase.adapters;

import com.google.bigtable.v1.MutateRowRequest;
import com.google.bigtable.v1.Mutation;
import com.google.bigtable.v1.Mutation.SetCell.Builder;
import com.google.cloud.bigtable.hbase.BigtableConstants;
import com.google.protobuf.ByteString;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Put;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map.Entry;

/**
 * Adapt an HBase Put Operation into an Bigtable RowMutation
 */
public class PutAdapter implements OperationAdapter<Put, MutateRowRequest.Builder> {
  private int maxKeyValueSize;

  public PutAdapter(Configuration configuration) {
    maxKeyValueSize = configuration.getInt("hbase.client.keyvalue.maxsize", -1);
  }

  @Override
  public MutateRowRequest.Builder adapt(Put operation) {
    MutateRowRequest.Builder result = MutateRowRequest.newBuilder();
    result.setRowKey(ByteString.copyFrom(operation.getRow()));

    if (operation.isEmpty()) {
      throw new IllegalArgumentException("No columns to insert");
    }

    for (Entry<byte[], List<Cell>> entry : operation.getFamilyCellMap().entrySet()) {
      String familyString = new String(entry.getKey(), StandardCharsets.UTF_8);

      for (Cell cell : entry.getValue()) {
        // Since we are not using the interface involving KeyValues, we reconstruct how big they would be.
        // 20 bytes for metadata plus the length of all the elements.
        int keyValueSize = (20 +
            cell.getRowLength() +
            cell.getFamilyLength() +
            cell.getQualifierLength() +
            cell.getValueLength());
        if (maxKeyValueSize > 0 && keyValueSize > maxKeyValueSize) {
          throw new IllegalArgumentException("KeyValue size too large");
        }
        Mutation.Builder modBuilder = result.addMutationsBuilder();
        Builder setCellBuilder = modBuilder.getSetCellBuilder();

        ByteString cellQualifierByteString = ByteString.copyFrom(
            cell.getQualifierArray(),
            cell.getQualifierOffset(),
            cell.getQualifierLength());

        setCellBuilder.setFamilyName(familyString);
        setCellBuilder.setColumnQualifier(cellQualifierByteString);

        if (cell.getTimestamp() != HConstants.LATEST_TIMESTAMP) {
          long timestampMicros = BigtableConstants.BIGTABLE_TIMEUNIT.convert(
              cell.getTimestamp(),
              BigtableConstants.HBASE_TIMEUNIT);
          setCellBuilder.setTimestampMicros(timestampMicros);
        } else {
          setCellBuilder.setTimestampMicros(-1);
        }

        setCellBuilder.setValue(
            ByteString.copyFrom(
                cell.getValueArray(),
                cell.getValueOffset(),
                cell.getValueLength()));
      }
    }

    return result;
  }
}


text:
/* $Id: cmd-swap-window.c,v 1.1.1.2 2011/08/17 18:40:04 jmmv Exp $ */

/*
 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>

#include <stdlib.h>

#include "tmux.h"

/*
 * Swap one window with another.
 */

int	cmd_swap_window_exec(struct cmd *, struct cmd_ctx *);

const struct cmd_entry cmd_swap_window_entry = {
	"swap-window", "swapw",
	"ds:t:", 0, 0,
	"[-d] " CMD_SRCDST_WINDOW_USAGE,
	0,
	NULL,
	NULL,
	cmd_swap_window_exec
};

int
cmd_swap_window_exec(struct cmd *self, struct cmd_ctx *ctx)
{
	struct args		*args = self->args;
	const char		*target_src, *target_dst;
	struct session		*src, *dst;
	struct session_group	*sg_src, *sg_dst;
	struct winlink		*wl_src, *wl_dst;
	struct window		*w;

	target_src = args_get(args, 's');
	if ((wl_src = cmd_find_window(ctx, target_src, &src)) == NULL)
		return (-1);
	target_dst = args_get(args, 't');
	if ((wl_dst = cmd_find_window(ctx, target_dst, &dst)) == NULL)
		return (-1);

	sg_src = session_group_find(src);
	sg_dst = session_group_find(dst);
	if (src != dst &&
	    sg_src != NULL && sg_dst != NULL && sg_src == sg_dst) {
		ctx->error(ctx, "can't move window, sessions are grouped");
		return (-1);
	}

	if (wl_dst->window == wl_src->window)
		return (0);

	w = wl_dst->window;
	wl_dst->window = wl_src->window;
	wl_src->window = w;

	if (!args_has(self->args, 'd')) {
		session_select(dst, wl_dst->idx);
		if (src != dst)
			session_select(src, wl_src->idx);
	}
	session_group_synchronize_from(src);
	server_redraw_session_group(src);
	if (src != dst) {
		session_group_synchronize_from(dst);
		server_redraw_session_group(dst);
	}
	recalculate_sizes();

	return (0);
}


text:
<component name="libraryTable">
  <library name="Maven: com.vaadin:vaadin-client-compiler:7.4.4">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/vaadin/vaadin-client-compiler/7.4.4/vaadin-client-compiler-7.4.4.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/vaadin/vaadin-client-compiler/7.4.4/vaadin-client-compiler-7.4.4-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/vaadin/vaadin-client-compiler/7.4.4/vaadin-client-compiler-7.4.4-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
/*
 * GET create page.
 */

var Poll = require("../models/Poll.js");
var poll = new Poll();
var randomColour = require("randomcolor");
var randomString = require("randomstring");

exports.getCharts = (req, res) => {
    res.render("allCharts", {
        title: "All Polls"
    });
};

exports.create = (req, res) => {
    res.render("create", {
        title: "Poll & Votes"
    });
};

/*
 * AUTHENTICATED USER ACTIONS
 */

/* // CREATE NEW POLL
 * 1) Instantiate new Poll
 * 2) Create new dataset
 *
 */

exports.submit = (req, res) => {
    // Filters body options - if a user adds an input and doesn't use it, this is filtered
    var labels = req.body.option.filter(item => item.length > 0);
    var data = [];
    // For each non-empty option the value is set at 0
    labels.forEach(item => data.push(0));

    poll.polls.poll = {
        username        : req.session.passport.user,
        created         : Date.now(),
        title           : req.body.title,
        url             : randomString.generate(8),
        labels          : labels,
        dataset         : [{
            fillColor   : randomColour(),
            strokeColor : "rgba(220,220,220,0.8)",
            data        : data
        }]
    };

    poll.save((err) => {
        if (err) throw err;
        console.log("Successfully stored in the database");
    });

    res.redirect("/create");
};

/* // UPDATE EXISTING POLL
 * 1) Authenticate user - only logged in user can delete poll //  must be there their own poll
 * 2) If no authenticated, redirect to home/signup/login
 *
 * 1) FindOne Poll by ID
 * 2) Update new dataset/ push new data label to dataset
 *
 */

 exports.vote = (req, res) => {
    res.render("vote", {
       title: "Poll & Votes"
    });
 };

 exports.postVote = (req, res) =>{

 };

 /* // DELETE EXISTING POLL
 * 1) Authenticate user - only logged in user can delete poll //  must be there their own poll
 * 2) If no authenticated, redirect to home/signup/login
 *
 * 1) FindOne Poll by ID
 * 2) Update new dataset/ push new data label to dataset
 *
 */

 /*
    poll.remove({_id: id}(err) => {
        if (err) throw err;
        console.log("Successfully removed poll from data");
    });
 */

 /*
 * UNAUTHENTICATED USER ACTIONS
 */

/* // VOTE ON EXISTING POLL
 * 1) FindOne Poll by ID and label
 * 2) Update dataset on database
 * 3)
 */

 exports.addVote = (req, res) => {
    /*poll.findByIdAndUpdate(req.params[0], { $set: { size: 'large' }}, function (err, poll) {
        if (err) throw err;
        res.send(poll);
        });*/
    /*poll.update((err) => {
        if (err) throw err;
        console.log("Successfully updated the document in the database");
    });*/
 };

 /*
  * REDIRECT TO EXISTING POLL
  */

 exports.redirect = (req, res) => {
    res.render("vote");
 };


text:
import django_tables2 as tables
from .models import Topics, ButtonPresses

class TopicsTable(tables.Table):
    class Meta:
        model = Topics
        attrs = {'class': 'table-center mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp'}
        row_attrs = {'class': 'mdl-data-table__cell--non-numeric'}

class RivaTable(tables.Table):
    class Meta:
        model = ButtonPresses
        attrs = {'class': 'table-center mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp full-width'}
        row_attrs = {'class': 'mdl-data-table__cell--non-numeric'}


text:
using System;
using System.IO;
using Xunit;

//
// System.Console BCL test cases
//
public class SetIn
{
    [Fact]
    public static void SetInThrowsOnNull()
    {
        TextReader savedIn = Console.In;
        try
        {
            Assert.Throws<ArgumentNullException>(() => Console.SetIn(null));
        }
        finally
        {
            Console.SetIn(savedIn);
        }
    }

    [Fact]
    public static void SetInReadLine()
    {
        const string TextStringFormat = "Test {0}";

        TextReader oldInToRestore = Console.In;
        try
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(memStream))
                {
                    for (int i = 0; i < 20; i++)
                    {
                        sw.WriteLine(string.Format(TextStringFormat, i));
                    }

                    sw.Flush();
                    memStream.Seek(0, SeekOrigin.Begin);

                    using (StreamReader sr = new StreamReader(memStream))
                    {
                        Console.SetIn(sr);
                        Assert.NotNull(Console.In);

                        for (int i = 0; i < 20; i++)
                        {
                            Assert.Equal(string.Format(TextStringFormat, i), Console.ReadLine());
                        }
                    }
                }
            }
        }
        finally
        {
            Console.SetIn(oldInToRestore);
        }
    }
}