text:
class Genre < ActiveRecord::Base
  has_many :movies, through: :movie_genres
  has_many :movie_genres
  has_many :shows, through: :show_genres
  has_many :show_genres
end

redpajama_set_name: RedPajamaGithub


text:
/*
    Shell sort
    ----------
    An in-place comparison sort which starts by sorting pairs of elements far
    apart from each other, then progressively reducing the gap between elements
    to be compared. The time complexity depends on the gap sequence, which is
    floor(N / 2^K) in this implementation.

    Time complexity
    ---------------
    O(N^2), where N is the nubmer of elements.

    Space complexity
    ----------------
    O(1).
*/

#include <iostream>
#include <vector>

#include "sorting/utils.hpp"

using namespace std;

void shell_sort(vector<int>& values, const int order = 1, const bool to_show_state = false) {
    int n = values.size();
    int temp;
    int i, j;

    // gap sequence is n/2, n/4, n/8, ..., 1
    for (int gap = n / 2; gap > 0; gap /= 2) {
        for (i = gap; i < n; i++) {
            temp = values[i];
            j = i;
            while (j >= gap and values[j - gap] * order > temp * order) {
                values[j] = values[j - gap];
                j -= gap;
            }
            values[j] = temp;

            if (to_show_state)
                display_state(values);
        }
    }
}

int main() {
    size_t size;
    get_input_size(size);

    vector<int> values(size);
    get_input_values(values, size);

    int order;
    string order_text;
    get_order(order, order_text);

    bool to_show_state;
    get_whether_to_show_state(to_show_state);

    shell_sort(values, order, to_show_state);

    cout << "\nThe values in " << order_text << " order are:\n";
    display_state(values);

    return 0;
}


text:
    <select ng-change="fetchImages()" ng-model="page" ng-options="page for page in imagePages track by page">
    </select>

    <input ng-model="limit" type="number" min="1" max="50" ng-change="fetchImages()" />


text:
BOSSA 1.4 for Arduino

This version of BOSSA is a fork of the original project and contains some
patches specific for the Arduino products that are unlike to be accepted
upstream.

The original software is developed by Scott Shumate and can be found here:

http://www.shumatech.com/web/products/bossa

BOSSA 1.5-arduino
-----------------

* Added Codelite project for easier development and debug.
* Improved support for SAMD21 chip by using existing applet already in use for other devices.
  * Added time count for operations erase, write, read and verify.
  * Added Devices.h for global definitions for each devices.
  * NVMFlash::write() rewritten.
  * Removed some useless functions from 1.4 release.
  * Added a mask for SAMD chipid: DIE and REV bitfields are not taken into account as they may vary in the time without impacting the features.
  * Improved write time performance by a factor of 2x

BOSSA 1.4-arduino
-----------------

* Added support for SAMD21 chip

BOSSA 1.2
---------

FILES
bossa-1.2.msi -- Windows 2000+
bossa64-1.2.msi -- Windows 2000+ 64-bit
bossa-i686-1.2.tgz -- Linux GTK
bossa-x86_64-1.2.tgz -- Linux GTK 64-bit
bossa-1.2.dmg -- MAC OS X 10.6+

NEW IN THIS RELEASE
* New BOSSA shell command line application to do basic memory, flash, and PIO diagnostics
* Workaround for SAM3U firmware bug
* Fixed a bug with setting boot to flash bit on SAM3 devices

RELEASE NOTES
* The OS X USB driver detects an Atmel device as a USB modem.  When prompted about a new network interface, click Cancel to continue.
* Some stability issues have been seen with the OS X USB driver using BOSSA.  When running BOSSA a second time to the same Atmel device, the USB driver can lock up causing BOSSA to freeze.  As a workaround, always disconnect and reconnect the Atmel device before running BOSSA again.
* The firmware inside of SAM3U devices has a bug where non-word flash reads return zero instead of the real data.  BOSSA implements a transparent workaround for flash operations that copies flash to SRAM before reading.  Direct reads using the BOSSA shell will see the bug.
* There are reports that the USB controller in some AMD-based systems has difficulty communicating with SAM devices.  The only known workaround is to use a different, preferrably Intel-based, system.


text:
\documentclass[12pt]{report}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage[autostyle]{csquotes}
\usepackage{amsmath}
\usepackage{subcaption}
\usepackage{array}
\newcolumntype{P}[1]{>{\centering\arraybackslash}p{#1}}
\usepackage[labelfont=bf]{caption}
\usepackage{indentfirst}
\graphicspath{{resources/}}
\usepackage[a4paper,width=150mm,top=25mm,bottom=25mm]{geometry}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead{}
\lhead{Thesis Title}
\fancyfoot{}
\rfoot{\thepage}
\lfoot[LO,C]{Chapter \thechapter}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}

\newcommand{\quotes}[1]{\lq{#1}\rq}

% bibliography resources
\usepackage{biblatex}
\addbibresource{references.bib}

\title{Thesis Title}
\author{Austin Derrow-Pinion}
\date{October 2017}

\begin{document}

\input{sections/titlepage}

\chapter*{Abstract}
\input{sections/abstract}

\tableofcontents

\chapter{Introduction}
\input{sections/introduction}

\chapter{Background}
\input{sections/background}

\chapter{Procedures}
\section{Dynamic Memory Allocation}
\input{sections/repeat_copy}

\section{DNA Sequencing for Pre-Segmented MinION Nanopore Reads}
\input{sections/dna_sequencing}

% \chapter{Extraction-Based Summarization Task}
% \input{sections/stack_exchange_tags}

\chapter{Conclusion}
\input{sections/conclusion}

% \appendix
% \chapter{Appendix Title}
% \input{sections/appendix}

\printbibliography

\end{document}


text:
package ini

import (
	"os"
	"regexp"
	"runtime"
	"strings"
)

const (
	// DefaultSection is the name of default section. You can use this constant or the string literal.
	// In most of cases, an empty string is all you need to access the section.
	DefaultSection = "DEFAULT"

	// Maximum allowed depth when recursively substituing variable names.
	depthValues = 99
)

var (
	// LineBreak is the delimiter to determine or compose a new line.
	// This variable will be changed to "\r\n" automatically on Windows at package init time.
	LineBreak = "\n"

	// Variable regexp pattern: %(variable)s
	varPattern = regexp.MustCompile(`%\(([^)]+)\)s`)

	// DefaultHeader explicitly writes default section header.
	DefaultHeader = false

	// PrettySection indicates whether to put a line between sections.
	PrettySection = true
	// PrettyFormat indicates whether to align "=" sign with spaces to produce pretty output
	// or reduce all possible spaces for compact format.
	PrettyFormat = true
	// PrettyEqual places spaces around "=" sign even when PrettyFormat is false.
	PrettyEqual = false
	// DefaultFormatLeft places custom spaces on the left when PrettyFormat and PrettyEqual are both disabled.
	DefaultFormatLeft = ""
	// DefaultFormatRight places custom spaces on the right when PrettyFormat and PrettyEqual are both disabled.
	DefaultFormatRight = ""
)

var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")

func init() {
	if runtime.GOOS == "windows" && !inTest {
		LineBreak = "\r\n"
	}
}

// LoadOptions contains all customized options used for load data source(s).
type LoadOptions struct {
	// Loose indicates whether the parser should ignore nonexistent files or return error.
	Loose bool
	// Insensitive indicates whether the parser forces all section and key names to lowercase.
	Insensitive bool
	// InsensitiveSections indicates whether the parser forces all section to lowercase.
	InsensitiveSections bool
	// InsensitiveKeys indicates whether the parser forces all key names to lowercase.
	InsensitiveKeys bool
	// IgnoreContinuation indicates whether to ignore continuation lines while parsing.
	IgnoreContinuation bool
	// IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value.
	IgnoreInlineComment bool
	// SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs.
	SkipUnrecognizableLines bool
	// ShortCircuit indicates whether to ignore other configuration sources after loaded the first available configuration source.
	ShortCircuit bool
	// AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing.
	// This type of keys are mostly used in my.cnf.
	AllowBooleanKeys bool
	// AllowShadows indicates whether to keep track of keys with same name under same section.
	AllowShadows bool
	// AllowNestedValues indicates whether to allow AWS-like nested values.
	// Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values
	AllowNestedValues bool
	// AllowPythonMultilineValues indicates whether to allow Python-like multi-line values.
	// Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure
	// Relevant quote:  Values can also span multiple lines, as long as they are indented deeper
	// than the first line of the value.
	AllowPythonMultilineValues bool
	// SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value.
	// Docs: https://docs.python.org/2/library/configparser.html
	// Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names.
	// In the latter case, they need to be preceded by a whitespace character to be recognized as a comment.
	SpaceBeforeInlineComment bool
	// UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format
	// when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value"
	UnescapeValueDoubleQuotes bool
	// UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format
	// when value is NOT surrounded by any quotes.
	// Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all.
	UnescapeValueCommentSymbols bool
	// UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise
	// conform to key/value pairs. Specify the names of those blocks here.
	UnparseableSections []string
	// KeyValueDelimiters is the sequence of delimiters that are used to separate key and value. By default, it is "=:".
	KeyValueDelimiters string
	// KeyValueDelimiterOnWrite is the delimiter that are used to separate key and value output. By default, it is "=".
	KeyValueDelimiterOnWrite string
	// ChildSectionDelimiter is the delimiter that is used to separate child sections. By default, it is ".".
	ChildSectionDelimiter string
	// PreserveSurroundedQuote indicates whether to preserve surrounded quote (single and double quotes).
	PreserveSurroundedQuote bool
	// DebugFunc is called to collect debug information (currently only useful to debug parsing Python-style multiline values).
	DebugFunc DebugFunc
	// ReaderBufferSize is the buffer size of the reader in bytes.
	ReaderBufferSize int
	// AllowNonUniqueSections indicates whether to allow sections with the same name multiple times.
	AllowNonUniqueSections bool
}

// DebugFunc is the type of function called to log parse events.
type DebugFunc func(message string)

// LoadSources allows caller to apply customized options for loading from data source(s).
func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) {
	sources := make([]dataSource, len(others)+1)
	sources[0], err = parseDataSource(source)
	if err != nil {
		return nil, err
	}
	for i := range others {
		sources[i+1], err = parseDataSource(others[i])
		if err != nil {
			return nil, err
		}
	}
	f := newFile(sources, opts)
	if err = f.Reload(); err != nil {
		return nil, err
	}
	return f, nil
}

// Load loads and parses from INI data sources.
// Arguments can be mixed of file name with string type, or raw data in []byte.
// It will return error if list contains nonexistent files.
func Load(source interface{}, others ...interface{}) (*File, error) {
	return LoadSources(LoadOptions{}, source, others...)
}

// LooseLoad has exactly same functionality as Load function
// except it ignores nonexistent files instead of returning error.
func LooseLoad(source interface{}, others ...interface{}) (*File, error) {
	return LoadSources(LoadOptions{Loose: true}, source, others...)
}

// InsensitiveLoad has exactly same functionality as Load function
// except it forces all section and key names to be lowercased.
func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) {
	return LoadSources(LoadOptions{Insensitive: true}, source, others...)
}

// ShadowLoad has exactly same functionality as Load function
// except it allows have shadow keys.
func ShadowLoad(source interface{}, others ...interface{}) (*File, error) {
	return LoadSources(LoadOptions{AllowShadows: true}, source, others...)
}


text:
var express = require('express')
var http = require('http')

module.exports = function (config) {
  var router = require(__dirname + '/router.js')(config)
  var app = express()
  var port = config.port || 5050
  app.set('port', port)
  // mount router
  app.use('/', router)
  var server = http.createServer(app)
  server.app = app
  return server
}


text:
<!DOCTYPE HTML>
<html>
<!--
Copyright 2007 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<head>
<title>Sub pixel rendering</title>
<script type="text/javascript" src="../../base.js"></script>
<script type="text/javascript">

goog.require('goog.dom');
goog.require('goog.graphics');

</script>
<script type="text/javascript">

function testLineWidth() {
  var graphics = goog.graphics.createGraphics(100, 100);

  // vertical line
  for (var i = 0; i < 100; i++) {
    var stroke = new goog.graphics.Stroke(i / 100, 'black');
    var path = graphics.createPath();
    path.moveTo(49.5, i);
    path.lineTo(49.5, i + 1);
    path.close();
    graphics.drawPath(path, stroke, null);
  }

  // horizontal line
  for (var i = 0; i < 100; i++) {
    var stroke = new goog.graphics.Stroke(i / 100, 'black');
    var path = graphics.createPath();
    path.moveTo(i, 49.5);
    path.lineTo(i + 1, 49.5);
    path.close();
    graphics.drawPath(path, stroke, null);
  }

  graphics.render();
}

function testLinePos() {
  var graphics = goog.graphics.createGraphics(100, 100);
  var stroke = new goog.graphics.Stroke(1, 'black');

  // vertical line
  for (var i = 0; i < 100; i++) {
    var path = graphics.createPath();
    path.moveTo(49 + i / 100, i);
    path.lineTo(49 + i / 100, i + 1);
    path.close();
    graphics.drawPath(path, stroke, null);
  }

  // horizontal line
  for (var i = 0; i < 100; i++) {
    var path = graphics.createPath();
    path.moveTo(i, 49.5 + i / 100);
    path.lineTo(i + 1, 49.5 + i / 100);
    path.close();
    graphics.drawPath(path, stroke, null);
  }

  graphics.render();
}

</script>
</head>
<body>
<script>
testLineWidth();
document.write('<br>');
testLinePos();
</script>
</body>
</html>


text:
import json
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from requests.packages.urllib3.exceptions import InsecureRequestWarning

def pretty(data):
    print '\n', json.dumps(data, sort_keys=True, indent=4), '\n'

class OpsCenter:
    """Class to contain OpsC ip/url/session state plus REST API methods"""
    def __init__(self, ip, user, password):
        self.ip = ip
        self.url = "http://" + ip + ":8888"
        self.user = user
        self.password = password
        self.session = requests.Session()
        # Explicitly ignoring self-signed SSL certs, this prints warnings
        self.session.verify = False
        # supress warnings
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        # These scripts don't create new sessions, therefore we're setting the
        # retry logic here. The adapter mounting means any http(s) calls will
        # retry with an exponential backoff
        retries = 10,
        backoff_factor = 0.1,
        status_forcelist = (500, 502, 504)
        retry = Retry(
            total=retries,
            read=retries,
            connect=retries,
            backoff_factor=backoff_factor,
            status_forcelist=status_forcelist,
        )
        adapter = HTTPAdapter(max_retries=retry)
        self.session.mount('http://', adapter)
        self.session.mount('https://', adapter)

    def setupSession(self, pause, trys):
        # Constants that should go elsewhere?
        tout = 25
        # maxtrys * pause = 600 sec or 10 min, should be enough time for
        # OpsC instance to come up.
        count = 0
        while True:
            count += 1
            if count > trys:
                print "Error: OpsC connection failed after {n} trys".format(n=trys)
                return
            try:
                print "Trying: {url}/meta".format(url=self.url)
                meta = self.session.get("{url}/meta".format(url=self.url), timeout=tout)
            except requests.exceptions.Timeout as e:
                print "Request {c} to OpsC timeout, wait {p} sec...".format(c=count, p=pause)
                time.sleep(pause)
                continue
            except requests.exceptions.ConnectionError as e:
                print "Request {c} to OpsC refused, wait {p} sec...".format(c=count, p=pause)
                time.sleep(pause)
                continue
            except Exception as e:
                print "Request {c} to OpsC failed, wait {p} sec...".format(c=count, p=pause)
                time.sleep(pause)
                continue
            if (len(meta.history) > 0) and meta.history[0].status_code == 302:
                self.url = "https://" + self.ip + ":8443"
                print "Rerdirect detected, changing base url to: {url}".format(url=self.url)
            if meta.status_code == 200:
                data = meta.json()
                print "Found OpsCenter version: {version}".format(version=data['version'])
                return
            if meta.status_code == 401:
                print "Found OpsCenter with auth enabled, attempting login..."
                resp = self.attemptLogin(6)
                if resp == None:
                    print "All login attempts failed, exiting..."
                    exit(1)

    def attemptLogin(self, trys):
        count = 0
        while count < trys:
            resp = self.session.post("{url}/login".format(url=self.url), data={"username":self.user, "password":self.password}, timeout=25)
            if resp.status_code == 200:
                self.session.headers.update(resp.json())
                return resp
            else:
                print "Login attempt {c} failed, response: {j}".format(c=count, j=resp.json())
                print "Sleeping 10s before retry..."
                time.sleep(10)
            count += 1
        print "Error: OpsC connection failed after {n} trys".format(n=trys)
        return None

    def addCluster(self, cname, credid, repoid, configid, password):
        try:
            conf = json.dumps({
                'name': cname,
                'machine-credential-id': credid,
                'repository-id': repoid,
                'config-profile-id': configid,
                'old-password': 'cassandra',
                'new-password': password})
            clusterconf = self.session.post("{url}/api/v2/lcm/clusters/".format(url=self.url), data=conf).json()
            print "Added cluster, json:"
            pretty(clusterconf)
            return clusterconf['id']
        except requests.exceptions.Timeout as e:
            print "Request for cluster config timed out."
            return None
        except requests.exceptions.ConnectionError as e:
            print "Request for cluster config refused."
            return None
        except Exception as e:
            # Do something?
            raise
        return clusterconf

    def addCred(self, cred):
        try:
            creds = self.session.get("{url}/api/v2/lcm/machine_credentials/".format(url=self.url)).json()
            if creds['count'] == 0:
                creds = self.session.post("{url}/api/v2/lcm/machine_credentials/".format(url=self.url), data=cred).json()
                print "Added default dse creds, json:"
                pretty(creds)
                return creds
        except requests.exceptions.Timeout as e:
            print "Request to add ssh creds timed out."
            return None
        except requests.exceptions.ConnectionError as e:
            print "Request to add ssh creds refused."
            return None
        except Exception as e:
            # Do something?
            raise

    def addConfig(self, conf):
        try:
            configs = self.session.get("{url}/api/v2/lcm/config_profiles/".format(url=self.url)).json()
            if configs['count'] == 0:
                config = self.session.post("{url}/api/v2/lcm/config_profiles/".format(url=self.url), data=conf).json()
                print "Added default config profile, json:"
                pretty(config)
                return config
        except requests.exceptions.Timeout as e:
            print "Request to add config profile timed out."
            return None
        except requests.exceptions.ConnectionError as e:
            print "Request to add config profile refused."
            return None
        except Exception as e:
            # Do something?
            raise

    def addRepo(self, repo):
        try:
            repos = self.session.get("{url}/api/v2/lcm/repositories/".format(url=self.url)).json()
            if repos['count'] == 0:
                repconf = self.session.post("{url}/api/v2/lcm/repositories/".format(url=self.url), data=repo).json()
                print "Added default repo, json:"
                pretty(repconf)
                return repconf
        except requests.exceptions.Timeout as e:
            print "Request to add repo timed out."
            return None
        except requests.exceptions.ConnectionError as e:
            print "Request to add repo refused."
            return None
        except Exception as e:
            # Do something?
            raise

    def waitForCluster(self, cname, pause, trys):
        count = 0
        while True:
            count += 1
            if count > trys:
                return False
            found = self.checkForCluster(cname)
            if found:
                print "Cluster found."
                return True
            print "Cluster not found on try {c}, wait {p} sec...".format(c=count, p=pause)
            time.sleep(pause)

    def waitForNodes(self, numnodes, pause, trys):
        count = 0
        while True:
            count += 1
            if count > trys:
                return False
            nodes = self.session.get("{url}/api/v2/lcm/nodes/".format(url=self.url)).json()
            ncount = nodes["count"]
            if ncount >= numnodes:
                print "{n} nodes found.".format(n=numnodes)
                return True
            print "Only found {f} < {n} on try {c}, wait {p} sec...".format(f=ncount, n=numnodes, c=count, p=pause)
            time.sleep(pause)

    def checkForCluster(self, cname):
        try:
            clusters = self.session.get("{url}/api/v2/lcm/clusters/".format(url=self.url)).json()
            if not ('results' in clusters):
                return False
            for r in clusters['results']:
                if r['name'] == cname:
                    return True
            return False
        except requests.exceptions.Timeout as e:
            print "Request for cluster config timed out."
            return False
        except requests.exceptions.ConnectionError as e:
            print "Request for cluster config refused."
            return False
        except Exception as e:
            # Do something?
            raise

    def checkForDC(self, dcname):
        try:
            dcs = self.session.get("{url}/api/v2/lcm/datacenters/".format(url=self.url)).json()
            exists = False
            for dc in dcs['results']:
                if dc['name'] == dcname:
                    exists = True
            return exists
        except requests.exceptions.Timeout as e:
            print "Request to add repo timed out."
            return None
        except requests.exceptions.ConnectionError as e:
            print "Request to add repo refused."
            return None
        except Exception as e:
            # Do something?
            raise

    def addDC(self, dcname, cid, nograph):
        try:
            dc = {
                'name': dcname,
                'cluster-id': cid,
                "graph-enabled": True,
                "solr-enabled": True,
                "spark-enabled": True}
            if nograph:
                print "Disabling graph workload"
                dc['graph-enabled'] = False
            dcjson = json.dumps(dc)
            dcconf = self.session.post("{url}/api/v2/lcm/datacenters/".format(url=self.url), data=dcjson).json()
            # edge case where api returns "server error" string not json
            if isinstance(dcconf, (str, unicode)):
                print "Unexpected return value: ", dcconf
                print "Retry after 5s sleep..."
                time.sleep(5)
                dcconf = self.session.post("{url}/api/v2/lcm/datacenters/".format(url=self.url), data=dcjson).json()
            if 'code' in dcconf and (dcconf['code'] == 409):
                print "Warning: {d}".format(d=dcconf)
                print "Finding id for dcname='{n}'".format(n=dcname)
                alldcs = self.session.get("{url}/api/v2/lcm/datacenters/".format(url=self.url)).json()
                for r in alldcs['results']:
                    if r['name'] == dcname:
                        print "Found id='{n}'".format(n=r['id'])
                        return r['id']
            print "Added datacenter {n}, json:".format(n=dcname)
            pretty(dcconf)
            return dcconf['id']
        except requests.exceptions.Timeout as e:
            print "Request to add repo timed out."
            return None
        except requests.exceptions.ConnectionError as e:
            print "Request to add repo refused."
            return None
        except Exception as e:
            # Do something?
            raise

    # Install will use larger scope, if both passed.
    def triggerInstall(self, cid, dcid):
        scope = "datacenter"
        r_id = dcid
        if cid != None:
            scope = "cluster"
            r_id = cid
        job = {"job-type":"install",
               "job-scope":scope,
               "resource-id":r_id,
               "auto-bootstrap":False,
               "continue-on-error":True}
        data = json.dumps(job)
        response = self.session.post("{url}/api/v2/lcm/actions/install".format(url=self.url), data=data).json()
        pretty(response)


text:
module Spree
  module Admin
    class OrdersController < Spree::Admin::BaseController
      before_action :initialize_order_events
      before_action :load_order, only: [:edit, :update, :cancel, :resume, :approve, :resend, :open_adjustments, :close_adjustments, :cart]

      respond_to :html

      def index
        params[:q] ||= {}
        params[:q][:completed_at_not_null] ||= '1' if Spree::Config[:show_only_complete_orders_by_default]
        @show_only_completed = params[:q][:completed_at_not_null] == '1'
        params[:q][:s] ||= @show_only_completed ? 'completed_at desc' : 'created_at desc'
        params[:q][:completed_at_not_null] = '' unless @show_only_completed

        # As date params are deleted if @show_only_completed, store
        # the original date so we can restore them into the params
        # after the search
        created_at_gt = params[:q][:created_at_gt]
        created_at_lt = params[:q][:created_at_lt]

        params[:q].delete(:inventory_units_shipment_id_null) if params[:q][:inventory_units_shipment_id_null] == "0"

        if params[:q][:created_at_gt].present?
          params[:q][:created_at_gt] = Time.zone.parse(params[:q][:created_at_gt]).beginning_of_day rescue ""
        end

        if params[:q][:created_at_lt].present?
          params[:q][:created_at_lt] = Time.zone.parse(params[:q][:created_at_lt]).end_of_day rescue ""
        end

        if @show_only_completed
          params[:q][:completed_at_gt] = params[:q].delete(:created_at_gt)
          params[:q][:completed_at_lt] = params[:q].delete(:created_at_lt)
        end

        @search = Order.accessible_by(current_ability, :index).ransack(params[:q])

        # lazyoading other models here (via includes) may result in an invalid query
        # e.g. SELECT  DISTINCT DISTINCT "spree_orders".id, "spree_orders"."created_at" AS alias_0 FROM "spree_orders"
        # see https://github.com/spree/spree/pull/3919
        @orders = @search.result(distinct: true).
          page(params[:page]).
          per(params[:per_page] || Spree::Config[:orders_per_page])

        # Restore dates
        params[:q][:created_at_gt] = created_at_gt
        params[:q][:created_at_lt] = created_at_lt
      end

      def new
        @order = Order.create(order_params)
        redirect_to cart_admin_order_url(@order)
      end

      def edit
        can_not_transition_without_customer_info

        unless @order.completed?
          @order.refresh_shipment_rates
        end
      end

      def cart
        unless @order.completed?
          @order.refresh_shipment_rates
        end
        if @order.shipped_shipments.count > 0
          redirect_to edit_admin_order_url(@order)
        end
      end

      def update
        if @order.update_attributes(params[:order]) && @order.line_items.present?
          @order.update!
          unless @order.completed?
            # Jump to next step if order is not completed.
            redirect_to admin_order_customer_path(@order) and return
          end
        else
          @order.errors.add(:line_items, Spree.t('errors.messages.blank')) if @order.line_items.empty?
        end

        render :action => :edit
      end

      def cancel
        @order.canceled_by(try_spree_current_user)
        flash[:success] = Spree.t(:order_canceled)
        redirect_to :back
      end

      def resume
        @order.resume!
        flash[:success] = Spree.t(:order_resumed)
        redirect_to :back
      end

      def approve
        @order.approved_by(try_spree_current_user)
        flash[:success] = Spree.t(:order_approved)
        redirect_to :back
      end

      def resend
        OrderMailer.confirm_email(@order.id, true).deliver_later
        flash[:success] = Spree.t(:order_email_resent)

        redirect_to :back
      end

      def open_adjustments
        adjustments = @order.all_adjustments.where(state: 'closed')
        adjustments.update_all(state: 'open')
        flash[:success] = Spree.t(:all_adjustments_opened)

        respond_with(@order) { |format| format.html { redirect_to :back } }
      end

      def close_adjustments
        adjustments = @order.all_adjustments.where(state: 'open')
        adjustments.update_all(state: 'closed')
        flash[:success] = Spree.t(:all_adjustments_closed)

        respond_with(@order) { |format| format.html { redirect_to :back } }
      end

      private
        def order_params
          params[:created_by_id] = try_spree_current_user.try(:id)
          params.permit(:created_by_id)
        end

        def load_order
          @order = Order.includes(:adjustments).find_by_number!(params[:id])
          authorize! action, @order
        end

        # Used for extensions which need to provide their own custom event links on the order details view.
        def initialize_order_events
          @order_events = %w{approve cancel resume}
        end

        def model_class
          Spree::Order
        end
    end
  end
end


text:
package templates

import chisel3._
import chisel3.util.{log2Ceil, isPow2}
import chisel3.internal.sourceinfo._
import types._

class PRNG(val seed: Int, val bitWidth:Int = 32) extends Module {

  val io = IO( new Bundle {
    val en = Input(Bool())
    val output = Output(UInt(bitWidth.W))
  })

  // // Single Cycle Version
  // val reg = RegInit(seed.U(bitWidth.W))
  // val shifted = ((reg ^ (reg << 1)) ^ ((reg ^ (reg << 1)) >> 3)) ^ (((reg ^ (reg << 1)) ^ ((reg ^ (reg << 1)) >> 3)) << 10)
  // reg := Mux(io.en, shifted, reg)

  // 3 Cycle Version
  val reg = RegInit(seed.U(bitWidth.W))
  val cnt = RegInit(0.U(2.W))
  cnt := Mux(io.en, Mux(cnt === 2.U, 0.U, cnt + 1.U), cnt)
  val shift_options = List((0.U -> {reg << 1}), (1.U -> {reg >> 3}), (2.U -> {reg << 10}))
  reg := Mux(io.en, reg ^ chisel3.util.MuxLookup(cnt, 0.U, shift_options), reg)

  io.output := reg

}

// MAXJ VERSION:

// package engine;
//   import com.maxeler.maxcompiler.v2.kernelcompiler.KernelLib;
//   import com.maxeler.maxcompiler.v2.statemachine.DFEsmInput;
//   import com.maxeler.maxcompiler.v2.statemachine.DFEsmOutput;
//   import com.maxeler.maxcompiler.v2.statemachine.DFEsmStateEnum;
//   import com.maxeler.maxcompiler.v2.statemachine.DFEsmStateValue;
//   import com.maxeler.maxcompiler.v2.statemachine.DFEsmValue;
//   import com.maxeler.maxcompiler.v2.statemachine.kernel.KernelStateMachine;
//   import com.maxeler.maxcompiler.v2.statemachine.types.DFEsmValueType;

// class PRNGFastSM extends KernelStateMachine {

//     // States
//     enum States {
//       INIT,
//       HOLD,
//       SHIFT
//     }

//     // State IO
//     private final DFEsmOutput oNumber;
//     private final DFEsmInput iNext;
//     private final int mSeed;

//     // State storage
//     private final DFEsmStateValue sNumber;
//     private final DFEsmStateEnum<States> sMode;

//     // Initialize state machine in constructor
//     public PRNGFastSM(KernelLib owner, int seed) {
//       super(owner);
//       mSeed = seed;

//       // Declare all types required to wire the state machine together
//       DFEsmValueType numberType = dfeInt(32);
//       DFEsmValueType uType = dfeUInt(32);
//       DFEsmValueType wireType = dfeBool();

//       // Define state machine IO
//       oNumber = io.output("oNumber", uType);
//       iNext = io.input("iNext", wireType);

//       // Define state storage elements and initial state
//       sMode = state.enumerated(States.class, States.INIT);
//       sNumber = state.value(numberType, mSeed);
//     }

//     private DFEsmValue Gen(DFEsmStateValue number) {
//       // // Separated XORSHIFT
//       // DFEsmValue s1 = number ^ (number << 1);
//       // DFEsmValue s2 = s1 ^ (s1 >> 3);
//       // DFEsmValue s3 = s2 ^ (s2 << 10);
//       // return s3;

//       // In-lined XORSHIFT via substitution
//       return ((number ^ (number << 1)) ^ ((number ^ (number << 1)) >> 3)) ^ (((number ^ (number << 1)) ^ ((number ^ (number << 1)) >> 3)) << 10);
//     }

//     @Override
//     protected void nextState() {
//       SWITCH(sMode) {
//         CASE(States.INIT) {
//           IF(iNext === true) {
//             sNumber.next <== sNumber;
//             sMode.next <== States.SHIFT;
//           } ELSE {
//             sNumber.next <== sNumber;
//             sMode.next <== States.HOLD;
//           }
//         }
//         CASE(States.SHIFT) {
//           IF(iNext === true) {
//             sNumber.next <== Gen(sNumber); // DO LOGIC
//             sMode.next <== States.SHIFT;
//           } ELSE {
//             sNumber.next <== sNumber;
//             sMode.next <== States.HOLD;
//           }
//         }
//         CASE(States.HOLD) {
//           IF(iNext === true) {
//             sNumber.next <== Gen(sNumber); // DO LOGIC
//             sMode.next <== States.SHIFT;
//           } ELSE {
//             sNumber.next <== sNumber;
//             sMode.next <== States.HOLD;
//           }
//         }
//       }
//     }

//   @Override
//     protected void outputFunction() {
//       DFEsmValueType numberType = dfeUInt(32);
//       oNumber <== sNumber.cast(numberType);
//     }
// }


text:
package push

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// QueryPushStatByMsg invokes the push.QueryPushStatByMsg API synchronously
// api document: https://help.aliyun.com/api/push/querypushstatbymsg.html
func (client *Client) QueryPushStatByMsg(request *QueryPushStatByMsgRequest) (response *QueryPushStatByMsgResponse, err error) {
	response = CreateQueryPushStatByMsgResponse()
	err = client.DoAction(request, response)
	return
}

// QueryPushStatByMsgWithChan invokes the push.QueryPushStatByMsg API asynchronously
// api document: https://help.aliyun.com/api/push/querypushstatbymsg.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) QueryPushStatByMsgWithChan(request *QueryPushStatByMsgRequest) (<-chan *QueryPushStatByMsgResponse, <-chan error) {
	responseChan := make(chan *QueryPushStatByMsgResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.QueryPushStatByMsg(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// QueryPushStatByMsgWithCallback invokes the push.QueryPushStatByMsg API asynchronously
// api document: https://help.aliyun.com/api/push/querypushstatbymsg.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) QueryPushStatByMsgWithCallback(request *QueryPushStatByMsgRequest, callback func(response *QueryPushStatByMsgResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *QueryPushStatByMsgResponse
		var err error
		defer close(result)
		response, err = client.QueryPushStatByMsg(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// QueryPushStatByMsgRequest is the request struct for api QueryPushStatByMsg
type QueryPushStatByMsgRequest struct {
	*requests.RpcRequest
	AppKey    requests.Integer `position:"Query" name:"AppKey"`
	MessageId requests.Integer `position:"Query" name:"MessageId"`
}

// QueryPushStatByMsgResponse is the response struct for api QueryPushStatByMsg
type QueryPushStatByMsgResponse struct {
	*responses.BaseResponse
	RequestId string    `json:"RequestId" xml:"RequestId"`
	PushStats PushStats `json:"PushStats" xml:"PushStats"`
}

// CreateQueryPushStatByMsgRequest creates a request to invoke QueryPushStatByMsg API
func CreateQueryPushStatByMsgRequest() (request *QueryPushStatByMsgRequest) {
	request = &QueryPushStatByMsgRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Push", "2016-08-01", "QueryPushStatByMsg", "", "")
	return
}

// CreateQueryPushStatByMsgResponse creates a response to parse from QueryPushStatByMsg response
func CreateQueryPushStatByMsgResponse() (response *QueryPushStatByMsgResponse) {
	response = &QueryPushStatByMsgResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
using UnityEngine;
using System.Collections;

public class TouchLayer : MonoBehaviour {

	private TextMesh textMesh;

	private Rect rect1 = new Rect(0,50,200,200);
	private Rect rect2 = new Rect(300,50,200,135);

	// Subscribe to events
	void OnEnable(){
		EasyTouch.On_TouchStart += On_TouchStart;
	}

	void OnDisable(){
		EasyTouch.On_TouchStart -= On_TouchStart;
	}

	void OnDestroy(){
		EasyTouch.On_TouchStart -= On_TouchStart;
	}

	void Start () {
		textMesh =(TextMesh)GameObject.Find("TouchOnLayer").transform.gameObject.GetComponent("TextMesh");
		EasyTouch.AddReservedGuiArea( rect1 );
		EasyTouch.AddReservedGuiArea( rect2 );
	}

	void OnGUI(){
		GUI.Box( rect1,"Reserved area");
		GUI.Box( rect2,"Reserved area");
	}

	// At the touch beginning
	public void On_TouchStart(Gesture gesture){

		// Verification that the action on the object
		if (gesture.pickObject !=null && !gesture.isHoverReservedArea){
			gesture.pickObject.renderer.material.color = new Color( Random.Range(0.0f,1.0f),  Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f));

			if (gesture.pickCamera == null){
				textMesh.text = "Touch on layer :" + LayerMask.LayerToName( gesture.pickObject.layer);
			}
			else{
				textMesh.text = "Touch on layer :" + LayerMask.LayerToName( gesture.pickObject.layer) + " / Camera : " + gesture.pickCamera.name;
			}
		}
		else{
			if (gesture.isHoverReservedArea){
				textMesh.text = "You touch a reserved area";
			}
			else{
				textMesh.text = "Yout touch a free zone";
			}
		}

	}
}


text:
package org.gearvrf;

import android.content.res.AssetManager;

import org.gearvrf.utility.VrAppSettings;

/**
 * {@inheritDoc}
 */
final class MonoscopicActivityDelegate extends GVRApplication.ActivityDelegateStubs {
    @Override
    public void onCreate(GVRApplication activity) {
        if (null == activity) {
            throw new IllegalArgumentException();
        }

        mApplication = activity;
    }

    @Override
    public GVRViewManager makeViewManager() {
        return new MonoscopicViewManager(mApplication, mApplication.getMain(), mXmlParser);
    }

    @Override
    public GVRCameraRig makeCameraRig(GVRContext context) {
        return new GVRCameraRig(context);
    }

    @Override
    public GVRConfigurationManager makeConfigurationManager() {
        return new MonoscopicConfigurationManager(mApplication);
    }

    @Override
    public void parseXmlSettings(AssetManager assetManager, String dataFilename) {
        mXmlParser = new MonoscopicXMLParser(assetManager, dataFilename, mApplication.getAppSettings());
    }

    @Override
    public boolean onBackPress() {
        return true;
    }

    @Override
    public boolean setMain(GVRMain gvrMain, String dataFileName) {
        return true;
    }

    @Override
    public VrAppSettings makeVrAppSettings() {
        return new MonoscopicVrAppSettings();
    }

    private GVRApplication mApplication;
    private MonoscopicXMLParser mXmlParser;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. nat. Oyonnax 8: 76 (1954)

#### Original name
Pleurotellus acerosus var. tenellus Kühner

### Remarks
null


text:
published: true
title: Tetse
layout: post
---
testando blog


text:
title: Working Group on Open Expenditure Data
---

## Working Group on Open Spending Data

### Purpose

* Act as a central point of reference and support for people who are interested in open spending data.
* Develop principles for making official and unofficial information about spending legally and technically open
* Document background and status of initiatives to make official information open in different countries
* Support efforts to make spending data discoverable and channels and methods for collaboration around it.
* Work closely with the [Working Group on Open Data in Economics](http://wiki.okfn.org/Working_Groups/Economics) to help contextualise spending and budget data for the purposes of analysis and research.

### Possible activities (to be reviewed)

* Contributing to / providing feedback on  a Spending Data Manual - A wiki-like, community driven manual on acquiring, working with, publishing and archiving spending data, (building on and referencing other works e.g. World Bank's work on budget classifications)
* Keeping their eye-out for new and interesting initiatives springing up around spending and budget data and invite new members to join the discussion
* Help to build up a registry of spending datasets by adding to the [OpenSpending group on the DataHub](http://thedatahub.org/group/openspending)
* Writing blog updates on new developments e.g. new datasets becoming available, updates to laws in your country affecting spending data, new tools to work with, share and collaborate on data
* Considering possibilities for a Spending Data Camp, most likely at or around OGDCamp 2012 with hands-on sessions on licensing, working with and publishing data, aimed at CSOs from around the world.
* ERDF collection.

### Members

* **Alexandre Ciconello**, [INESC](http://www.inesc.org.br/news), *Brazil*
* **Avani Kapur**, [Accountability Initiative](http://www.accountabilityindia.in/), *India*
* **Codru Vrabie**, [Bribemarket](http://www.piatadespaga.ro/), *Romania*
* **Damir Mehmedbasic**, [Public Interest Advocacy Centre](http://cpi.ba/), *Bosnia and Herzegovina*
* **David Cabo**, Pro Bono Publico, *Spain*
* **Diego de la Mora**, [Fundar](http://fundar.org.mx/index.html/), *Mexico*
* **Dr Effie Vraniali**,[Fondafip](http://www.fondafip.org) and Member of Transparency International *Greece*
* **Elena Calistru**, [Lost Money](http://banipierduti.cloudapp.net/), *Romania*
* **Eva Vozarova**, [Fair-Play Alliance](http://www.fair-play.sk/index.php),  *Slovakia*
* **Federico Ramírez**, [Fundar](http://fundar.org.mx/index.html/), *Mexico*
* **Friedrich Lindenberg**, [Open Knowledge Foundation](http://okfn.org/), *Germany*
* **Hille Hinsberg**, [Praxis Policy Centre](http://www.praxis.ee/index.php?id=96&L=1), *Estonia*
* **Kaitlin Lee**, [Sunlight Foundation](http://sunlightfoundation.com/), *USA*
* **Laina Emmanuel**, [Accountability Initiative](http://www.accountabilityindia.in/), *India*
* **Lucy Chambers**, [Open Knowledge Foundation](http://okfn.org/), *United Kingdom*
* **Mark Brough**, Research Officer, [Publish What You Fund](http://www.publishwhatyoufund.org/), *United Kingdom*
* **Martin Keegan**, [Open Knowledge Foundation](http://okfn.org/), *United Kingdom*
* **Maurice Nsabimana**, [World Bank](http://www.worldbank.org/)
* **Michael Roberts**, Co-founder, [Acclar](http://acclar.org/)
* **Michal Skop**, [KohoVolit.eu](http://en.kohovolit.eu/), *Czech Republic*
* **Oluseun Onigbinde**, [BudgIT](http://yourbudgit.com/), *Nigeria*
* **Photios Zygoulis**, e-gov Coordinator, [Municipality of Neo Iraklio Attikis](http://www.iraklio.gr), *Greece*
* **Sam Lee**, [World Bank Finances](https://finances.worldbank.org/), *USA*
* **Sam Smith**, Organiser of [OpenTech](http://www.ukuug.org/events/opentech2011/), *United Kingdom*

### CSOs

* [Participatory Budgeting Unit](http://participatorybudgeting.org.uk/), UK

### Contact

* There is a [mailing list](http://lists.okfn.org/mailman/listinfo/openspending) where anyone can subscribe. Mailing list archives are public.
* Twitter: [@openspending](http://twitter.com/openspending)
* Twitter list of organisations who work with spending data: [Spending Orgs List](https://twitter.com/#!/openspending/lists)


text:
package projet.cadre.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/deconnexionDirection")
public class DeconnexionDirectionServlet extends HttpServlet {

	private static final long serialVersionUID = 790144859160282054L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().removeAttribute("directeurConnecte");
		response.sendRedirect("connexionIntranetDirection");
	}

}


text:
import CustomStackNavigator from '../CustomStackNavigator'

import Welcome from './Welcome'
import BonjourScanContainer from './BonjourScanContainer'
import AuthContainer from './AuthContainer'
import SetupEndContainer from './SetupEndContainer'

export default CustomStackNavigator({
  Welcome: {screen: Welcome},
  BonjourScan: {screen: BonjourScanContainer},
  Auth: {screen: AuthContainer},
  SetupEnd: {screen: SetupEndContainer}
})


text:
package com.gary.garytool;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.gary.garytool.function.shape.StyleActivity;
import com.gary.garytool.function.spinner.SpinnerActivity;
import com.gary.garytool.function.toast.ToastActivity;
import com.gary.garytool.util.Util;
import java.util.ArrayList;
import java.util.List;

/**
 *  Created by gary on 2016/06/29.
 * @author gary guo
 * 本类用于记录安卓系统控件的基础用法
 */
public class MainControlActivity extends Activity {
    private ListView lvList;
    private  List<String> mData=new ArrayList<String>(){
        {
            add("Style");//shape selector anim theme
            add("TextView");
            add("EditText");
            add("Button");
            add("ImageView");
            add("Spinner");
            add("进度条");
            add("对话框");
            add("Toast");
            add("Notification");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);
        lvList = (ListView) findViewById(R.id.lv_list);
        MyAdapter adapter = new MyAdapter(this);
        lvList.setAdapter(adapter);
    }

    private class MyAdapter extends BaseAdapter {

        private void onItemClick(int position) {
            String value= (String) getItem(position);
            if(value.equals("Spinner"))
                Util.startActivity(MainControlActivity.this, SpinnerActivity.class);
            else if(value.equals("Toast"))
                Util.startActivity(MainControlActivity.this, ToastActivity.class);
            else if(value.equals("Style"))
                Util.startActivity(MainControlActivity.this, StyleActivity.class);
        }

        private LayoutInflater mInflater;
        public MyAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

                ViewHolder holder;
                if (convertView == null) {
                    holder = new ViewHolder();
                    convertView = mInflater.inflate(R.layout.listview_item, null);
                    holder.item = (Button) convertView.findViewById(R.id.list_item);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.item.setText(mData.get(position));
                holder.item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onItemClick(position);
                    }
                });
            return convertView;
        }

        @Override
        public int getCount() {
            return mData.size();
        }
        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }

        public final class ViewHolder {
            public Button item;
        }

    }

}


text:
<?php

namespace RA\OroCrmTimeLapBundle\Model;

class Period implements PeriodInterface
{
    const DEFAULT_TIMEZONE = 'UTC';

    /**
     * @var \DateTime
     */
    private $begin;

    /**
     * @var \DateTime
     */
    private $end;

    /**
     * @param \DateTime $begin should be in UTC date time zone, if not - it will be cast to UTC
     * @param \DateTime $end should be in UTC date time zone, if not - it will be cast to UTC
     */
    public function __construct(\DateTime $begin, \DateTime $end)
    {
        if ($begin > $end) {
            throw new \InvalidArgumentException('Begin date can not be greater than end date.');
        }
        $timezone = new \DateTimeZone(self::DEFAULT_TIMEZONE);
        $this->begin = clone $begin;
        $this->end = clone $end;
        $this->begin->setTimezone($timezone);
        $this->end->setTimezone($timezone);
    }

    /**
     * {@inheritdoc}
     */
    public function getBegin()
    {
        return clone $this->begin;
    }

    /**
     * {@inheritdoc}
     */
    public function getEnd()
    {
        return clone $this->end;
    }
}


text:
#pragma once

namespace ABI43_0_0facebook {
namespace ABI43_0_0React {

enum class EventPriority : int {
  SynchronousUnbatched,
  SynchronousBatched,
  AsynchronousUnbatched,
  AsynchronousBatched,

  Sync = SynchronousUnbatched,
  Work = SynchronousBatched,
  Interactive = AsynchronousUnbatched,
  Deferred = AsynchronousBatched
};

} // namespace ABI43_0_0React
} // namespace ABI43_0_0facebook


text:
'use strict';

var path = require('path');

require('shelljs/global');

var cwd = pwd().toString();
var npmVersion = parseInt(exec('npm --version', { silent: true }), 10);

// Copy the legal files from the root of the repo so they are included in the
// release
cp(path.join(__dirname, '../AUTHORS'), cwd);
cp(path.join(__dirname, '../CONTRIBUTORS'), cwd);
cp(path.join(__dirname, '../COPYING'), cwd);

var args = process.argv.splice(1);
var moduleName = args[1];
var newVersion = args[2].replace(/^v*/, '');
var tagName = [moduleName, newVersion].join('-');

if (moduleName === 'google-cloud') {
  if (npmVersion < 3) {
    throw new Error([
      'Publishing google-cloud requires the latest npm.',
      'Please update by running `npm install -g npm` before publishing.'
    ].join(' '));
  }

  tagName = ('v' + newVersion);
  cp(path.join(__dirname, '../README.md'), cwd);
}

// Increment the version
exec('npm --no-git-tag-version version ' + newVersion, {
  cwd: cwd
});

console.log('Publishing package in 10 seconds. Exit process to abort');

setTimeout(function() {
  console.log('Publishing now');

  if (moduleName === 'google-cloud') {
    exec('rm -rf node_modules', {
      cwd: cwd
    });

    exec('npm install', {
      cwd: cwd
    });

    exec('npm dedupe', {
      cwd: cwd
    });

    exec('npm shrinkwrap', {
      cwd: cwd
    });
  }

  // To circumvent an npm bug which can publish empty node_modules
  exec('rm -rf node_modules', {
    cwd: cwd
  });

  // Publish the module
  exec('npm publish', {
    cwd: cwd
  });

  // Remove the duplicated files
  rm([
    path.join(cwd, 'AUTHORS'),
    path.join(cwd, 'CONTRIBUTORS'),
    path.join(cwd, 'COPYING')
  ]);

  exec('git commit -am "' + moduleName + ' @ ' + newVersion + ' tagged."');

  // Create a git tag
  exec('git tag -a ' + tagName + ' -m "' + moduleName + ' release for ' + newVersion + '"', {
    cwd: cwd
  });

  console.log('Now push to master: git push origin master --follow-tags"');
}, 10000);


text:
#include "DavidsonDiagonalizer.h"
#include "../MathUtils.h"
#include "DiagonalizerSettings.h"
#include "PreconditionerEvaluator.h"
#include "SubspaceOrthogonalizer.h"
#include <Core/Log.h>
#include <Eigen/Eigenvalues>

namespace Scine {
namespace Utils {

NonOrthogonalDavidson::NonOrthogonalDavidson(int eigenvaluesToCompute, int totalDimension)
  : KrylovDiagonalizer(eigenvaluesToCompute, totalDimension) {
}

NonOrthogonalDavidson::~NonOrthogonalDavidson() = default;

EigenContainer NonOrthogonalDavidson::eigenDecomposition(const Eigen::MatrixXd& projectedMatrix) const {
  auto algorithm = settings_->getString(gepAlgorithmForBalancedMethodOption);
  if (algorithm == "standard")
    return MathUtils::stabilizedGeneralizedEigendecomposition<MathUtils::GepAlgorithm::Standard>(
        projectedMatrix, basisOverlap_.selfadjointView<Eigen::Upper>());
  else if (algorithm == "cholesky")
    return MathUtils::stabilizedGeneralizedEigendecomposition<MathUtils::GepAlgorithm::Cholesky>(
        projectedMatrix, basisOverlap_.selfadjointView<Eigen::Upper>());
  else if (algorithm == "simultaneous_diag")
    return MathUtils::stabilizedGeneralizedEigendecomposition<MathUtils::GepAlgorithm::SimultaneousDiagonalization>(
        projectedMatrix, basisOverlap_.selfadjointView<Eigen::Upper>());
  else
    throw InvalidDiagonalizerInputException("Algorithm " + algorithm + " not available for stable GEP solution.");
}

inline void NonOrthogonalDavidson::onSigmaMatrixEvaluation(const Eigen::MatrixXd& projector) {
  decltype(basisOverlap_)::Index newCols = subspaceDimension_ - basisOverlap_.cols();
  basisOverlap_.conservativeResize(subspaceDimension_, subspaceDimension_);
  Eigen::MatrixXd rightCols = projector.rightCols(newCols);
  basisOverlap_.rightCols(newCols) = projector.transpose() * rightCols;
}

inline void NonOrthogonalDavidson::filterCorrectionVectors(const Eigen::MatrixXd& projector,
                                                           Eigen::MatrixXd& newGuessVectors) const {
  double absNorm =
      std::abs(newGuessVectors.col(newGuessVectors.cols() - 1).transpose() * projector.col(projector.cols() - 1));
  if (absNorm > 1.0 - settings_->getDouble(correctionToleranceOption)) {
    newGuessVectors.col(newGuessVectors.cols() - 1) = residualVectors_.col(newGuessVectors.cols() - 1);
  }
}

void NonOrthogonalDavidson::callCollapserImpl() {
  guessVectors_ = subspaceCollapser_->getCollapsedNonOrthogonalSubspace();
  subspaceDimension_ = guessVectors_.cols();
  basisOverlap_.resize(0, 0);
}

OrthogonalDavidson::OrthogonalDavidson(int eigenvaluesToCompute, int totalDimension)
  : KrylovDiagonalizer(eigenvaluesToCompute, totalDimension) {
}

OrthogonalDavidson::~OrthogonalDavidson() = default;

inline void OrthogonalDavidson::filterCorrectionVectors(const Eigen::MatrixXd& projector, Eigen::MatrixXd& newGuessVectors) const {
  Eigen::MatrixXd orthogonalizedCorrectionVector = newGuessVectors;
  Eigen::VectorXd correctionVectorsNorms = newGuessVectors.colwise().norm();

  int dimension = 0;
  double maxNorm = 0;
  Eigen::VectorXd maxNormOrthogonalizedVector;
  for (int i = 0; i < orthogonalizedCorrectionVector.cols(); ++i) {
    Eigen::VectorXd orthogonalizedVector;
    SubspaceOrthogonalizer::orthogonalizeToSubspace(orthogonalizedCorrectionVector.col(i), projector, orthogonalizedVector);

    double norm = orthogonalizedVector.norm() / correctionVectorsNorms(i);
    if (norm > maxNorm) {
      std::swap(norm, maxNorm);
      maxNormOrthogonalizedVector = orthogonalizedVector;
    }

    if (norm / correctionVectorsNorms(i) > settings_->getDouble(correctionToleranceOption)) {
      newGuessVectors.col(dimension++) = orthogonalizedVector;
    }
  }
  // Retain one at least if everything is thrown away, the one that corrects the most
  if (dimension == 0) {
    newGuessVectors.col(0) = maxNormOrthogonalizedVector;
    dimension = 1;
  }
  newGuessVectors.conservativeResize(Eigen::NoChange, dimension);
}

inline void OrthogonalDavidson::onIterationStart() {
  KrylovDiagonalizer::onIterationStart();
  SubspaceOrthogonalizer::qrOrthogonalize(guessVectors_, subspaceDimension_);
  guessVectors_.leftCols(subspaceDimension_).colwise().normalize();
}

EigenContainer OrthogonalDavidson::eigenDecomposition(const Eigen::MatrixXd& projectedMatrix) const {
  EigenContainer result;
  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> subspaceDiagonalizer(projectedMatrix);
  result.eigenVectors = subspaceDiagonalizer.eigenvectors();
  result.eigenValues = subspaceDiagonalizer.eigenvalues();
  return result;
}

void OrthogonalDavidson::callCollapserImpl() {
  guessVectors_ = subspaceCollapser_->getCollapsedOrthogonalSubspace();
  subspaceDimension_ = guessVectors_.cols();
}
} // namespace Utils
} // namespace Scine


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.hadoop.portmap (Apache Hadoop NFS 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.portmap

Classes

PortmapMapping

PortmapRequest

PortmapResponse


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Collema tenax var. litoreum Sommerf.

### Remarks
null


text:
var expect = require('expect.js');
var Server = require('../').NetrixServer;
var Client = require('../').NetrixClient;

describe('intergation', function () {

  beforeEach('reset metrics', function () {
    this.metrics = [];
  });

  beforeEach('start server', function () {
    var _this = this;
    this.server = new Server({
      port: 49494,
      flushInterval: 200
    });
    this.server.on('flush', function (timestamp, metrics) {
      _this.metrics.push(metrics);
    });
    return this.server.start();
  });

  beforeEach('start client', function () {
    this.client = new Client({
      host: 'localhost',
      port: 49494,
      flushInterval: 50,
      maxDatagram: 1024
    });
    return this.client.start();
  });

  afterEach('stop client', function () {
    return this.client.stop();
  });

  afterEach('stop server', function () {
    return this.server.stop();
  });

  it('emits collected and aggregated counter metrics', function (done) {
    var _this = this;

    setTimeout(function () {
      // scaled up to per second from per 200ms
      expect(_this.metrics[0].counters['counter.name']).to.equal(5);
      expect(_this.metrics[1].counters['counter.name']).to.equal(0);
      expect(_this.metrics[2].counters['counter.name']).to.equal(15);

      done();
    }, 700); // encapsulates 3 x 200ms (flushInterval)

    setTimeout(function () {
      _this.client.increment('counter.name');
    }, 100); // into first report (flush)

    setTimeout(function () {
      _this.client.increment('counter.name');
      _this.client.increment('counter.name');
      _this.client.increment('counter.name');
    }, 450); // into 3rd report (flush)
  });

  it('emits collected and aggregated gauge metrics', function (done) {
    var _this = this;

    setTimeout(function () {
      expect(_this.metrics[0].gauges['gauge.name']).to.equal(1.5);
      expect(_this.metrics[1].gauges['gauge.name']).to.equal(1.5);
      expect(_this.metrics[2].gauges['gauge.name']).to.equal(1.15);

      done();
    }, 700); // encapsulates 3 x 200ms (flushInterval)

    setTimeout(function () {
      _this.client.gauge('gauge.name', 1.5);
    }, 100); // into first report (flush)

    setTimeout(function () {
      _this.client.gauge('gauge.name', 1.2);
      _this.client.gauge('gauge.name', 1.1);
      // _this.client.gauge('gauge.name', 1);
    }, 450); // into 3rd report (flush)
  });

  it('counts metrics and messages', function (done) {
    var _this = this;

    this.client.increment('counter.name');
    this.client.increment('counter.name');
    this.client.increment('counter.name');
    this.client.increment('counter.name');
    this.client.increment('counter.name');

    setTimeout(function () {
      expect(_this.metrics[0].counters['netrix.bytes.received']).to.equal(420);
      expect(_this.metrics[0].counters['netrix.frames.received']).to.equal(5);
      expect(_this.metrics[0].counters['netrix.metrics.received']).to.equal(25);

      done();
    }, 300);

  });

  it('gauges flush lag', function (done) {
    var _this = this;

    setTimeout(function () {

      expect(_this.metrics[0].gauges['netrix.flush.lag']).to.be.lessThan(10);
      done();

    }, 300);

  });

  it('can reset metrics', function (done) {
    var _this = this;

    this.client.increment('counter.name');

    setTimeout(function () {
      _this.server.reset();
      _this.metrics.length = 0;
    }, 300);

    setTimeout(function () {

      expect(_this.metrics[0].counters).to.eql({
        'netrix.bytes.received': 0,
        'netrix.frames.received': 0,
        'netrix.metrics.received': 0
      });

      expect(Object.keys(_this.metrics[0].gauges)).to.eql([
        'netrix.flush.lag'
      ]);

      done();
    }, 500);

  });

});


text:
package io.vertx.example.webclient.send.helloworld;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.buffer.Buffer;
import io.vertx.example.util.Runner;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;

/*
 * @author Julien Viet
 */
public class Client extends AbstractVerticle {

  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(Client.class);
  }

  @Override
  public void start() throws Exception {

    WebClient client = WebClient.create(vertx);

    Buffer body = Buffer.buffer("Hello World");

    client.put(8080, "localhost", "/").sendBuffer(body, ar -> {
      if (ar.succeeded()) {
        HttpResponse<Buffer> response = ar.result();
        System.out.println("Got HTTP response with status " + response.statusCode());
      } else {
        ar.cause().printStackTrace();
      }
    });
  }
}


text:
package com.samuel.downloader.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;

public class FocusGallery extends Gallery {

	public FocusGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	 private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2){
	     return e2.getX() > e1.getX();
	    }
	  @Override
	  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
	    float velocityY) {
		   int kEvent;
		   if(isScrollingLeft(e1, e2)){
			   kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
		   }else{
		    	kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
		   }
		   onKeyDown(kEvent, null);
		   return true;
	 }

}


text:
Adaptive Span is a novel self-attention mechanism that can learn its optimal
attention span. This allows us to extend significantly the maximum context size
used in Transformer, while maintaining control over their memory footprint
and computational time. It uses the Truncated BPTT technique for training,
as in [transformerXL](https://github.com/pytorch/fairseq/blob/main/examples/truncated_bptt/README.md).

Adaptive Span was introduced by paper:
[Adaptive Attention Span in Transformers](https://arxiv.org/abs/1905.07799),
which achieved state-of-the-art language modeling results at the time of publication.

We manage to reproduce their result in fairseq and keep most of the
[original implementation](https://github.com/facebookresearch/adaptive-span) untouched.
You can refer to the their sweep file as well if any combination of hyperparameter is not clear.

##### 0. Setup

First you need to process the Enwik8 dataset, we use the pre-tokenized dataset
from [adaptive span paper](https://github.com/facebookresearch/adaptive-span/blob/master/get_data.sh).
You can download the dataset, and then run:
```bash
fairseq-preprocess --only-source --trainpref ~/data/enwik8/train.txt \
    --validpref ~/data/enwik8/valid.txt --testpref ~/data/enwik8/test.txt \
    --destdir ~/data/enwik8/data-bin/ --joined-dictionary --workers 20
```

##### 1. Train a Adaptive Span model on Enwik8

We will train a 12-layer Adaptive Span model following the [hyperparameters
used in the original
paper](https://github.com/facebookresearch/adaptive-span/blob/master/experiments/enwik8.sh).

The following command assumes 4 GPUs, so that the total batch size is 64
sequences (4 x 16). Training should take 2-3 days on 4 V100 GPUs:
```bash
CUDA_VISIBLE_DEVICES=0,1,2,3 fairseq-train \
    --user-dir examples/adaptive_span \
    --data  ~/data/enwik8/data-bin/ \
    --fp16 --fp16-no-flatten-grads --max-update 600000 \
    --task truncated_bptt_lm --tokens-per-sample 512 --arch adaptive_span \
    --n-layer 12 --d-model 512 --n-head 8 --d-inner 2048 --dropout 0.3 \
    --attn-span 8192 --optimizer adagrad_with_grad_clip --adagrad-clip 0.03 \
    --validate-interval-updates 1000 \
    --lr-scheduler fixed --warmup-updates 32000 --batch-size-valid 32 \
    --lr 0.07 --criterion adaptive_span_loss --batch-size 16 --update-freq 1 \
    --seed 2 --log-format json --log-interval 25 --aux-loss-scaler 5e-07
```
This should land around 1.05 on validation, 1.03 on test. You can lower the
--aux-loss-scaler for better performance (longer span). It gives ~0.03 bpc
improvement to the transformerXL baseline here.
If training on a single GPU, set `--update-freq=4` to accumulate 4x gradients
and simulate training on 4 GPUs.
You can also reproduce the transformerXL result on enwik8 using this code base.
It should land around 1.06 on test,matching the [original paper](https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/run_enwik8_base.sh).
You can try by
```bash
CUDA_VISIBLE_DEVICES=0,1,2,3 fairseq-train \
    --user-dir examples/truncated_bptt \
    ~/data/enwik8/data-bin/ \
    --task truncated_bptt_lm  --fp16 --max-update 400000 \
    --tokens-per-sample 512 --arch transformer_xl --n-layer 12 \
    --d-model 512 --n-head 8 --d-head 64 --d-inner 2048 --dropout 0.1 \
    --dropatt 0.0 --mem-len 512 --optimizer adam --clip-norm 0.25 \
    --lr-scheduler cosine --warmup-updates 0 \
    --lr 0.0 --lr 0.00025 --batch-size 15 \
    --update-freq 1 --seed 2 --log-format json --log-interval 25 \
    --fp16
```

##### 2. Evaluate
For Adaptive Span:
```bash
fairseq-eval-lm ~/data/enwik8/data-bin/ --path model/checkpoint_best.pt \
 --user-dir examples/adaptive_span \
 --task truncated_bptt_lm --batch-size 8 --tokens-per-sample 512 --gen-subset test
```
For Transformer-XL evaluation:
```bash
fairseq-eval-lm ~/data/enwik8/data-bin/ --path model/checkpoint_best.pt \
    --user-dir examples/truncated_bptt/ --task truncated_bptt_lm --batch-size 8 \
    --tokens-per-sample 80 \
    --model-overrides '{"mem_len":2100,"clamp_len":820,"same_length":True}' \
    --gen-subset valid
```

*Note:* During training the model saw 512 tokens of context
(``--tokens-per-sample=512``), with batch size 8. These settings match the evaluation
settings from [the original
paper](https://github.com/facebookresearch/adaptive-span/blob/master/experiments/enwik8.sh).


text:
from ._jpackage import *
from ._jclass import *
from ._jarray import *
from ._jwrapper import *
from ._jproxy import *
from ._jexception import *
from ._core import *
from ._gui import *

# Module version (same as in the setup file)
__version_info__ = (0, 5, 5, 2)
__version__ = ".".join(str(x) for x in __version_info__)

java = JPackage("java")
javax = JPackage("javax")


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Angular et Browserify</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/solarized.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Angular + Browserify

Comment tirer le meilleur des deux

						Jean-Baptiste Dusseaut / Arpinum

Les problèmes à résoudre

Ce qui ne va pas

Penser à ajouter les balises

Les dépendances ne sont pas explicites

Chargement

Et aussi

Isoler la plomberie Angular de notre code

Organiser notre code en modules

Approche naïve

todo.js

										'use strict';
var angular = require('angular');

angular
.module('myApp')
.controller('TodoCtrl', function($scope, TodoService) {
  ...
});

app.js

							var angular = require('angular');
var app = angular.module('myApp', [ 'ngRoute' ]);

require('./service/todos');

							Ok…

Nous avons éliminé l'énumération de scripts

Mais nous avons la même énumération dans le code

Cela ne nous aide pas vraiment à organiser notre code

Duplication du nom du module

Mieux : un index par répertoire + un module angular

app.js

							var angular = require('angular');
var app = angular.module('myApp', [
'ngRoute',
require("./services/todos")
]);

index.js

							'use strict';
var myModule = require("angular").module("myApp.mySubmodule", []);
require('./edit_todo');
require('./footer');
require('./todo');
require('./todo_list');
require('./imprint');
module.exports = myModule.name;

Encore mieux: Isoler la plomberie

index.js

						'use strict';
var myModule = require('angular').module('myAPp.mySubmodule', []);

app.controller('EditTodoCtrl', require('./edit_todo'));
module.exports = myModule.name;

edit_todo.js

						'use strict';

module.exports = function($scope, TodoService) {
  ...
};

Bonus : Tests unitaires

var TodoController = require('./todos.js');

describe('The TodoController', function() {
  var controller;

  beforeEach(function() {
    controller = new TodoController();
  });

  it('should have some todos initially', function() {
    var todos = controller.getTodos();
    expect(todos.length).to.equal(4);
    expect(todos[0].title).to.equal('Buy milk');
  });
});


text:
namespace ArduinoJson {
template <typename TDerived>
class JsonBufferBase : public JsonBuffer {
 public:
  // Allocates and populate a JsonArray from a JSON string.
  //
  // The First argument is a pointer to the JSON string, the memory must be
  // writable
  // because the parser will insert null-terminators and replace escaped chars.
  //
  // The second argument set the nesting limit
  //
  // Returns a reference to the new JsonObject or JsonObject::invalid() if the
  // allocation fails.
  // With this overload, the JsonBuffer will make a copy of the string
  //
  // JsonArray& parseArray(TString);
  // TString = const std::string&, const String&
  template <typename TString>
  typename TypeTraits::EnableIf<!TypeTraits::IsArray<TString>::value,
                                JsonArray &>::type
  parseArray(const TString &json,
             uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseArray();
  }
  //
  // JsonArray& parseArray(TString);
  // TString = const char*, const char[N], const FlashStringHelper*
  template <typename TString>
  JsonArray &parseArray(
      TString *json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseArray();
  }
  //
  // JsonArray& parseArray(TString);
  // TString = std::istream&, Stream&
  template <typename TString>
  JsonArray &parseArray(
      TString &json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseArray();
  }

  // Allocates and populate a JsonObject from a JSON string.
  //
  // The First argument is a pointer to the JSON string, the memory must be
  // writable
  // because the parser will insert null-terminators and replace escaped chars.
  //
  // The second argument set the nesting limit
  //
  // Returns a reference to the new JsonObject or JsonObject::invalid() if the
  // allocation fails.
  //
  // JsonObject& parseObject(TString);
  // TString = const std::string&, const String&
  template <typename TString>
  typename TypeTraits::EnableIf<!TypeTraits::IsArray<TString>::value,
                                JsonObject &>::type
  parseObject(const TString &json,
              uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseObject();
  }
  //
  // JsonObject& parseObject(TString);
  // TString = const char*, const char[N], const FlashStringHelper*
  template <typename TString>
  JsonObject &parseObject(
      TString *json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseObject();
  }
  //
  // JsonObject& parseObject(TString);
  // TString = std::istream&, Stream&
  template <typename TString>
  JsonObject &parseObject(
      TString &json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseObject();
  }

  // Generalized version of parseArray() and parseObject(), also works for
  // integral types.
  //
  // JsonVariant parse(TString);
  // TString = const std::string&, const String&
  template <typename TString>
  typename TypeTraits::EnableIf<!TypeTraits::IsArray<TString>::value,
                                JsonVariant>::type
  parse(const TString &json,
        uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseVariant();
  }
  //
  // JsonVariant parse(TString);
  // TString = const char*, const char[N], const FlashStringHelper*
  template <typename TString>
  JsonVariant parse(TString *json,
                    uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseVariant();
  }
  //
  // JsonVariant parse(TString);
  // TString = std::istream&, Stream&
  template <typename TString>
  JsonVariant parse(TString &json,
                    uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) {
    return Internals::makeParser(that(), json, nestingLimit).parseVariant();
  }

 private:
  TDerived *that() {
    return static_cast<TDerived *>(this);
  }
};
}

#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
#pragma GCC diagnostic pop
#endif
#endif


text:
from flask import Flask, request, render_template
from flask_socketio import SocketIO

# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
async_mode = 'eventlet'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/danmu')
def index():
    return render_template('danmu.html', async_mode=socketio.async_mode)

@app.route('/trigger')
def trigger():
    danmu = request.args.get('danmu', '')
    print(danmu)
    socketio.emit('my_response',
        {'data': danmu},
        namespace='/channel')
    return 'emitted!'

if __name__ == '__main__':
    socketio.run(app)
    #app.run(debug=True, port=5005, host='127.0.0.1')


text:
Codebase API Python Client
==========================

A Python client providing read/write access to the [Codebase API](http://support.codebasehq.com/kb) with a small, but powerful, CLI.

Install
-------

    pip install git+git://github.com/igniteflow/codebase-python-api-client

CLI
---
* After pip install the `codebase` command is availably globally

To use the command-line interface, create a file called .codebase in your home directory and add your Codebase username and apikey (found in your Codebase settings page) in the following JSON format:

    {
        "CODEBASE_USERNAME": "foo/bar",
        "CODEBASE_APIKEY": "4ofh783o4hf78o4fh4o"
    }

You can now explore the API.  To see the available methods:

    codebase

To view all categories for a project and see the response in the terminal:

    codebase [project] categories

Or search:

    codebase [project] search [search term]

The CLI can call any function in the CodeBaseAPI class using the syntax:

    codebase [project] [function name] *[args]

Use the client in your code
---------------------------

    from codebase.client import CodeBaseAPI

    codebase = CodeBaseAPI(username='walter-white', apikey='84gf6479gf674gf', project='MyProject')

	# get all notes for a ticket
	notes = codebase.notes(ticket_id=1) # notes returned as a Python dict

	# update the status of a ticket (see http://support.codebasehq.com/kb/tickets-and-milestones/updating-tickets)
	note_data = {
        'ticket_note': {
            u'content': u'This is the note comment',
            u'changes': {
                u'status_id': u'1631923',
            },
        },
    }
    codebase.add_note(ticket_id=1, data=note_data)


text:
# Copyright 2020 Google
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import dataclasses
import datetime
import glob
import io
import itertools
import os
import sys
from typing import Dict, Any, Type, Union, List, Optional

import numpy as np

import cirq
from cirq import protocols

if sys.version_info > (3, 8):
    from typing import Protocol
else:
    Protocol = object

class Task(Protocol):
    fn: str

def exists(task: Task, base_dir: str):
    fn = f'{base_dir}/{task.fn}.json'
    return os.path.exists(fn)

def save(task: Task, data: Dict[str, Any], base_dir: str, mode='x'):
    with_meta = {
        'timestamp': datetime.datetime.now().isoformat(),
        'task': task,
    }
    with_meta.update(data)

    fn = f'{base_dir}/{task.fn}.json'
    os.makedirs(os.path.dirname(fn), exist_ok=True)
    with open(fn, mode) as f:
        protocols.to_json(with_meta, f)
    return fn

class Registry:
    """Mutable registry of cirq_type class name to class object to
    assist in deserialization.
    """

    def __init__(self):
        self._mapping = dict()

    def register(self, cirq_type: str, cls):
        if not cirq_type.startswith('recirq.'):
            raise ValueError("Please only use recirq.Registry for objects "
                             "in the recirq namespace.")

        self._mapping[cirq_type] = cls

    def get(self, cirq_type: str):
        return self._mapping.get(cirq_type, None)

# Singleton pattern:
Registry = Registry()

class NumpyArray:
    """Support for compact serialization of a numpy array.

    Instead of transforming data to a list-of-lists, this hex-encodes
    a binary representation of the numpy array.
    """

    def __init__(self, a: np.ndarray):
        self.a = a

    def _json_dict_(self):
        buffer = io.BytesIO()
        np.save(buffer, self.a, allow_pickle=False)
        buffer.seek(0)
        d = {
            'npy': buffer.read().hex(),
        }

        if cirq.__version__ < '0.15':
            d['cirq_type'] = 'recirq.' + self.__class__.__name__

        buffer.close()
        return d

    @classmethod
    def _json_namespace_(cls):
        return 'recirq'

    @classmethod
    def _from_json_dict_(cls, npy: str, **kwargs):
        buffer = io.BytesIO()
        buffer.write(bytes.fromhex(npy))
        buffer.seek(0)
        a = np.load(buffer, allow_pickle=False)
        buffer.close()
        return cls(a)

    def __str__(self):
        return f'recirq.NumpyArray({self.a})'

    def __repr__(self):
        return f'recirq.NumpyArray({repr(self.a)})'

    def __eq__(self, other):
        return np.array_equal(self.a, other.a)

class BitArray:
    """A serializable wrapper for arrays specifically of bits.

    This is very similar to ``NumpyArray``, except it first "packs"
    bits into uint8's, potentially saving a factor of eight in storage
    size. The resulting binary buffer is still hex encoded into
    a JSON string.
    """

    def __init__(self, bits: np.ndarray):
        self.bits = bits

    def _json_dict_(self):
        packed_bits = np.packbits(self.bits)
        assert packed_bits.dtype == np.uint8, packed_bits.dtype
        if cirq.__version__ <= '0.15':
            d = {
                'cirq_type': 'recirq.' + self.__class__.__name__,
                'shape': self.bits.shape,
                'packedbits': packed_bits.tobytes().hex(),
            }
        else:
            d = {
                'shape': self.bits.shape,
                'packedbits': packed_bits.tobytes().hex(),
            }

        return d

    @classmethod
    def _json_namespace_(cls):
        return 'recirq'

    @classmethod
    def _from_json_dict_(cls, shape: List[int], packedbits: str, **kwargs):
        # Hex -> bytes -> packed array -> padded array -> final array
        bits_bytes = bytes.fromhex(packedbits)
        bits = np.frombuffer(bits_bytes, dtype=np.uint8)
        bits = np.unpackbits(bits)
        bits = bits[:np.prod(shape)].reshape(shape)
        return cls(bits)

    def __str__(self):
        return f'recirq.BitArray({self.bits})'

    def __repr__(self):
        return f'recirq.BitArray({repr(self.bits)})'

    def __eq__(self, other):
        return np.array_equal(self.bits, other.bits)

def json_serializable_dataclass(_cls: Optional[Type] = None,
                                *,
                                namespace: Optional[str] = None,
                                registry: Optional[Any] = None,
                                init: bool = True,
                                repr: bool = True,
                                eq: bool = True,
                                order: bool = False,
                                unsafe_hash: bool = False,
                                frozen: bool = False):
    """
    Create a dataclass that supports JSON serialization

    This function defers to the ordinary ``dataclass`` decorator but appends
    the ``_json_dict_`` protocol method which automatically determines
    the appropriate fields from the dataclass.

    Args:
        namespace: An optional prefix to the value associated with the
            key "cirq_type". The namespace name will be joined with the
            class name via a dot (.)
        init, repr, eq, order, unsafe_hash, frozen: Forwarded to the
            ``dataclass`` constructor.
    """

    def wrap(cls):
        cls = dataclasses.dataclass(cls,
                                    init=init,
                                    repr=repr,
                                    eq=eq,
                                    order=order,
                                    unsafe_hash=unsafe_hash,
                                    frozen=frozen)

        cls._json_namespace_ = lambda obj: namespace

        cls._json_dict_ = lambda obj: cirq.obj_to_dict_helper(
            obj, [f.name for f in dataclasses.fields(cls)])

        if registry is not None:
            if namespace is not None:
                prefix = '{}.'.format(namespace)
            else:
                prefix = ''
            registry.register(prefix + cls.__name__, cls)

        return cls

    # _cls is used to deduce if we're being called as
    # @json_serialiable_dataclass or @json_serializable_dataclass().
    if _cls is None:
        # We're called with parens.
        return wrap

    # We're called as @dataclass without parens.
    return wrap(_cls)

def _recirq_class_resolver(cirq_type: str) -> Union[None, Type]:
    from recirq import BitArray, NumpyArray
    return {
        'recirq.BitArray': BitArray,
        'recirq.NumpyArray': NumpyArray,
    }.get(cirq_type)

DEFAULT_RESOLVERS = [_recirq_class_resolver, Registry.get] \
                    + protocols.DEFAULT_RESOLVERS

def read_json(file_or_fn=None, *, json_text=None, resolvers=None):
    """Read a JSON file that optionally contains cirq objects.

    This differs from cirq.read_json by its default argument for
    `resolvers`. Use this function if your JSON document contains
    recirq objects.
    """
    if resolvers is None:
        resolvers = DEFAULT_RESOLVERS

    return protocols.read_json(file_or_fn=file_or_fn,
                               json_text=json_text,
                               resolvers=resolvers)

def load(task, base_dir):
    fn = f'{base_dir}/{task.fn}.json'
    return read_json(fn)

def iterload_records(dataset_id: str, base_dir: str):
    """Helper function to iteratively load records saved while
    following the data collection idioms.

    The yielded records will be dictionaries exactly as structured in the
    JSON document.
    """
    for fn in glob.iglob(f'{base_dir}/{dataset_id}/**/*.json', recursive=True):
        yield read_json(fn)

def load_records(dataset_id: str, base_dir: str):
    """Helper function to load records saved while
    following the data collection idioms.

    The returned records will be dictionaries exactly as structured in the
    JSON document.
    """
    return list(iterload_records(dataset_id, base_dir))

def flatten_dataclass_into_record(record, key):
    """Helper function to 'flatten' a dataclass.

    This is useful for flattening a JSON hierarchy for construction
    of a Pandas DataFrame.
    """
    dc = record[key]
    updated_keys = set()
    for field in dataclasses.fields(dc):
        k = field.name
        v = getattr(dc, k)
        if k in record:
            k = f'{key}.{k}'
        record[k] = v
        updated_keys.add(k)
    if key not in updated_keys:
        # Otherwise, we've already overwritten the original key
        del record[key]

def roundrobin(*iterables):
    """Iterate through `iterables` in a 'roundrobin' fashion.

    Taken from
    https://docs.python.org/3.7/library/itertools.html#itertools-recipes
    """
    num_active = len(iterables)
    nexts = itertools.cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = itertools.cycle(itertools.islice(nexts, num_active))


text:
#include <aws/medialive/model/M2tsEsRateInPes.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace MediaLive
  {
    namespace Model
    {
      namespace M2tsEsRateInPesMapper
      {

        static const int EXCLUDE_HASH = HashingUtils::HashString("EXCLUDE");
        static const int INCLUDE_HASH = HashingUtils::HashString("INCLUDE");

        M2tsEsRateInPes GetM2tsEsRateInPesForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == EXCLUDE_HASH)
          {
            return M2tsEsRateInPes::EXCLUDE;
          }
          else if (hashCode == INCLUDE_HASH)
          {
            return M2tsEsRateInPes::INCLUDE;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<M2tsEsRateInPes>(hashCode);
          }

          return M2tsEsRateInPes::NOT_SET;
        }

        Aws::String GetNameForM2tsEsRateInPes(M2tsEsRateInPes enumValue)
        {
          switch(enumValue)
          {
          case M2tsEsRateInPes::EXCLUDE:
            return "EXCLUDE";
          case M2tsEsRateInPes::INCLUDE:
            return "INCLUDE";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace M2tsEsRateInPesMapper
    } // namespace Model
  } // namespace MediaLive
} // namespace Aws


text:
package org.apereo.portal.groups;

import java.util.Collections;
import org.apereo.portal.concurrency.IEntityLock;

/**
 * Extends EntityGroupImpl to make it lockable for writing.
 *
 *

 *
 * @author Dan Ellentuck
 */
public class LockableEntityGroupImpl extends EntityGroupImpl implements ILockableEntityGroup {
    protected IEntityLock lock;
    /**
     * LockableEntityGroupImpl constructor.
     *
     * @param groupKey java.lang.String
     * @param groupType java.lang.Class
     * @exception GroupsException
     */
    public LockableEntityGroupImpl(String groupKey, Class groupType) throws GroupsException {
        super(groupKey, groupType);
    }

    /** Delegates to the factory. */
    @Override
    public void delete() throws GroupsException {
        getLockableGroupService().deleteGroup(this);
    }

    /** @return org.apereo.portal.concurrency.IEntityLock */
    @Override
    public IEntityLock getLock() {
        return lock;
    }

    /** @return org.apereo.portal.groups.ILockableGroupService */
    protected ILockableGroupService getLockableGroupService() throws GroupsException {
        return (ILockableGroupService) super.getLocalGroupService();
    }

    /**
     * Ask the service to update this group (in the store), update the back-pointers of the updated
     * members, and force the retrieval of containing groups in case the memberships of THIS group
     * have changed during the time the group has been locked.
     */
    private void primUpdate(boolean renewLock) throws GroupsException {
        getLockableGroupService().updateGroup(this, renewLock);
        clearPendingUpdates();
        this.invalidateInParentGroupsCache(Collections.singleton((IGroupMember) this));
    }

    /**
     * Ask the service to update this group (in the store), update the back-pointers of the updated
     * members, and force the retrieval of containing groups in case the memberships of THIS group
     * have changed during the time the group has been locked.
     */
    private void primUpdateMembers(boolean renewLock) throws GroupsException {
        getLockableGroupService().updateGroupMembers(this, renewLock);
        clearPendingUpdates();
        this.invalidateInParentGroupsCache(Collections.singleton((IGroupMember) this));
    }

    /** @param newLock org.apereo.portal.concurrency.IEntityLock */
    @Override
    public void setLock(IEntityLock newLock) {
        lock = newLock;
    }

    @Override
    public String toString() {
        return "LockableEntityGroupImpl (" + getKey() + ") " + getName();
    }

    @Override
    public void update() throws GroupsException {
        primUpdate(false);
    }

    @Override
    public void updateAndRenewLock() throws GroupsException {
        primUpdate(true);
    }

    @Override
    public void updateMembers() throws GroupsException {
        primUpdateMembers(false);
    }
}


text:
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using AntlrGrammarEditor.WorkflowState;
using static AntlrGrammarEditor.Helpers;

namespace AntlrGrammarEditor.Processors.ParserCompilers
{
    public class ParserCompilerJava : ParserCompiler
    {
        public ParserCompilerJava(ParserGeneratedState state)
            : base(state)
        {
        }

        // Lexer.java:98: error: cannot find symbol
        protected override Regex ParserCompilerMessageRegex { get; } =
            new($@"^(?<{FileMark}>.+?):(?<{LineMark}>\d+): (?<{TypeMark}>[^:]+): (?<{MessageMark}>.+)",
                RegexOptions.Compiled);

        protected override string PrepareFilesAndGetArguments()
        {
            var compiledFiles = new StringBuilder();

            string packageName = Result.ParserGeneratedState.PackageName ?? "";

            compiledFiles.Append('"' + CurrentRuntimeInfo.MainFile + '"');

            var filesToCompile =
                Directory.GetFiles(Path.Combine(WorkingDirectory, packageName), "*.java");

            foreach (string helperFile in filesToCompile)
            {
                compiledFiles.Append(" \"");

                if (!string.IsNullOrEmpty(packageName))
                {
                    compiledFiles.Append(Result.ParserGeneratedState.PackageName);
                    compiledFiles.Append(Path.DirectorySeparatorChar);
                }

                compiledFiles.Append(Path.GetFileName(helperFile));

                compiledFiles.Append("\"");
            }

            return $@"-cp ""{Path.Combine("..", "..", "..", RuntimeLibraryPath)}"" -Xlint:deprecation " + compiledFiles;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Harentius\BlogBundle\Sitemap;

use Harentius\BlogBundle\Homepage;
use Presta\SitemapBundle\Event\SitemapPopulateEvent;
use Presta\SitemapBundle\Sitemap\Url\UrlConcrete;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class HomepageSubscriber implements EventSubscriberInterface
{
    /**
     * @var UrlGeneratorInterface
     */
    private $urlGenerator;

    /**
     * @var Homepage
     */
    private $homepage;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param Homepage $homepage
     */
    public function __construct(UrlGeneratorInterface $urlGenerator, Homepage $homepage)
    {
        $this->urlGenerator = $urlGenerator;
        $this->homepage = $homepage;
    }

    /**
     * {@inheritdoc}
     */
    public function populate(SitemapPopulateEvent $event): void
    {
        $event->getGenerator()->addUrl(
            new UrlConcrete(
                $this->urlGenerator->generate('harentius_blog_homepage', [], UrlGeneratorInterface::ABSOLUTE_URL),
                $this->homepage->getUpdatedAt(),
                UrlConcrete::CHANGEFREQ_WEEKLY,
                1.0
            ),
            'pages'
        );
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            SitemapPopulateEvent::ON_SITEMAP_POPULATE => 'populate',
        ];
    }
}


text:
require 'virtus'

module Instapaper
  class User
    include Virtus.value_object

    values do
      attribute :username, String
      attribute :user_id, Integer
      attribute :type, String
      attribute :subscription_is_active, Axiom::Types::Boolean
    end
  end
end


text:
var MongoClient = require('mongodb').MongoClient

// mind the type coercion
var lowestAge = +process.argv[2]
var url = 'mongodb://localhost:27017/learnyoumongo'

MongoClient.connect(url, function(err, db) {
  if (err) return console.error(err)
  db.collection('parrots').count({
    age: {
      $gt: lowestAge
    }
  }, function(err, count) {
    if (err) return console.error(err)
    console.log(count)
    db.close()
  })
})