text:
from __future__ import absolute_import, unicode_literals

import os

from sphinx_celery import conf

globals().update(conf.build_config(
    'django_celery_results', __file__,
    project='django_celery_results',
    # version_dev='2.0',
    # version_stable='1.4',
    canonical_url='http://django-celery-results.readthedocs.io',
    webdomain='',
    github_project='celery/django-celery-results',
    copyright='2009-2016',
    django_settings='proj.settings',
    include_intersphinx={'python', 'sphinx', 'django', 'celery'},
    path_additions=[os.path.join(os.pardir, 't')],
    extra_extensions=['sphinx.ext.napoleon'],
    html_logo='images/logo.png',
    html_favicon='images/favicon.ico',
    html_prepend_sidebars=[],
    apicheck_ignore_modules=[
        'django_celery_results',
        'django_celery_results.apps',
        'django_celery_results.admin',
        r'django_celery_results.migrations.*',
    ],
))


text:
Tim M. Heneroty:  Senior Financial Analyst | Web Developer with NodeJS, AngularJS, Express, & MongoDB | Hockey Coach

        <address>contact: TH@gmail  ♦ current location    : Pittsburgh, PA 15215  ♦ USA ♦
        </address>

        <ui-view>

Welcome!

Every now & then I use this site as a testing-ground for implementing new web technologies which I discover around the web.  It's also somewhat of a business card or reference point of my contact info and glimpse into my skillset.

Finance

7+ years experience with Fortune 500 companies.

Web Development

Enthusiast web developer, designer, + digital advertiser.

Hockey

15+ years as a hockey coach.
Specialize in goalie instruction.

View Me On LinkedIn

Visit CMC,LLC. Website

Request a Lesson

Finance

        </ui-view>

Finance

        Roles

supply chain finance

P&L management

Forecasting, Planning & Analysis

GL Accounting

Inventory / Cost Accounting

Statistical Modeling + Predicitive Analytics

Business Consulting

Controllership

Capital budgeting

Operational analysis + management

Hockey

        Teaching style includes:

Squareness to the Puck

Depth & Quickness to Angles

Explosive Movement While Down

Strong Backside Recovery

Advanced Post Protection techniques

Visualization + preparation

Video-based performance analysis

Off-ice: speed, strength & coordination training

Natural, healthy, and organic nutrition

Stretching, Yoga, & Pilates

Personal Development

Goal Setting & continual refinement

Tech + Web Development

        Technologies and services include:

NodeJS

AngularJS

Express server

MongoDB

HTML5 + CSS3

Cloud-hosting

Heroku

Google App Engine

Amazon Web Services

Google

Analytics

AdWords / AdSense

Webmaster tools

Places for Business

RESTful Web services

redpajama_set_name: RedPajamaGithub


text:
<?php
return array (
  'Hide file info (name, size) for images on wall' => 'Skrýt informace o souboru pro všechny obrázky ve výpisu příspěvků',
  'Hide file list widget from showing files for these objects on wall.' => '',
  'Maximum preview image height (in pixels, optional)' => '',
  'Maximum preview image width (in pixels, optional)' => '',
  'Allowed file extensions' => 'Povolené přípony souborů',
  'Convert command not found!' => 'Příkaz pro převod nebyl nalezen!',
  'Got invalid image magick response! - Correct command?' => 'Neplatná odpověď programu ImageMagic! – Je příkaz správný?',
  'Image Magick convert command (optional)' => 'Program pro převod ImageMagic (volitelné)',
  'Maximum upload file size (in MB)' => 'Maximální velikost nahrávaného souboru (v MB)',
  'Use X-Sendfile for File Downloads' => 'Pro stahování souborů použít metodu X-Sendfile',
);


text:
package command.grid;

import com.smoothcsv.commons.functions.IntRangeConsumer;
import com.smoothcsv.commons.utils.ArrayUtils;
import com.smoothcsv.core.command.GridCommand;
import com.smoothcsv.core.csvsheet.CsvGridSheetModel;
import com.smoothcsv.core.csvsheet.CsvGridSheetPane;
import com.smoothcsv.core.csvsheet.edits.EditTransaction;
import com.smoothcsv.swing.gridsheet.model.DefaultGridSheetSelectionModel;

/**
 * @author kohii
 */
public class DeleteRowsCommand extends GridCommand {

  @Override
  public void run(CsvGridSheetPane gridSheetPane) {
    run(gridSheetPane, null);
  }

  public void run(CsvGridSheetPane gridSheetPane, int[] selectedRowIndices) {

    gridSheetPane.stopCellEditingIfEditing();

    try (EditTransaction tran = gridSheetPane.transaction()) {

      CsvGridSheetModel model = gridSheetPane.getModel();

      if (selectedRowIndices == null) {
        selectedRowIndices = gridSheetPane.getSelectionModel().getSelectedRows();
      }

      ArrayUtils.processIntArrayAsBlock(new IntRangeConsumer() {
        @Override
        public void accept(int start, int end) {
          model.deleteRow(start, end - start + 1);
        }
      }, selectedRowIndices, true);

      if (model.getRowCount() == 0) {
        // insert empty row if there is no row
        model.insertRow(0, 1);
        model.deleteCell(0, 0, model.getColumnCount() - 1);
      }

      DefaultGridSheetSelectionModel sm = gridSheetPane.getSelectionModel();
      sm.clearHeaderSelection();
      sm.correctSelectionIfInvalid();
    }
  }
}


text:
import os
from PySide import QtCore, QtUiTools

def load_ui_widget(uifilename, parent=None):
    loader = QtUiTools.QUiLoader()
    uifile = QtCore.QFile(os.path.join(os.path.dirname(os.path.abspath(__file__)), uifilename))
    uifile.open(QtCore.QFile.ReadOnly)
    ui = loader.load(uifile, parent)
    uifile.close()
    return ui


text:
import { NgModule }      from '@angular/core';
import { RouterModule,Routes } from '@angular/router';
import {StateDetailComponent} from './state-detail.component';
import {StatesComponent } from './states.component';
import {DashboardComponent} from './dashboard.component';

const routes: Routes =[
        {
    path: 'states',
    component: StatesComponent
        },
        {
  path: '',
  redirectTo: '/dashboard',
  pathMatch: 'full'
},

        {
  path: 'dashboard',
  component: DashboardComponent
},
{
  path: 'detail/:id',
  component: StateDetailComponent
}];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}


text:
package cn.newcapec.jwxt.jcxxgl.model;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * JwxtKqxtKqrz entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name="JWXT_KQXT_KQRZ"
    ,schema="JWXT"
)

public class JwxtKqxtKqrz extends cn.newcapec.function.digitalcampus.common.model.AbstractModel implements java.io.Serializable {

    // Fields

     private String id;
     private String kqrq;
     private Date kssj;
     private Date jssj;
     private String hs;
     private String cjr;
     private String jlssdw;
     private Date whsj;
     private Date cjsj;

    // Constructors

    /** default constructor */
    public JwxtKqxtKqrz() {
    }

	/** minimal constructor */
    public JwxtKqxtKqrz(String id, String kqrq, Date kssj, Date jssj, String cjr, String jlssdw, Date cjsj) {
        this.id = id;
        this.kqrq = kqrq;
        this.kssj = kssj;
        this.jssj = jssj;
        this.cjr = cjr;
        this.jlssdw = jlssdw;
        this.cjsj = cjsj;
    }

    /** full constructor */
    public JwxtKqxtKqrz(String id, String kqrq, Date kssj, Date jssj, String hs, String cjr, String jlssdw, Date whsj, Date cjsj) {
        this.id = id;
        this.kqrq = kqrq;
        this.kssj = kssj;
        this.jssj = jssj;
        this.hs = hs;
        this.cjr = cjr;
        this.jlssdw = jlssdw;
        this.whsj = whsj;
        this.cjsj = cjsj;
    }

    // Property accessors
    @Id

    @Column(name="ID", unique=true, nullable=false, length=32)

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Column(name="KQRQ", nullable=false, length=10)

    public String getKqrq() {
        return this.kqrq;
    }

    public void setKqrq(String kqrq) {
        this.kqrq = kqrq;
    }
    @Temporal(TemporalType.DATE)
    @Column(name="KSSJ", nullable=false, length=7)

    public Date getKssj() {
        return this.kssj;
    }

    public void setKssj(Date kssj) {
        this.kssj = kssj;
    }
    @Temporal(TemporalType.DATE)
    @Column(name="JSSJ", nullable=false, length=7)

    public Date getJssj() {
        return this.jssj;
    }

    public void setJssj(Date jssj) {
        this.jssj = jssj;
    }

    @Column(name="HS", length=10)

    public String getHs() {
        return this.hs;
    }

    public void setHs(String hs) {
        this.hs = hs;
    }

    @Column(name="CJR", nullable=false, length=32)

    public String getCjr() {
        return this.cjr;
    }

    public void setCjr(String cjr) {
        this.cjr = cjr;
    }

    @Column(name="JLSSDW", nullable=false, length=32)

    public String getJlssdw() {
        return this.jlssdw;
    }

    public void setJlssdw(String jlssdw) {
        this.jlssdw = jlssdw;
    }
    @Temporal(TemporalType.DATE)
    @Column(name="WHSJ", length=7)

    public Date getWhsj() {
        return this.whsj;
    }

    public void setWhsj(Date whsj) {
        this.whsj = whsj;
    }
    @Temporal(TemporalType.DATE)
    @Column(name="CJSJ", nullable=false, length=7)

    public Date getCjsj() {
        return this.cjsj;
    }

    public void setCjsj(Date cjsj) {
        this.cjsj = cjsj;
    }

}


text:
from __future__ import absolute_import
from __future__ import print_function

from django.conf import settings
settings.RUNNING_INSIDE_TORNADO = True
# We must call zerver.lib.tornado_ioloop_logging.instrument_tornado_ioloop
# before we import anything else from our project in order for our
# Tornado load logging to work; otherwise we might accidentally import
# zerver.lib.queue (which will instantiate the Tornado ioloop) before
# this.
from zerver.lib.tornado_ioloop_logging import instrument_tornado_ioloop
instrument_tornado_ioloop()

from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
import os
import sys
import tornado.web
import logging
from tornado import ioloop
from zerver.lib.debug import interactive_debug_listen
from zerver.lib.response import json_response
from zerver.lib.event_queue import process_notification, missedmessage_hook
from zerver.lib.event_queue import setup_event_queue, add_client_gc_hook
from zerver.lib.queue import setup_tornado_rabbitmq
from zerver.lib.socket import get_sockjs_router, respond_send_message
from zerver.middleware import async_request_stop

if settings.USING_RABBITMQ:
    from zerver.lib.queue import get_queue_client

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--nokeepalive', action='store_true',
            dest='no_keep_alive', default=False,
            help="Tells Tornado to NOT keep alive http connections."),
        make_option('--noxheaders', action='store_false',
            dest='xheaders', default=True,
            help="Tells Tornado to NOT override remote IP with X-Real-IP."),
    )
    help = "Starts a Tornado Web server wrapping Django."
    args = '[optional port number or ipaddr:port]\n  (use multiple ports to start multiple servers)'

    def handle(self, addrport, **options):
        # setup unbuffered I/O
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
        sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)
        interactive_debug_listen()

        import django
        from tornado import httpserver, web

        try:
            addr, port = addrport.split(':')
        except ValueError:
            addr, port = '', addrport

        if not addr:
            addr = '127.0.0.1'

        if not port.isdigit():
            raise CommandError("%r is not a valid port number." % (port,))

        xheaders = options.get('xheaders', True)
        no_keep_alive = options.get('no_keep_alive', False)
        quit_command = 'CTRL-C'

        if settings.DEBUG:
            logging.basicConfig(level=logging.INFO,
                format='%(asctime)s %(levelname)-8s %(message)s')

        def inner_run():
            from django.conf import settings
            from django.utils import translation
            translation.activate(settings.LANGUAGE_CODE)

            print("Validating Django models.py...")
            self.validate(display_num_errors=True)
            print("\nDjango version %s" % (django.get_version()))
            print("Tornado server is running at http://%s:%s/" % (addr, port))
            print("Quit the server with %s." % (quit_command,))

            if settings.USING_RABBITMQ:
                queue_client = get_queue_client()
                # Process notifications received via RabbitMQ
                queue_client.register_json_consumer('notify_tornado', process_notification)
                queue_client.register_json_consumer('tornado_return', respond_send_message)

            try:
                urls = (r"/notify_tornado",
                        r"/json/get_events",
                        r"/json/events",
                        r"/api/v1/events",
                        )

                # Application is an instance of Django's standard wsgi handler.
                application = web.Application([(url, AsyncDjangoHandler) for url in urls]
                                              + get_sockjs_router().urls,
                                                debug=django.conf.settings.DEBUG,
                                              # Disable Tornado's own request logging, since we have our own
                                              log_function=lambda x: None)

                # start tornado web server in single-threaded mode
                http_server = httpserver.HTTPServer(application,
                                                    xheaders=xheaders,
                                                    no_keep_alive=no_keep_alive)
                http_server.listen(int(port), address=addr)

                if django.conf.settings.DEBUG:
                    ioloop.IOLoop.instance().set_blocking_log_threshold(5)

                setup_event_queue()
                add_client_gc_hook(missedmessage_hook)
                setup_tornado_rabbitmq()
                ioloop.IOLoop.instance().start()
            except KeyboardInterrupt:
                sys.exit(0)

        inner_run()

#
#  Modify the base Tornado handler for Django
#
from threading import Lock
from django.core.handlers import base
from django.core.urlresolvers import set_script_prefix
from django.core import signals

class AsyncDjangoHandler(tornado.web.RequestHandler, base.BaseHandler):
    initLock = Lock()

    def __init__(self, *args, **kwargs):
        super(AsyncDjangoHandler, self).__init__(*args, **kwargs)

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        self._request_middleware = None
        self.initLock.acquire()
        # Check that middleware is still uninitialised.
        if self._request_middleware is None:
            self.load_middleware()
        self.initLock.release()
        self._auto_finish = False
        self.client_descriptor = None

    def get(self):
        from tornado.wsgi import WSGIContainer
        from django.core.handlers.wsgi import WSGIRequest, get_script_name
        import urllib

        environ  = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
        request  = WSGIRequest(environ)
        request._tornado_handler     = self

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            response = self.get_response(request)

            if not response:
                return
        finally:
            signals.request_finished.send(sender=self.__class__)

        self.set_status(response.status_code)
        for h in response.items():
            self.set_header(h[0], h[1])

        if not hasattr(self, "_new_cookies"):
            self._new_cookies = []
        self._new_cookies.append(response.cookies)

        self.write(response.content)
        self.finish()

    def head(self):
        self.get()

    def post(self):
        self.get()

    def delete(self):
        self.get()

    def on_connection_close(self):
        if self.client_descriptor is not None:
            self.client_descriptor.disconnect_handler(client_closed=True)

    # Based on django.core.handlers.base: get_response
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django import http
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                response = None

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                ### ADDED BY ZULIP
                request._resolver = resolver
                ### END ADDED BY ZULIP

                callback, callback_args, callback_kwargs = resolver.resolve(
                        request.path_info)

                # Apply view middleware
                if response is None:
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback, callback_args, callback_kwargs)
                        if response:
                            break

                ### THIS BLOCK MODIFIED BY ZULIP
                if response is None:
                    from ...decorator import RespondAsynchronously

                    try:
                        response = callback(request, *callback_args, **callback_kwargs)
                        if response is RespondAsynchronously:
                            async_request_stop(request)
                            return
                    except Exception as e:
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                if response is None:
                    try:
                        view_name = callback.__name__
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__'
                    raise ValueError("The view %s.%s returned None." %
                                     (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404 as e:
                if settings.DEBUG:
                    from django.views import debug
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        try:
                            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
                        finally:
                            signals.got_request_exception.send(sender=self.__class__, request=request)
            except exceptions.PermissionDenied:
                logging.warning(
                    'Forbidden (Permission denied): %s', request.path,
                    extra={
                        'status_code': 403,
                        'request': request
                    })
                try:
                    callback, param_dict = resolver.resolve403()
                    response = callback(request, **param_dict)
                except:
                    try:
                        response = self.handle_uncaught_exception(request,
                            resolver, sys.exc_info())
                    finally:
                        signals.got_request_exception.send(
                            sender=self.__class__, request=request)
            except SystemExit:
                # See https://code.djangoproject.com/ticket/4701
                raise
            except Exception as e:
                exc_info = sys.exc_info()
                signals.got_request_exception.send(sender=self.__class__, request=request)
                return self.handle_uncaught_exception(request, resolver, exc_info)
        finally:
            # Reset urlconf on the way out for isolation
            urlresolvers.set_urlconf(None)

        ### ZULIP CHANGE: The remainder of this function was moved
        ### into its own function, just below, so we can call it from
        ### finish().
        response = self.apply_response_middleware(request, response, resolver)

        return response

    ### Copied from get_response (above in this file)
    def apply_response_middleware(self, request, response, resolver):
        try:
            # Apply response middleware, regardless of the response
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        except: # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        return response

    def zulip_finish(self, response, request, apply_markdown):
        # Make sure that Markdown rendering really happened, if requested.
        # This is a security issue because it's where we escape HTML.
        # c.f. ticket #64
        #
        # apply_markdown=True is the fail-safe default.
        if response['result'] == 'success' and 'messages' in response and apply_markdown:
            for msg in response['messages']:
                if msg['content_type'] != 'text/html':
                    self.set_status(500)
                    return self.finish('Internal error: bad message format')
        if response['result'] == 'error':
            self.set_status(400)

        # Call the Django response middleware on our object so that
        # e.g. our own logging code can run; but don't actually use
        # the headers from that since sending those to Tornado seems
        # tricky; instead just send the (already json-rendered)
        # content on to Tornado
        django_response = json_response(res_type=response['result'],
                                        data=response, status=self.get_status())
        django_response = self.apply_response_middleware(request, django_response,
                                                         request._resolver)
        # Pass through the content-type from Django, as json content should be
        # served as application/json
        self.set_header("Content-Type", django_response['Content-Type'])
        return self.finish(django_response.content)


text:
"use strict";

/**
 * Module dependencies.
 */

var _ = require("lodash")
  , chalk = require("chalk")
  ;

module.exports = function(vantage, options) {

  var users
    , connections = {}
    ;

  options = _.defaults((options || {}), {
    users: [],
    deny: void 0,
    unlockTime: void 0
  });

  if (options.users.length < 1) {
    throw new Error("Vantage basic authentication cannot be called without passing in at least one user into the options parameter.");
  }

  users = options.users.map(function(cred){
    var user = cred.user || cred.username
      , pass = cred.pass || cred.password || cred.secret
      ;
    if (!user) {
      throw new Error("Vantage basic authentication: no 'user' string was passed in a submitted user: " + JSON.stringify(cred));
    }
    if (!pass) {
      throw new Error("Vantage basic authentication: no 'pass' string was passed in a submitted user: " + JSON.stringify(cred));
    }
    return ({
      user: user,
      pass: pass
    });
  });

  var strategy = function(args, callback) {

    var self = this
      , deny = (options.deny === 0) ? 0 : (options.deny || 3)
      , unlockTime = (options.unlockTime || 30000)
      , retry = (options.retry === 0) ? 0 : (options.retry || 3)
      , retryTime = (options.retryTime || 1000)
      , handshake = (args.handshake)
      , host = ((handshake) ? handshake.host : void 0)
      , port = ((handshake) ? handshake.port : void 0)
      , id = host + ":" + port
      , questions = [{
          type: "input",
          name: "answer",
          message: chalk.white("login as:")
        }, {
          type: "password",
          name: "answer",
          message: chalk.white("password:")
        }]
      , state = {
          user: args.user || void 0,
          pass: args.pass || void 0
        }
      ;

    connections[id] = connections[id] || {
      attempts: 0,
      deny: 0
    };

    if (!handshake) {
      callback("Access denied: no connection handshake.", false);
      return;
    }

    if (!host) {
      callback("Access denied: no host specified in connection handshake.", false);
      return;
    }

    // Check if submitted user matches anything.
    function search(user, pass, userArray) {
      return _.findWhere(userArray, { user: user, pass: pass });
    }

    // If a value is given, skip, otherwise
    // prompt user for data.
    function ask(question, cbk, skip) {
      if (skip) {
        cbk(skip);
        return;
      }
      self.prompt(question, function(answ) {
        if (String(answ.answer).trim() === "") {
          return ask(question, cbk);
        } else {
          cbk(answ.answer);
        }
      });
    }

    // Ask for a user and password.
    // If a user is passed in, just ask for
    // a password and skip the user.
    function gather(cbk) {
      ask(questions[0], function(user) {
        state.user = user;
        ask(questions[1], function(pass){
          state.pass = pass;
          cbk(state.user, state.pass);
        }, state.pass);
      }, state.user);
    }

    // Authentication attempt logic,
    // including adding up retry and
    // deny counts, etc.
    function attempt() {
      connections[id].attempts++;
      if (connections[id].attempts > retry) {
        connections[id].attempts = 0;
        connections[id].deny++;
        self.log(chalk.yellow("Access denied: too many attempts."));
        callback("Access denied: too many attempts.", false);
        return;
      }
      if (connections[id].deny >= deny && unlockTime > 0) {
        setTimeout(function(){
          connections[id].deny = 0;
        }, unlockTime);
        connections[id].attempts = 0;
        self.log(chalk.yellow("Account locked out: too many login attempts."));
        callback("Account locked out: too many login attempts.", false);
        return;
      }
      gather(function(user, pass){
        user = search(user, pass, users);
        if (user) {
          connections[id].attempts = 0;
          connections[id].deny = 0;
          callback("Successfully Authenticated.", true);
        } else {
          state.pass = void 0;
          setTimeout(function(){
            if (connections[id].attempts <= retry) {
              self.log("Access denied.");
            }
            attempt();
          }, retryTime);
        }
      });
    }

    attempt();

  };

  return strategy;
};


text:
FactoryGirl.define do

  factory :person do
    sequence(:name) { |n| "Person Name #{n}" }
  end

end


text:
class RenameSitesToProjects < ActiveRecord::Migration
  def change
    rename_table :sites, :projects
  end
end


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ObjectPool : MonoBehaviour
{
    public RecycleGameObject prefab;

    private List<RecycleGameObject> poolInstances = new List<RecycleGameObject>();

    public int count = 0;

    void Awake()
    {
        gameObject.isStatic = true;
    }

    private RecycleGameObject CreateInstance(Vector3 pos)
    {
        RecycleGameObject clone = GameObject.Instantiate(prefab);
        clone.transform.position = pos;
        clone.transform.parent = transform;

        poolInstances.Add(clone);

        return clone;
    }

    public RecycleGameObject NextObject(Vector3 pos)
    {
        RecycleGameObject instance = null;

        foreach (RecycleGameObject go in poolInstances)
        {
            if (go.gameObject.activeSelf != true)
            {
                instance = go;
                instance.transform.position = pos;
            }
        }

        if (instance == null)
            instance = CreateInstance(pos);

        instance.Restart();

        return instance;
    }
}


text:
title: "2016-05-03のJS: Node.js 6.0.0、GitHub Fetch 1.0.0、-webkit- prefixのポリシー"
author: azu
layout: post
date : 2016-05-03T22:50
category: JSer
tags:
    - Node.js
    - Fetch
    - WebKit
    - polyfill

---

JSer.info #277 - [Node v6.0.0](https://nodejs.org/en/blog/release/v6.0.0/)がリリースされました。

- [Node.js v6.0 (Current) がリリースされました。 - from scratch](http://yosuke-furukawa.hatenablog.com/entry/2016/04/27/110027 "Node.js v6.0 (Current) がリリースされました。 - from scratch")

6.xは[long term support (LTS)](https://medium.com/@nodesource/essential-steps-long-term-support-for-node-js-8ecf7514dbd "long term support (LTS)")となるバージョンなので、LTSではない5.xを使っている人はアップデートが推奨されています。
4.xはLTSなので、2017年4月までサポートされます。

6.0.0では[Node v5.10.0](https://nodejs.org/en/blog/release/v5.10.0/ "Node v5.10.0")にもバックポートされたBuffer APIの変更や、
[V8 5.0](http://v8project.blogspot.jp/2016/03/v8-release-50.html)へのアップデートにより、ES6の93%(Moduleを除く)が利用できるようになっています。

------

[Fetch API](https://fetch.spec.whatwg.org/ "Fetch API")のpolyfillである[github/fetch](https://github.com/github/fetch "github/fetch") 1.0.0がリリースされました。

- [Release Fetch 1.0.0 · github/fetch](https://github.com/github/fetch/releases/tag/v1.0.0)

IE9のサポートが終了され、`URLSearchParams`のサポートの追加などがされています。

----

[Updating Our Prefixing Policy | WebKit](https://webkit.org/blog/6131/updating-our-prefixing-policy/)という記事では、WebKit/Safariの実験的prefixに関するポリシーの変更が書かれています。

詳細は以下に書かれていますが、今後は新しい機能を導入する際はChromeやFirefoxのようにランタイムフラグ制に変更されます。

- [Feature Policy | WebKit](https://webkit.org/feature-policy/ "Feature Policy | WebKit")

今まで、`-webkit-` prefixで新機能を導入し、それがあまりにもウェブサイトで使われた結果、ブラウザの実装から`-webkit-`を無くすとBreak the webとなる問題が多く発生していました。
`-webkit-transform-3d`のように[互換仕様としてウェブ標準に`-webkit` prefix](https://miketaylr.com/posts/2016/01/at-media-webkit-transform-three-dee.html)が存在します。

- [Webkit! RESOLVED FIXED - otsukare](http://www.otsukare.info/2016/01/04/webkit-resolved-fixed "Webkit! RESOLVED FIXED - otsukare")

そのため、ブラウザの設定から有効にしないと新しい機能が利用できない**runtime flags**へと変更されました。

----

ヘッドライン

----

## Node v6.0.0 (Current) | Node.js
[nodejs.org/en/blog/release/v6.0.0/](https://nodejs.org/en/blog/release/v6.0.0/ "Node v6.0.0 (Current) | Node.js")

node.js ReleaseNote

Node.js 6.0.0(LTS)リリース。
v8のアップデートを含むため、Native addonは`npm rebuid`での再ビルドが必要。
Buffer APIが新しくなり、古いAPIは非推奨へ、`worker.suicide`は`worker.exitedAfterDisconnect`に変更、`querystring.parse()`が返すオブジェクトは`Object.prototype`を継承しないようになるなど

- [Node.js v6.0 (Current) がリリースされました。 - from scratch](http://yosuke-furukawa.hatenablog.com/entry/2016/04/27/110027 "Node.js v6.0 (Current) がリリースされました。 - from scratch")

----

## Chromium Blog: Chrome 51 Beta: Credential Management API and reducing the overhead of offscreen rendering
[blog.chromium.org/2016/04/chrome-51-beta-credential-management.html](http://blog.chromium.org/2016/04/chrome-51-beta-credential-management.html "Chromium Blog: Chrome 51 Beta: Credential Management API and reducing the overhead of offscreen rendering")

Chrome ReleaseNote

Chrome 51 Betaリリース。
Credential Management APIのサポート。
offscreenの場合、crosss originのframeにおいては`requestAnimationFrame()`が呼ばれないように、Intersection Observer 、`passive`イベントオプション、V8 5.1へのアップデートなど。

- [V8 JavaScript Engine: V8 Release 5.1](http://v8project.blogspot.jp/2016/04/v8-release-51.html "V8 JavaScript Engine: V8 Release 5.1")
- [IntersectionObserver/explainer.md at gh-pages · WICG/IntersectionObserver](https://github.com/WICG/IntersectionObserver/blob/gh-pages/explainer.md "IntersectionObserver/explainer.md at gh-pages · WICG/IntersectionObserver")
- [Throttling Blink's rendering pipeline for hidden content](https://docs.google.com/document/d/1Dd4qi1b_iX-OCZpelvXxizjq6dDJ76XNtk37SZEoTYQ/pub "Throttling Blink's rendering pipeline for hidden content")
- [Power usage impact of render pipeline throttling - Google ドキュメント](https://docs.google.com/document/d/1jMuvRYWptZfP5zpvWmPJPRL-iowtgBVX45rSvew0VH4/edit "Power usage impact of render pipeline throttling - Google ドキュメント")

----

## Release v6.8.0 · babel/babel
[github.com/babel/babel/releases/tag/v6.8.0](https://github.com/babel/babel/releases/tag/v6.8.0 "Release v6.8.0 · babel/babel")

babel ReleaseNote

Babel v6.8.0リリース。
Babel自体がBabel 6でTranspileするようになり、runtimeが5に依存していた問題が修正された

----

## Release Fetch 1.0.0 · github/fetch
[github.com/github/fetch/releases/tag/v1.0.0](https://github.com/github/fetch/releases/tag/v1.0.0 "Release Fetch 1.0.0 · github/fetch")

JavaScript htto library

Fetch APIのpolyfillであるGitHub Fetch 1.0.0リリース。
IE9のサポートを終了、`timeout`イベントをハンドルするように、`URLSearchParams`のサポートなど

----

## ESLint v2.9.0 released - ESLint - Pluggable JavaScript linter
[eslint.org/blog/2016/04/eslint-v2.9.0-released](http://eslint.org/blog/2016/04/eslint-v2.9.0-released "ESLint v2.9.0 released - ESLint - Pluggable JavaScript linter")

JavaScript Tools ReleaseNote

ESLint v2.9.0リリース。
Autofix `--fix` オプションの改善。
今までは一度のパスで適応できないものは諦めていたが、複数回のパスで修正を適応を試みるようになった。

- [ESLint v2.9.0 - Qiita](http://qiita.com/mysticatea/items/1d377b67465664009ad5 "ESLint v2.9.0 - Qiita")

----

## Release SlimerJS 0.10.0 · laurentj/slimerjs
[github.com/laurentj/slimerjs/releases/tag/0.10.0](https://github.com/laurentj/slimerjs/releases/tag/0.10.0 "Release SlimerJS 0.10.0 · laurentj/slimerjs")

firefox ReleaseNote

Firefox版のPhantomJS APIの互換実装であるSlimerJS 0.10.0リリース。

----

## Release Notes for Safari Technology Preview 3 | WebKit
[webkit.org/blog/6143/release-notes-for-safari-technology-preview-3/](https://webkit.org/blog/6143/release-notes-for-safari-technology-preview-3/ "Release Notes for Safari Technology Preview 3 | WebKit")

safari ReleaseNote

Safari Technology Preview 3リリース。
`Symbol.isConcatSpreadable`などのwell-known Symbol実装の追加、
`:host()`擬似クラス、IndexedDBが`Blob`をサポート、`Crypto`、CSP周りの仕様準拠度の向上など

----

アーティクル

----

## Scroll-linked effects - Mozilla | MDN
[developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked\_effects](https://developer.mozilla.org/en-US/docs/Mozilla/Performance/Scroll-linked_effects "Scroll-linked effects - Mozilla | MDN")

JavaScript document

`onscroll`にhookして同期的に位置を変更する処理に対しては警告メッセージが出るようになった。
その場合の対処法についてのドキュメント

- [スクロール連動位置合わせは非同期スクロールと相性が悪い場合があり、コンソールに警告が表示されます | Firefox サイト互換性情報](https://www.fxsitecompat.com/ja/docs/2016/scroll-linked-positioning-effects-may-not-work-well-with-async-scrolling-console-warns/ "スクロール連動位置合わせは非同期スクロールと相性が悪い場合があり、コンソールに警告が表示されます | Firefox サイト互換性情報")

----

## Announcing Vue.js 2.0 — The Vue Point — Medium
[medium.com/the-vue-point/announcing-vue-js-2-0-8af1bde7ab9](https://medium.com/the-vue-point/announcing-vue-js-2-0-8af1bde7ab9 "Announcing Vue.js 2.0 — The Vue Point — Medium")

JavaScript DOM library

Vue.js 2.0のパブリックプレビュー版リリース。
SnabbdomベースのVirtua lDOM実装の追加など

- [paldepind/snabbdom: A virtual DOM library with focus on simplicity, modularity, powerful features and performance.](https://github.com/paldepind/snabbdom "paldepind/snabbdom: A virtual DOM library with focus on simplicity, modularity, powerful features and performance.")

----

## Updating Our Prefixing Policy | WebKit
[webkit.org/blog/6131/updating-our-prefixing-policy/](https://webkit.org/blog/6131/updating-our-prefixing-policy/ "Updating Our Prefixing Policy | WebKit")

webkit safari

Safari/WebKitは新しい機能などは今後Vendor prefixではなく、フラグのON/OFFを追加していくようにするポリシーの変更について。
`-webkit-` prefixがあまりに使われてしまい、後方互換性のためにprefixが標準仕様となってしまった歴史などもあるため

- [Feature Policy | WebKit](https://webkit.org/feature-policy/ "Feature Policy | WebKit")

----

## How to Make Your React Apps 15x Faster – ReactJS News
[reactjsnews.com/how-to-make-your-react-apps-10x-faster](https://reactjsnews.com/how-to-make-your-react-apps-10x-faster "How to Make Your React Apps 15x Faster – ReactJS News")

React 設定

Reactはデバッグ向けのコードが大量に入っているため、production(`NODE_ENV=production`)ビルドや機械的に最適化できるBabelプラグインを導入するだけでも速度が大分変わるという話

- [thejameskyle/babel-react-optimize: A Babel preset and plugins for optimizing React code.](https://github.com/thejameskyle/babel-react-optimize "thejameskyle/babel-react-optimize: A Babel preset and plugins for optimizing React code.")

----

## V8 JavaScript Engine: ES6, ES7, and beyond
[v8project.blogspot.com/2016/04/es6-es7-and-beyond.html](http://v8project.blogspot.com/2016/04/es6-es7-and-beyond.html "V8 JavaScript Engine: ES6, ES7, and beyond")

ECMAScript V8 JavaScript

V8が既存のウェブとの互換性を持ちつつ次期ECMAScriptの仕様を実装しているかのプロセスについて。
ES6の実装が完了する前にドラフトバージョンを実装することで見つけられる後方互換性の問題がある話。
またECMAScriptという複雑な言語仕様のtest suiteであるtest262について。

----

## npmで同じライブラリの複数バージョンをインストールして使う方法 | Web Scratch
[efcl.info/2016/05/02/npm-package-mixed-multiple-versions-demo/](http://efcl.info/2016/05/02/npm-package-mixed-multiple-versions-demo/ "npmで同じライブラリの複数バージョンをインストールして使う方法 | Web Scratch")

npm Tips node.js JavaScript

一つのプロジェクト内に同名ライブラリの複数バージョンをインストールして扱う方法について

----

## A look at ES6 Maps - Barbarian Meets Coding
[www.barbarianmeetscoding.com/blog/2016/04/27/a-look-at-es6-maps](http://www.barbarianmeetscoding.com/blog/2016/04/27/a-look-at-es6-maps "A look at ES6 Maps - Barbarian Meets Coding")

JavaScript ECMAScript

ES6 Mapについての解説。
データ構造としてのMap、Iterableについて

----

## Turbocharged JavaScript refactoring with codemods — Airbnb Engineering & Data Science — Medium
[medium.com/airbnb-engineering/turbocharged-javascript-refactoring-with-codemods-b0cae8b326b9](https://medium.com/airbnb-engineering/turbocharged-javascript-refactoring-with-codemods-b0cae8b326b9 "Turbocharged JavaScript refactoring with codemods — Airbnb Engineering & Data Science — Medium")

JavaScript Tools

codemodを使ったリファクタリングについて

----

スライド、動画関係

----

## Almin.js | JavaScriptアーキテクチャ
[azu.github.io/slide/2016/child\_process\_sushi/almin-javascript-architecture.html](http://azu.github.io/slide/2016/child_process_sushi/almin-javascript-architecture.html "Almin.js | JavaScriptアーキテクチャ")

JavaScript スライド

[Almin.js](https://github.com/almin/almin "Almin.js")の設計の概念的な話やパターンについて。
FluxやCQRSといったパターンにおいて、ドメインモデルをどうやったら考えて実装できるようになるかという話。

----

サイト、サービス、ドキュメント

----

## Diffee Checker
[una.im/diffee/](http://una.im/diffee/ "Diffee Checker")

CSS

CSS blend modesを使いiframe同士の描画結果の差分を表示するデモ

----

ソフトウェア、ツール、ライブラリ関係

----

## Galooshi/import-js: A tool to simplify importing JS modules
[github.com/Galooshi/import-js](https://github.com/Galooshi/import-js "Galooshi/import-js: A tool to simplify importing JS modules")

JavaScript Tools editor

指定した関数名から、該当するモジュールのimport文を自動的に探索して追加できるツール。
各種エディタ連携などもある

----

## ericholiveira/studio: A nodejs framework to create decoupled and scalable applications
[github.com/ericholiveira/studio](https://github.com/ericholiveira/studio "ericholiveira/studio: A nodejs framework to create decoupled and scalable applications")

node.js

ActorモデルインスパイアなNode.jsのフレームワーク

----

## flickr/yakbak: Record and playback HTTP responses
[github.com/flickr/yakbak](https://github.com/flickr/yakbak "flickr/yakbak: Record and playback HTTP responses")

node.js HTTP testing library

ProxyとしてHTTPリクエストとレスポンスを記録し、リプレイしたレスポンスを返すことができるNode.jsライブラリ

- [Introducing yakbak: Record and playback HTTP interactions in NodeJS | code.flickr.com](http://code.flickr.net/2016/04/25/introducing-yakbak-record-and-playback-http-interactions-in-nodejs/ "Introducing yakbak: Record and playback HTTP interactions in NodeJS | code.flickr.com")

----

## jeromeetienne/babel-plugin-jsdoced: babel plugin which use jsdoc to implement strong typing in javascript
[github.com/jeromeetienne/babel-plugin-jsdoced](https://github.com/jeromeetienne/babel-plugin-jsdoced "jeromeetienne/babel-plugin-jsdoced: babel plugin which use jsdoc to implement strong typing in javascript")

babel JSDoc plugin

jsdoced.jsを使いJSDocからランタイムassertを追加するBabelプラグイン。
jsdoc-to-assertと似てるが、返り値のチェックやProxy APIを使ってプロパティの代入もチェックしている

- [jsdoced.js - test your code with jsdoc](http://jsdocedjs.org/ "jsdoced.js - test your code with jsdoc")
- [JSDocをランタイムassertに変換するBabelプラグインを書いた | Web Scratch](http://efcl.info/2016/03/25/jsdoc-to-assert/ "JSDocをランタイムassertに変換するBabelプラグインを書いた | Web Scratch")

----


text:
AxisInputSignal::AxisInputSignal(InputDevice* device, QString name, QString description) :
		_settings(PSettingsManager::instance()),
		InputSignal(device, name, description)
{
	QVariantMap calibrationConfig = calibration();
	_centerValue = calibrationConfig.value("centerValue", 0).toDouble();
	_deadZone = calibrationConfig.value("deadZone", 0).toDouble();
	_maxValue = calibrationConfig.value("maxValue", 1).toDouble();
	_minValue = calibrationConfig.value("minValue", -1).toDouble();
} // end AxisInputSignal

const InputSignal::Type AxisInputSignal::type() const
{
	return InputSignal::AXIS;
} // end type

float AxisInputSignal::centerValue() const
{
	return _centerValue;
} // end centerValue

float AxisInputSignal::deadZone() const
{
	return _deadZone;
} // end deadZone

float AxisInputSignal::maxValue() const
{
	return _maxValue;
} // end maxValue

float AxisInputSignal::minValue() const
{
	return _minValue;
} // end minValue

QVariantMap AxisInputSignal::calibration() const
{
	return device()->config()["calibration"]
			.toMap()[name()]
			.toMap();
} // end calibration

void AxisInputSignal::setCenterValue(float value)
{
	_centerValue = value;
} // end setCenterValue

void AxisInputSignal::setDeadZone(float value)
{
	_deadZone = value;
} // end setDeadZone

void AxisInputSignal::setMaxValue(float value)
{
	_maxValue = value;
} // end setMaxValue

void AxisInputSignal::setMinValue(float value)
{
	_minValue = value;
} // end setMinValue

void AxisInputSignal::emitUpdated(float position)
{
	position -= _centerValue;

	float max = _maxValue;

	if(position < 0)
	{
		position *= -1;
		max = _minValue;
	} // end if

	if(position < _deadZone)
	{
		position = 0;
	}
	else
	{
		position -= _deadZone;
		position /= max;
	} // end if

	emit updated(position);
} // end emitUpdated


text:
#include "OgreShaderFFPTransform.h"
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
#include "OgreShaderFFPRenderState.h"
#include "OgreShaderProgram.h"
#include "OgreShaderParameter.h"
#include "OgreShaderProgramSet.h"
#include "OgreMaterialSerializer.h"

namespace Ogre {
namespace RTShader {

/************************************************************************/
/*                                                                      */
/************************************************************************/
String FFPTransform::Type = "FFP_Transform";

//-----------------------------------------------------------------------
const String& FFPTransform::getType() const
{
    return Type;
}

//-----------------------------------------------------------------------
int FFPTransform::getExecutionOrder() const
{
    return FFP_TRANSFORM;
}

//-----------------------------------------------------------------------
bool FFPTransform::createCpuSubPrograms(ProgramSet* programSet)
{
    Program* vsProgram = programSet->getCpuVertexProgram();
    Function* vsEntry = vsProgram->getEntryPointFunction();

    // Resolve World View Projection Matrix.
    UniformParameterPtr wvpMatrix = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX, 0);

    // Resolve input position parameter.
    ParameterPtr positionIn = vsEntry->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);

    // Resolve output position parameter.
    ParameterPtr positionOut = vsEntry->resolveOutputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_PROJECTIVE_SPACE, GCT_FLOAT4);

    if (!(wvpMatrix.get()) || !(positionIn.get()) || !(positionOut.get()))
    {
        OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR,
                "Not all parameters could be constructed for the sub-render state.",
                "FFPTransform::createCpuSubPrograms" );
    }

    // Add dependency.
    vsProgram->addDependency(FFP_LIB_TRANSFORM);

    FunctionInvocation* transformFunc = OGRE_NEW FunctionInvocation(FFP_FUNC_TRANSFORM,  FFP_VS_TRANSFORM, 0);

    transformFunc->pushOperand(wvpMatrix, Operand::OPS_IN);
    transformFunc->pushOperand(positionIn, Operand::OPS_IN);
    transformFunc->pushOperand(positionOut, Operand::OPS_OUT);

    vsEntry->addAtomInstance(transformFunc);

    return true;
}

//-----------------------------------------------------------------------
void FFPTransform::copyFrom(const SubRenderState& rhs)
{

}

//-----------------------------------------------------------------------
const String& FFPTransformFactory::getType() const
{
    return FFPTransform::Type;
}

//-----------------------------------------------------------------------
SubRenderState* FFPTransformFactory::createInstance(ScriptCompiler* compiler,
                                                   PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)
{
    if (prop->name == "transform_stage")
    {
        if(prop->values.size() == 1)
        {
            String modelType;

            if(false == SGScriptTranslator::getString(prop->values.front(), &modelType))
            {
                compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                return NULL;
            }

            if (modelType == "ffp")
            {
                return createOrRetrieveInstance(translator);
            }
        }
    }

    return NULL;
}

//-----------------------------------------------------------------------
void FFPTransformFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState,
                                       Pass* srcPass, Pass* dstPass)
{
    ser->writeAttribute(4, "transform_stage");
    ser->writeValue("ffp");
}

//-----------------------------------------------------------------------
SubRenderState* FFPTransformFactory::createInstanceImpl()
{
    return OGRE_NEW FFPTransform;
}

}
}

#endif


text:
describe('Court Musician', function() {
    integration(function() {
        describe('Court Musician\'s ability for regular actions', function() {
            beforeEach(function () {
                this.setupTest({
                    phase: 'conflict',
                    player1: {
                        inPlay: ['solemn-scholar'],
                        hand: ['bayushi-kachiko', 'against-the-waves', 'clarity-of-purpose'],
                        fate: 10
                    },
                    player2: {
                        inPlay: ['court-musician'],
                        hand: ['earth-becomes-sky', 'mirumoto-daisho', 'festival-for-the-fortunes'],
                        fate: 10
                    }
                });

                this.solemn = this.player1.findCardByName('solemn-scholar');
                this.kachiko = this.player1.findCardByName('bayushi-kachiko');
                this.againstTheWaves = this.player1.findCardByName('against-the-waves');
                this.clarity = this.player1.findCardByName('clarity-of-purpose');

                this.courtMusician = this.player2.findCardByName('court-musician');
                this.ebs = this.player2.findCardByName('earth-becomes-sky');
                this.daisho = this.player2.findCardByName('mirumoto-daisho');
                this.festival = this.player2.findCardByName('festival-for-the-fortunes');

                this.noMoreActions();
                this.initiateConflict({
                    type: 'political',
                    attackers: [this.solemn],
                    defenders: [this.courtMusician]
                });

                this.solemn.bowed = true;
            });

            it('should decrease the cost of the next actions by each player by 1. (event/attachment)', function () {
                this.player2.clickCard(this.courtMusician);

                this.player1.clickCard(this.clarity);
                this.player1.clickCard(this.solemn);

                expect(this.player1.fate).toBe(10);

                this.player2.clickCard(this.daisho);
                this.player2.clickCard(this.courtMusician);

                expect(this.player2.fate).toBe(9);

                this.player1.clickCard(this.kachiko);
                this.player1.clickPrompt('0');
                this.player1.clickPrompt('Conflict');

                expect(this.player1.fate).toBe(5);

                this.player2.clickCard(this.festival);

                expect(this.player2.fate).toBe(6);
            });

            it('should decrease the cost of the next actions by each player by 1. (conflict character)', function () {
                this.player2.clickCard(this.courtMusician);

                this.player1.clickCard(this.kachiko);
                this.player1.clickPrompt('0');
                this.player1.clickPrompt('Conflict');

                expect(this.player1.fate).toBe(6);

                this.player2.clickCard(this.festival);
                this.player2.clickCard(this.courtMusician);

                expect(this.player2.fate).toBe(8);
            });

            it('should also decrease the cost of any interrupts/reactions during the next action opportunities by each player by 1.', function () {
                this.player2.clickCard(this.courtMusician);

                this.player1.clickCard(this.againstTheWaves);
                this.player1.clickCard(this.solemn);
                expect(this.player1.fate).toBe(10);
                this.player2.clickCard(this.ebs);
                expect(this.player2.fate).toBe(10);

                expect(this.solemn.bowed).toBe(true);
                expect(this.player2).toHavePrompt('Conflict Action Window');
            });
        });
    });
});


text:
import time
from datetime import datetime
import logging
import os.path
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from github_analysis_tool.github_parser.requester import GitHubRequester
from github_analysis_tool.services.database_service import DatabaseService
from github_analysis_tool.services.db_column_constants import Columns
from github_analysis_tool import OUTPUT_DIR

class GitHubHarvester:
    """
    End point for harvesting GitHub API
    """
    def __init__(self):
        # Generate a github_requester with imported GitHub tokens
        self.__requester = GitHubRequester()
        self.__databaseService = DatabaseService()
        logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG,
                            filename=os.path.join(OUTPUT_DIR, "github_parser_log.log"))

    def fetch_repo(self, owner, repo, since_date=None, until_date=None, force_fetch=False):
        repo_url = "https://api.github.com/repos/" + owner + "/" + repo
        time_param = self.__build_time_parameter_string(since_date, until_date)
        res = self.__requester.make_request(repo_url)

        if res.status_code == 200:  # API has responded with OK status
            repo = res.json()
            repo_id = repo['id']
            if repo["language"] is None:
                print("Project language is none, skipped.")
                logging.info("Project language is none, skipped.")
                return
            user_login = repo["owner"]["login"]
            if not self.__databaseService.check_if_github_user_exists(user_login):
                self.__retrieve_user(user_login)
            self.__databaseService.insert_repo(repo)
        else:  # Request gave an error
            print("Error while retrieving: " + repo_url)
            print("Status code: " + str(res.status_code))
            logging.info("Error while rertieving :" + str(repo_url) + "Status code: " + str(res.status_code))
            return

        if not force_fetch and self.__databaseService.check_if_repo_filled(repo_id):
            # Repo filled before so i can skip it now
            print("Repo already fetched: " + repo_url)
            logging.info("Repo already fetched: " + repo_url)
            return

        print("---> Fetching: " + repo_url)
        logging.info("---> Fetching: " + repo_url)
        # Repo can be new as it's first info
        start_time_string = str(datetime.now())
        start_time = time.time()
        #self.__retrieve_issues_of_repo(repo_url, repo_id)
        self.__retrieve_commits_of_repo(repo_url, repo_id, time_param)
        #self.__retrieveIssuesofRepo(repo_url, repo_id)
        # Let's mark the repo as filled with time which is beginning of fetching
        self.__databaseService.set_repo_filled_at(repo_id, start_time_string)
        elapsed_time = time.time() - start_time
        print("---> " + repo_url + " fetched in " + str(elapsed_time) + " seconds.")
        logging.info("---> " + repo_url + " fetched in " + str(elapsed_time) + " seconds.")
        return

    def fetch_repos(self, min_stars, since_date=None, until_date=None, force_fetch=False):
        #self.__retrieve_repos(min_stars)

        repos = self.__databaseService.get_repo_urls()
        for repo in repos:
            repo_url = repo[Columns.Repo.url]
            if repo_url == "https://api.github.com/repos/torvalds/linux":
                continue

            repo_id = repo[Columns.Repo.id]

            print("---> Fetching: " + repo_url)
            logging.info("---> Fetching: " + repo_url)
            # Repo can be new as it's first info
            start_time_string = str(datetime.now())
            start_time = time.time()

            if repo[Columns.Repo.filled_at] is not None and force_fetch is False:
                repo_filled_at = repo[Columns.Repo.filled_at]
                print("---> Repo: " + repo_url + " has some data in it, starting from this time: " + str(repo_filled_at))
                logging.info("---> Repo: " + repo_url + " has some data in it, starting from this time: " + str(repo_filled_at))
                repo_filled_at_str = str(repo_filled_at).split()
                repo_filled_at_string = repo_filled_at_str[0] + "T" + repo_filled_at_str[1] + "Z"
                time_param = self.__build_time_parameter_string(repo_filled_at_string, until_date)
            else:
                time_param = self.__build_time_parameter_string(since_date, until_date)

            #self.__retrieve_issues_of_repo(repo_url, repo_id)
            self.__retrieve_commits_of_repo(repo_url, repo_id, time_param)

            # Let's mark the repo as filled with time which is beginning of fetching
            self.__databaseService.set_repo_filled_at(repo_id, start_time_string)
            elapsed_time = time.time() - start_time
            print("---> " + repo_url + " fetched in " + str(elapsed_time) + " seconds.")
            logging.info("---> " + repo_url + " fetched in " + str(elapsed_time) + " seconds.")

    def __retrieve_repos(self, stars_count):
        request_url = "https://api.github.com/search/repositories?q=stars:>" + str(stars_count) + "&page=1&per_page=100"
        res = self.__requester.make_request(request_url)
        print("Started retriving projects")
        logging.info("Started retriving projects")
        if res.status_code == 200: # API has responded with OK status
            return_json = res.json()
            if res.links:
                index_start = res.links["last"]["url"].find("page=")
                index_end = res.links["last"]["url"].find("&per_page")
                last = res.links["last"]["url"][index_start+5:index_end]
            else:
                last = 1

            for i in range(1, int(last)+1):
                print("Repositories: " + str(i))
                logging.info("Repositories: " + str(i))
                _requestURL = "https://api.github.com/search/repositories?q=stars:>" + str(stars_count) + "&page=" + str(i) + "&per_page=100"
                res = self.__requester.make_request(_requestURL)
                return_json = res.json()

                for project in return_json["items"]:
                    if project["language"] is None:
                        continue
                    user_login = project["owner"]["login"]
                    if not self.__databaseService.check_if_github_user_exists(user_login):
                        self.__retrieve_user(user_login)
                    self.__databaseService.insert_repo(project)
        else: # Request gave an error
            print("Error while retrieving: " + request_url)
            print("Status code: " + str(res.status_code))
        print("Finished retrieving projects")
        return

    def __retrieve_user(self, user_login):
        user_url = "https://api.github.com/users/" + user_login
        res = self.__requester.make_request(user_url)
        user_data = res.json()
        if res.status_code == 200:  # API has responded with OK status
            self.__databaseService.insert_github_user(user_data)
        else:  # Request gave an error
            print("Error while retrieving: " + user_url)
            print("Status code: " + str(res.status_code))
            logging.info("Error while rertieving :" + str(user_url) + "Status code: " + str(res.status_code))

        return

    def __retrieve_commits_of_repo(self, repo_url, repo_id, since):
        print("Retrieving commits from " + repo_url)
        logging.info("Retrieving commits from " + repo_url)
        request_url = str(repo_url) + "/commits?" + since + "&page=1&per_page=100"
        res = self.__requester.make_request(request_url)
        if res.status_code == 200: # API has responded with OK status
            return_json = res.json()
            if res.links:
                index_start = res.links["last"]["url"].find("page=")
                index_end = res.links["last"]["url"].find("&per_page")
                last = res.links["last"]["url"][index_start+5:index_end]
            else:
                last = 1

            for i in range(1, int(last)+1):
                print("Commits page: ", i)
                logging.info("Commits page: " + str(i))
                _requestURL = str(repo_url) + "/commits?" + since + "&page=" + str(i) + "&per_page=100"
                res = self.__requester.make_request(_requestURL)
                return_json = res.json()

                for commit in return_json:
                    if self.__databaseService.check_if_commit_exists(commit["sha"]):
                        continue
                    __requestURL = str(repo_url) + "/commits/" + str(commit["sha"])
                    res = self.__requester.make_request(__requestURL)
                    commit_detail = res.json()

                    # print( str(repoURL) + " current commit sha: " + commitDetail["sha"])
                    if commit_detail is None:
                        continue

                    try:
                        # insert Author
                        if commit_detail["author"] is not None: # if there's an author field.
                            # if user does not exist in database.
                            if not self.__databaseService.check_if_github_user_exists(commit_detail["author"]["login"]):
                                self.__retrieve_user(commit_detail["author"]["login"]) # retrieve and add user.

                        else: # if there's no author field. --> non-github user.
                            # if non-github user exist in database
                            if commit_detail["commit"]["author"]["email"]: # if non-github user has an email info.
                                if not self.__databaseService.check_if_commit_exists(commit_detail["commit"]["author"]["email"]):
                                    self.__databaseService.insert_non_github_user(commit_detail["commit"]["author"]) # add non-github user.
                            else:
                                raise

                        # insert Committer key

                        if commit_detail["committer"] is not None: # if there's an committer field.
                            # if user does not exist in database.
                            if not self.__databaseService.check_if_github_user_exists(commit_detail["committer"]["login"]):
                                    self.__retrieve_user(commit_detail["committer"]["login"]) # retrieve and add user.

                        else: # if there's no committer field. --> non-github user.
                            # if non-github user exist in database
                            if commit_detail["commit"]["committer"]["email"]:
                                if not self.__databaseService.check_if_user_exists(commit_detail["commit"]["committer"]["email"]):
                                    self.__databaseService.insert_non_github_user(commit_detail["commit"]["committer"]) # add non-github user

                            else:
                                raise

                        self.__databaseService.insert_commit(commit_detail, repo_id)

                    except Exception:
                        with open("commit_problems.txt", "a") as commit_problems_file:
                                if "sha" not in commit_detail:
                                    commit_problems_file.write(str(datetime.now()) + " " + str(repo_url) +
                                                               " page: " + str(i) + "\n")
                                    logging.info(" " + str(repo_url) + " page: " + str(i))
                                else:
                                    commit_problems_file.write(str(datetime.now()) + " " + str(repo_url) +
                                                               "/commits/" + commit_detail["sha"] + "\n")
                                    logging.info(str(datetime.now()) + " " + str(repo_url) +
                                                               "/commits/" + commit_detail["sha"])
                        pass

        else:  # Request gave an error
            print("Error while retrieving: " + request_url)
            print("Status code: " + str(res.status_code))

    def __retrieve_contributors_of_repo(self, repo_url, repo_id):
        index = 1

        while True:
            contributions_url = repo_url + "/contributors?page= " + str(index) + "&per_page=100"
            result = self.__requester.make_request(contributions_url)

            if result.status_code == 200:
                result_json = result.json()
                index = index + 1

                if not result_json:
                    break
                else:
                    for contributor in result_json:
                        login = contributor["login"]
                        contributions = contributor["contributions"]

                        # TODO: Debug log here
                        # print("Adding the user with login: " + login)
                        if self.__databaseService.check_if_github_user_exists(login) is False:
                            # There is no user entry in our DB with this login info so just fetch and insert it
                            self.__retrieve_user(login)

                        user_id = self.__databaseService.get_user_id_from_login(login)
                        self.__databaseService.insert_contribution(user_id, repo_id, contributions)

            else: # Request gave an error
                print("Error while retrieving: " + contributions_url)
                print("Status code: " + str(result.status_code))

    def __retrieve_issues_of_repo(self, repo_url, repo_id):
        index = 400
        paginationend = True
        while paginationend:
            events_url = repo_url + "/issues/events?page=" + str(index) + "&per_page=100"
            result = self.__requester.make_request(events_url)
            print("Issues page: " + str(index))
            if result.status_code == 200:
                result_json = result.json()
                index = index + 1

                if not result_json:
                    break

                for events in result_json:
                    if events["documentation_url"] is not None:
                        pagionaionend = False
                        break

                    if events["event"] == "closed":
                        print(events["url"])
                        if events["actor"] is not None:
                            closedby = events["actor"]
                            closedbyid = closedby["id"]
                        else:
                            closedbyid = None
                        issues = events["issue"]
                        issue_id = issues["id"]
                        url = issues["url"]
                        number = issues["number"]
                        title =  issues["title"]
                        repo_id = repo_id
                        reporter_id = issues["user"]["id"]
                        assignee_id = None
                        #assignee_id = issues["assignee"]
                        #if assignee_id:
                        # assignee_id =assignee_id["id"]
                        state = issues["state"]
                        comments = issues["comments"]
                        #body = issues["body"]
                        created_at = str(issues["created_at"])[:10]
                        updated_at = str(issues["updated_at"])[:10]
                        closed_at = "0000-00-00"
                        if str(issues["closed_at"]) == "None":
                            closed_at = "2000-01-01 00:00:00"
                        else:
                            closed_at = str(issues["closed_at"])[:10]
                        #print(issues["number"])
                        print(title)
                        #print(closed_at)
                        if self.__databaseService.check_if_issue_exists(issue_id) is None:
                            self.__databaseService.insert_issue(issue_id,url,number,title,repo_id,reporter_id, assignee_id, state,comments, created_at, updated_at, closed_at,closedbyid)
                        print(str(url))

            else:  # Request gave an error
                print("Error while retrieving: " + events_url)
                print("Status code: " + str(result.status_code))

    def __build_time_parameter_string(self, since_date, until_date):
        # Let's build time parameters string for requests that accept time intervals as parameters
        time_param = ""
        if since_date is not None:
            time_param = time_param + "&since=" + since_date
        if until_date is not None:
            time_param = time_param + "&until=" + until_date
        return time_param


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class EndScreenPenalty : MonoBehaviour
{
    [SerializeField] private Text MissedText;
    [SerializeField] private Text TimeText;

    private const string sMainText = "No Penalty";
    private const string sMissedEnd = " Missed";
    private const string sTimeEnd = " Secs";

    public void Setup()
    {
        if (GameData.Instance.iTargsLft > 0)
        {
            GetComponent<Text>().text = "Penalty";
            MissedText.text = GameData.Instance.iTargsLft.ToString() + sMissedEnd;
            TimeText.text = "+" + GameData.Instance.fTimePenalty.ToString() + sTimeEnd;
        }
        else
        {
            GetComponent<Text>().text = sMainText;
            MissedText.text = " ";
            TimeText.text = " ";
        }
    }
}


text:
The [InterPlanetary File System (IPFS)](https://ipfs.io/) is a new hypermedia distribution protocol, addressed by content and identity. IPFS enables the creation of completely distributed applications. It aims to make the web faster, safer, and more open. Since that's a pretty large scope, we track development across the ecosystem in this weekly dispatch.

Looking to get involved? Click on some of the links below, see what we're up to on [GitHub](https://github.com/ipfs), or join us in [chat](https://riot.im/app/#/room/#ipfs:matrix.org).

Want this update in your inbox? [Subscribe to our weekly newsletter!](http://eepurl.com/gL2Pi5)

Here are some of the highlights since the last IPFS Weekly.

## The latest

### New Tutorial: Use go-ipfs as a Library (no separate process needed!)

In case you missed it, learn how to spawn a go-ipfs node using the go-ipfs core API in [this new tutorial](https://github.com/ipfs/go-ipfs/tree/master/docs/examples/go-ipfs-as-a-library).

## IPFS in the wild
*Do you follow [IPFS on Twitter](https://twitter.com/IPFSbot)? For the latest mentions of IPFS in the news, check our Twitter feed or see the [latest articles on Awesome IPFS](https://awesome.ipfs.io/articles/).*

+ [TemporalX Development Environment Is Live](https://www.reddit.com/r/ipfs/comments/dqu45y/temporalx_development_environment_is_live/), 3 Nov 2019
+ [Video Of The Week: Filecoin and Web3](https://avc.com/2019/11/video-of-the-week-filecoin-and-web3/), AVC, 2 Nov 2019
+ PHOTO: [Textile CEO Andrew Hill explaining Interplanetary File System coolness at our Data Science Wrangle](https://twitter.com/bethann_nyc/status/1189725609414385664?s=20), Bethann Noble, 30 Oct 2019
+ [The Decentralization Dance.](https://medium.com/the-decentralization-dance-enable-not-control/the-decentralization-dance-a8a670bf852b) Aicumen, 29 Oct 2019
+ PODCAST: [Qri: Talking Data Sets with Brendan O'Brien & Rico Gardaphe](https://bettermousetrap.nyc/podcast/qri-talking-data-sets-with-brendan-obrien-rico-gardaphe/), A Better Mouse Trap, 29 Oct 2019
+ [The definite guide to your high-performance IPFS Gateway](https://blog.stacktical.com/ipfs/gateway/dapp/2019/09/21/ipfs-server-google-cloud-platform.html), Stacktical, 21 Sep 2019

## Open Positions working on IPFS

+ [Tech Lead, Distributed Systems Test Infrastructure](https://jobs.lever.co/protocol/1ef5b878-573d-44fc-9fe6-c3745597c1fd), Protocol Labs, Remote
+ [Distributed Systems Engineer, IPFS Cluster (Go)](https://jobs.lever.co/protocol/29207ca7-76a4-470f-b94a-e24244f9adc1), Protocol Labs, Remote
+ [Senior Backend Engineer](https://www.golangprojects.com/golang-go-job-dcr-Senior-Backend-Engineer-Berlin-MXC-Foundation-gGmbH.html), MXC Foundation gGmbH, Berlin, Germany
+ [Distributed Systems Technical Lead, IPFS](https://jobs.lever.co/protocol/9283f9b0-de64-4e1f-a221-5d02b0202198), Protocol Labs, Remote

## Coming up in the Community
*Did you know IPFS has a community forum at [discuss.ipfs.io](https://discuss.ipfs.io/)? Sign up to participate in discussions about coding, tutorials, see announcements and learn about upcoming community events.*

+ **6 November 2019:** [Paris P2P Monthly Peer to Beer](https://p2p.paris/en/event/monthly-3/) is a monthly meetup organized by and for the community of P2P and cryptography enthusiasts. Paris, France.
+ **14 November 2019:** [DWeb Talks: Carson Farmer of Textile.io](https://www.meetup.com/ProtoSchool-Seattle-Learn-to-Make-the-Decentralized-Web/events/263590720/) hosted by ProtoSchool Seattle. Come and hear from decentralized web developer Carson Farmer on Textile.io! Seattle, WA (US)
+ **6 December 2019:** [React Day Berlin](https://reactday.berlin/): Build code, not walls. Take part in the exploration of the React universe! Focusing on in-depth talks, hands-on workshops, and finding new opportunities, React Day Berlin conference provides space for everyone to make friends and develop stellar apps together. Berlin, Germany.

## Thanks for reading ☺

That's it for this week's news on all things IPFS. If we missed something, [reply to this email](mailto:newsletter@ipfs.io) and let us know! That way we can feature you in next week's edition.


text:
//////////////////////////////////////////////////////////////////////
//Headset Presenter by w2solutions (Johan Rosenquist)
//(C) All rights reserved 2002-2007
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "HeadsetPresenter.h"
#include "..\header files\modedialog.h"
#include "SettingsDialog.h"
#include "InfoDialog.h"

#include "SS_Log.h"

// ModeDialog dialog

IMPLEMENT_DYNAMIC(ModeDialog, CDialog)
ModeDialog::ModeDialog(CWnd* pParent /*=NULL*/)
	: HPDialog(ModeDialog::IDD)
{
	hasUpperLine = true;
	imageToDraw = IDB_LOGO_50x50;
}

ModeDialog::~ModeDialog()
{
}

void ModeDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BOOL ModeDialog::OnInitDialog()
{
	PrintStaticHeadlines("Choose HeadsetPresenter Mode");
	if(supportedModes & NORMAL_MODE_WIDCOMM || supportedModes & NORMAL_MODE_MICROSOFT || supportedModes & NORMAL_MODE_BLUESOLEIL || supportedModes & NORMAL_MODE_TOSHIBA)
	{
		Log("MD:Supporting normal mode");
		CheckRadioButton(IDC_RADIO1, IDC_RADIO2, IDC_RADIO1);
	}
	else
	{
		Log("MD:Supporting Advanced mode");
		CheckRadioButton(IDC_RADIO1, IDC_RADIO2, IDC_RADIO2);
		CButton* myRButton = (CButton*)GetDlgItem(IDC_RADIO1);
		myRButton->EnableWindow(false);
		SetDlgItemText(IDC_RADIO1,"Normal (Not supported by the installed Bluetooth drivers)");
	}

	if(!(supportedModes & ADVANCED_MODE))
	{
		Log("MD:Not supporting advanced mode");
		CButton* myRButton = (CButton*)GetDlgItem(IDC_RADIO2);
		myRButton->EnableWindow(false);
		SetDlgItemText(IDC_RADIO2,"Advanced (Not supported by the installed Bluetooth drivers)");
	}
	return TRUE;
}

void ModeDialog::SetSupportedModes(int iSupportedModes)
{
	supportedModes = iSupportedModes;
}

BEGIN_MESSAGE_MAP(ModeDialog, CDialog)
	ON_BN_CLICKED(IDBACK, OnBnClickedBack)
	ON_BN_CLICKED(IDNEXT, OnBnClickedNext)
	ON_WM_CTLCOLOR()
	ON_WM_ERASEBKGND()
	ON_WM_PAINT()
	ON_BN_CLICKED(IDCANCEL3, OnBnClickedCancel3)
	ON_BN_CLICKED(IDC_RADIO2, OnBnClickedRadio2)
END_MESSAGE_MAP()

// ModeDialog message handlers

int ModeDialog::GetSelectedMode()
{
	Log("MD:Returning selected mode as %d:",selectedMode);
	return selectedMode;
}

void ModeDialog::SetSettingsControl(SettingsControl* iSettingsControl)
{
	mySettingsControl = iSettingsControl;
}

void ModeDialog::OnBnClickedBack()
{
	OnCancel();
}

void ModeDialog::OnBnClickedNext()
{
	int checkedButton = GetCheckedRadioButton(IDC_RADIO1, IDC_RADIO2);
	if(checkedButton == IDC_RADIO1)
	{
		selectedMode = supportedModes  & ~ADVANCED_MODE;  //Mask away advanced mode so we know which normal mode that is selected
		Log("MD:Selected normal mode no: %d", selectedMode);
	}
	else
	{
		selectedMode = ADVANCED_MODE;
		Log("MD:Selected advanced mode: %d",selectedMode);
	}
	OnOK();
}

HBRUSH ModeDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	return HPDialog::OnCtlColor(pDC,pWnd,nCtlColor);
}

BOOL ModeDialog::OnEraseBkgnd(CDC* pDC)
{
	return HPDialog::OnEraseBkgnd(pDC);
}

void ModeDialog::OnPaint()
{
	HPDialog::OnPaint();
}

void ModeDialog::OnBnClickedCancel3()
{
	OnCancel();
}

void ModeDialog::OnBnClickedRadio2()
{
	InfoDialog myInfoDlg;
	myInfoDlg.SetSettingsControl(mySettingsControl);
	myInfoDlg.SetBoxId(INFO_DLG_ADVANCED_MODE_BOX);
	myInfoDlg.SetText("Advanced mode","Important information","Advanced mode sets high requirements on your Bluetooth dongle, software and operating system.\n\nAdvanced mode has been successfully tested with Bluetooth dongles from more then 30 vendors. However especially when using drivers from Toshiba or BlueSoleil some manual tuning might be required.\n\nHeadsetPresenter will try to do this automatically but it might be necessary to consult the documentation or support in case of problems.");
	if(myInfoDlg.ShowBox())
	{
		myInfoDlg.DoModal();
	}
}


text: For E/// Design Pattern Learning Program 2015


text:
'use strict';

var assert = require('assert');
var koaRequestInformationExtractor =
  require('../../../src/request-extractors/koa.js');
var Fuzzer = require('../../../utils/fuzzer.js');

describe('koaRequestInformationExtractor', function() {
  describe('Behaviour under invalid input', function() {
    it('Should produce a default value', function() {
      var DEFAULT_RETURN_VALUE = {
        method: '',
        url: '',
        userAgent: '',
        referrer: '',
        statusCode: 0,
        remoteAddress: ''
      };
      var f = new Fuzzer();
      var cbFn = function(value) {
        assert.deepEqual(value, DEFAULT_RETURN_VALUE);
      };
      f.fuzzFunctionForTypes(koaRequestInformationExtractor,
        ['object', 'object'], cbFn);
    });
  });
  describe('Behaviour under valid input', function() {
    it('Should produce the expected value', function() {
      var FULL_REQ_DERIVATION_VALUE = {
        method: 'STUB_METHOD',
        url: 'www.TEST-URL.com',
        headers: {
          'user-agent': 'Something like Mozilla',
          referrer: 'www.ANOTHER-TEST.com'
        },
        ip: '0.0.0.0'
      };
      var FULL_RES_DERIVATION_VALUE = {
        status: 200
      };
      var FULL_REQ_EXPECTED_VALUE = {
        method: 'STUB_METHOD',
        url: 'www.TEST-URL.com',
        userAgent: 'Something like Mozilla',
        referrer: 'www.ANOTHER-TEST.com',
        remoteAddress: '0.0.0.0',
        statusCode: 200
      };
      assert.deepEqual(
        koaRequestInformationExtractor(FULL_REQ_DERIVATION_VALUE,
          FULL_RES_DERIVATION_VALUE),
        FULL_REQ_EXPECTED_VALUE);
    });
  });
});


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

using System;
using System.Collections;
using System.Collections.Generic;

namespace Boo.Lang.Compiler.Ast
{

	/// <summary>
	/// Node collection base class.
	/// </summary>
	public class NodeCollection<T> : ICollection<T>, ICollection, ICloneable, IEquatable<NodeCollection<T>>
		where T : Node
	{
		private Node _parent;
		private readonly List<T> _list;

		protected NodeCollection()
		{
			_list = new List<T>();
		}

		protected NodeCollection(Node parent)
		{
			_parent = parent;
			_list = new List<T>();
		}

		protected NodeCollection(Node parent, IEnumerable<T> list)
		{
			if (null == list) throw new ArgumentNullException("list");

			_parent = parent;
			_list = new List<T>(list);
		}

		public T this[int index]
		{
			get { return _list[index]; }
			set
			{
				if (_list[index] == value)
					return;
				_list[index] = value;
				OnChanged();
			}
		}

		public IEnumerator<T> GetEnumerator()
		{
			return _list.GetEnumerator();
		}

		public Node ParentNode
		{
			get { return _parent; }
		}

		public bool IsEmpty
		{
			get { return 0 == _list.Count; }
		}

		public int Count
		{
			get { return _list.Count; }
		}

		public int IndexOf(T item)
		{
			return _list.IndexOf(item);
		}

		public bool IsReadOnly
		{
			get { return false; }
		}

		public bool IsSynchronized
		{
			get { return false; }
		}

		public object SyncRoot
		{
			get { return this; }
		}

		public void CopyTo(Array array, int index)
		{
			((ICollection)_list).CopyTo(array, index);
		}

		public void CopyTo(T[] array, int index)
		{
			_list.CopyTo(array, index);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _list.GetEnumerator();
		}

		public void Clear()
		{
			_list.Clear();
			OnChanged();
		}

		public T[] ToArray()
		{
			return _list.ToArray();
		}

		public TOut[] ToArray<TOut>(Function<T, TOut> selector)
		{
			return _list.ToArray(selector);
		}

		public T[] ToReverseArray()
		{
			T[] array = ToArray();
			Array.Reverse(array);
			return array;
		}

		public IEnumerable<T> Except<UnwantedNodeType>() where UnwantedNodeType : T
		{
			foreach (T node in _list)
				if (!(node is UnwantedNodeType))
					yield return node;
		}

		public IEnumerable<T> Except<UnwantedNodeType,UnwantedNodeType2>()
			where UnwantedNodeType : T
			where UnwantedNodeType2 : T
		{
			foreach (T node in _list)
				if (!(node is UnwantedNodeType) && !(node is UnwantedNodeType2))
					yield return node;
		}

		protected IEnumerable InternalPopRange(int begin)
		{
			OnChanged();
			return _list.PopRange(begin);
		}

		public bool Contains(T node)
		{
			foreach (T n in _list)
				if (n == node) return true;
			return false;
		}

		[Obsolete("Use Contains(T node) instead.")]
		public bool ContainsNode(T node)
		{
			return Contains(node);
		}

		public bool Contains(Predicate<T> condition)
		{
			return _list.Contains(condition);
		}

		public bool ContainsEntity(TypeSystem.IEntity entity)
		{
			foreach (T node in _list)
				if (entity == node.Entity)
					return true;
			return false;
		}

		public Node RemoveByEntity(TypeSystem.IEntity entity)
		{
			if (null == entity)
				throw new ArgumentNullException("entity");
			for (int i = 0; i < _list.Count; ++i)
			{
				Node node = _list[i];
				if (entity == node.Entity)
				{
					RemoveAt(i);
					return node;
				}
			}
			return null;
		}

		public virtual object Clone()
		{
			var clone = (NodeCollection<T>)Activator.CreateInstance(GetType());
			var cloneList = clone._list;
			foreach (T node in _list)
				cloneList.Add((T)node.CloneNode());
			return clone;
		}

		public void ClearTypeSystemBindings()
		{
			foreach (T node in _list)
				node.ClearTypeSystemBindings();
		}

		internal List<T> InnerList
		{
			get { return _list; }
		}

		internal void InitializeParent(Node parent)
		{
			_parent = parent;
			foreach (T node in _list)
				node.InitializeParent(_parent);
		}

		public void Reject(Predicate<T> condition)
		{
			if (null == condition)
				throw new ArgumentNullException("condition");

			var index = 0;
			foreach (T node in ToArray())
				if (condition(node))
					RemoveAt(index);
				else
					++index;
		}

		public void RemoveAt(int index)
		{
			//Node existing = (Node)InnerList[index];
			//existing.InitializeParent(null);
			_list.RemoveAt(index);
			OnChanged();
		}

		public void ExtendWithClones(IEnumerable<T> items)
		{
			foreach (T item in items)
				Add((T)item.CloneNode());
		}

		public void ReplaceAt(int i, T newItem)
		{
			Initialize(newItem);
			_list[i] = newItem;
			OnChanged();
		}

		public void Add(T item)
		{
			Initialize(item);
			_list.Add(item);
			OnChanged();
		}

		[Obsolete("Use AddRange")]
		public void Extend(IEnumerable<T> items)
		{
			AddRange(items);
		}

		public void AddRange(IEnumerable<T> items)
		{
			AssertNotNull("items", items);
			foreach (T item in items)
				Add(item);
		}

		public bool Replace(T existing, T newItem)
		{
			AssertNotNull("existing", existing);
			for (int i = 0; i < _list.Count; ++i)
			{
				if (this[i] == existing)
				{
					if (null == newItem)
						RemoveAt(i);
					else
						ReplaceAt(i, newItem);
					return true;
				}
			}
			return false;
		}

		public void Insert(int index, T item)
		{
			Initialize(item);
			_list.Insert(index, item);
			OnChanged();
		}

		public bool Remove(T item)
		{
			if (((ICollection<T>)_list).Remove(item))
			{
				OnChanged();
				return true;
			}
			return false;
		}

		public event EventHandler Changed;

		private void OnChanged()
		{
			var changed = Changed;
			if (changed != null)
				changed(this, EventArgs.Empty);
		}

		override public int GetHashCode()
		{
			return _list.GetHashCode();
		}

		override public bool Equals(object other)
		{
			return Equals(other as NodeCollection<T>);
		}

		public bool Equals(NodeCollection<T> other)
		{
			if (null == other) return false;
			if (this == other) return true;
			if (InnerList.Count != other.Count) return false;

			IEnumerator<T> enumerator = other.GetEnumerator();
			foreach (T mine in this)
			{
				if (!enumerator.MoveNext()) return false;
				if (!mine.Equals(enumerator.Current)) return false;
			}
			return true;
		}

		void Initialize(Node item)
		{
			AssertNotNull("item", item);
			if (null != _parent)
				item.InitializeParent(_parent);
		}

		private static void AssertNotNull(string descrip, object o)
		{
			if (o == null)
				throw new ArgumentException(String.Format("null reference for: {0}", descrip));
		}

		public NodeCollection<TNew> Cast<TNew>() where TNew : Node
		{
			return Cast<TNew>(0);
		}

		public NodeCollection<TNew> Cast<TNew>(int index) where TNew : Node
		{
			if (index < 0 || index > Count)
				throw new ArgumentOutOfRangeException("index");

			if (0 == (Count - index)) //empty or no item to cast
				return Empty<TNew>(ParentNode);

			NodeCollection<TNew> nodes = new NodeCollection<TNew>(ParentNode);
			int i = -1;

			foreach (T node in _list)
			{
				++i;
				if (i < index)
					continue;

				TNew cnode = node as TNew;
				if (null == cnode)
				{
					ExpressionStatement es = node as ExpressionStatement;
					if (null != es)
						cnode = es.Expression as TNew;
				}
				if (null == cnode)
					throw new InvalidCastException(
						string.Format("Cannot cast item #{0} from `{1}` to `{2}`",
						              i+1, node.GetType(), typeof(TNew)));

				nodes.Add(cnode);
			}
			return nodes;
		}

		public static NodeCollection<TNode> Empty<TNode>(Node parent) where TNode : Node
		{
			//TODO: cache?
			return new NodeCollection<TNode>(parent);
		}

		public bool StartsWith<TNode>() where TNode : T
		{
			return !IsEmpty && (First is TNode);
		}

		public bool EndsWith<TNode>() where TNode : T
		{
			return !IsEmpty && (Last is TNode);
		}

		public T First
		{
			get { return (IsEmpty ? null : _list[0]); }
		}

		public T Last
		{
			get { return (IsEmpty ? null : _list[Count - 1]); }
		}
	}
}


text:
package gossip

import (
	"regexp"
	"strings"

	"github.com/cockroachdb/cockroach/proto"
)

// separator is used to separate the non-prefix components of a
// Gossip key, facilitating the automated generation of regular
// expressions for various prefixes.
// It must not be contained in any of the other keys defined here.
const separator = ":"

// Constants for gossip keys.
const (
	// KeyClusterID is the unique UUID for this Cockroach cluster.
	// The value is a string UUID for the cluster.  The cluster ID is
	// gossiped by all nodes that contain a replica of the first range,
	// and it serves as a check for basic gossip connectivity. The
	// Gossip.Connected channel is closed when we see this key.
	KeyClusterID = "cluster-id"

	// KeyConfigZone is the zone configuration map.
	KeyConfigZone = "zones"

	// KeyStorePrefix is the key prefix for gossiping stores in the network.
	// The suffix is a store ID and the value is proto.StoreDescriptor.
	KeyStorePrefix = "store"

	// KeyNodeIDPrefix is the key prefix for gossiping node id
	// addresses. The actual key is suffixed with the decimal
	// representation of the node id and the value is the host:port
	// string address of the node. E.g. node:1 => 127.0.0.1:24001
	KeyNodeIDPrefix = "node"

	// KeySentinel is a key for gossip which must not expire or
	// else the node considers itself partitioned and will retry with
	// bootstrap hosts.  The sentinel is gossiped by the node that holds
	// the leader lease for the first range.
	KeySentinel = "sentinel"

	// KeyFirstRangeDescriptor is the descriptor for the "first"
	// range. The "first" range contains the meta1 key range, the first
	// level of the bi-level key addressing scheme. The value is a slice
	// of storage.Replica structs.
	KeyFirstRangeDescriptor = "first-range"

	// KeySystemDB is the gossip key for the system DB span.
	KeySystemDB = "system-db"
)

// MakeKey creates a canonical key under which to gossip a piece of
// information. The first argument will typically be one of the key constants
// defined in this package.
func MakeKey(components ...string) string {
	return strings.Join(components, separator)
}

// MakePrefixPattern returns a regular expression pattern that
// matches precisely the Gossip keys created by invocations of
// MakeKey with multiple arguments for which the first argument
// is equal to the given prefix.
func MakePrefixPattern(prefix string) string {
	return regexp.QuoteMeta(prefix+separator) + ".*"
}

// MakeNodeIDKey returns the gossip key for node ID info.
func MakeNodeIDKey(nodeID proto.NodeID) string {
	return MakeKey(KeyNodeIDPrefix, nodeID.String())
}

// MakeStoreKey returns the gossip key for the given store.
func MakeStoreKey(storeID proto.StoreID) string {
	return MakeKey(KeyStorePrefix, storeID.String())
}


text:
package jsat.distributions.multivariate;

import java.io.Serializable;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import jsat.DataSet;
import jsat.classifiers.DataPoint;
import jsat.linear.Vec;

/**
 * This interface represents the contract that any continuous multivariate distribution must implement
 *
 * @author Edward Raff
 */
public interface MultivariateDistribution extends Cloneable, Serializable
{
    /**
     * Computes the log of the probability density function. If the
     * probability of the input is zero, the log of zero would be
     * {@link Double#NEGATIVE_INFINITY}. Instead, -{@link Double#MAX_VALUE} is returned.
     *
     * @param x the array for the vector the get the log probability of
     * @return the log of the probability.
     * @throws ArithmeticException if the vector is not the correct length, or the distribution has not yet been set
     */
    public double logPdf(double... x);

    /**
     * Computes the log of the probability density function. If the
     * probability of the input is zero, the log of zero would be
     * {@link Double#NEGATIVE_INFINITY}. Instead, -{@link Double#MAX_VALUE} is returned.
     *
     * @param x the vector the get the log probability of
     * @return the log of the probability.
     * @throws ArithmeticException if the vector is not the correct length, or the distribution has not yet been set
     */
    public double logPdf(Vec x);

    /**
     * Returns the probability of a given vector from this distribution. By definition,
     * the probability will always be in the range [0, 1].
     *
     * @param x the array of the vector the get the log probability of
     * @return the probability
     * @throws ArithmeticException if the vector is not the correct length, or the distribution has not yet been set
     */
    public double pdf(double... x);

    /**
     * Returns the probability of a given vector from this distribution. By definition,
     * the probability will always be in the range [0, 1].
     *
     * @param x the vector the get the log probability of
     * @return the probability
     * @throws ArithmeticException if the vector is not the correct length, or the distribution has not yet been set
     */
    public double pdf(Vec x);

    /**
     * Sets the parameters of the distribution to attempt to fit the given list of vectors.
     * All vectors are assumed to have the same weight.
     * @param <V> the vector type
     * @param dataSet the list of data points
     * @return <tt>true</tt> if the distribution was fit to the data, or <tt>false</tt>
     * if the distribution could not be fit to the data set.
     */
    public <V extends Vec> boolean setUsingData(List<V> dataSet);

    /**
     * Sets the parameters of the distribution to attempt to fit the given list of vectors.
     * All vectors are assumed to have the same weight.
     * @param <V> the vector type
     * @param dataSet the list of data points
     * @param threadpool the source of threads for computation
     * @return <tt>true</tt> if the distribution was fit to the data, or <tt>false</tt>
     * if the distribution could not be fit to the data set.
     */
    public <V extends Vec> boolean setUsingData(List<V> dataSet, ExecutorService threadpool);

    /**
     * Sets the parameters of the distribution to attempt to fit the given list of data points.
     * The {@link jsat.classifiers.DataPoint#getWeight()  weights} of the data points will be used.
     *
     * @param dataPoints the list of data points to use
     * @return <tt>true</tt> if the distribution was fit to the data, or <tt>false</tt>
     * if the distribution could not be fit to the data set.
     */
    public boolean setUsingDataList(List<DataPoint> dataPoints);

    /**
     * Sets the parameters of the distribution to attempt to fit the given list of data points.
     * The {@link DataPoint#getWeight()  weights} of the data points will be used.
     *
     * @param dataPoints the list of data points to use
     * @param threadpool the source of threads for computation
     * @return <tt>true</tt> if the distribution was fit to the data, or <tt>false</tt>
     * if the distribution could not be fit to the data set.
     */
    public boolean setUsingDataList(List<DataPoint> dataPoints, ExecutorService threadpool);

    /**
     * Sets the parameters of the distribution to attempt to fit the given list of data points.
     * The {@link DataPoint#getWeight()  weights} of the data points will be used.
     *
     * @param dataSet the data set to use
     * @return <tt>true</tt> if the distribution was fit to the data, or <tt>false</tt>
     * if the distribution could not be fit to the data set.
     */
    public boolean setUsingData(DataSet dataSet);

    /**
     * Sets the parameters of the distribution to attempt to fit the given list of data points.
     * The {@link DataPoint#getWeight()  weights} of the data points will be used.
     *
     * @param dataSet the data set to use
     * @param threadpool the source of threads for computation
     * @return <tt>true</tt> if the distribution was fit to the data, or <tt>false</tt>
     * if the distribution could not be fit to the data set.
     */
    public boolean setUsingData(DataSet dataSet, ExecutorService threadpool);

    public MultivariateDistribution clone();

    /**
     * Performs sampling on the current distribution.
     * @param count the number of iid samples to draw
     * @param rand the source of randomness
     * @return a list of sample vectors from this distribution
     */
    public List<Vec> sample(int count, Random rand);
}


text:
//using System;
//using System.Collections.Generic;
//using System.Text;
//using System.Threading.Tasks;
//using Discord.Addons.TriviaGames;
//using Discord.Commands;

//namespace Kohaku
//{
//    [Group("trivia"), Name("Trivia")]
//    public class TriviaImpl : TriviaModuleBase
//    {
//        public TriviaImpl(TriviaService service) : base(service)
//        {
//        }

//        [Command("start")]
//        public override async Task NewGameCmd(int turns)
//        {
//            // You should check if there's not already
//            // a game going on in this channel
//            if (GameInProgress)
//            {
//                await ReplyAsync("Already playing");
//                return;
//            }

//            var game = new TriviaGame(Service.TriviaData, Context.Channel, turns);
//            if (Service.AddNewGame(Context.Channel.Id, game))
//            {
//                await game.Start();
//            }
//        }

//        [Command("stop")]
//        public override async Task EndGameCmd()
//        {
//            // Here check if there IS a game going on.
//            if (GameInProgress)
//            {
//                await Game.End();
//            }
//            else
//            {
//                await ReplyAsync("No game going on.");
//            }
//        }
//    }
//}