text:
Cam Scroller is an open-source Chrome extension that uses your webcam and
[deeplearn.js](https://deeplearnjs.org) to enable scrolling through webpages
using custom gestures that you define.

The Chrome extension can be found in the Chrome web store at this link: https://chrome.google.com/webstore/detail/cam-scroller/egljnginfcbpehnpfojpbogiopdgjjak

It makes use of the deeplearn.js [KNN image classifier](https://github.com/PAIR-code/deeplearnjs/blob/master/models/knn_image_classifier/knn_image_classifier.ts)
in the same manner as [Teachable Machine](https://teachablemachine.withgoogle.com/)
and [Cam Arcade](https://deeplearnjs.org/demos/teachable_gaming/).

In doing so, your webcam images are processed locally on your machine and at no
time is any information collected or sent externally.

This simple Chrome extension is meant to show, through a minimal example, the
types of experiences that can be enabled through the use of browser-based
machine learning.

![GIF showing training process](https://gist.githubusercontent.com/jameswex/d9506ffef04976e37d577e2907cac276/raw/38ef1cd3a60e0f3a4db56b93c87470a51c3eda45/CamScrollerTraining.gif)

## Usage

### How to install and configure the extension

1. Install the extension from the Chrome store.
1. Upon initial installation, the extension will ask for permission to access
the webcam. After granting permission, you can close the welcome page.
   * Note that the extension keeps your webcam open, but at no point is any
   information from the webcam ever sent anywhere. All processing happens local
   to your machine.
1. Click the Cam Scroller browser action icon next to the address bar. In the
popup, you should see a display of what your webcam is seeing. Click the "Create
scrolling gestures" button and follow the on-screen instructions to create your
custom scrolling gestures.
   * You will be asked to train three different poses: one for scrolling down,
   one for scrolling up, and one for the steady state of not scrolling at all.

From this point on, for any new tab/page you load, scrolling can be
controlled by the gestures you trained. You will see a visual scrolling
indicator on the right side of the page when scrolling is being controlled by
your gestures.

The KNN image classifier weights for the trained gestures are stored in
Chrome local storage, so the gestures do not have to be retrained when you
close and then relaunch Chrome.

### Controls available in the extension

If you want to temporarily turn off the Cam Scrolling capability,
uncheck the checkbox in the Cam Scroller browser action popup.

If at any time you wish to retrain the gestures, just click the "Create
scrolling gestures" button again in the extension popup.

## Code breakdown

welcome.[html/js] - Page launched on initial extension installation which
requests webcam access for the extension.

popup.[html/js] - Browser action popup page. Displays the webcam and has
controls for training the scrolling gestures and enabling/disabling scrolling.
Passes messages to the background page to do the actual processing.

background.[html/js] - Contains all the machine learning logic for the
extension. Trains the KNN image classifier when in training mode, infers which
scrolling gestures are being performed when in inference mode, and sends
messages to the content script to perform scrolling.

content.js - Content script running with webpages loaded in Chrome. Calls
window.scrollBy to scroll webpages and places visual indicators on the page when
scrolling.

## Notice

This is not an officially supported Google product.


text:
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using KidoZen;

#if WINDOWS_PHONE
using Microsoft.Phone.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#elif NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#endif

namespace test
{
    [TestClass]
    [Tag("storage")]
    public class Storage : WorkItemTest
    {
        static KZApplication app;
        static KidoZen.Storage objectSet;

        [ClassInitialize]
        [Asynchronous]
#if WINDOWS_PHONE
        public async Task ClassInit()
#elif NETFX_CORE
        static public async Task ClassInit(TestContext context)
#endif
        {
            app = new KZApplication(test.Constants.MarketplaceUrl, test.Constants.AppName);
            await app.Initialize();
            var user = await app.Authenticate(test.Constants.User, test.Constants.Password, test.Constants.Provider);
            objectSet = app.Storage["test"];
            EnqueueTestComplete();
        }

        [TestInitialize]
        [Asynchronous]
        public async Task TestInit()
        {
            var insResult = await objectSet.Insert(new { Foo = "foo" });
            var dropResult = await objectSet.Drop();
            EnqueueTestComplete();
        }

        [TestMethod]
        public void CanGetAnInstance()
        {
            Assert.AreEqual(test.Constants.AppUrl + "/storage/local/test", objectSet.Url.ToString());
        }

        [TestMethod]
        [Asynchronous]
        public async Task GetById()
        {
            var insResult = await objectSet.Insert(new { Foo = "foo" });
            var getResult = await objectSet.Get(insResult.Data._id);
            Assert.IsNotNull(getResult.Data);
            Assert.AreEqual(HttpStatusCode.OK, getResult.StatusCode);
            Assert.AreEqual("foo", getResult.Data.Value<string>("Foo"));
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task Update()
        {
            var insResult = await objectSet.Insert(new { Foo = "foo" });
            var updResult = await objectSet.Update(insResult.Data._id, new { Foo = "bar", _metadata = insResult.Data._metadata });
            var getResult = await objectSet.Get(insResult.Data._id);
            Assert.IsNotNull(getResult.Data);
            Assert.AreEqual("bar", getResult.Data.Value<string>("Foo"));
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task Drop()
        {
            var insResult = await objectSet.Insert(new { Foo = "foo" });
            var dropResult = await objectSet.Drop();
            Assert.AreEqual(HttpStatusCode.OK, dropResult.StatusCode);
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task Delete()
        {
            var insResult = await objectSet.Insert(new { Foo = "foo" });
            var delResult = await objectSet.Delete(insResult.Data._id);
            Assert.AreEqual(HttpStatusCode.OK, delResult.StatusCode);
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task QueryDoesFindObjects()
        {
            var insResult = await objectSet.Insert(new { x = 1 });
            insResult = await objectSet.Insert(new { x = 2 });
            insResult = await objectSet.Insert(new { x = 3 });

            var result = await objectSet.Query(@"{""x"":{""$gt"":1}}");
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(2, result.Data.Count);
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task QueryDoesNotFindObjects()
        {
            var insResult = await objectSet.Insert(new { x = 1 });
            insResult = await objectSet.Insert(new { x = 2 });
            insResult = await objectSet.Insert(new { x = 3 });

            var result = await objectSet.Query(@"{""x"":{""$gt"":3}}");
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(0, result.Data.Count);
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task QuerySkipAndLimit()
        {
            var insResult = await objectSet.Insert(new { x = 1 });
            insResult = await objectSet.Insert(new { x = 2 });
            insResult = await objectSet.Insert(new { x = 3 });
            insResult = await objectSet.Insert(new { x = 4 });

            var result = await objectSet.Query("{}", @"{""$skip"":1,""$limit"":2}");
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(2, result.Data.Count);
            Assert.AreEqual(2, result.Data[0].Value<int>("x"));
            Assert.AreEqual(3, result.Data[1].Value<int>("x"));
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task QueryCount()
        {
            var insResult = await objectSet.Insert(new { x = 1 });
            insResult = await objectSet.Insert(new { x = 2 });
            insResult = await objectSet.Insert(new { x = 3 });

            var result = await objectSet.Query(@"{""x"":{""$gt"":1}}", @"{""$count"":true}");
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(1, result.Data.Count);
            Assert.AreEqual(2, result.Data[0]);
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task QuerySelect()
        {
            var insResult = await objectSet.Insert(new { x = 1, y = 2, z = 3 });
            var result = await objectSet.Query(fields: @"{""y"":1}");
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(1, result.Data.Count);
            var obj = (JObject)result.Data[0];
            Assert.AreEqual(2, obj.Properties().Count()); // _id and y
            Assert.AreEqual(2, obj.Value<int>("y"));
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task All()
        {
            var insResult = await objectSet.Insert(new { x = 1 });
            insResult = await objectSet.Insert(new { x = 2 });
            insResult = await objectSet.Insert(new { x = 3 });

            var result = await objectSet.All();
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(3, result.Data.Count);
            EnqueueTestComplete();
        }

        [TestMethod]
        [Asynchronous]
        public async Task Insert()
        {
            var result = await objectSet.Insert(new { Foo = "foo" });
            Assert.AreEqual(HttpStatusCode.Created, result.StatusCode);
            Assert.IsNotNull(result.Data);
            Assert.IsFalse(string.IsNullOrWhiteSpace(result.Data._id));
            Assert.IsNotNull(result.Data._metadata);
            EnqueueTestComplete();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<ion-header>
    <ion-toolbar>
        <ion-buttons slot="start">
            <ion-back-button [text]="'core.back' | translate"></ion-back-button>
        </ion-buttons>
        <ion-title>

                <core-format-text [text]="title" contextLevel="module" [contextInstanceId]="moduleId" [courseId]="courseId">
                </core-format-text>

        </ion-title>
    </ion-toolbar>
</ion-header>
<ion-content class="limited-width">
    <ion-refresher slot="fixed" [disabled]="!entryLoaded || !(isPullingToRefresh || !renderingEntry && !loadingRating && !loadingComments)"
        (ionRefresh)="refreshDatabase($event.target)">
        <ion-refresher-content pullingText="{{ 'core.pulltorefresh' | translate }}"></ion-refresher-content>
    </ion-refresher>
    <core-loading [hideUntil]="entryLoaded && (isPullingToRefresh || !renderingEntry && !loadingRating && !loadingComments)">

        <ion-card class="core-warning-card" *ngIf="entry && entry.hasOffline">
            <ion-item>
                <ion-icon name="fas-exclamation-triangle" slot="start" aria-hidden="true"></ion-icon>
                <ion-label>{{ 'core.hasdatatosync' | translate: {$a: moduleName} }}</ion-label>
            </ion-item>
        </ion-card>

        <ion-item class="ion-text-wrap core-group-selector" *ngIf="groupInfo && (groupInfo.separateGroups || groupInfo.visibleGroups)">
            <ion-label id="addon-data-groupslabel">
                <ng-container *ngIf="groupInfo.separateGroups">{{ 'core.groupsvisible' | translate }}</ng-container>
                <ng-container *ngIf="groupInfo.visibleGroups">{{ 'core.groupsseparate' | translate }}</ng-container>
            </ion-label>
            <ion-select [(ngModel)]="selectedGroup" (ionChange)="setGroup(selectedGroup)" aria-labelledby="addon-data-groupslabel"
                interface="action-sheet" [interfaceOptions]="{header: 'core.group' | translate}">
                <ion-select-option *ngFor="let groupOpt of groupInfo.groups" [value]="groupOpt.id">
                    {{groupOpt.name}}
                </ion-select-option>
            </ion-select>
        </ion-item>

            <core-style [css]="database.csstemplate" prefix=".addon-data-entries-{{database.id}}"></core-style>

            <core-compile-html [text]="entryHtml" [jsData]="jsData" [extraImports]="extraImports" (compiling)="setRenderingEntry($event)">
            </core-compile-html>

        <core-rating-rate *ngIf="database && entry && ratingInfo && (!database.approval || entry.approved)" [ratingInfo]="ratingInfo"
            contextLevel="module" [instanceId]="database.coursemodule" [itemId]="entry.id" [itemSetId]="0" [courseId]="courseId"
            [aggregateMethod]="database.assessed" [scaleId]="database.scale" [userId]="entry.userid" (onLoading)="setLoadingRating($event)"
            (onUpdate)="ratingUpdated()">
        </core-rating-rate>
        <core-rating-aggregate *ngIf="database && entry && ratingInfo" [ratingInfo]="ratingInfo" contextLevel="module"
            [instanceId]="database.coursemodule" [itemId]="entry.id" [courseId]="courseId" [aggregateMethod]="database.assessed"
            [scaleId]="database.scale">
        </core-rating-aggregate>

        <core-comments *ngIf="database && database.comments && entry && entry.id > 0 && commentsEnabled" contextLevel="module"
            [instanceId]="database.coursemodule" component="mod_data" [itemId]="entry.id" area="database_entry" [courseId]="courseId"
            (onLoading)="setLoadingComments($event)" [showItem]="true">
        </core-comments>
    </core-loading>

        <ion-row class="ion-justify-content-between ion-align-items-center ion-no-padding ion-wrap">
            <ion-col class="ion-text-start ion-no-padding core-navigation-arrow" size="auto">
                <ion-button [disabled]="!hasPrevious" fill="clear" [attr.aria-label]="'core.previous' | translate"
                    (click)="gotoEntry(offset! -1)">
                    <ion-icon name="fas-chevron-left" slot="icon-only" aria-hidden="true"></ion-icon>
                </ion-button>
            </ion-col>
            <ion-col class="ion-text-center">
            </ion-col>
            <ion-col class="ion-text-end ion-no-padding core-navigation-arrow" size="auto">
                <ion-button [disabled]="!hasNext" fill="clear" [attr.aria-label]=" 'core.next' | translate"
                    (click)="gotoEntry(offset! + 1)">
                    <ion-icon name="fas-chevron-right" slot="icon-only" aria-hidden="true"></ion-icon>
                </ion-button>
            </ion-col>
        </ion-row>

</ion-content>


text:
<?php

/**
 * This file is part of the Minty templating library.
 * (c) Dániel Buga <daniel@bugadani.hu>
 *
 * For licensing information see the LICENSE file.
 */

namespace Minty\Compiler\Tags;

use Minty\Compiler\Compiler;
use Minty\Compiler\Exceptions\SyntaxException;
use Minty\Compiler\Nodes\RootNode;
use Minty\Compiler\Nodes\TagNode;
use Minty\Compiler\Parser;
use Minty\Compiler\Stream;
use Minty\Compiler\Tag;
use Minty\Compiler\Token;

class IfTag extends Tag
{

    public function hasEndingTag()
    {
        return true;
    }

    public function getTag()
    {
        return 'if';
    }

    public function compile(Compiler $compiler, TagNode $node)
    {
        $first = true;
        $else  = null;
        foreach ($node->getChildren() as $branch) {
            if ($first) {
                $compiler->indented('if(');
                $first = false;
            } elseif (!$branch->hasChild('condition')) {
                $else = $branch->getChild('body');
                continue;
            } else {
                $compiler->add(' elseif(');
            }

            $compiler
                ->compileNode($branch->getChild('condition'))
                ->add(') {')
                ->indent()
                ->compileNode($branch->getChild('body'))
                ->outdent()
                ->indented('}');
        }
        if ($else !== null) {
            $compiler
                ->add(' else {')
                ->indent()
                ->compileNode($else)
                ->outdent()
                ->indented('}');
        }
    }

    public function parse(Parser $parser, Stream $stream)
    {
        $node      = new TagNode($this);
        $condition = $parser->parseExpression($stream);

        $hasElse = false;
        do {
            $branchNode = $node->addChild(new RootNode());

            if ($condition !== null) {
                $branchNode->addChild($condition, 'condition');
            }

            $body = $parser->parseBlock($stream, ['else', 'elseif', 'endif']);
            $branchNode->addChild($body, 'body');

            $token   = $stream->current();
            $tagName = $token->getValue();
            if ($tagName === 'else') {
                if ($hasElse) {
                    throw new SyntaxException(
                        'If blocks may only contain one else tag',
                        $token->getLine()
                    );
                }
                $condition = null;
                $hasElse   = true;
                $stream->expect(Token::TAG_END);
            } elseif ($tagName === 'elseif') {
                $condition = $parser->parseExpression($stream);
            }
        } while ($tagName !== 'endif');

        $stream->expect(Token::TAG_END);

        return $node;
    }
}


text:
import copy
import random
import tempfile
import time
from collections import Counter

import ethereum.keys
import gevent
import simpy
from ethereum import slogging
from ethereum.db import EphemDB
from ethereum.utils import big_endian_to_int, sha3, privtoaddr
from pyethapp.accounts import Account, AccountsService

from hydrachain import hdc_service
from hydrachain.consensus import protocol as hdc_protocol
from hydrachain.consensus.base import Block
from hydrachain.consensus.manager import ConsensusManager
from hydrachain.consensus.utils import num_colors, phx
from hydrachain.hdc_service import ChainService

log = slogging.get_logger('hdc.sim')

# stop on exception
gevent.get_hub().SYSTEM_ERROR = BaseException

# reduce key derivation iterations
ethereum.keys.PBKDF2_CONSTANTS['c'] = 100

privkeys = [chr(i) * 32 for i in range(1, 11)]
validators = privkeys[:]

empty = object()

random.seed(42)

def mk_privkeys(num):
    "make privkeys that support coloring, see utils.cstr"
    privkeys = []
    assert num <= num_colors
    for i in range(num):
        j = 0
        while True:
            k = sha3(str(j))
            a = privtoaddr(k)
            an = big_endian_to_int(a)
            if an % num_colors == i:
                break
            j += 1
        privkeys.append(k)
    return privkeys

class Transport(object):

    def __init__(self, simenv=None):
        self.simenv = simenv

    def delay(self, sender, receiver, packet, add_delay=0):
        """
        bandwidths are inaccurate, as we don't account for parallel transfers here
        """
        bw = min(sender.ul_bandwidth, receiver.dl_bandwidth)
        delay = sender.base_latency + receiver.base_latency
        delay += len(packet) / bw
        delay += add_delay
        return delay

    def deliver(self, sender, receiver, packet, add_delay=0):
        delay = self.delay(sender, receiver, packet, add_delay)
        if self.simenv:
            self.simenv_deliver(sender, receiver, packet, delay)
        else:
            self.gevent_deliver(sender, receiver, packet, delay)

    def gevent_deliver(self, sender, receiver, packet, delay):
        assert sender != receiver

        def transfer():
            gevent.sleep(delay)
            receiver.receive_packet(sender, packet)
        gevent.spawn(transfer)

    def simenv_deliver(self, sender, receiver, packet, delay):
        def transfer():
            yield self.simenv.timeout(delay)
            receiver.receive_packet(sender, packet)

        self.simenv.process(transfer())

class NoTransport(Transport):

    def deliver(self, sender, receiver, packet):
        pass

class SlowTransport(Transport):

    def deliver(self, sender, receiver, packet):
        "deliver on edge of timeout_window"
        to = ConsensusManager.round_timeout
        assert to > 0
        print "in slow transport deliver"
        super(SlowTransport, self).deliver(sender, receiver, packet, add_delay=to)

class PeerMock(object):

    ul_bandwidth = 1 * 10 ** 6  # bytes/s net bandwidth
    dl_bandwidth = 1 * 10 ** 6  # bytes/s net bandwidth
    base_latency = 0.05  # secs
    ingress_bytes = 0
    egress_bytes = 0

    def __init__(self, app, transport):
        self.app = app
        self.config = app.config
        self.remote_client_version = empty
        self.peer = None
        self.protocol = None
        self.transport = transport

    def __repr__(self):
        return "<PeerMock(A:%s > R:%s)>" % (phx(self.coinbase), phx(self.peer.coinbase))

    @property
    def coinbase(self):
        return self.app.services.chainservice.chain.coinbase

    def send_packet(self, packet):
        assert self.peer
        # log.debug('send_packet', sender=self, receiver=self.peer, len=len(packet))
        self.egress_bytes += len(packet)
        self.transport.deliver(self, self.peer, packet)

    def receive_packet(self, sender, packet):
        assert self.app.isactive
        assert sender != self
        # log.debug('receive_packet', sender=sender, receiver=self, len=len(packet))
        self.ingress_bytes += len(packet)
        self.protocol.receive_packet(packet)

    def __eq__(self, other):
        return repr(self) == repr(other)

    def __hash__(self):
        return hash(repr(self))

class PeerManagerMock(object):

    def __init__(self, app):
        self.app = app
        self.peers = []

    def __repr__(self):
        return "<PeerManager(A:%s)>" % phx(self.coinbase)

    @property
    def coinbase(self):
        return self.app.services.chainservice.chain.coinbase

    def broadcast(self, protocol, command_name, args=[], kargs={},
                  num_peers=None, exclude_peers=[]):
        for p in self.peers:
            assert p.coinbase == self.coinbase
            assert p.peer.coinbase != self.coinbase
            assert isinstance(p.protocol, (protocol, hdc_protocol.HDCProtocol))
            if not exclude_peers or p not in exclude_peers:
                log.debug('broadcasting', sender=self, receiver=p, obj=args)
                func = getattr(p.protocol, 'send_' + command_name)
                func(*args, **kargs)

class SimChainService(ChainService):

    processing_time = 0.1  # time to validate block

    def __init__(self, *args, **kargs):
        self.simenv = kargs.pop('simenv')
        super(SimChainService, self).__init__(*args, **kargs)

    @property
    def now(self):
        assert self.simenv
        return self.simenv.now

    def setup_alarm(self, delay, cb, *args):
        assert self.simenv

        def _trigger():
            yield self.simenv.timeout(delay)
            cb(*args)
        self.simenv.process(_trigger())

    def on_receive_newblockproposal(self, proto, proposal):

        def process():
            yield self.simenv.timeout(self.processing_time)
            super(SimChainService, self).on_receive_newblockproposal(proto, proposal)

        self.simenv.process(process())

class AppMock(object):

    class Services(dict):
        pass

    def __init__(self, privkey, validators, simenv=None):
        self.config = copy.deepcopy(hdc_service.ChainService.default_config)
        self.config['db'] = dict(path='_db')
        self.config['data_dir'] = tempfile.mkdtemp()
        self.config['hdc']['validators'] = validators

        initial_alloc = dict((a, dict(wei=2 ** 200)) for a in validators)
        self.config['eth']['block']['GENESIS_INITIAL_ALLOC'] = initial_alloc

        self.simenv = simenv
        self.services = self.Services()
        self.services.db = EphemDB()
        self.services.accounts = AccountsService(self)
        self.services.peermanager = PeerManagerMock(self)
        account = Account.new(password='', key=privkey)
        self.services.accounts.add_account(account, store=False)
        if simenv:
            self.services.chainservice = SimChainService(self, simenv=simenv)
        else:
            self.services.chainservice = hdc_service.ChainService(self)
        self.isactive = True

    def __repr__(self):
        return '<AppMock(%s)>' % phx(self.services.chainservice.chain.coinbase)

    def add_peer(self, peer):
        if peer in self.services.peermanager.peers:
            return
        self.services.peermanager.peers.append(peer)
        proto = hdc_protocol.HDCProtocol(peer, self.services.chainservice)
        peer.protocol = proto
        return True

    def connect_app(self, other):
        log.debug('connecting', node=self, other=other)
        transport = Transport(self.simenv)
        p = PeerMock(self, transport)
        op = PeerMock(other, transport)
        p.peer = op
        op.peer = p
        if self.add_peer(p):
            self.services.chainservice.on_wire_protocol_start(p.protocol)
        if other.add_peer(op):
            other.services.chainservice.on_wire_protocol_start(op.protocol)

class Network(object):

    starttime = None

    def __init__(self, num_nodes=2, simenv=None):
        if simenv:
            self.simenv = simpy.Environment()
        else:
            self.simenv = None
        privkeys = mk_privkeys(num_nodes)
        validators = [privtoaddr(p) for p in privkeys]
        self.nodes = []
        for i in range(num_nodes):
            app = AppMock(privkeys[i], validators, self.simenv)
            self.nodes.append(app)

    def connect_nodes(self):
        # connect nodes
        for i, n in enumerate(self.nodes):
            for o in self.nodes[i + 1:]:
                if n.isactive and o.isactive:
                    n.connect_app(o)

    def start(self):
        # start nodes
        for n in self.nodes:
            if n.isactive:
                cm = n.services.chainservice.consensus_manager
                if True or self.simenv:   # set dummy ready!"
                    cm.ready_validators = set(range(int(len(cm.contract.validators))))
                    assert cm.is_ready
                cm.process()

    def run(self, duration):
        if self.simenv:
            self.simenv.run(until=self.elapsed + duration)
        else:
            if not self.starttime:
                self.starttime = time.time()
            gevent.sleep(duration)

    @property
    def elapsed(self):
        if self.simenv:
            return self.simenv.now
        else:
            return time.time() - self.starttime

    def disable_validators(self, num):
        assert num <= len(self.nodes)
        for i in range(num):
            n = self.nodes[i]
            for p in n.services.peermanager.peers:
                p.transport = NoTransport(self.simenv)

    def throttle_validators(self, num):
        assert num <= len(self.nodes)
        for i in reversed(range(num)):
            n = self.nodes[i]
            for p in n.services.peermanager.peers:
                p.transport = SlowTransport(self.simenv)

    def normvariate_base_latencies(self, sigma_factor=0.5, base_latency=None):
        min_latency = 0.001
        for n in self.nodes:
            for p in n.services.peermanager.peers:
                p.base_latency = base_latency or p.base_latency
                sigma = p.base_latency * sigma_factor
                p.base_latency = max(min_latency, random.normalvariate(p.base_latency, sigma))
                assert p.base_latency > 0

    def consensus_managers(self):
        return [n.services.chainservice.consensus_manager for n in self.nodes]

    def check_consistency(self):
        if self.simenv:
            elapsed = self.simenv.now
        else:
            elapsed = time.time() - self.starttime
        cs = self.consensus_managers()
        # check they are all on the same block or the previous one
        heights = Counter(c.chain.head.number for c in cs)
        height_distance = max(heights.keys()) - min(heights.keys())
        max_height = height = max(heights)

        # check they are all using the same block
        while height > 0:
            bs = list(set(c.chain.index.get_block_by_number(height) for c in cs
                          if c.chain.index.has_block_by_number(height)))
            assert len(bs) == 1 or (len(bs) == 2 and None in bs), bs
            height -= 1

        # highest round seen (i.e. number of failed proposers)
        max_rounds = 0
        for c in cs:
            blk = c.chain.head
            while blk.number > 0:
                p = c.load_proposal(blk.hash)
                max_rounds = max(max_rounds, p.signing_lockset.round)
                bh = c.chain.index.get_block_by_number(blk.number - 1)
                blk = c.chain.get(bh)
                assert isinstance(blk, Block)
        max_rounds += 1

        # messages
        ingress_bytes_transfered = 0
        egress_bytes_transfered = 0

        for n in self.nodes:
            for p in n.services.peermanager.peers:
                ingress_bytes_transfered += p.ingress_bytes
                egress_bytes_transfered += p.egress_bytes

        r = dict(max_height=max_height,
                 max_rounds=max_rounds,
                 heights=heights,
                 ingress_bytes_transfered=ingress_bytes_transfered,
                 egress_bytes_transfered=egress_bytes_transfered,
                 elapsed=elapsed,
                 height_distance=height_distance)
        log.debug('checked consistency', r=r)
        return r

# funcs making assumptions on the return value of Network.check_consistency

def assert_blocktime(r, max_avg_blocktime=1):
    print r
    assert r['elapsed'] / r['max_height'] < max_avg_blocktime

def assert_maxrounds(r, max_rounds=1):
    assert max_rounds > 0
    assert r['max_rounds'] == max_rounds

def assert_heightdistance(r, max_distance=0):
    assert r['max_height'] > 0
    assert r['height_distance'] <= max_distance

def main(num_nodes=10, sim_duration=10, timeout=0.5,
         base_latency=0.05, latency_sigma_factor=0.5,
         num_faulty_nodes=3, num_slow_nodes=0):

    slogging.configure(config_string=':debug')

    orig_timeout = ConsensusManager.round_timeout
    ConsensusManager.round_timeout = timeout
    network = Network(num_nodes, simenv=True)
    network.connect_nodes()
    network.normvariate_base_latencies(latency_sigma_factor, base_latency)
    network.disable_validators(num_faulty_nodes)
    network.throttle_validators(num_slow_nodes)
    network.start()
    network.run(sim_duration)
    network.check_consistency()
    ConsensusManager.round_timeout = orig_timeout
    return network

if __name__ == '__main__':
    num_nodes = 10
    faulty_fraction = 1 / 3. * 0  # nodes not sending anything
    # nodes sending votes and proposals at the edge of the timeout window
    slow_fraction = 1 / 3. * 0

    network = main(num_nodes=num_nodes,
                   sim_duration=10,
                   timeout=0.5,
                   base_latency=0.05,
                   latency_sigma_factor=0.5,
                   num_faulty_nodes=int(num_nodes * faulty_fraction),
                   num_slow_nodes=int(num_nodes * slow_fraction)
                   )


text:
import React from 'react'
import Link from './Link'
import Drawer from './Drawer'
import * as colors from './styles/colors'
import Header from './Header'
import Body from './Body'

import styled from 'styled-components'

const Container = styled.div`
  flex: 1;
  font-family: 'Roboto';
  height: 100vh;
`

const Footer = styled.div`
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 35px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  text-align: center;
  border-top: 1px solid ${colors.borderGrey};
`

const Entry = (props, context) => {
  return (
    <Container>
      <Header />
      <Body />
      <Drawer />
      <Footer>Copyright © 2016-2017 Michael Arnaldi</Footer>
    </Container>
  )
}

export default Entry


text:
class AddCoverImageToUserDetails < ActiveRecord::Migration
  def up
    execute <<-SQL
    CREATE OR REPLACE FUNCTION cover_image_url(users) RETURNS text
    LANGUAGE sql STABLE SECURITY DEFINER
    AS $_$
            SELECT
              'https://' || (SELECT value FROM settings WHERE name = 'aws_host') ||
              '/' || (SELECT value FROM settings WHERE name = 'aws_bucket') ||
              '/uploads/user/cover_image/' || $1.id::text ||
              '/base_' || $1.cover_image
            $_$;

    CREATE OR REPLACE VIEW "1".user_details AS
      SELECT u.id,
        u.name,
        u.address_city,
        u.deactivated_at,
        thumbnail_image(u.*) AS profile_img_thumbnail,
        u.facebook_link,
        u.twitter AS twitter_username,
            CASE
                WHEN is_owner_or_admin(u.id) THEN u.email
                ELSE NULL::text
            END AS email,
        COALESCE(ut.total_contributed_projects, 0::bigint) AS total_contributed_projects,
        COALESCE(ut.total_published_projects, 0::bigint) AS total_published_projects,
        ( SELECT json_agg(DISTINCT ul.link) AS json_agg
               FROM user_links ul
              WHERE ul.user_id = u.id) AS links,
        (select count(*) from user_follows uf WHERE user_id = u.id) AS follows_count,
        (select count(*) from user_follows uf WHERE follow_id = u.id) AS followers_count,
        (CASE
             WHEN public.is_owner_or_admin(u.id) THEN
               json_build_object('street', u.address_street, 'number', u.address_number, 'complement', u.address_complement, 'neighbourhood', u.address_neighbourhood, 'city', u.address_city, 'state', u.address_state, 'zipcode', u.address_zip_code, 'phonenumber', u.phone_number, 'country_id', u.country_id)
             ELSE NULL::json
         END) AS address,
        (CASE
            WHEN public.is_owner_or_admin(u.id) THEN u.cpf
            ELSE NULL::text
         END) AS owner_document,
       cover_image_url(u.*) AS profile_cover_image,
       u.created_at,
       u.about_html,
       is_owner_or_admin(u.id) AS is_owner_or_admin
       FROM users u
         LEFT JOIN "1".user_totals ut ON ut.user_id = u.id;

       GRANT SELECT ON "1".user_details to admin;
       GRANT SELECT ON "1".user_details to web_user;
       GRANT SELECT ON "1".user_details to anonymous;
    SQL
  end
  def down
    execute <<-SQL
    CREATE OR REPLACE VIEW "1".user_details AS
      SELECT u.id,
        u.name,
        u.address_city,
        u.deactivated_at,
        thumbnail_image(u.*) AS profile_img_thumbnail,
        u.facebook_link,
        u.twitter AS twitter_username,
            CASE
                WHEN is_owner_or_admin(u.id) THEN u.email
                ELSE NULL::text
            END AS email,
        COALESCE(ut.total_contributed_projects, 0::bigint) AS total_contributed_projects,
        COALESCE(ut.total_published_projects, 0::bigint) AS total_published_projects,
        ( SELECT json_agg(DISTINCT ul.link) AS json_agg
               FROM user_links ul
              WHERE ul.user_id = u.id) AS links,
        (select count(*) from user_follows uf WHERE user_id = u.id) AS follows_count,
        (select count(*) from user_follows uf WHERE follow_id = u.id) AS followers_count,
        (CASE
             WHEN public.is_owner_or_admin(u.id) THEN
               json_build_object('street', u.address_street, 'number', u.address_number, 'complement', u.address_complement, 'neighbourhood', u.address_neighbourhood, 'city', u.address_city, 'state', u.address_state, 'zipcode', u.address_zip_code, 'phonenumber', u.phone_number, 'country_id', u.country_id)
             ELSE NULL::json
         END) AS address,
        (CASE
            WHEN public.is_owner_or_admin(u.id) THEN u.cpf
            ELSE NULL::text
         END) AS owner_document
       FROM users u
         LEFT JOIN "1".user_totals ut ON ut.user_id = u.id;

       GRANT SELECT ON "1".user_details to admin;
       GRANT SELECT ON "1".user_details to web_user;
       GRANT SELECT ON "1".user_details to anonymous;
    SQL
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="account_label">dinger</string>
    <string name="account_type">org.stoyicker.dinger</string>
    <string name="authentication_notification_title">Manual authentication required</string>
    <string name="authentication_notification_body">Tap here to proceed</string>
    <string name="authentication_notification_channel_name">Authentication</string>
</resources>


text:
A short introduction on how to setup a project using the chili-core.

### Dependencies

The distributions are provided through jitpack, this means an additional
repository needs to be specified in the build setup.

As a dependency with Gradle
```groovy
allprojects {
    repositories {
        // mavenLocal, mavenCentral etc.
        maven { url 'https://jitpack.io' }
    }
}
```

```groovy
dependencies {
    implementation 'com.github.codingchili.chili-core:chili-core:${project.version}'
}
```

As a dependency with Maven

```xml
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>
```

```xml
<dependency>
    <groupId>com.github.codingchili.chili-core</groupId>
    <artifactId>chili-core</artifactId>
    <version>${project.version}</version>
</dependency>
```

### Optional dependencies

Some dependencies are not required unless specific features are accessed. Excluding
optional dependencies will greatly reduce the amount of transitive dependencies used. When
all optionals are included the distribution lands at 50+ MB, mostly thanks to ElasticSearch,
Hazelcast and SQLite.

The following dependencies are optional in some cases,

|Dependency|Size|Required when
|---|---|---|
|ElasticSearch|15+ MB|ElasticMap is used.
|CQEngine|7.5 MB|IndexedMap* is used.
|Hazelcast|10 MB|Clustering/HazelMap is used.
|MongoDB|1 MB|MongoDBMap is used.

These are rough estimates.

##### Excluding optional dependencies
An example on how to exclude all optionals

```groovy
dependencies {
    compile("com.github.codingchili.chili-core:core:$project.version") {
        exclude group: 'org.elasticsearch.client', module: 'elasticsearch-rest-high-level-client'
        exclude group: 'com.googlecode.cqengine', module: 'cqengine'
        exclude group: 'io.vertx', module: 'vertx-hazelcast'
        exclude group: 'io.vertx', module: 'vertx-mongo-client'
    }
}
```

When excluding all of the optional dependencies the jar size is 12MB.


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CalculatorService } from './services/calc.service';
import { CalculatorComponent } from './calc.component';
import { calculatorReducer } from './services/calc.reducer';
import { StoreModule } from '@ngrx/store';

@NgModule({
    imports: [
        CommonModule,
        StoreModule.provideStore({ calculatorR: calculatorReducer })
    ],
    declarations: [CalculatorComponent],
    exports: [CalculatorComponent],
    providers: [CalculatorService]
})

export class CalcModule {}


text:
class download(object):
    pass


text:
'''
A tool which takes as input a multispectral mask and a PAN image,
and scales and crops the former to agree with the latter. Used
during shallow-water bathymetry. See:
https://stereopipeline.readthedocs.io/en/latest
'''
from __future__ import print_function
import sys, os, subprocess

# The path to the ASP python files
basepath    = os.path.abspath(sys.path[0])
pythonpath  = os.path.abspath(basepath + '/../Python')  # for dev ASP
libexecpath = os.path.abspath(basepath + '/../libexec') # for packaged ASP
sys.path.insert(0, basepath) # prepend to Python path
sys.path.insert(0, pythonpath)
sys.path.insert(0, libexecpath)

import asp_system_utils, asp_image_utils
asp_system_utils.verify_python_version_is_supported()

# Prepend to system PATH
os.environ["PATH"] = libexecpath + os.pathsep + os.environ["PATH"]

if len(sys.argv) < 4:
    print("Usage: " + sys.argv[0] + " ms_mask.tif pan_image.tif output_pan_mask.tif [num_left_cols_crop]")
    sys.exit(1)

ms_mask = sys.argv[1]
pan_image = sys.argv[2]

if not os.path.exists(ms_mask):
    print("Missing file: " + ms_mask)
    sys.exit(1)

if not os.path.exists(pan_image):
    print("Missing file: " + pan_image)
    sys.exit(1)

# It is not clear how much to crop on the left
# A value of 50 seems to work better with WV03 and 48 with WV02.
crop_len = 50
if len(sys.argv) >= 5:
    crop_len = sys.argv[4]
print("Will remove " + str(crop_len) + " columns on the left after scaling the mask.")

output_pan_mask = sys.argv[3]
tmp_pan_mask = os.path.splitext(output_pan_mask)[0]+'_tmp.tif'

ms_width, ms_height = asp_image_utils.getImageSize(ms_mask)
pan_width, pan_height = asp_image_utils.getImageSize(pan_image)

# gdal_translate with options
gdt = 'gdal_translate -co compress=lzw -co TILED=yes -co INTERLEAVE=BAND ' + \
      '-co BLOCKXSIZE=256 -co BLOCKYSIZE=256 '

# Scale up the mask. Cast to float32.
cmd = gdt + '-outsize 400% 400% -ot float32 ' + ms_mask + " " + tmp_pan_mask

print(cmd)
os.system(cmd)

scaled_width, scaled_height = asp_image_utils.getImageSize(tmp_pan_mask)

# Remove crop_len pixels from the left edge, then adjust the other dimensions
# so that the resulting PAN mask dimensions agree with the PAN image.
cmd = gdt + "-srcwin " + str(crop_len) + " 0 " + str(pan_width) + " " + str(pan_height) + \
      " " + tmp_pan_mask + " " + output_pan_mask
print(cmd)
os.system(cmd)

# Wipe the temporary file
print("Removing: " + tmp_pan_mask)
os.remove(tmp_pan_mask)


text:
package printers

import (
	"fmt"
	"strings"

	"github.com/spf13/cobra"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"

	"k8s.io/kubernetes/pkg/kubectl/scheme"
)

// NamePrintFlags provides default flags necessary for printing
// a resource's fully-qualified Kind.group/name, or a successful
// message about that resource if an Operation is provided.
type NamePrintFlags struct {
	// DryRun indicates whether the "(dry run)" message
	// should be appended to the finalized "successful"
	// message printed about an action on an object.
	DryRun bool
	// Operation describes the name of the action that
	// took place on an object, to be included in the
	// finalized "successful" message.
	Operation string
}

// ToPrinter receives an outputFormat and returns a printer capable of
// handling --output=name printing.
// Returns false if the specified outputFormat does not match a supported format.
// Supported format types can be found in pkg/printers/printers.go
func (f *NamePrintFlags) ToPrinter(outputFormat string) (ResourcePrinter, bool, error) {
	decoders := []runtime.Decoder{scheme.Codecs.UniversalDecoder(), unstructured.UnstructuredJSONScheme}
	namePrinter := &NamePrinter{
		Operation: f.Operation,
		DryRun:    f.DryRun,
		Typer:     scheme.Scheme,
		Decoders:  decoders,
	}

	outputFormat = strings.ToLower(outputFormat)
	switch outputFormat {
	case "name":
		return namePrinter, true, nil
	case "":
		return nil, false, fmt.Errorf("missing output format")
	default:
		return nil, false, nil
	}
}

// AddFlags receives a *cobra.Command reference and binds
// flags related to name printing to it
func (f *NamePrintFlags) AddFlags(c *cobra.Command) {}

// NewNamePrintFlags returns flags associated with
// --name printing, with default values set.
func NewNamePrintFlags(operation string, dryRun bool) *NamePrintFlags {
	return &NamePrintFlags{
		Operation: operation,
		DryRun:    dryRun,
	}
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Compute.Models
{
    public partial class ApiEntityReference : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Id != null)
            {
                writer.WritePropertyName("id");
                writer.WriteStringValue(Id);
            }
            writer.WriteEndObject();
        }

        internal static ApiEntityReference DeserializeApiEntityReference(JsonElement element)
        {
            string id = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    id = property.Value.GetString();
                    continue;
                }
            }
            return new ApiEntityReference(id);
        }
    }
}


text:
@import AppKit;

#import "JSSUtils.h"

@implementation JSSCombiner {
  NSString *_imagePath;
  NSString *_sheetName;
  NSInteger _sheetWidth;
  NSInteger _sheetHeight;
  NSInteger _spriteHeight;
  NSInteger _spriteWidth;
}

-(instancetype)initWithImagePath:(NSString *)imagePath
                       sheetName:(NSString *)sheetName
                      sheetWidth:(NSInteger)sheetWidth
                     sheetHeight:(NSInteger)sheetHeight
                     spriteWidth:(NSInteger)spriteWidth
                    spriteHeight:(NSInteger)spriteHeight {
  if(self = [super init]) {
    _imagePath = [imagePath copy];
    _sheetName = [sheetName copy];
    _sheetWidth = sheetWidth;
    _sheetHeight = sheetHeight;
    _spriteHeight = spriteHeight;
    _spriteWidth = spriteWidth;
  }

  return self;
}

-(void)combine {
  NSBitmapImageRep *imageRep =
      [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL
                                              pixelsWide: _sheetWidth
                                              pixelsHigh: _sheetHeight
                                           bitsPerSample: 8
                                         samplesPerPixel: 4
                                                hasAlpha: YES
                                                isPlanar: NO
                                          colorSpaceName: NSDeviceRGBColorSpace
                                            bitmapFormat: NSAlphaFirstBitmapFormat
                                             bytesPerRow: _sheetWidth * 4
                                            bitsPerPixel: 32];

  NSXMLDocument *spriteSheetDoc = [[NSXMLDocument alloc] init];
  NSXMLElement *rootElement = [NSXMLElement elementWithName: @"spritesheet"];
  [spriteSheetDoc setRootElement: rootElement];
  NSXMLElement *nameElement = [NSXMLElement elementWithName: @"name" stringValue: _sheetName];
  [rootElement addChild: nameElement];
  [rootElement addChild: [NSXMLElement elementWithName: @"width" stringValue: [@(_sheetWidth) stringValue]]];
  [rootElement addChild: [NSXMLElement elementWithName: @"height" stringValue: [@(_sheetHeight) stringValue]]];
  [rootElement addChild: spriteSize(_spriteWidth, _spriteHeight)];
  NSXMLElement *spritesElement = [NSXMLElement elementWithName: @"sprites"];
  [rootElement addChild: spritesElement];

  NSGraphicsContext *graphicsContext =
      [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep];

  [NSGraphicsContext saveGraphicsState];
  [NSGraphicsContext setCurrentContext: graphicsContext];

  NSFileManager *files = [NSFileManager defaultManager];
  NSMutableArray *images = [NSMutableArray array];
  for(NSString *file in [files contentsOfDirectoryAtPath: _imagePath error: nil]) {
    if(![[file lowercaseString] containsString: @".png"]) {
      continue;
    }
    [images addObject: file];
  }

  NSInteger spritesPerRow = _sheetWidth / _spriteWidth;
  [images enumerateObjectsUsingBlock: ^(NSString *imageName, NSUInteger idx, BOOL *stop) {
    NSInteger x = idx % spritesPerRow;
    NSInteger y = idx / spritesPerRow;

    // Process Image
    NSString *fullPath = [NSString pathWithComponents: @[_imagePath, imageName] ];
    NSImage *sprite = [[NSImage alloc] initWithContentsOfFile: fullPath];
    [sprite drawInRect: NSMakeRect(x * _spriteWidth, y * _spriteHeight, _spriteWidth, _spriteHeight)];

    // Update XML
    NSXMLElement *spriteElement = [NSXMLElement elementWithName: @"sprite"];
    [spriteElement setAttributesWithDictionary: @{
      @"name" : [imageName stringByDeletingPathExtension],
      @"x" : [@(x) stringValue],
      @"y" : [@(y) stringValue]}
     ];
    [spritesElement addChild: spriteElement];
  }];

  NSData *pngData = [imageRep representationUsingType: NSPNGFileType properties: @{}];
  [pngData writeToFile: [NSString stringWithFormat: @"%@.png", _sheetName] atomically: NO];

  NSData *xmlData = [spriteSheetDoc XMLDataWithOptions: NSXMLNodePrettyPrint];
  [xmlData writeToFile: [NSString stringWithFormat: @"%@.xml", _sheetName] atomically: NO];

  [NSGraphicsContext restoreGraphicsState];
}

@end


text:
/* @flow */
'use strict'

import { describe, it, beforeEach } from 'mocha'
import expect from 'expect'

import moment from 'moment'
import {
  Map,
  List,
} from 'immutable'

import {
  getDailyTotals,
} from '../../../../../app/js/selectors/graph-data-helpers'

import {
  getGraphData,
} from '../../../../../app/js/selectors'

describe('Graph Data Daily Selector', () => {
  let state
  let data
  let range: Map<string, string|number>

  beforeEach(() => {
    state = {
      graphData: new Map({
        data: new Map(),
      }),
    }

    const path = moment()
    const todayPath = path.clone().format('YY/MM/DD').split('/')
    const yesterdayPath = path.clone()
                              .subtract(1, 'day')
                              .format('YY/MM/DD')
                              .split('/')
    const TwoDaysAgoPath = path.clone()
                                .subtract(2, 'day')
                                .format('YY/MM/DD')
                                .split('/')

    const pathArray = (p) => ['data'].concat(p).concat(['payingCustomersData'])

    state.graphData = state.graphData.setIn(pathArray(todayPath), 1)
    state.graphData = state.graphData.setIn(pathArray(yesterdayPath), 2)
    state.graphData = state.graphData.setIn(pathArray(TwoDaysAgoPath), 3)
    // state.graphData = state.graphData.setIn(pathArray(TwoDaysAgoPath).splice(0, 4))

    data = getGraphData(state)
    range = new Map({
      range: 'set',
      from: +moment().subtract(2, 'days').format('x'),
      to: +moment().format('x'),
    })
  })
  describe('#getDailyTotals()', () => {
    // should throw when dates not passed in
    it('should throw if no arguments passed in in', () => {
      expect(getDailyTotals.bind(null)).toThrow()
      expect(getDailyTotals.bind(null, data, range)).toNotThrow()
    })
    // should throw when data not passed in
    it('should throw if no data passed in', () => {
      expect(getDailyTotals.bind(null)).toThrow()
      expect(getDailyTotals.bind(null, 'data')).toThrow()
      expect(getDailyTotals.bind(null, data)).toThrow()
      expect(getDailyTotals.bind(null, data, 'range')).toThrow()
      expect(getDailyTotals.bind(null, data, range)).toNotThrow()
    })

    // should throw if no range passed in
    it('should throw if no range passed in', () => {
      expect(getDailyTotals.bind(null, data, 'range')).toThrow()
      expect(getDailyTotals.bind(null, data, range)).toNotThrow()
      expect(getDailyTotals.bind(null, data, range, 1)).toNotThrow()
    })

    // should return a Map
    it('should return a Map', () => {
      expect(getDailyTotals(data, range)).toBeA(Map)
    })

    // mapShould have 2 keys
    it('should have 2 keys', () => {
      expect(getDailyTotals(data, range).keySeq().count()).toBe(2)
    })

    // dates in map should be a list of strings
    it('dates in map should be a list of strings', () => {
      expect(getDailyTotals(data, range).get('dates')).toBeA(List)
      getDailyTotals(data, range).get('dates')
        .forEach((date) => expect(date).toBeA('string'))
    })

    // totals should be a list of maps
    it('totals should be a list of maps', () => {
      expect(getDailyTotals(data, range).get('totals')).toBeA(List)
      getDailyTotals(data, range).get('totals')
        .forEach((total) => expect(total).toBeA(Map))
    })
  })
})


text:
#include "util/Standard.hh"
#include "PluginManager.hpp"
#include <boost/filesystem.hpp>

namespace Sirikata {

/** Get a listing of all the files (no directories) in the given path. */
static std::list<String> getDirectoryFiles(const String& dirpath) {
    using namespace boost::filesystem;

    std::list<String> files;

    path dir = dirpath;
    if ( !exists(dir) || !is_directory(dir) )
        return files;

    directory_iterator end;
    for(directory_iterator di(dir); di != end; di++) {
        if (is_directory(di->status()))
            continue;
        files.push_back(di->path().string());
    }

    return files;
}

PluginManager::PluginManager() {
}

PluginManager::~PluginManager() {
}

void PluginManager::searchPath(const String& path) {
    std::list<String> files = getDirectoryFiles(path);

    for(std::list<String>::iterator it = files.begin(); it != files.end(); it++) {
        String filename = *it;
        load(filename);
    }
}

void PluginManager::load(const String& filename) {
    Plugin* plugin = new Plugin(filename);

    if (!plugin->load()) {
        delete plugin;
        return;
    }

    plugin->initialize();

    PluginInfo* pi = new PluginInfo();
    pi->plugin = plugin;
    pi->filename = filename;
    pi->name = plugin->name();

    mPlugins.push_back(pi);
}

void PluginManager::gc() {
    for(PluginInfoList::iterator it = mPlugins.begin(); it != mPlugins.end();) {
        PluginInfo* pi = *it;
        if (pi->plugin != NULL && pi->plugin->refcount() <= 1) {
            if (pi->plugin->refcount()==0) {
                pi->plugin->destroy();
                pi->plugin->unload();//unload plugin straight away, no outstanding variables
            }else {
                pi->plugin->destroy();//destroy the plugin, but leave program code for outstanding destructors
            }
            delete pi->plugin;
            pi->plugin = NULL;
            delete pi;
            PluginInfoList::iterator eraseme=it;
            ++it;
            mPlugins.erase(eraseme);
        }else{
            ++it;
        }
    }
}

} // namespace Sirikata


text:
      Nouvel évènement

<a href="<?php  echo BaseUrl; ?>/"> Accueil

Nouvel évènement

        <form role="form" class="newEventForm">

Basics

                Nom de l'évènement
                <input type="text" class="form-control" id="eventName" name="eventName" placeholder="name"  value="<?php  echo $event['name']; ?>" required>

                Description
                <textarea class="form-control" id="eventDescription" name="eventDescription" placeholder="description" required><?php  echo $event['description']; ?></textarea>

                Addresse
                <input type="text" class="form-control" id="eventAdress" name="eventAdress" placeholder="adress"  value="<?php  echo $event['adress']; ?>" required>

                      Ville
                      <input type="text" class="form-control" id="eventCity" name="eventCity" placeholder="city"  value="<?php  echo $event['city']; ?>" required>

                      Code Postal
                      <input type="text" class="form-control" id="eventZip" name="eventZip" placeholder="zip"  value="<?php  echo $event['zip']; ?>" required>

Dates

                Date de début

                      <input type="text" class="form-control" id="eventDateStart" name="eventDateStart" placeholder="dateStart"  value="<?php  echo date('d/m/Y',strtotime($event['dateStart'])); ?>" required>

                                  <input  type="text" class="form-control input-small"  name="eventTimeStart"  value="<?php    echo date('H:i',strtotime($event['dateStart'])); ?>" required>

                Date de fin

                      <input type="text" class="form-control" id="eventDateEnd" name="eventDateEnd" placeholder="dateEnd"  value="<?php  echo date('d/m/Y',strtotime($event['dateEnd'])); ?>" required>

                                  <input  type="text" class="form-control input-small"  name="eventTimeEnd"  value="<?php  echo date('H:i',strtotime($event['dateEnd'])); ?>" required>

Information supplémentaire

                Note/Information
                <textarea  class="form-control" id="eventNote" name="eventNote" placeholder="note"><?php  echo $event['note']; ?></textarea>

Informations de contact

              Contact n°1

                          </button>

                          <img class="img-circle" src="<?php  echo BaseUrl;?>/assets/img/user.png" alt="User Avatar">

<input type="text" class="form-control" id="eventContactName1" name="eventContactName1" placeholder="contactName1"  value="<?php  echo $event['contactName1']; ?>">

<input type="text" class="form-control" id="eventContactType1" name="eventContactType1" placeholder="contactType1"  value="<?php  echo $event['contactType1']; ?>">

                      <input type="text" class="form-control" id="eventContactPhone1" name="eventContactPhone1" placeholder="contactPhone1"  value="<?php  echo $event['contactPhone1']; ?>">

              Contact n°2

                          </button>

                          <img class="img-circle" src="<?php  echo BaseUrl;?>/assets/img/user.png" alt="User Avatar">

<input type="text" class="form-control" id="eventContactName2" name="eventContactName2" placeholder="contactName2"  value="<?php  echo $event['contactName2']; ?>">

<input type="text" class="form-control" id="eventContactType2" name="eventContactType2" placeholder="contactType2"  value="<?php  echo $event['contactType2']; ?>">

                      <input type="text" class="form-control" id="eventContactPhone2" name="eventContactPhone2" placeholder="contactPhone2"  value="<?php  echo $event['contactPhone2']; ?>">

Prestation

                  Type de prestation
                  <select class="form-control select-presta">
                    <option value="0"><?php  echo $event['type']; ?> (Actuel)</option><?php
                  foreach ($prestas->presta as $presta) {
                    echo '<option value="'.$presta['id'].'">'.$presta['type'].'</option>';
                  }
                  ?></select>
                  Réglages avancés

                    type
                    <input type="text" class="form-control" id="eventType" name="eventType" placeholder="type"  value="<?php  echo $event['type']; ?>" required>

                        timeIn/Out

                            <input  type="text" class="form-control input-small"  id="eventTimeIn" name="eventTimeIn"  value="<?php  echo $event['timeIn']; ?>" required>

                              <input  type="text" class="form-control input-small" id="eventTimeOut" name="eventTimeOut"  value="<?php  echo $event['timeOut']; ?>" required>

                        icon
                        <input type="text" class="form-control" id="eventIcon" name="eventIcon" placeholder="icon"  value="<?php  echo $event['icon']; ?>" required>

                        color
                        <input type="text" class="form-control" id="eventColor" name="eventColor" placeholder="color"  value="<?php  echo $event['color']; ?>"  required>

              <button type="submit" class="submit btn btn-primary">Créer</button>
              <?php
              if($User->getAdmin()){
                echo 'Supprimer';
              }
              ?>

      </form>

<input name="prestas" value='<?php echo json_encode($prestas->presta); ?>' type="hidden">
<input name="eventId" value='<?php echo $event['id']; ?>' type="hidden">


text:
<?php
/**
* single member page
* also show complete subs history
*
*/

// enable form fields when creating a new member
$m = isset($member);
?>
<?php echo (isset($member->id)) ? 'Golygu' : 'Ychwanegu'; ?> Aelod

<?php if(isset($member->id)): ?>
	<a href="#" class="btn btn-success" id="allow-edit" title="Clic i newid manylion <?=$member->first_name?>">
<?php endif; ?>

<?php echo validation_errors();?>
<form action="" method="post" class="form form-horizontal" id="edit-member">

<?php if(isset($member->id)): ?>
	<input type="hidden" name="id" value="<?php echo $member->id; ?>" />

		Rhif:

			<input type="text" value="<?php echo $member->id; ?>" class="small" disabled />

<?php endif; ?>

		Enw Cyntaf:

			<input type="text" name="first_name" id="first_name" value="<?php echo @set_value('first_name', $member->first_name); ?>" class="" <?=set_disabled($m)?> />

		Cyfenw:

			<input type="text" name="last_name" id="last_name" value="<?php echo @set_value('last_name', $member->last_name); ?>" class="" <?=set_disabled($m)?> />

		Ebost:

			<input type="email" name="email" id="email" value="<?php echo @set_value('email', $member->email); ?>" class="" <?=set_disabled($m)?> />

		Cyfeiriad 1:

			<input type="text" name="billing_address1" id="billing_address1" value="<?php echo @set_value('billing_address1', $member->billing_address1); ?>" class="" <?=set_disabled($m)?> />

		Cyfeiriad 2:

			<input type="text" name="billing_address2" id="billing_address2" value="<?php echo @set_value('billing_address2', $member->billing_address2); ?>" class="" <?=set_disabled($m)?> />

		Tref:

			<input type="text" name="billing_town" id="billing_town" value="<?php echo @set_value('billing_town', $member->billing_town); ?>" class="" <?=set_disabled($m)?> />

		Cod Post:

			<input type="text" name="billing_postcode" id="billing_postcode" value="<?php echo @set_value('billing_postcode', $member->billing_postcode); ?>" class="" <?=set_disabled($m)?> />

		Ffôn:

			<input type="text" name="rhif_ffon" id="rhif_ffon" value="<?php echo @set_value('rhif_ffon', $member->rhif_ffon); ?>" class="" <?=set_disabled($m)?> />

		<button type="submit" class="btn btn-primary" <?=set_disabled($m)?> id="save-edit">Cadw</button>

		<?php $refer_url = $this->session->flashdata('refer'); ?>
		  neu <a href="<?=$refer_url?>" rel="tooltip" title="Canslo a Dychwelyd i'r Rhestr Aelodaeth">Canslo

</form>

<?php if(isset($member->id) && count($member->subs) > 0): ?>

Payments

		Dyddiad
		Swm
		Lefel
		Hyd at
		Dull

	<?php
	foreach($member->subs as $s):
		// show red for expired, green for current or yellow for pending
		$class = (mktime() < strtotime($s->ends_on)) ? ( ($s->status == 'paid') ? 'success' : 'warning') : 'error';
	?>
		<tr class="<?php echo $class; ?>">
			<td title="Subs ID: <?=$s->subs_id?>"><?php echo date('j M, Y', strtotime($s->created_on)); ?>
			£<?php echo $s->amount; ?>
			<?php echo $s->membership_type; ?>
			<?php echo date('Y', strtotime($s->ends_on)); ?>
			<?php echo ucfirst($s->method); ?>
			<?php
			if(!is_null($s->notes) && $s->notes != '')
			{
				echo '<button class="btn view-note" title="Darllen y nodyn sydd ar y taliad hwn"></button>';
				echo '	';
				echo ''.$s->notes;
			}
			else
				echo ' ';
		  ?>

	<?php
	endforeach;
	?>

<?php echo anchor('admin/aelodaeth/adnewyddu/'.$member->id, 'Adnewyddu', array('class'=>'btn btn-primary')); ?>
	Adnewyddu Aelodaeth <?php echo $member->first_name.' '.$member->last_name; ?>.

Information

Crewyd ar <?=date('d/m/Y H:i', strtotime($member->m_created_on));?>

<?php if($member_groups): ?>

Mae <?=$member->first_name?> yn aelod o'r grwpiau canlynol:

	<?php foreach($member_groups as $g): ?>

<?php echo anchor('admin/mgroups/grwp/'.$g->id, $g->groupname_cy.'|'.$g->groupname_en); echo ' ('.$g->notes.')' ?>

	<?php endforeach;?>

<?php endif; ?>
<?php endif;?>


text:
package com.google.samples.quickstart.admobexample.java;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.samples.quickstart.admobexample.R;
import com.google.samples.quickstart.admobexample.databinding.FragmentFirstBinding;

class FirstFragment extends Fragment {

    private static final String TAG = "MainActivity";
    private static final String TEST_APP_ID = "ca-app-pub-3940256099942544~3347511713";

    private AdView mAdView;
    private InterstitialAd mInterstitialAd;
    private Button mLoadInterstitialButton;
    private FragmentFirstBinding binding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        checkIds();

        // Initialize the Google Mobile Ads SDK
        MobileAds.initialize(getContext());

        mAdView = binding.adView;

        requestNewInterstitial();

        mLoadInterstitialButton = binding.loadInterstitialButton;
        mLoadInterstitialButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInterstitialAd != null) {
                    mInterstitialAd.show(getActivity());
                } else {
                    beginSecondActivity();
                }
            }
        });

        // Disable button if an interstitial ad is not loaded yet.
        mLoadInterstitialButton.setEnabled(mInterstitialAd != null);
    }

    /**
     * Load a new interstitial ad asynchronously.
     */
    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        // AdMob ad unit IDs are not currently stored inside the google-services.json file.
        // Developers using AdMob can store them as custom values in a string resource file or
        // simply use constants. Note that the ad units used here are configured to return only test
        // ads, and should not be used outside this sample.
        InterstitialAd.load(getContext(), getString(R.string.interstitial_ad_unit_id), adRequest, new InterstitialAdLoadCallback() {
            @Override
            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                super.onAdLoaded(interstitialAd);
                mInterstitialAd = interstitialAd;

                // Ad received, ready to display
                if (mLoadInterstitialButton != null) {
                    mLoadInterstitialButton.setEnabled(true);
                }

                mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                    @Override
                    public void onAdDismissedFullScreenContent() {
                        super.onAdDismissedFullScreenContent();
                        requestNewInterstitial();
                        beginSecondActivity();
                    }
                });
            }

            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                mInterstitialAd = null;
                Log.w(TAG, "onAdFailedToLoad:" + loadAdError.getMessage());
            }
        });
    }

    private void beginSecondActivity() {
        NavHostFragment.findNavController(this).navigate(R.id.action_FirstFragment_to_SecondFragment);
    }

    /** Called when leaving the activity */
    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    /** Called when returning to the activity */
    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
        if (mInterstitialAd == null) {
            requestNewInterstitial();
        }
    }

    /** Called before the activity is destroyed */
    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }

    @VisibleForTesting
    public AdView getAdView() {
        return mAdView;
    }

    private void checkIds() {
        if (TEST_APP_ID.equals(getString(R.string.admob_app_id))) {
            Log.w(TAG, "Your admob_app_id is not configured correctly, please see the README");
        }
    }
}


text:
@implementation NSError (FLTimeout)
+ (NSError*) timeoutError {
    return [NSError errorWithDomain:NSURLErrorDomain
                                   code:FLErrorCodeTimedOut
                   localizedDescription:NSLocalizedString(@"TimeOut Error", @"used in cancel error localized description")];
}

- (BOOL) isTimeoutError {
	return	FLStringsAreEqual(NSURLErrorDomain, self.domain) &&
			self.code == FLErrorCodeTimedOut;
}
@end


text:
struct ImDrawData;
struct ID3D11Device;
struct ID3D11DeviceContext;
struct ID3D11Buffer;
struct ID3D10Blob;
struct ID3D11VertexShader;
struct ID3D11InputLayout;
struct ID3D11PixelShader;
struct ID3D11SamplerState;
struct ID3D11ShaderResourceView;
struct ID3D11RasterizerState;
struct ID3D11BlendState;
struct ID3D11DepthStencilState;

namespace NLE
{
	namespace GRAPHICS
	{
		class ImguiD3D11Renderer
		{
		public:
			ImguiD3D11Renderer();
			~ImguiD3D11Renderer();

			bool initialize(ID3D11Device* device, ID3D11DeviceContext* devCon);
			void render(ID3D11Device* device, ID3D11DeviceContext* devCon, ImDrawData* data);

		private:
			bool createDeviceObjects(ID3D11Device* device, ID3D11DeviceContext* devCon);
			bool createFontAndTextures(ID3D11Device* device, ID3D11DeviceContext* devCon);

			ID3D11Buffer*            _vertexBuffer;
			ID3D11Buffer*            _indexBuffer;
			ID3D10Blob*             _vertexShaderBlob;
			ID3D11VertexShader*      _vertexShader;
			ID3D11InputLayout*       _inputLayout;
			ID3D11Buffer*            _vertexConstantBuffer;
			ID3D10Blob *             _pixelShaderBlob;
			ID3D11PixelShader*       _pixelShader;
			ID3D11SamplerState*      _fontSampler;
			ID3D11ShaderResourceView*_fontTextureView;
			ID3D11RasterizerState*   _rasterizerState;
			ID3D11BlendState*        _blendState;
			ID3D11DepthStencilState* _depthStencilState;
			int                      _vertexBufferSize;
			int						_indexBufferSize;
		};
	}
}


text:
const common = require('../../@util/integration-common.js');
const router = require('../../../src/routes/users/index.js');
const config = require('nconf');

describe('Users', function() {
    this.timeout(common.defaultTimeout);
    describe('Search for Users', function() {
        it('Happy case', function(done) {
            common.request
                .get('/users')
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.success(200))
                .expect(common.matchesSwaggerSchema)
                .expect(common.hasResults)
                .end(common.logResponse(done));
        });
        it('No Authentication', function(done) {
            common.request
                .get('/users')
                .expect(common.error(401))
                .expect(common.matchesSwaggerSchema)
                .end(common.logResponse(done));
        });
    });

    describe('Get User By Email.', function() {
        it('Happy case', function(done) {
            common.request
                .get('/users/:email')
                .use(common.urlTemplate({ email: config.get('tests').adminUser._id }))
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.success(200))
                .expect(common.matchesSwaggerSchema)
                .end(common.logResponse(done));
        });
        it('No Authentication', function(done) {
            common.request
                .get('/users/:email')
                .use(common.urlTemplate({ email: config.get('tests').adminUser._id }))
                .expect(common.error(401))
                .expect(common.matchesSwaggerSchema)
                .end(common.logResponse(done));
        });
        it('Invalid path parameter', function(done) {
            common.request
                .get('/users/:email')
                .use(common.urlTemplate({ email: '2b8934a4-82ee-4cae-9ce8-0e3379254e4d' }))
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.error(404))
                .expect(common.matchesSwaggerSchema)
                .end(common.logResponse(done));
        });
    });

    describe('Posts Through An User To Be Created.', function() {
        it('Happy case', function(done) {
            common.request
                .post('/users')
                .send(common.generateDataFromSchema(router.metadata.schemas.creation))
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.success(201))
                .expect(common.matchesSwaggerSchema)
                .end(common.logResponse(done));
        });
        it('No Authentication', function(done) {
            common.request
                .post('/users')
                .send(common.generateDataFromSchema(router.metadata.schemas.creation))
                .expect(common.error(401))
                .expect(common.matchesSwaggerSchema)
                .end(common.logResponse(done));
        });
        it('No Data', function(done) {
            common.request
                .post('/users')
                .send({})
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.error(400))
                .expect(common.matchesSwaggerSchema)
                .end(common.logResponse(done));
        });
    });

    describe('Updates a User By Email', function() {
        it('Happy case', function(done) {
            common.request
                .put('/users/:email')
                .use(common.urlTemplate({ email: config.get('tests').adminUser._id }))
                .send(common.generateDataFromSchema(router.metadata.schemas.update))
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.success(204))
                .end(common.logResponse(done));
        });
        it('No Authentication', function(done) {
            common.request
                .put('/users/:email')
                .use(common.urlTemplate({ email: config.get('tests').adminUser._id }))
                .send(common.generateDataFromSchema(router.metadata.schemas.update))
                .expect(common.error(401))
                .end(common.logResponse(done));
        });
        it('No Data', function(done) {
            common.request
                .put('/users/:email')
                .use(common.urlTemplate({ email: config.get('tests').adminUser._id }))
                .send({})
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.error(400))
                .end(common.logResponse(done));
        });
    });

    describe('Updates the status of a User By Email', function() {
        it('Happy case', function(done) {
            common.request
                .put('/users/:email/:newStatusName')
                .use(
                    common.urlTemplate({
                        email: config.get('tests').adminUser._id,
                        newStatusName: 'testStatus'
                    })
                )
                .send(common.generateDataFromSchema(router.metadata.schemas.updateStatus))
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.success(204))
                .end(common.logResponse(done));
        });
        it('Happy case - custom status schema', function(done) {
            common.request
                .put('/users/:email/:newStatusName')
                .use(
                    common.urlTemplate({
                        email: config.get('tests').adminUser._id,
                        newStatusName: 'inactive'
                    })
                )
                .send({ potatoes: 4 })
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.success(204))
                .end(common.logResponse(done));
        });
        it('No Authentication', function(done) {
            common.request
                .put('/users/:email/:newStatusName')
                .use(
                    common.urlTemplate({
                        email: config.get('tests').adminUser._id,
                        newStatusName: 'testStatus'
                    })
                )
                .send(common.generateDataFromSchema(router.metadata.schemas.updateStatus))
                .expect(common.error(401))
                .end(common.logResponse(done));
        });
        it('No Data', function(done) {
            common.request
                .put('/users/:email/:newStatusName')
                .use(
                    common.urlTemplate({
                        email: config.get('tests').adminUser._id,
                        newStatusName: 'testStatus'
                    })
                )
                .send({})
                .set(common.authentication({ user: config.get('tests').adminUser }))
                .expect(common.error(400))
                .end(common.logResponse(done));
        });
    });
});


text:
package org.openestate.io.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A general CSV format specification, that supports reading through
 * {@link CsvParser} and writing through {@link CsvPrinter}.
 *
 * @param <Record>  the class used for CSV records
 * @param <Parser>  the class used for parsing of CSV records
 * @param <Printer> the class used for printing of CSV records
 * @author Andreas Rudolph
 * @since 1.0
 */
public abstract class CsvFormat<Record extends CsvRecord, Parser extends CsvParser<Record>, Printer extends CsvPrinter<Record>> {
    @SuppressWarnings("unused")
    private final static Logger LOGGER = LoggerFactory.getLogger(CsvFormat.class);
    private final CSVFormat format;

    /**
     * Create with specifications of a {@link CSVFormat}.
     *
     * @param format the CSV format from
     *               commons-csv
     */
    protected CsvFormat(CSVFormat format) {
        this.format = format;
    }

    /**
     * Returns the encoding of created CSV data.
     *
     * @return encoding
     */
    public abstract String getEncoding();

    /**
     * Returns the contained {@link CSVFormat}.
     *
     * @return the contained format
     */
    public final CSVFormat getFormat() {
        return this.format;
    }

    /**
     * Creates a new {@link CsvParser} for a {@link CSVParser}.
     *
     * @param parser the CSV parser from
     *               commons-csv
     * @return created parser
     */
    protected abstract Parser newParser(CSVParser parser);

    /**
     * Creates a new {@link CsvPrinter} for a {@link CSVPrinter}.
     *
     * @param printer the CSV printer from
     *                commons-csv
     * @return created printer
     */
    protected abstract Printer newPrinter(CSVPrinter printer);

    /**
     * Creates a {@link CsvParser} from a {@link String} with CSV data.
     *
     * @param csvString CSV string
     * @return created parser
     * @throws IOException if CSV is not readable
     */
    public final Parser parse(String csvString) throws IOException {
        return this.parse(new StringReader(csvString));
    }

    /**
     * Creates a {@link CsvParser} from a {@link File} with CSV data.
     *
     * @param csvFile CSV file
     * @return created parser
     * @throws IOException if CSV is not readable
     */
    public final Parser parse(File csvFile) throws IOException {
        return this.parse(new FileInputStream(csvFile));
    }

    /**
     * Creates a {@link CsvParser} from an {@link InputStream} with CSV data.
     *
     * @param input CSV input
     * @return created parser
     * @throws IOException if CSV is not readable
     */
    public final Parser parse(InputStream input) throws IOException {
        return this.parse(new InputStreamReader(input, this.getEncoding()));
    }

    /**
     * Creates a {@link CsvParser} from a {@link Reader} with CSV data.
     *
     * @param input CSV input
     * @return created parser
     * @throws IOException if CSV is not readable
     */
    public Parser parse(Reader input) throws IOException {
        return this.newParser(new CSVParser(input, this.getFormat()));
    }

    /**
     * Creates a {@link CsvPrinter}, that writes CSV data into a
     * {@link StringBuffer}.
     *
     * @param csvString where CSV is written to
     * @return created printer
     * @throws IOException if CSV is not writable
     */
    public final Printer print(StringBuffer csvString) throws IOException {
        return print((Appendable) csvString);
    }

    /**
     * Creates a {@link CsvPrinter}, that writes CSV data into a
     * {@link StringBuilder}.
     *
     * @param csvString where CSV is written to
     * @return created printer
     * @throws IOException if CSV is not writable
     */
    public final Printer print(StringBuilder csvString) throws IOException {
        return print((Appendable) csvString);
    }

    /**
     * Creates a {@link CsvPrinter}, that writes CSV data into a {@link File}.
     *
     * @param csvFile where CSV is written to
     * @return created printer
     * @throws IOException if CSV is not writable
     */
    public final Printer print(File csvFile) throws IOException {
        return print(new FileOutputStream(csvFile));
    }

    /**
     * Creates a {@link CsvPrinter}, that writes CSV data into an
     * {@link OutputStream}.
     *
     * @param output where CSV is written to
     * @return created printer
     * @throws IOException if CSV is not writable
     */
    public final Printer print(OutputStream output) throws IOException {
        return print(new OutputStreamWriter(output, this.getEncoding()));
    }

    /**
     * Creates a {@link CsvPrinter}, that writes CSV data into a {@link Writer}.
     *
     * @param output where CSV is written to
     * @return created printer
     * @throws IOException if CSV is not writable
     */
    public final Printer print(Writer output) throws IOException {
        return print((Appendable) output);
    }

    /**
     * Creates a {@link CsvPrinter}, that writes CSV data into an
     * {@link Appendable} object.
     *

     * Use this function to, to override the print methods through inheritance.
     *
     * @param output where CSV is written to
     * @return created printer
     * @throws IOException if CSV is not writable
     */
    protected Printer print(Appendable output) throws IOException {
        return newPrinter(new CSVPrinter(output, this.getFormat()));
    }
}


text:
//
// DataSource.m
// FluzzView
//
// Created by wangchaojs02 on 15/3/29.
// Copyright (c) 2015年 wangchaojs02. All rights reserved.
//

#import "DataSource.h"
#import "DataSourceRequest.h"

@interface DataSource ()
@property (nonatomic, strong) NSOperationQueue    *requestQueue;
@property (nonatomic, strong) NSMutableDictionary *requests;
@end

@implementation DataSource
+ (instancetype)sharedDataSource
{
    static dispatch_once_t onceToken;
    static DataSource     *shared;

    dispatch_once(&onceToken, ^{
        shared = [DataSource new];
    });

    return shared;
}

+ (void)requestDataWithID:(NSString*)ID
                   params:(id)params
                   worker:(id<DataSourceWorker>)worker
                 complete:(DataSourceComplete)complete
{
    [[DataSource sharedDataSource]
     requestDataWithID:ID
                params:params
                worker:worker
              complete:complete];
}

+ (void)cancelRequestWithID:(NSString*)ID
{
    [[DataSource sharedDataSource] cancelRequestWithID:ID];
}

- (instancetype)init
{
    self = [super init];

    if (self)
    {
        _requestQueue                             = [[NSOperationQueue alloc] init];
        _requestQueue.name                        = @"request-data";
        _requestQueue.qualityOfService            = NSQualityOfServiceUserInitiated;
        _requestQueue.maxConcurrentOperationCount = 3;

        _requests                                 = [NSMutableDictionary dictionary];
    }
    return self;
} /* init */

- (void)requestDataWithID:(NSString*)ID
                   params:(id)params
                   worker:(id<DataSourceWorker>)worker
                 complete:(DataSourceComplete)complete
{
    DataSourceRequest *request = [_requests valueForKey:ID];

    if (!request)
    {
        request        = [DataSourceRequest requestWithID:ID params:params];
        request.worker = worker;
        [_requests setValue:request forKey:ID];
    }
    else
    {
        if (!request.isExecuting)
        {
            [request cancel];
        }
    }

    WEAK_OBJ(request);
    WEAK_OBJ(self);
    [request setCompletionBlock: ^{
        STRONG_OBJ(self);
        [self->_requests removeObjectForKey:ID];

        STRONG_OBJ(request);

        if (complete)
        {
            complete(request.result, request.error);
        }
    }];

    if ( ![request isExecuting]
         && ([_requestQueue.operations indexOfObject:request] == NSNotFound) )
    {
        [_requestQueue addOperation:request];
    }
} /* requestDataWithID */

- (void)cancelRequestWithID:(NSString*)ID
{
    DataSourceRequest *request = [_requests valueForKey:ID];

    if (request)
    {
        [request cancel];
        [_requests removeObjectForKey:ID];
    }
}

@end


text:
package com.huchiwei.zhihudailynews.common.support.recyclerview;

import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Support RecyclerView Item Click Event
 *
 * @author huchiwei
 * @version 1.0.0
 */
public abstract class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    private GestureDetectorCompat mGestureDetector;
    protected RecyclerView mRecyclerView;

    public RecyclerItemClickListener(){}

    public RecyclerItemClickListener(RecyclerView recyclerView){
        this.mRecyclerView = recyclerView;
        this.mGestureDetector = new GestureDetectorCompat(mRecyclerView.getContext(), new GestureListener());
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        this.mGestureDetector.onTouchEvent(e);
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        this.mGestureDetector.onTouchEvent(e);
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        // do nothing....
    }

    /**
     * 待实现click事件
     * @param holder
     */
    public abstract void onItemClick(RecyclerView.ViewHolder holder);

    /**
     * 手势监听器,
     */
    private class GestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            View child = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null) {
                RecyclerView.ViewHolder VH = mRecyclerView.getChildViewHolder(child);
                onItemClick(VH);
            }
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null) {
                RecyclerView.ViewHolder VH = mRecyclerView.getChildViewHolder(child);
                onItemClick(VH);
            }
        }
    }
}


text:
package org.openid4java.consumer;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.util.InternetDateFormat;

/**
 * @author Marius Scurtescu, Johnny Bufu
 */
public abstract class AbstractNonceVerifier implements NonceVerifier
{
    private static Log _log = LogFactory.getLog(AbstractNonceVerifier.class);
    private static final boolean DEBUG = _log.isDebugEnabled();

    protected static InternetDateFormat _dateFormat = new InternetDateFormat();

    protected int _maxAgeSeconds;

    /**
     * @param maxAge maximum token age in seconds
     */
    protected AbstractNonceVerifier(int maxAge)
    {
        _maxAgeSeconds = maxAge;
    }

    public int getMaxAge()
    {
        return _maxAgeSeconds;
    }

    public void setMaxAge(int ageSeconds)
    {
        _maxAgeSeconds = ageSeconds;
    }

    /**
     * Checks if nonce date is valid and if it is in the max age boundary. Other checks are delegated to {@link #seen(java.util.Date, String, String)}
     */
    public synchronized int seen(String opUrl, String nonce)
    {
        if (DEBUG) _log.debug("Verifying nonce: " + nonce);

        Date now = new Date();

        try
        {
            Date nonceDate = _dateFormat.parse(nonce);

            if (isTooOld(now, nonceDate))
            {
                _log.warn("Nonce is too old: " + nonce);
                return TOO_OLD;
            }

            return seen(now, opUrl, nonce);
        }
        catch (ParseException e)
        {
            _log.error("Error verifying the nonce: " + nonce, e);
            return INVALID_TIMESTAMP;
        }
    }

    /**
     * Subclasses should implement this method and check if the nonce was seen before.
     * The nonce timestamp was verified at this point, it is valid and it is in the max age boudary.
     *
     * @param now The timestamp used to check the max age boudary.
     */
    protected abstract int seen(Date now, String opUrl, String nonce);

    protected boolean isTooOld(Date now, Date nonce)
    {
        long age = now.getTime() - nonce.getTime();

        return age > _maxAgeSeconds * 1000;
    }
}


text:
.PHONY:	clean

# ----------------------------------------------------------------------

../README.md:	README-header.md API.html README-footer.md
		cat $^  >$@

API.html:	../lzjb.py docbuilder.py Makefile
		./docbuilder.py -pathprefix=.. lzjb "Size encoding:size_encode,size_decode" "Data compression:compress,decompress" > $@

# ----------------------------------------------------------------------

clean:
	rm -f README README.md API.htm


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class UpdateFeedVideosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('feed_videos', function (Blueprint $blueprint) {
            $blueprint->index('feed_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}


text:
package org.jutils.jprocesses.info;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Helper class of windows implementation to create and execute VBS scripts
 *
 * @author Javier Garcia Alonso
 */
class VBScriptHelper {

    private static final String CRLF = "\r\n";

    //Hide constructor
    private VBScriptHelper() {
    }

    private static String executeScript(String scriptCode) {
        String scriptResponse = "";
        File tmpFile = null;
        FileWriter writer = null;
        BufferedReader processOutput = null;
        BufferedReader errorOutput = null;

        try {
            tmpFile = File.createTempFile("wmi4java" + new Date().getTime(), ".vbs");
            writer = new FileWriter(tmpFile);
            writer.write(scriptCode);
            writer.flush();
            writer.close();

            Process process = Runtime.getRuntime().exec(
                    new String[]{"cmd.exe", "/C", "cscript.exe", "/NoLogo", tmpFile.getAbsolutePath()});
            processOutput
                    = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = processOutput.readLine()) != null) {
                if (!line.isEmpty()) {
                    scriptResponse += line + CRLF;
                }
            }

            if (scriptResponse.isEmpty()) {
                errorOutput
                        = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String errorResponse = "";
                while ((line = errorOutput.readLine()) != null) {
                    if (!line.isEmpty()) {
                        errorResponse += line + CRLF;
                    }
                }
                if (!errorResponse.isEmpty()) {
                    Logger.getLogger(VBScriptHelper.class.getName()).log(Level.SEVERE, "WMI operation finished in error: ");
                }
                errorOutput.close();
            }

        } catch (Exception ex) {
            Logger.getLogger(VBScriptHelper.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (processOutput != null) {
                    processOutput.close();
                }
                if (errorOutput != null) {
                    errorOutput.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (tmpFile != null) {
                    tmpFile.delete();
                }
            } catch (IOException ioe) {
                Logger.getLogger(VBScriptHelper.class.getName()).log(Level.SEVERE, null, ioe);
            }
        }
        return scriptResponse.trim();
    }

    /**
     * Retrieve the owner of the processes.
     *
     * @return list of strings composed by PID and owner, separated by :
     */
    public static String getProcessesOwner() {

        try {
            StringBuilder scriptCode = new StringBuilder(200);

            scriptCode.append("Set objWMIService=GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\")
                    .append(".").append("/").append("root/cimv2").append("\")").append(CRLF);

            scriptCode.append("Set colProcessList = objWMIService.ExecQuery(\"Select * from Win32_Process\")").append(CRLF);

            scriptCode.append("For Each objProcess in colProcessList").append(CRLF);
            scriptCode.append("colProperties = objProcess.GetOwner(strNameOfUser,strUserDomain)").append(CRLF);
            scriptCode.append("Wscript.Echo objProcess.ProcessId & \":\" & strNameOfUser").append(CRLF);
            scriptCode.append("Next").append(CRLF);

            return executeScript(scriptCode.toString());
        } catch (Exception ex) {
            Logger.getLogger(VBScriptHelper.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * Changes the priority of a process
     *
     * @param pid the PID
     * @param newPriority the priority to set @see Windo
     * @return the output of the script
     */
    public static String changePriority(int pid, int newPriority) {

        try {
            StringBuilder scriptCode = new StringBuilder(200);

            scriptCode.append("Set objWMIService=GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\")
                    .append(".").append("/").append("root/cimv2").append("\")").append(CRLF);

            scriptCode.append("Set colProcesses = objWMIService.ExecQuery(\"Select * from Win32_Process Where ProcessId = ")
                    .append(pid).append("\")").append(CRLF);

            scriptCode.append("For Each objProcess in colProcesses").append(CRLF);
            scriptCode.append("objProcess.SetPriority(").append(newPriority).append(")").append(CRLF);
            scriptCode.append("Next").append(CRLF);

            return executeScript(scriptCode.toString());
        } catch (Exception ex) {
            Logger.getLogger(VBScriptHelper.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }
}