text:
#include "maindialog.h"
#include <QApplication>

#include <QLabel>
#include <QScrollArea>
#include <QFileDialog>
#include <QMessageBox>
#include <QVBoxLayout>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainDialog w;

    QLabel* imageLabel = new QLabel;
    imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);

    QScrollArea* scrollArea = new QScrollArea;
    scrollArea->setWidget(imageLabel);

    QString fileName = QFileDialog::getOpenFileName(&w,
                                    "Open File", QDir::currentPath());
    if (!fileName.isEmpty())
    {
        QImage image(fileName);
        if (image.isNull())
        {
            QMessageBox::information(&w, "Scroll Area",
                                     QString("Cannot load %1.").arg(fileName));
            return 0;
        }

        imageLabel->setPixmap(QPixmap::fromImage(image));
        imageLabel->adjustSize();

        QVBoxLayout* layout = new QVBoxLayout();
        layout->addWidget(scrollArea);
        w.setLayout(layout);
    }

    w.show();

    return a.exec();
}

redpajama_set_name: RedPajamaGithub


text:
This example trains a PPO agent ([Proximal Policy Optimization Algorithms](http://arxiv.org/abs/1707.06347)) on MuJoCo benchmarks from OpenAI Gym.

We follow the training and evaluation settings of [Deep Reinforcement Learning that Matters](https://arxiv.org/abs/1709.06560), which provides thorough, highly tuned benchmark results.

## Requirements

- MuJoCo Pro 1.5
- mujoco_py>=1.50, <2.1

## Running the Example

```
python train_ppo.py [options]
```

### Useful Options

- `--gpu`. Specifies the GPU. If you do not have a GPU on your machine, run the example with the option `--gpu -1`. E.g. `python train_ppo.py --gpu -1`.
- `--env`. Specifies the environment. E.g. `python train_ppo.py --env HalfCheetah-v2`.
- `--render`. Add this option to render the states in a GUI window.
- `--seed`. This option specifies the random seed used.
- `--outdir` This option specifies the output directory to which the results are written.

To view the full list of options, either view the code or run the example with the `--help` option.

## Known differences

- While the original paper initialized weights by normal distribution (https://github.com/Breakend/baselines/blob/50ffe01d254221db75cdb5c2ba0ab51a6da06b0a/baselines/ppo1/mlp_policy.py#L28), we use orthogonal initialization as the latest openai/baselines does (https://github.com/openai/baselines/blob/9b68103b737ac46bc201dfb3121cfa5df2127e53/baselines/a2c/utils.py#L61).

## Results

These scores are evaluated by average return +/- standard error of 100 evaluation episodes after 2M training steps.

Reported scores are taken from Table 1 of [Deep Reinforcement Learning that Matters](https://arxiv.org/abs/1709.06560).

ChainerRL scores are based on 20 trials using different random seeds, using the following command.

```
python train_ppo.py --gpu -1 --seed [0-19] --env [env]
```

| Environment    | ChainerRL Score | Reported Score |
| -------------- |:---------------:|:--------------:|
| HalfCheetah-v2 |  **2404**+/-185 |     2201+/-323 |
| Hopper-v2      |       2719+/-67 |  **2790**+/-62 |
| Walker2d-v2    |      2994+/-113 |            N/A |
| Swimmer-v2     |         111+/-4 |            N/A |

### Training times
These training times were obtained by running `train_ppo.py` on a single CPU and no GPU.

| Game        | ChainerRL Time           |
| ------------- |:-------------:|
| HalfCheetah | 2.054 hours |
| Hopper | 2.057 hours |
| Swimmer | 2.051 hours |
| Walker2d | 2.065 hours |

| Statistic        |            |            |
| ------------- |:-------------:|:-------------:|
| Mean time (in hours) across all domains        |  2.057 |
| Fastest Domain |  Swimmer | 2.051 |
| Slowest Domain |  Walker2d | 2.065 |

### Learning Curves

The shaded region represents a standard deviation of the average evaluation over 20 trials.

![HalfCheetah-v2](assets/HalfCheetah-v2.png)
![Hopper-v2](assets/Hopper-v2.png)
![Walker2d-v2](assets/Walker2d-v2.png)
![Swimmer-v2](assets/Swimmer-v2.png)


text:
<tool id="svm_rank.classify" name="SVM Rank Classify" version="1.0.0">
    <description>SVM classify</description>
    <command>svm_rank_classify $example $model $output</command>
    <inputs>
        <param name="example" type="data" format="txt" label="Test data"/>
        <param name="model" type="data" format="txt" label="Model"/>
    </inputs>
    <outputs>
        <data name="output" format="txt" label="Predictions"/>
    </outputs>
    <help>SVM Classification</help>
</tool>


text:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import (QVBoxLayout, QGridLayout, QPushButton)
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
import random

class Plugin(BasePlugin):
    vkb = None
    vkb_index = 0

    @hook
    def password_dialog(self, pw, grid, pos):
        vkb_button = QPushButton(_("+"))
        vkb_button.setFixedWidth(20)
        vkb_button.clicked.connect(lambda: self.toggle_vkb(grid, pw))
        grid.addWidget(vkb_button, pos, 2)
        self.kb_pos = 2
        self.vkb = None

    def toggle_vkb(self, grid, pw):
        if self.vkb:
            grid.removeItem(self.vkb)
        self.vkb = self.virtual_keyboard(self.vkb_index, pw)
        grid.addLayout(self.vkb, self.kb_pos, 0, 1, 3)
        self.vkb_index += 1

    def virtual_keyboard(self, i, pw):
        i = i % 3
        if i == 0:
            chars = 'abcdefghijklmnopqrstuvwxyz '
        elif i == 1:
            chars = 'ABCDEFGHIJKLMNOPQRTSUVWXYZ '
        elif i == 2:
            chars = '1234567890!?.,;:/%&()[]{}+-'

        n = len(chars)
        s = []
        for i in range(n):
            while True:
                k = random.randint(0, n - 1)
                if k not in s:
                    s.append(k)
                    break

        def add_target(t):
            return lambda: pw.setText(str(pw.text()) + t)

        vbox = QVBoxLayout()
        grid = QGridLayout()
        grid.setSpacing(2)
        for i in range(n):
            l_button = QPushButton(chars[s[i]])
            l_button.setFixedWidth(25)
            l_button.setFixedHeight(25)
            l_button.clicked.connect(add_target(chars[s[i]]))
            grid.addWidget(l_button, i // 6, i % 6)

        vbox.addLayout(grid)

        return vbox


text:
module ExcelFunctions

  def roundup(number,decimal_places)
    number = number_argument(number)
    decimal_places = number_argument(decimal_places)

    return number if number.is_a?(Symbol)
    return decimal_places if decimal_places.is_a?(Symbol)

    if number < 0
      (number * 10**decimal_places).floor.to_f / 10**decimal_places
    else
      (number * 10**decimal_places).ceil.to_f / 10**decimal_places
    end
  end

end


text:
layout: base
title: "Publikationen"
hide_hero: true
---

Workshops für Jugendliche

Handbuch zur Durchführung medienpädagogischer Workshops

          Im Rahmen der Demokratielabore haben wir sieben Workshopformate entwickelt, die die digitale Mündigkeit Jugendliche fördern. Dieses Handbuch richtet sich  Pädagog*innen, Mitarbeiter*innen aus Jugendeinrichtungen sowie Fachkräfte der politischen Bildung und soll dazu befähigen, unsere Workshopformate eigenständig durchzuführen. Wir liefern eine detaillierte Anleitung und führen durch die einzelnen Schritte der Umsetzung – von der Planung, Organisation und Kommunikation bis hin zur Nachbereitung und individuellen Anpassung.

          <button type="button" class="btn-arrow">Zu Kapitel 1 </button>
          Download PDF

Workshops für Fachkräfte

Citizen Science – Mit Arduinos und Sensoren selbst aktiv werden

Offene Daten und digitale Beteiligung – Daten in der Jugendarbeit nutzen

Digitales Storytelling – Daten visualisieren und Geschichten erzählen

Eliza meets Tay – Bots bauen und Debatten auf Twitter analysieren


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

import Color from '../color';

export default class Logger {
    static log(message) {
        console.log(message);
    }

    static warn(message) {
        console.warn(Color.yellow + message + Color.reset);
    }

    static error(message, watching) {
        console.error(Color.red + message + Color.reset);

        watching = watching === undefined ? false : watching;
        if (!watching) {
            process.exit(1);
        }
    }
}


text:
layout: post
title: Which do you use? - Donor management software / CRM
author: inspiredangela
nid: 415
comments: true
redirect_from: /forum/topics/415/
created: 1323707828
---
Hi, friends. I'm back in action on OSC, wanting your advice.

I work for a non-profit Catholic evangelization apostolate with lots of ministries under our umbrella. Our donor database was written ages ago using MS Access, and it's now a dinosaur. (IOW, not meeting our needs.)

What Donor Magement / Customer Relationship Management software have you had experience with / heard of, in a Catholic setting?

We're definitely cash-strapped, but willing to invest in something that will be with us for the long haul.

Thoughts?


text:
/**
 * @requires OpenLayers/Format/XLS/v1.js
 */

/**
 * Class: OpenLayers.Format.XLS.v1_1_0
 * Read / write XLS version 1.1.0.
 *
 * Inherits from:
 *  - <OpenLayers.Format.XLS.v1>
 */
OpenLayers.Format.XLS.v1_1_0 = OpenLayers.Class(
    OpenLayers.Format.XLS.v1, {

    /**
     * Constant: VERSION
     * {String} 1.1
     */
    VERSION: "1.1",

    /**
     * Property: schemaLocation
     * {String} http://www.opengis.net/xls
     *   http://schemas.opengis.net/ols/1.1.0/LocationUtilityService.xsd
     */
    schemaLocation: "http://www.opengis.net/xls http://schemas.opengis.net/ols/1.1.0/LocationUtilityService.xsd",

    /**
     * Constructor: OpenLayers.Format.XLS.v1_1_0
     * Instances of this class are not created directly.  Use the
     *     <OpenLayers.Format.XLS> constructor instead.
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */

    CLASS_NAME: "OpenLayers.Format.XLS.v1_1_0"

});

// Support non standard implementation
OpenLayers.Format.XLS.v1_1 = OpenLayers.Format.XLS.v1_1_0;


text:
'use strict'

module.exports = (function(){

	var policies = require(ROOT+'/config/policies.js')
  	var controllers = Object.keys(policies)
  	var policyFiles = require('fs').readdirSync(ROOT+'/api/policies')
  	var policyResults = []

  	policyFiles.forEach(function(file, key){
    	file = file.replace('.js', '')
	    policyFiles[key] = file
  	})

  	controllers.forEach(function(controller){
    	let functions = Object.keys(policies[controller])

    	functions.forEach(function(name){

    		let value = policies[controller][name]
      		let obj = {}

    		if(name !== '*'){

	      		if(typeof(value) === "boolean"){

	        		if(value) obj = {run:true, controller : controller, index : name}
	        		else obj = {run:false, controller:controller, index: name}

	      		}else{
	      			try {

	      				let file = ROOT+'/api/policies/'+value+'.js'
						let src = require('fs').readFileSync(file);
						let err = require('syntax-error')(src, file);
						if (err) throw(err)

		        		let func = require(ROOT+'/api/policies/'+value+'.js')
		        		if(policyFiles.contains(value)) obj = {run:true, controller : controller, index : name, func : func}
	      			}catch(err){
	      				return log.error(err)
	      			}
	      		}

	      		policyResults.push(obj)

	      	}else {

	      		try {

	      				let file = ROOT+'/api/controllers/'+controller+'.js'
						let src = require('fs').readFileSync(file);
						let err = require('syntax-error')(src, file);
						if (err) throw(err)

		      			let controllerObj = require(ROOT+'/api/controllers/'+controller+'.js')

			      		for(let name in controllerObj){

				      		if(typeof(value) === "boolean"){

				        		if(value) obj = {run:true, controller : controller, index : name}
				        		else obj = {run:false, controller : controller, index : name}

				      		}else{

				        		let func = require(ROOT+'/api/policies/'+value+'.js')

				        		if(policyFiles.contains(value)) obj = {run : true, controller : controller, index : name, func : func}
				      		}

				      		policyResults.push(obj)
				      	}

		      	}catch(err){
		      		return log.error(err)
	      		}
	      	}
		})
	})

	return policyResults
})()


text:
title: Markers 的使用
order: 1
---

本及介绍创建大量标记的基本用法

```jsx
import { Map, Markers } from 'react-amap';

const randomPosition = () => ({
  longitude: 100 + Math.random() * 20,
  latitude: 30 + Math.random() * 20
})
const randomMarker = (len) => (
  Array(len).fill(true).map((e, idx) => ({
    position: randomPosition()
  }))
);
class App extends React.Component{
  constructor(){
    super();
    this.state = {
      markers: randomMarker(100),
      center: randomPosition()
    }
    this.randomMarkers = this.randomMarkers.bind(this)
  }

  randomMarkers() {
    this.setState({
      markers: randomMarker(100)
    })
  }

  render(){
    return <div>
      <div style={{width: '100%', height: 372}}>
        <Map plugins={['ToolBar']} center={this.state.center} zoom={6}>
          <Markers
            markers={this.state.markers}
          />
        </Map>
      </div>
      <button onClick={this.randomMarkers}>Random Markers</button>
    </div>
  }
}

ReactDOM.render(<App/>, mountNode)
```


text:
@implementation MyFFUser

@synthesize profilePic, home;

@end


text:
layout: default
---
Modifying a Collection
======================

<!-- js/actions/api-collection.js -->
{% docublock put_api_collection_load %}

<!-- js/actions/api-collection.js -->
{% docublock put_api_collection_unload %}

<!-- js/actions/api-collection.js -->
{% docublock put_api_collection_load_indexes_into_memory %}

<!-- js/actions/api-collection.js -->
{% docublock put_api_collection_properties %}

<!-- js/actions/api-collection.js -->
{% docublock put_api_collection_rename %}

<!-- js/actions/api-collection.js -->
{% docublock put_api_collection_rotate %}

<!-- js/actions/api-collection.js -->
{% docublock put_api_collection_recalculate_count %}


text:
"""IMDB movie review sentiment classification dataset."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.keras.datasets.imdb import get_word_index
from tensorflow.python.keras.datasets.imdb import load_data

del absolute_import
del division
del print_function


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

    <title>Test-NodeExists :: Blade :: PowerShell Testing Module</title>
	<link href="styles.css" type="text/css" rel="stylesheet" />

Topics

about_Blade

Commands

Assert-Contains

Assert-ContainsLike

Assert-ContainsNotLike

Assert-DirectoryDoesNotExist

Assert-DirectoryExists

Assert-DoesNotContain

Assert-Empty

Assert-Equal

Assert-Error

Assert-False

Assert-FileContains

Assert-FileDoesNotExist

Assert-FileExists

Assert-GreaterThan

Assert-Is

Assert-LastProcessFailed

Assert-LastProcessSucceeded

Assert-LessThan

Assert-Like

Assert-Match

Assert-NodeDoesNotExist

Assert-NodeExists

Assert-NoError

Assert-NotEmpty

Assert-NotEqual

Assert-NotNull

Assert-Null

Assert-True

New-AssertionException

New-TempDirectory

New-TempDirectoryTree

Test-NodeExists

Scripts

blade.ps1

Import-Blade.ps1

Test-NodeExists

Tests if a node exists in an XML document.

Syntax

Test-NodeExists [-Xml] <XmlDocument> [-XPath] <String> [[-DefaultNamespacePrefix] <String>] [<CommonParameters>]

Description

It's usually pretty easy in PowerShell to check if a node exists in an XML document: simply test if a property exists on that node.  If, however, that XML document has namespaces, you have to do extra setup with the XML document so that you can find the node.  This function does that work for you.

Related Commands

Assert-NodeExists

Assert-NodeDoesNotExist

 Parameters

				Name
                Type
				Description
				Required?
				Pipeline Input
				Default Value

				Xml
				XmlDocument
				The XML Document to check

				true
				false

				XPath
				String
				The XPath to use for the node whose existence to check.

				true
				false

				DefaultNamespacePrefix
				String
				The prefix of the XML document's default namespace.

				false
				false

EXAMPLE 1

<bar><baz /></bar></foo>' '/foo/bar/baz'

Returns $true if a node selected by XPath is found.


text:
#include "muscle.h"
#include "tree.h"

#define TRACE	0

/***
Algorithm to compare two trees, X and Y.

A node x in X and node y in Y are defined to be
similar iff the set of leaves in the subtree under
x is identical to the set of leaves under y.

A node is defined to be dissimilar iff it is not
similar to any node in the other tree.

Nodes x and y are defined to be married iff every
node in the subtree under x is similar to a node
in the subtree under y. Married nodes are considered
to be equal. The subtrees under two married nodes can
at most differ by exchanges of left and right branches,
which we do not consider to be significant here.

A node is defined to be a bachelor iff it is not
married. If a node is a bachelor, then it has a
dissimilar node in its subtree, and it follows
immediately from the definition of marriage that its
parent is also a bachelor. Hence all nodes on the path
from a bachelor node to the root are bachelors.

We assume the trees have the same set of leaves, so
every leaf is trivially both similar and married to
the same leaf in the opposite tree. Bachelor nodes
are therefore always internal (i.e., non-leaf) nodes.

A node is defined to be a diff iff (a) it is married
and (b) its parent is a bachelor. The subtree under
a diff is maximally similar to the other tree. (In
other words, you cannot extend the subtree without
adding a bachelor).

The set of diffs is the subset of the two trees that
we consider to be identical.

Example:

              -----A
        -----k
   ----j      -----B
--i     -----C
   ------D

              -----A
        -----p
   ----n      -----B
--m     -----D
   ------C

The following pairs of internal nodes are similar.

	Nodes	Set of leaves
	-----	-------------
	k,p		A,B
	i,m		A,B,C,D

Bachelors in the first tree are i and j, bachelors
in the second tree are m and n.

Node k and p are married, but i and m are not (because j
and n are bachelors). The diffs are C, D and k.

The set of bachelor nodes can be viewed as the internal
nodes of a tree, the leaves of which are diffs. (To see
that there can't be disjoint subtrees, note that the path
from a diff to a root is all bachelor nodes, so there is
always a path between two diffs that goes through the root).
We call this tree the "diffs tree".

There is a simple O(N) algorithm to build the diffs tree.
To achieve O(N) we avoid traversing a given subtree multiple
times and also avoid comparing lists of leaves.

We visit nodes in depth-first order (i.e., a node is visited
before its parent).

If either child of a node is a bachelor, we flag it as
a bachelor.

If both children of the node we are visiting are married,
we check whether the spouses of those children have the
same parent in the other tree. If the parents are different,
the current node is a bachelor. If they have the same parent,
then the node we are visiting is the spouse of that parent.
We assign this newly identified married couple a unique integer
id. The id of a node is in one-to-one correspondence with the
set of leaves in its subtree. Two nodes have the same set of
leaves iff they have the same id. Bachelor nodes do not get
an id.
***/

static void BuildDiffs(const Tree &tree, unsigned uTreeNodeIndex,
  const bool bIsDiff[], Tree &Diffs, unsigned uDiffsNodeIndex,
  unsigned IdToDiffsLeafNodeIndex[])
	{
#if	TRACE
	Log("BuildDiffs(TreeNode=%u IsDiff=%d IsLeaf=%d)\n",
	  uTreeNodeIndex, bIsDiff[uTreeNodeIndex], tree.IsLeaf(uTreeNodeIndex));
#endif
	if (bIsDiff[uTreeNodeIndex])
		{
		unsigned uLeafCount = tree.GetLeafCount();
		unsigned *Leaves = new unsigned[uLeafCount];
		GetLeaves(tree, uTreeNodeIndex, Leaves, &uLeafCount);
		for (unsigned n = 0; n < uLeafCount; ++n)
			{
			const unsigned uLeafNodeIndex = Leaves[n];
			const unsigned uId = tree.GetLeafId(uLeafNodeIndex);
			if (uId >= tree.GetLeafCount())
				Quit("BuildDiffs, id out of range");
			IdToDiffsLeafNodeIndex[uId] = uDiffsNodeIndex;
#if	TRACE
			Log("  Leaf id=%u DiffsNode=%u\n", uId, uDiffsNodeIndex);
#endif
			}
		delete[] Leaves;
		return;
		}

	if (tree.IsLeaf(uTreeNodeIndex))
		Quit("BuildDiffs: should never reach leaf");

	const unsigned uTreeLeft = tree.GetLeft(uTreeNodeIndex);
	const unsigned uTreeRight = tree.GetRight(uTreeNodeIndex);

	const unsigned uDiffsLeft = Diffs.AppendBranch(uDiffsNodeIndex);
	const unsigned uDiffsRight = uDiffsLeft + 1;

	BuildDiffs(tree, uTreeLeft, bIsDiff, Diffs, uDiffsLeft, IdToDiffsLeafNodeIndex);
	BuildDiffs(tree, uTreeRight, bIsDiff, Diffs, uDiffsRight, IdToDiffsLeafNodeIndex);
	}

void DiffTrees(const Tree &Tree1, const Tree &Tree2, Tree &Diffs,
  unsigned IdToDiffsLeafNodeIndex[])
	{
#if	TRACE
	Log("Tree1:\n");
	Tree1.LogMe();
	Log("\n");
	Log("Tree2:\n");
	Tree2.LogMe();
#endif

	if (!Tree1.IsRooted() || !Tree2.IsRooted())
		Quit("DiffTrees: requires rooted trees");

	const unsigned uNodeCount = Tree1.GetNodeCount();
	const unsigned uNodeCount2 = Tree2.GetNodeCount();

	const unsigned uLeafCount = Tree1.GetLeafCount();
	const unsigned uLeafCount2 = Tree2.GetLeafCount();
	assert(uLeafCount == uLeafCount2);

	if (uNodeCount != uNodeCount2)
		Quit("DiffTrees: different node counts");

// Allocate tables so we can convert tree node index to
// and from the unique id with a O(1) lookup.
	unsigned *NodeIndexToId1 = new unsigned[uNodeCount];
	unsigned *IdToNodeIndex2 = new unsigned[uNodeCount];

	bool *bIsBachelor1 = new bool[uNodeCount];
	bool *bIsDiff1 = new bool[uNodeCount];

	for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
		{
		NodeIndexToId1[uNodeIndex] = uNodeCount;
		bIsBachelor1[uNodeIndex] = false;
		bIsDiff1[uNodeIndex] = false;

	// Use uNodeCount as value meaning "not set".
		IdToNodeIndex2[uNodeIndex] = uNodeCount;
		}

// Initialize node index <-> id lookup tables
	for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
		{
		if (Tree1.IsLeaf(uNodeIndex))
			{
			const unsigned uId = Tree1.GetLeafId(uNodeIndex);
			if (uId >= uNodeCount)
				Quit("Diff trees requires existing leaf ids in range 0 .. (N-1)");
			NodeIndexToId1[uNodeIndex] = uId;
			}

		if (Tree2.IsLeaf(uNodeIndex))
			{
			const unsigned uId = Tree2.GetLeafId(uNodeIndex);
			if (uId >= uNodeCount)
				Quit("Diff trees requires existing leaf ids in range 0 .. (N-1)");
			IdToNodeIndex2[uId] = uNodeIndex;
			}
		}

// Validity check. This verifies that the ids
// pre-assigned to the leaves in Tree1 are unique
// (note that the id<N check above does not rule
// out two leaves having duplicate ids).
	for (unsigned uId = 0; uId < uLeafCount; ++uId)
		{
		unsigned uNodeIndex2 = IdToNodeIndex2[uId];
		if (uNodeCount == uNodeIndex2)
			Quit("DiffTrees, check 2");
		}

// Ids assigned to internal nodes are N, N+1 ...
// An internal node id uniquely identifies a set
// of two or more leaves.
	unsigned uInternalNodeId = uLeafCount;

// Depth-first traversal of tree.
// The order guarantees that a node is visited before
// its parent is visited.
	for (unsigned uNodeIndex1 = Tree1.FirstDepthFirstNode();
	  NULL_NEIGHBOR != uNodeIndex1;
	  uNodeIndex1 = Tree1.NextDepthFirstNode(uNodeIndex1))
		{
#if	TRACE
		Log("Main loop: Node1=%u IsLeaf=%d IsBachelor=%d\n",
		  uNodeIndex1,
		  Tree1.IsLeaf(uNodeIndex1),
		  bIsBachelor1[uNodeIndex1]);
#endif

	// Leaves are trivial; nothing to do.
		if (Tree1.IsLeaf(uNodeIndex1) || bIsBachelor1[uNodeIndex1])
			continue;

	// If either child is a bachelor, flag
	// this node as a bachelor and continue.
		unsigned uLeft1 = Tree1.GetLeft(uNodeIndex1);
		if (bIsBachelor1[uLeft1])
			{
			bIsBachelor1[uNodeIndex1] = true;
			continue;
			}

		unsigned uRight1 = Tree1.GetRight(uNodeIndex1);
		if (bIsBachelor1[uRight1])
			{
			bIsBachelor1[uNodeIndex1] = true;
			continue;
			}

	// Both children are married.
	// Married nodes are guaranteed to have an id.
		unsigned uIdLeft = NodeIndexToId1[uLeft1];
		unsigned uIdRight = NodeIndexToId1[uRight1];

		if (uIdLeft == uNodeCount || uIdRight == uNodeCount)
			Quit("DiffTrees, check 5");

	// uLeft2 is the spouse of uLeft1, and similarly for uRight2.
		unsigned uLeft2 = IdToNodeIndex2[uIdLeft];
		unsigned uRight2 = IdToNodeIndex2[uIdRight];

		if (uLeft2 == uNodeCount || uRight2 == uNodeCount)
			Quit("DiffTrees, check 6");

	// If the spouses of uLeft1 and uRight1 have the same
	// parent, then this parent is the spouse of uNodeIndex1.
	// Otherwise, uNodeIndex1 is a diff.
		unsigned uParentLeft2 = Tree2.GetParent(uLeft2);
		unsigned uParentRight2 = Tree2.GetParent(uRight2);

#if	TRACE
		Log("L1=%u R1=%u L2=%u R2=%u PL2=%u PR2=%u\n",
		  uLeft1,
		  uRight1,
		  uLeft2,
		  uRight2,
		  uParentLeft2,
		  uParentRight2);
#endif

		if (uParentLeft2 == uParentRight2)
			{
			NodeIndexToId1[uNodeIndex1] = uInternalNodeId;
			IdToNodeIndex2[uInternalNodeId] = uParentLeft2;
			++uInternalNodeId;
			}
		else
			bIsBachelor1[uNodeIndex1] = true;
		}

	unsigned uDiffCount = 0;
	for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
		{
		if (bIsBachelor1[uNodeIndex])
			continue;
		if (Tree1.IsRoot(uNodeIndex))
			{
		// Special case: if no bachelors, consider the
		// root a diff.
			if (!bIsBachelor1[uNodeIndex])
				bIsDiff1[uNodeIndex] = true;
			continue;
			}
		const unsigned uParent = Tree1.GetParent(uNodeIndex);
		if (bIsBachelor1[uParent])
			{
			bIsDiff1[uNodeIndex] = true;
			++uDiffCount;
			}
		}

#if	TRACE
	Log("Tree1:\n");
	Log("Node    Id  Bach  Diff  Name\n");
	Log("----  ----  ----  ----  ----\n");
	for (unsigned n = 0; n < uNodeCount; ++n)
		{
		Log("%4u  %4u     %d     %d",
		  n,
		  NodeIndexToId1[n],
		  bIsBachelor1[n],
		  bIsDiff1[n]);
		if (Tree1.IsLeaf(n))
			Log("  %s", Tree1.GetLeafName(n));
		Log("\n");
		}
	Log("\n");
	Log("Tree2:\n");
	Log("Node    Id              Name\n");
	Log("----  ----              ----\n");
	for (unsigned n = 0; n < uNodeCount; ++n)
		{
		Log("%4u                  ", n);
		if (Tree2.IsLeaf(n))
			Log("  %s", Tree2.GetLeafName(n));
		Log("\n");
		}
#endif

	Diffs.CreateRooted();
	const unsigned uDiffsRootIndex = Diffs.GetRootNodeIndex();
	const unsigned uRootIndex1 = Tree1.GetRootNodeIndex();

	for (unsigned n = 0; n < uLeafCount; ++n)
		IdToDiffsLeafNodeIndex[n] = uNodeCount;

	BuildDiffs(Tree1, uRootIndex1, bIsDiff1, Diffs, uDiffsRootIndex,
	  IdToDiffsLeafNodeIndex);

#if TRACE
	Log("\n");
	Log("Diffs:\n");
	Diffs.LogMe();
	Log("\n");
	Log("IdToDiffsLeafNodeIndex:");
	for (unsigned n = 0; n < uLeafCount; ++n)
		{
		if (n%16 == 0)
			Log("\n");
		else
			Log(" ");
		Log("%u=%u", n, IdToDiffsLeafNodeIndex[n]);
		}
	Log("\n");
#endif

	for (unsigned n = 0; n < uLeafCount; ++n)
		if (IdToDiffsLeafNodeIndex[n] == uNodeCount)
			Quit("TreeDiffs check 7");

	delete[] NodeIndexToId1;
	delete[] IdToNodeIndex2;

	delete[] bIsBachelor1;
	delete[] bIsDiff1;
	}


text:
#include "Wt/Chart/WChart2DImplementation"
#include "Wt/Chart/WCartesianChart"
#include "Wt/WAbstractItemModel"
#include "Wt/WPainter"

#include "WebUtils.h"

namespace Wt {
  namespace Chart {

bool ExtremesIterator::startSeries(const WDataSeries& series, double groupWidth,
				   int numBarGroups, int currentBarGroup)
{
  return axis_ == XAxis || series.axis() == axis_;
}

void ExtremesIterator::newValue(const WDataSeries& series, double x, double y,
				double stackY, const WModelIndex& xIndex,
				const WModelIndex& yIndex)
{
  double v = axis_ == XAxis ? x : y;

  if (!Utils::isNaN(v) && (scale_ != LogScale || v > 0.0)) {
    maximum_ = std::max(v, maximum_);
    minimum_ = std::min(v, minimum_);
  }
}

WChart2DImplementation::WChart2DImplementation(WCartesianChart *chart)
  : chart_(chart)
{ }

ChartType WChart2DImplementation::chartType() const
{
  return chart_->type();
}

void WChart2DImplementation::update()
{
  chart_->update();
}

int WChart2DImplementation::axisPadding() const
{
  return chart_->axisPadding();
}

int WChart2DImplementation::numberOfCategories(Axis axis) const
{
  if (chart_->model())
    return chart_->model()->rowCount();
  else
    return 0;
}

Orientation WChart2DImplementation::orientation() const
{
  return chart_->orientation();
}

WString WChart2DImplementation::categoryLabel(int u, Axis axis) const
{
  if (chart_->XSeriesColumn() != -1) {
    return asString(chart_->model()->data(u, chart_->XSeriesColumn()));
  } else {
    return WString();
  }
}

WChart2DImplementation::RenderRange WChart2DImplementation::computeRenderRange(Axis axis, AxisScale scale) const
{
  ExtremesIterator iterator(axis, scale);

  chart_->iterateSeries(&iterator, 0);

  RenderRange range;
  range.minimum = iterator.minimum();
  range.maximum = iterator.maximum();

  return range;
}

  }
}


text:
package com.cloudmine.api;

import com.cloudmine.api.rest.JsonUtilities;
import org.junit.Test;

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

import static junit.framework.Assert.*;

public class CMAccessListTest {

    @Test
    public void testAddUser() {
        JavaCMUser owner = new JavaCMUser("name@w.com", "t");
        owner.setObjectId(CMObject.generateUniqueObjectId());
        JavaAccessListController list = new JavaAccessListController(owner);
        JavaCMUser userToAddDirectly = new JavaCMUser("user@u.com", "pw");
        userToAddDirectly.setObjectId(CMObject.generateUniqueObjectId());
        JavaCMUser userToAddById = new JavaCMUser("another@u.com", "pw");
        userToAddById.setObjectId(CMObject.generateUniqueObjectId());

        list.grantAccessTo(userToAddDirectly);
        list.grantAccessTo(userToAddById.getObjectId());

        assertTrue(list.doesAllowAccessTo(userToAddDirectly));
        assertTrue(list.doesAllowAccessTo(userToAddById));

        assertTrue(list.doesAllowAccessTo(userToAddDirectly.getObjectId()));
        assertFalse(list.doesAllowAccessTo(new JavaCMUser("nope@not.com", "f")));
    }

    @Test
    public void testIsOwner() {
        JavaCMUser owner = new JavaCMUser("wat@wat.com", "ff");
        JavaAccessListController list = new JavaAccessListController(owner);
        assertTrue(list.isOwnedBy(owner));
        JavaCMUser notOwner = new JavaCMUser("wat@wat.com", "f");
        assertFalse(list.isOwnedBy(notOwner));
    }

    @Test
    public void testPermissions() {
        JavaCMUser owner = new JavaCMUser("whatever@gmail.com", "t");
        JavaAccessListController list = new JavaAccessListController(owner, CMAccessPermission.UPDATE, CMAccessPermission.READ);

        assertTrue(list.doesGrantPermissions(CMAccessPermission.UPDATE, CMAccessPermission.READ));
        assertFalse(list.doesGrantPermissions(CMAccessPermission.DELETE));
        assertFalse(list.doesGrantPermissions(CMAccessPermission.READ, CMAccessPermission.CREATE));
    }

    @Test
    public void testAsJson() {

        JavaCMUser owner = new JavaCMUser("bobdole@bobdole.com", "imbobdole");
        JavaAccessListController list = new JavaAccessListController(owner);
        list.grantPermissions(CMAccessPermission.CREATE);

        String json = list.transportableRepresentation();

        JavaAccessListController convertedList = JsonUtilities.jsonToClass(json, JavaAccessListController.class);
        assertEquals(convertedList,  list);

        Map<String, Object> asMap = JsonUtilities.jsonToMap(json);
        List permissions = (List)asMap.get("permissions");
        assertEquals(1, permissions.size());
        assertEquals("c", permissions.get(0));
    }
}


text:
package com.amazonaws.services.inspector.model;

import java.io.Serializable;

/**
 *

 * The metadata about the Inspector application data metrics collected by the
 * agent. This data type is used as the response element in the
 * GetTelemetryMetadata action.
 *

 */
public class TelemetryMetadata implements Serializable, Cloneable {

    /**
     *

     * A specific type of behavioral data that is collected by the agent.
     *

     */
    private String messageType;
    /**
     *

     * The count of messages that the agent sends to the Inspector service.
     *

     */
    private Long count;
    /**
     *

     * The data size of messages that the agent sends to the Inspector service.
     *

     */
    private Long dataSize;

    /**
     *

     * A specific type of behavioral data that is collected by the agent.
     *

     *
     * @param messageType
     *        A specific type of behavioral data that is collected by the agent.
     */

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    /**
     *

     * A specific type of behavioral data that is collected by the agent.
     *

     *
     * @return A specific type of behavioral data that is collected by the
     *         agent.
     */

    public String getMessageType() {
        return this.messageType;
    }

    /**
     *

     * A specific type of behavioral data that is collected by the agent.
     *

     *
     * @param messageType
     *        A specific type of behavioral data that is collected by the agent.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public TelemetryMetadata withMessageType(String messageType) {
        setMessageType(messageType);
        return this;
    }

    /**
     *

     * The count of messages that the agent sends to the Inspector service.
     *

     *
     * @param count
     *        The count of messages that the agent sends to the Inspector
     *        service.
     */

    public void setCount(Long count) {
        this.count = count;
    }

    /**
     *

     * The count of messages that the agent sends to the Inspector service.
     *

     *
     * @return The count of messages that the agent sends to the Inspector
     *         service.
     */

    public Long getCount() {
        return this.count;
    }

    /**
     *

     * The count of messages that the agent sends to the Inspector service.
     *

     *
     * @param count
     *        The count of messages that the agent sends to the Inspector
     *        service.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public TelemetryMetadata withCount(Long count) {
        setCount(count);
        return this;
    }

    /**
     *

     * The data size of messages that the agent sends to the Inspector service.
     *

     *
     * @param dataSize
     *        The data size of messages that the agent sends to the Inspector
     *        service.
     */

    public void setDataSize(Long dataSize) {
        this.dataSize = dataSize;
    }

    /**
     *

     * The data size of messages that the agent sends to the Inspector service.
     *

     *
     * @return The data size of messages that the agent sends to the Inspector
     *         service.
     */

    public Long getDataSize() {
        return this.dataSize;
    }

    /**
     *

     * The data size of messages that the agent sends to the Inspector service.
     *

     *
     * @param dataSize
     *        The data size of messages that the agent sends to the Inspector
     *        service.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public TelemetryMetadata withDataSize(Long dataSize) {
        setDataSize(dataSize);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getMessageType() != null)
            sb.append("MessageType: " + getMessageType() + ",");
        if (getCount() != null)
            sb.append("Count: " + getCount() + ",");
        if (getDataSize() != null)
            sb.append("DataSize: " + getDataSize());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof TelemetryMetadata == false)
            return false;
        TelemetryMetadata other = (TelemetryMetadata) obj;
        if (other.getMessageType() == null ^ this.getMessageType() == null)
            return false;
        if (other.getMessageType() != null
                && other.getMessageType().equals(this.getMessageType()) == false)
            return false;
        if (other.getCount() == null ^ this.getCount() == null)
            return false;
        if (other.getCount() != null
                && other.getCount().equals(this.getCount()) == false)
            return false;
        if (other.getDataSize() == null ^ this.getDataSize() == null)
            return false;
        if (other.getDataSize() != null
                && other.getDataSize().equals(this.getDataSize()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getMessageType() == null) ? 0 : getMessageType().hashCode());
        hashCode = prime * hashCode
                + ((getCount() == null) ? 0 : getCount().hashCode());
        hashCode = prime * hashCode
                + ((getDataSize() == null) ? 0 : getDataSize().hashCode());
        return hashCode;
    }

    @Override
    public TelemetryMetadata clone() {
        try {
            return (TelemetryMetadata) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
package im.actor.map;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import im.actor.maps.google.R;
import im.actor.sdk.controllers.fragment.BaseFragment;

public class MapFragment extends BaseFragment {
    double longitude;
    double latitude;

    public static MapFragment create(double longitude, double latitude) {
        MapFragment res = new MapFragment();
        Bundle arguments = new Bundle();
        arguments.putDouble("longitude", longitude);
        arguments.putDouble("latitude", latitude);
        res.setArguments(arguments);
        return res;
    }

    GoogleMap mapController;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        longitude = getArguments().getDouble("longitude");
        latitude = getArguments().getDouble("latitude");

        final MapView map = new MapView(getActivity());

        map.onCreate(null);

        map.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mapController = googleMap;
                googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(""));
                googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(latitude, longitude),
                        16));
                map.onResume();
            }
        });

        return map;

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.map, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.share) {
            String uri = "geo:" + latitude + ","
                    + longitude + "?q=" + latitude
                    + "," + longitude;
            startActivity(new Intent(android.content.Intent.ACTION_VIEW,
                    Uri.parse(uri)));
            return true;

        } else if (mapController != null) {
            if (item.getItemId() == R.id.roadmap) {
                mapController.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            } else if (item.getItemId() == R.id.satellite) {
                mapController.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            } else if (item.getItemId() == R.id.hybrid) {
                mapController.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            }
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
package org.parceler;

import java.util.HashMap;
import java.util.Map;
import com.codepath.apps.simpleclienttwitter.model.Tweet;
import com.codepath.apps.simpleclienttwitter.model.Tweet$$Parcelable;
import com.codepath.apps.simpleclienttwitter.model.User;
import com.codepath.apps.simpleclienttwitter.model.User$$Parcelable;

@Generated(value = "org.parceler.ParcelAnnotationProcessor", date = "2016-08-14T22:36-0700")
@SuppressWarnings({
    "unchecked",
    "deprecation"
})
public class Parceler$$Parcels
    implements Repository<org.parceler.Parcels.ParcelableFactory>
{

    private final Map<Class, org.parceler.Parcels.ParcelableFactory> map$$0 = new HashMap<Class, org.parceler.Parcels.ParcelableFactory>();

    public Parceler$$Parcels() {
        map$$0 .put(User.class, new Parceler$$Parcels.User$$Parcelable$$0());
        map$$0 .put(Tweet.class, new Parceler$$Parcels.Tweet$$Parcelable$$0());
    }

    public Map<Class, org.parceler.Parcels.ParcelableFactory> get() {
        return map$$0;
    }

    private final static class Tweet$$Parcelable$$0
        implements org.parceler.Parcels.ParcelableFactory<Tweet>
    {

        @Override
        public Tweet$$Parcelable buildParcelable(Tweet input) {
            return new Tweet$$Parcelable(input);
        }

    }

    private final static class User$$Parcelable$$0
        implements org.parceler.Parcels.ParcelableFactory<User>
    {

        @Override
        public User$$Parcelable buildParcelable(User input) {
            return new User$$Parcelable(input);
        }

    }

}


text:
/**
 * constants.js - Game-level constants.
 */

export const TURN_RATE = 0.003;
export const MOVE_SPEED = 0.075;
export const CUBE_SIZE = 5;

export const ARENA_SIZE = 100;
export const FLOOR_SIZE = 2 * ARENA_SIZE + CUBE_SIZE;

// Key mappings
export const KEY_LEFT = 65;
export const KEY_RIGHT = 68;
export const KEY_FORWARD = 87;
export const KEY_BACKWARD = 83;


text:
<div *ngIf="!isLoggedIn" >
  <external-login-buttons></external-login-buttons>
</div>
<div *ngIf="isLoggedIn" >
  <logined-user></logined-user>
</div>


text:
<?php

declare(strict_types=1);

namespace Zhiyi\Plus\Packages\Music\API\Controllers;

use Illuminate\Http\Request;
use Zhiyi\Plus\Http\Controllers\Controller;
use Illuminate\Contracts\Routing\ResponseFactory;
use Zhiyi\Component\ZhiyiPlus\PlusComponentMusic\Models\MusicSpecial;

class MusicSpecialController extends Controller
{
    /**
     * 获取专辑列表.
     *
     * @author bs<414606094@qq.com>
     * @return [type] [description]
     */
    public function list(Request $request, ResponseFactory $response)
    {
        $uid = $request->user('api')->id ?? 0;
        // 设置单页数量
        $limit = $request->limit ?? 15;
        $specials = MusicSpecial::with(['storage', 'paidNode'])
            ->when($request->max_id > 0, function ($query) use ($request) {
                return $query->where('id', '<', $request->max_id);
            })
            ->when(is_array($request->id), function ($query) use ($request) {
                return $query->whereIn('id', $request->id);
            })
            ->limit($limit)
            ->get();

        $specials = $specials->map(function ($special) use ($uid) {
            $special->has_collect = $special->hasCollected($uid);
            $special = $special->formatPaidNode($uid);

            return $special;
        });

        return $response->json($specials)->setStatusCode(200);
    }

    /**
     * 专辑详情.
     *
     * @author bs<414606094@qq.com>
     * @param  Request         $request
     * @param  MusicSpecial    $special
     * @param  ResponseFactory $response
     * @return mix
     */
    public function show(Request $request, MusicSpecial $special, ResponseFactory $response)
    {
        $uid = $request->user('api')->id ?? 0;

        if ($special->paidNode !== null && $special->paidNode->paid($uid) === false) {
            return response()->json([
                'message' => ['请购买专辑'],
                'paid_node' => $special->paidNode->id,
                'amount' => $special->paidNode->amount,
            ])->setStatusCode(403);
        }

        $special->load(['musics' => function ($query) {
            $query->with(['singer' => function ($query) {
                $query->with('cover');
            }])->orderBy('id', 'desc');
        }, 'storage']);

        $special = $special->formatPaidNode($uid);
        $special->has_collect = $special->hasCollected($uid);
        $special->musics->map(function ($music) use ($uid) {
            $music->has_like = $music->liked($uid);
            $music = $music->formatStorage($uid);
        });

        return $response->json($special)->setStatusCode(200);
    }

    /**
     * 增加分享数,供移动端分享专辑时调用.
     *
     * @author bs<414606094@qq.com>
     * @param  MusicSpecial $special_id
     * @return mixed
     */
    public function share(MusicSpecial $special)
    {
        $special->increment('share_count');

        return response()->json([])->setStatusCode(204);
    }
}


text:
using SmartCardApi.Infrastructure;
using SmartCardApi.Infrastructure.Interfaces;

namespace SmartCardApi.Cryptography.RandomKeys
{
    public class Kifd : IBinary
    {
        private readonly int _randomBytesCount = 16;
        public byte[] Bytes()
        {
            return new RandomBytes(_randomBytesCount)
                 .Bytes();
        }
    }
}


text:
module FakeDynamo
  class Attribute
    attr_accessor :name, :value, :type

    def initialize(name, value, type)
      @name, @type = name, type
      validate_name!
      return unless value

      @value = decode(value)
      validate_value!
    end

    def validate_name!
      if name == ''
        raise ValidationException, 'Empty attribute name'
      end
    end

    def validate_value!
      if ['NS', 'SS', 'BS'].include? @type
        raise ValidationException, 'An AttributeValue may not contain an empty set' if @value.empty?
        raise ValidationException, 'Input collection contains duplicates' if value.uniq!
      end

      if ['S', 'SS', 'S', 'BS'].include? @type
        Array(@value).each do |v|
          raise ValidationException, 'An AttributeValue may not contain an empty string or empty binary' if v == ''
        end
      end
    end

    def description
      {
        'AttributeName' => name,
        'AttributeType' => type
      }
    end

    def decode(value)
      case @type
      when 'B' then Base64.strict_decode64(value)
      when 'BS' then value.map { |v| Base64.strict_decode64(v) }
      when 'N' then Num.new(value)
      when 'NS' then value.map { |v| Num.new(v) }
      else value
      end
    end

    def encode(value)
      case @type
      when 'B' then Base64.strict_encode64(value)
      when 'BS' then value.map { |v| Base64.strict_encode64(v) }
      when 'N' then value.to_s
      when 'NS' then value.map(&:to_s)
      else value
      end
    end

    def as_hash
      { @name => { @type => encode(@value) } }
    end

    def ==(attribute)
      @name == attribute.name &&
        @type == attribute.type &&
        @value == attribute.value
    end

    def <=>(other)
      @value <=> other.value
    end

    def eql?(attribute)
      return false unless attribute.kind_of? Attribute

      self == attribute
    end

    def hash
      name.hash ^ value.hash ^ type.hash
    end

    class << self
      def from_data(data)
        Attribute.new(data['AttributeName'], nil, data['AttributeType'])
      end

      def from_hash(name, hash)
        Attribute.new(name, hash.values.first, hash.keys.first)
      end
    end
  end
end


text:
package my.school.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class BootDemoApplication {

    public static void main(String[] args) {
        Object[] sources = {
            BootDemoApplication.class
                //, GroovyController.class
        };
        SpringApplication.run(sources, args);
    }
}


text:
namespace bstrkr.providers.bus13.data
{
    public class Bus13RouteStop
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Descr { get; set; }

        public int Lat { get; set; }

        public int Lng { get; set; }

        public string Type { get; set; }
    }
}


text:
package fuzz

import (
	"github.com/tdewolff/minify/v2"
	"github.com/tdewolff/parse/v2"
)

// Fuzz is a fuzz test.
func Fuzz(data []byte) int {
	data = parse.Copy(data) // ignore const-input error for OSS-Fuzz
	_ = minify.DataURI(minify.New(), data)
	return 1
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_novo"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_new"/>

    <item
        android:id="@+id/menu_buscar"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

</menu>


text:
'use strict';

// @ngInject
module.exports = function($scope, MainServ) {

   $scope.demo = 'seed controller & ' + MainServ.demo;
   $scope.format = 'M/d/yy h:mm:ss a';
   $scope.data = 'Hello World';

   //bootstrap datepicker
   $scope.status = {
      opened: false
   };

   $scope.disabled = function(date, mode) {
        return mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 );
  };

  $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
  $scope.format = $scope.formats[0];

  $scope.open = function() {
    $scope.status.opened = true;
  };
  $scope.dt = new Date();

   $scope.minDate = $scope.minDate ? null : new Date();
   $scope.maxDate = new Date(2020, 5, 22);

   $scope.dateOptions = {
    formatYear: 'yy',
    startingDay: 1
  };

};


text:
<?php
/**
 * Initial setup and constants
 */
function roots_setup() {

  // Register wp_nav_menu() menus (http://codex.wordpress.org/Function_Reference/register_nav_menus)
  register_nav_menus(array(
    'primary_navigation' => __('Primary Navigation', 'roots'),
  ));

  // Add post thumbnails (http://codex.wordpress.org/Post_Thumbnails)
  add_theme_support('post-thumbnails');
  set_post_thumbnail_size(550, 350, true);

  add_image_size('project_thumb', 550, 350, true); // project thumbs
  add_image_size('slide_img', 1200, 800, true); // header graphics

  // Tell the TinyMCE editor to use a custom stylesheet
  add_editor_style('lib/css/editor-style.css');
}
add_action('after_setup_theme', 'roots_setup');

// Backwards compatibility for older than PHP 5.3.0
if (!defined('__DIR__')) { define('__DIR__', dirname(__FILE__)); }

// Define helper constants
$get_theme_name = explode('/themes/', get_template_directory());

define('WP_BASE',                   wp_base_dir());
define('THEME_NAME',                next($get_theme_name));
define('RELATIVE_PLUGIN_PATH',      str_replace(site_url() . '/', '', plugins_url()));
define('FULL_RELATIVE_PLUGIN_PATH', WP_BASE . '/' . RELATIVE_PLUGIN_PATH);
define('RELATIVE_CONTENT_PATH',     str_replace(site_url() . '/', '', content_url()));
define('THEME_PATH',                RELATIVE_CONTENT_PATH . '/themes/' . THEME_NAME);


text:
<!--
  Thank you for your pull request. Please provide a description
  above and review the requirements below.

  Contributors guide:
  https://github.com/MARKETProtocol/meta/blob/master/CONTRIBUTING.md
-->

##### Description
<!-- A description on what this PR aims to solve. -->

##### Checklist
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->

- [ ] Linter status: 100% pass
- [ ] Changes don't break existing behavior
- [ ] Tests coverage hasn't decreased

##### Affected core subsystem(s)
<!-- Provide affected core subsystem(s) (like Docs, UI, UX, Tests etc). -->

##### Testing
<!-- Why should the PR reviewer trust that this change doesn't break
  anything? How have you tested this change?
-->

##### Refers/Fixes
<!--
  Link to an issue if applicable. For example:
  If your PR fixes an issue -- Fixes: #102
  If your PR refers an issue -- Refs: #101
-->


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='CorrectionDegree',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('eyes', models.FloatField(default=0)),
                ('chin', models.FloatField(default=0)),
            ],
        ),
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('username', models.CharField(max_length=30)),
                ('password', models.CharField(max_length=20)),
                ('email', models.CharField(max_length=30)),
                ('correction_degree', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='apiserver.CorrectionDegree')),
            ],
        ),
    ]


text:
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
find_package(Filesystem REQUIRED)

set(SRC_DIR "${CMAKE_SOURCE_DIR}/third_party/libprocinfo")

add_library(libprocinfo STATIC)
file(GLOB libprocinfo_source_files ${SRC_DIR}/*.cpp)
list(FILTER libprocinfo_source_files EXCLUDE REGEX "_(test|fuzzer|benchmark)\.cpp$")

target_sources(libprocinfo PRIVATE ${libprocinfo_source_files})
target_include_directories(libprocinfo SYSTEM PUBLIC ${SRC_DIR}/include/)
target_link_libraries(libprocinfo PUBLIC libbase)

if(NOT MSVC)
  target_compile_options(libprocinfo PRIVATE
    -Wno-error=format=
    -Wno-error=unknown-pragmas
  )
endif()


text:
/*
 Fraise version 3.7 - Based on Smultron by Peter Borg

 Current Maintainer (since 2016):
 Andreas Bentele: abentele.github@icloud.com (https://github.com/abentele/Fraise)

 Maintainer before macOS Sierra (2010-2016):
 Jean-François Moy: jeanfrancois.moy@gmail.com (http://github.com/jfmoy/Fraise)

 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.
 */

#import "FRAAdvancedFindPanel.h"

@implementation FRAAdvancedFindPanel

- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSWindowStyleMask)windowStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation
{
	self = [super initWithContentRect:contentRect styleMask:windowStyle backing:bufferingType defer:deferCreation];

	if (self) {
		[self setContentBorderThickness:22.0 forEdge:NSMinYEdge];
	}

	return self;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 336315 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="imagickdraw.skewx">
 <refnamediv>
  <refname>ImagickDraw::skewX</refname>
  <refpurpose>Skews the current coordinate system in the horizontal direction</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>bool</type><methodname>ImagickDraw::skewX</methodname>
   <methodparam><type>float</type><parameter>degrees</parameter></methodparam>
  </methodsynopsis>
  &warn.undocumented.func;
  <para>
   Skews the current coordinate system in the horizontal direction.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>degrees</parameter></term>
     <listitem>
      <para>
       degrees to skew
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>

 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
  &return.void;
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
    <example>
      <title> <function>ImagickDraw::skewX</function></title>
      <programlisting role="php">
      <![CDATA[
<?php
function skewX($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
               $startX, $startY, $endX, $endY, $skew) {

    $draw = new \ImagickDraw();

    $draw->setStrokeColor($strokeColor);
    $draw->setStrokeWidth(2);
    $draw->setFillColor($fillColor);
    $draw->rectangle($startX, $startY, $endX, $endY);
    $draw->setFillColor($fillModifiedColor);
    $draw->skewX($skew);
    $draw->rectangle($startX, $startY, $endX, $endY);

    $image = new \Imagick();
    $image->newImage(500, 500, $backgroundColor);
    $image->setImageFormat("png");

    $image->drawImage($draw);

    header("Content-Type: image/png");
    echo $image->getImageBlob();
}

?>
]]>
      </programlisting>
    </example>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
function defaultExtension() {
  return this.options.defaultExtension;
}

this.name = "JS (Galen / GJSTestCase)";
this.testcaseExtension = ".test.js";
this.webdriver = true;

this.options = {
    receiver: "",
    rcHost: "localhost",
    rcPort: "4444",
    extendClassName: "GJSTestCase",
    environment: "firefox",

    indent: '4',
    initialIndents: '2',
    defaultExtension: "test.js",

    showSelenese: false
};

options.header = '' +
        'load("/GJSTestCase/devices.js");\n' +
        'load("/GJSTestCase/GJSTestCase.js");\n' +
        '\n' +
        'var options = {\n' +
        indents(1) + 'domain: "${baseURL}", \n' +
        indents(1) + 'spec_dir: "specs/", \n' +
        indents(1) + 'spec_extension: ".spec" \n' +
        '}; \n' +
        '\n' +
        'new ${extendClassName}(options).run("Test: ${className}", Device.BASE, function() { \n' +
        '\n' +
        indents(1) + 'this\n';

options.footer = '\n' +
        '});\n';

this.configForm =
    '<description>Class name for extends GJSTestCase</description>' +
    '<textbox id="options_extendClassName" />' +

    '<description>Header</description>' +
    '<textbox id="options_header" multiline="true" flex="1" rows="4"/>' +
    '<description>Footer</description>' +
    '<textbox id="options_footer" multiline="true" flex="1" rows="4"/>' +

    '<description>Indent</description>' +
    '<menulist id="options_indent"><menupopup>' +
    '<menuitem label="Tab" value="tab"/>' +
    '<menuitem label="2 spaces" value="2"/>' +
    '<menuitem label="4 spaces" value="4"/>' +
    '<menuitem label="8 spaces" value="8"/>' +
    '</menupopup></menulist>';


text:
<!DOCTYPE html>

            Should not wrap when zooming out.

A

B


text:
require_relative 'gen/user_task_lists_base'

module Asana
  module Resources
    # A _user task list_ represents the tasks assigned to a particular user. It provides API access to a user's "My Tasks" view in Asana.
    #
    # A user's "My Tasks" represent all of the tasks assigned to that user. It is
    # visually divided into regions based on the task's
    # [`assignee_status`](/developers/api-reference/tasks#field-assignee_status)
    # for Asana users to triage their tasks based on when they can address them.
    # When building an integration it's worth noting that tasks with due dates will
    # automatically move through `assignee_status` states as their due dates
    # approach; read up on [task
    # auto-promotion](/guide/help/fundamentals/my-tasks#gl-auto-promote) for more
    # infomation.
    class UserTaskList < UserTaskListsBase

      attr_reader :gid

      attr_reader :resource_type

      attr_reader :name

      attr_reader :owner

      attr_reader :workspace

      class << self
        # Returns the plural name of the resource.
        def plural_name
          'user_task_lists'
        end

        # Returns the full record for the user task list for the given user
        #
        # user - [String] An identifier for the user. Can be one of an email address,
        # the globally unique identifier for the user, or the keyword `me`
        # to indicate the current user making the request.
        #
        # workspace - [Gid] Globally unique identifier for the workspace or organization.
        #
        # options - [Hash] the request I/O options.
        def find_by_user(client, user: required("user"), workspace: required("workspace"), options: {})
          params = { workspace: workspace }.reject { |_,v| v.nil? || Array(v).empty? }
          Resource.new(parse(client.get("/users/#{user}/user_task_list", params: params, options: options)).first, client: client)
        end

        # Returns the full record for a user task list.
        #
        # id - [Gid] Globally unique identifier for the user task list.
        #
        # options - [Hash] the request I/O options.
        def find_by_id(client, id, options: {})

          self.new(parse(client.get("/user_task_lists/#{id}", options: options)).first, client: client)
        end
      end

      # Returns the compact list of tasks in a user's My Tasks list. The returned
      # tasks will be in order within each assignee status group of `Inbox`,
      # `Today`, and `Upcoming`.
      #
      # **Note:** tasks in `Later` have a different ordering in the Asana web app
      # than the other assignee status groups; this endpoint will still return
      # them in list order in `Later` (differently than they show up in Asana,
      # but the same order as in Asana's mobile apps).
      #
      # **Note:** Access control is enforced for this endpoint as with all Asana
      # API endpoints, meaning a user's private tasks will be filtered out if the
      # API-authenticated user does not have access to them.
      #
      # **Note:** Both complete and incomplete tasks are returned by default
      # unless they are filtered out (for example, setting `completed_since=now`
      # will return only incomplete tasks, which is the default view for "My
      # Tasks" in Asana.)
      #
      # completed_since - [String] Only return tasks that are either incomplete or that have been
      # completed since this time.
      #
      # per_page - [Integer] the number of records to fetch per page.
      # options - [Hash] the request I/O options.
      def tasks(completed_since: nil, per_page: 20, options: {})
        params = { completed_since: completed_since, limit: per_page }.reject { |_,v| v.nil? || Array(v).empty? }
        Collection.new(parse(client.get("/user_task_lists/#{gid}/tasks", params: params, options: options)), type: Task, client: client)
      end

    end
  end
end


text:
layout: doc
title: "Collection.length"
position: 0
---

Возвращает количество элементов в коллекции.

# Syntax

```js
Collection.length
```

## Returns

Количество элементов в коллекции.

# Examples

```js
var collection = new Collection(); // Collection.length === 0
collection.add('A'); // Collection.length === 1
collection.add('B'); // Collection.length === 2
collection.add('C'); // Collection.length === 3
```

# See Also

* [`size()`](../Collection.size/)


text:
package com.bct.gpstracker.baby.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewListener;
import com.bct.gpstracker.MainActivity;
import com.bct.gpstracker.R;
import com.bct.gpstracker.base.BaseActivity;
import com.bct.gpstracker.util.TTSController;

public class NavigatorActivity extends BaseActivity implements AMapNaviViewListener {
    private AMapNaviView mAmapAMapNaviView;

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

    /**
     * 初始化
     * @param savedInstanceState
     */
    private void init(Bundle savedInstanceState) {
        mAmapAMapNaviView = (AMapNaviView) findViewById(R.id.navi_map);
        mAmapAMapNaviView.onCreate(savedInstanceState);
        // 设置导航界面监听
        mAmapAMapNaviView.setAMapNaviViewListener(this);
        AMapNavi.getInstance(this).startNavi(AMapNavi.GPSNaviMode);
        TTSController.getInstance(this).startSpeaking();
    }

    /**
     * 导航界面左下角返回按钮回调
     *
     */
    @Override
    public void  onNaviCancel() {
        AMapNavi.getInstance(this).stopNavi();
        Intent intent = new Intent(NavigatorActivity.this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onNaviBackClick() {
        return false;
    }

    /**
     * 导航界面右下角功能设置按钮回调
     *
     */
    @Override
    public void onNaviSetting() {

    }

    @Override
    public void onNaviMapMode(int arg0) {

    }

    @Override
    public void onNaviTurnClick() {

    }

    @Override
    public void onNextRoadClick() {

    }

    @Override
    public void onScanViewButtonClick() {

    }

    @Override
    public void onLockMap(boolean b) {

    }

    /**
     * 返回键盘监听
     *
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AMapNavi.getInstance(this).stopNavi();
            Intent intent = new Intent(NavigatorActivity.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mAmapAMapNaviView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        mAmapAMapNaviView.onResume();
    };

    @Override
    public void onPause() {
        super.onPause();
        mAmapAMapNaviView.onPause();
        AMapNavi.getInstance(this).stopNavi();
    }

    @Override
    public void onDestroy(){
    	super.onDestroy();
        mAmapAMapNaviView.onDestroy();
        TTSController.getInstance(this).stopSpeaking();
        TTSController.getInstance(this).destroy();
    }
}


text:
id: 5900f4a31000cf542c50ffb6
challengeType: 5
title: 'Problem 311: Biclinic Integral Quadrilaterals'
videoUrl: ''
localeTitle: 'Problema 311: Cuadriláteros Integrales Biclínicos'
---

## Description

 ABCD es un cuadrilátero convexo de lados enteros con 1 ≤ AB <BC <CD <AD. BD tiene longitud entera. O es el punto medio de BD. AO tiene longitud entera. Llamaremos a ABCD cuadrilátero integral biclínico si AO = CO ≤ BO = DO.
 Por ejemplo, el siguiente cuadrilátero es un cuadrilátero integral biclínico: AB = 19, BC = 29, CD = 37, AD = 43, BD = 48 y AO = CO = 23.

 Sea B (N) el número de cuadriláteros integrales biclínicos distintos ABCD que satisfacen AB2 + BC2 + CD2 + AD2 ≤ N. Podemos verificar que B (10 000) = 49 y B (1 000 000) = 38239.

 Encuentre B (10 000 000 000).

## Instructions

## Tests

```yml
tests:
  - text: <code>euler311()</code> debe devolver 2466018557.
    testString: 'assert.strictEqual(euler311(), 2466018557, "<code>euler311()</code> should return 2466018557.");'

```

## Challenge Seed

```js
function euler311() {
  // Good luck!
  return true;
}

euler311();

```

## Solution

```js
// solution required
```


text:
package handy.marketsim.investors.holders;

import handy.marketsim.Position;

public class IvyPortfolioInvestor extends HoldPortfolioInvestor {
	public IvyPortfolioInvestor(double cash){
		super(cash);
		positions.add(new Position("VTI", 5.0f));
		positions.add(new Position("VO", 5.0f));
		positions.add(new Position("VB", 5.0f));
		positions.add(new Position("IWC", 5.0f));
		positions.add(new Position("VEU", 5.0f));
		positions.add(new Position("VWO", 5.0f));
		positions.add(new Position("GWX", 5.0f));
		positions.add(new Position("EWX", 5.0f));
		positions.add(new Position("BND", 5.0f));
		positions.add(new Position("TIP", 5.0f));
		positions.add(new Position("BWX", 5.0f));
		positions.add(new Position("ESD", 5.0f));
		positions.add(new Position("VNQ", 5.0f));
		positions.add(new Position("RWX", 5.0f));
		positions.add(new Position("IGF", 5.0f));
		positions.add(new Position("WOOD", 5.0f));
		positions.add(new Position("DBA", 5.0f));
		positions.add(new Position("DBE", 5.0f));
		positions.add(new Position("DBB", 5.0f));
		positions.add(new Position("DBP", 5.0f));
	}

}


text:
@interface TwitterStatusViewNameField : NTLNMessageViewClickableTextField {
    NTLNMessage *_status;
}

- (void) setStatus:(NTLNMessage*)status;

@end


text:
{% extends "fragments/default.html" %}
{% load crispy_forms_tags %}
{% block navbar %}
{% include "fragments/navbar.html" %}
{% endblock %}

{% block content %}

Account settings

        {% crispy form %}

{% endblock %}


text:
<?php

namespace yiingine\modules\customFields\models;

use \Yii;

/** A model for custom fields of type INTEGER.*/
class IntegerField extends CustomField
{
    /**
     * @return array validation rules for this model's attributes.
     */
    public function rules()
    {
        return array_merge([
            ['min_size', '\yiingine\validators\UnsafeValidator'], // This attribute should not be displayed or used.
            ['size', 'required'],
            ['size', 'integer', 'min' => 1, 'max' => 11, 'integerOnly' => true]
        ], parent::rules());
    }

    /**
     * Validate the configuration attribute.
     * @param string $attribute the attribute to validate.
     * @param array $params the parameters for the validator.
     * */
    public function validateConfiguration($attribute, $params)
    {
        if($this->hasErrors($attribute))
        {
            return;
        } // If there are errors, do not validate.

        $configuration = $this->getConfigurationArray();

        // For Integer, configuration must be in the form of array("minimum" => 1, maximum" => null), where null means no maximum of minimum.
        if($configuration['minimum'] !== null && !isset($configuration['minimum'])
           || $configuration['maximum'] !== null && !isset($configuration['maximum'])
           || ($configuration['maximum'] !== null && $configuration['minimum'] !== null && $configuration['maximum'] < $configuration['minimum'])
        )
        {
            $this->addError($attribute, Yii::t(\yiingine\modules\customFields\models\CustomField::className(), 'Configuration is invalid.'));
        }
    }

    /** @return array attribute descriptions (name => description). */
    public function attributeDescriptions()
    {
        return array_merge(parent::attributeDescriptions(), [
            'size' => Yii::t(__CLASS__, 'Defines the display width (ex: INT(SIZE) in MySQL).'),
        ]);
    }

    /** Returns an example configuration for this field to be used inside the descriptions
     * and as a default value. Has to be valid php.
     * @return string an example configuration.*/
    public function getExampleConfiguration()
    {
        return
'array(
    "minimum" => 0, // null for no minimum.
    "maximum" => 99, // null for no maximum.
)';
    }

    /** @return string the SQL that describes this field.*/
    public function getSql()
    {
        return 'int('.$this->size.') DEFAULT '.($this->default ? $this->default: 0);
    }
}


text:
package net.sf.jabref.gui.util;

import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import net.sf.jabref.Globals;

public class PositionWindow {

    private final String posXKey;
    private final String posYKey;
    private final String sizeXKey;
    private final String sizeYKey;
    private final Window window;

    public PositionWindow(Window window, String posXKey, String posYKey, String sizeXKey, String sizeYKey) {
        this.posXKey = posXKey;
        this.posYKey = posYKey;
        this.sizeXKey = sizeXKey;
        this.sizeYKey = sizeYKey;
        this.window = window;
        // Set up a ComponentListener that saves the last size and position of the dialog
        window.addComponentListener(new ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent e) {
                // Save dialog position
                storeWindowPosition();
            }

            @Override
            public void componentMoved(ComponentEvent e) {
                // Save dialog position
                storeWindowPosition();
            }
        });

    }

    public void setWindowPosition() {

        int sizeX = Globals.prefs.getInt(sizeXKey);
        int sizeY = Globals.prefs.getInt(sizeYKey);
        int posX = Globals.prefs.getInt(posXKey);
        int posY = Globals.prefs.getInt(posYKey);

        //
        // Fix for [ 1738920 ] Windows Position in Multi-Monitor environment
        //
        // Do not put a window outside the screen if the preference values are wrong.
        //
        // Useful reference: http://www.exampledepot.com/egs/java.awt/screen_ScreenSize.html?l=rel
        // googled on forums.java.sun.com graphicsenvironment second screen java
        //
        if (GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length >= 1) {
            Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0]
                    .getDefaultConfiguration().getBounds();
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

            // Make sure we are not above or to the left of the screen bounds:
            if (posX < bounds.x) {
                posX = bounds.x;
            }
            if (posY < bounds.y) {
                posY = bounds.y;
            }

            int height = (int) dim.getHeight();
            int width = (int) dim.getWidth();

            if ((posX + sizeX) > width) {
                if (sizeX <= width) {
                    posX = width - sizeX;
                } else {
                    posX = Globals.prefs.getIntDefault(posXKey);
                    sizeX = Globals.prefs.getIntDefault(sizeXKey);
                }
            }

            if ((posY + sizeY) > height) {
                if (sizeY <= height) {
                    posY = height - sizeY;
                } else {
                    posY = Globals.prefs.getIntDefault(posYKey);
                    sizeY = Globals.prefs.getIntDefault(sizeYKey);
                }
            }
        }
        window.setLocation(posX, posY);
        window.setSize(sizeX, sizeY);

    }

    public void storeWindowPosition() {
        Point p = window.getLocation();
        Dimension d = window.getSize();
        Globals.prefs.putInt(posXKey, p.x);
        Globals.prefs.putInt(posYKey, p.y);
        Globals.prefs.putInt(sizeXKey, d.width);
        Globals.prefs.putInt(sizeYKey, d.height);
    }

}


text:
package gossip

import (
	"testing"
	"time"

	"github.com/cockroachdb/cockroach/pkg/roachpb"
	"github.com/cockroachdb/cockroach/pkg/util/hlc"
	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
	"github.com/cockroachdb/cockroach/pkg/util/timeutil"
)

func newInfo(val float64) Info {
	now := timeutil.Now()

	v := roachpb.Value{Timestamp: hlc.Timestamp{WallTime: now.UnixNano()}}
	v.SetFloat(val)

	return Info{
		Value:     v,
		OrigStamp: now.UnixNano(),
		TTLStamp:  now.Add(time.Millisecond).UnixNano(),
	}
}

func TestExpired(t *testing.T) {
	defer leaktest.AfterTest(t)()

	i := newInfo(float64(1))
	if i.expired(i.Value.Timestamp.WallTime) {
		t.Error("premature expiration")
	}
	if !i.expired(i.TTLStamp) {
		t.Error("info should have expired")
	}
}

func TestIsFresh(t *testing.T) {
	defer leaktest.AfterTest(t)()

	i := newInfo(float64(1))
	if !i.isFresh(i.OrigStamp - 1) {
		t.Error("info should be fresh:", i)
	}
	if i.isFresh(i.OrigStamp) {
		t.Error("info should not be fresh:", i)
	}
	if i.isFresh(i.OrigStamp + 1) {
		t.Error("info should not be fresh:", i)
	}
	// Using timestamp 0 will always yield fresh data.
	if !i.isFresh(0) {
		t.Error("info should be fresh from node0:", i)
	}
}


text:
<?php
	namespace Mio\Vehicle;
	class VehicleType extends RemoteObj {
		public function getMakes() {
			return $this->_subs;
		}
		public function addMakes($makes) {
			foreach ($makes as $make) {
				$this->_subs[] = new Make($make['id'], $make['label']);
			}
			return $this->_subs;
		}
	}
?>


text:
import React from 'react';
import { shallow, mount } from 'enzyme';
import { Popper } from 'react-popper';
import { PopperContent } from '..';

describe('PopperContent', () => {
  let element;
  let container;

  beforeEach(() => {
    element = document.createElement('div');
    container = document.createElement('div');
    element.innerHTML =
      '
This is the popover target.
';
    container.setAttribute('id', 'container');
    element.appendChild(container);
    document.body.appendChild(element);

    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.clearAllTimers();
    document.body.removeChild(element);
    element = null;
  });

  it('should render a null by default', () => {
    const wrapper = shallow(<PopperContent target="target">Yo!</PopperContent>);

    expect(wrapper.type()).toBe(null);
  });

  it('should NOT render children when isOpen is false', () => {
    const wrapper = shallow(<PopperContent target="target">Yo!</PopperContent>);

    expect(wrapper.type()).toBe(null);
  });

  it('should render children when isOpen is true and container is inline', () => {
    const wrapper = mount(
      <PopperContent target="target" isOpen container="inline">
        Yo!
      </PopperContent>,
    );

    expect(wrapper.text()).toBe('Yo!');
  });

  it('should render children when isOpen is true and container is inline and DOM node passed directly for target', () => {
    const targetElement = element.querySelector('#target');

    const wrapper = mount(
      <PopperContent target={targetElement} isOpen container="inline">
        Yo!
      </PopperContent>,
    );
    expect(targetElement).toBeDefined();
    expect(wrapper.text()).toBe('Yo!');
  });

  it('should render an Arrow in the Popper when isOpen is true and container is inline', () => {
    const wrapper = mount(
      <PopperContent
        target="target"
        isOpen
        container="inline"
        arrowClassName="custom-arrow"
      >
        Yo!
      </PopperContent>,
    );

    expect(
      wrapper.containsMatchingElement(),
    ).toBe(true);
  });

  it('should NOT render an Arrow in the Popper when "hideArrow" is truthy', () => {
    const wrapper = mount(
      <PopperContent
        target="target"
        isOpen
        container="inline"
        arrowClassName="custom-arrow"
        hideArrow
      >
        Yo!
      </PopperContent>,
    );

    expect(
      wrapper.containsMatchingElement(),
    ).toBe(false);
  });

  it('should render with "hideArrow" false by default', () => {
    const wrapper = mount(<PopperContent target="target">Yo!</PopperContent>);

    expect(wrapper.prop('hideArrow')).toBe(false);
  });

  it('should render with "hideArrow" true when "hideArrow" prop is truthy', () => {
    const wrapper = mount(
      <PopperContent target="target" hideArrow>
        Yo!
      </PopperContent>,
    );

    expect(wrapper.prop('hideArrow')).toBe(true);
  });

  it('should not render children', () => {
    const wrapper = shallow(<PopperContent target="target">Yo!</PopperContent>);

    expect(wrapper.type()).toBe(null);
  });

  it('should pass additional classNames to the popper', () => {
    const wrapper = shallow(
      <PopperContent
        className="extra"
        target="target"
        isOpen
        container="inline"
      >
        Yo!
      </PopperContent>,
    );

    expect(wrapper.hasClass('extra')).toBe(true);
  });

  it('should allow custom modifiers and even allow overriding of default modifiers', () => {
    const wrapper = mount(
      <PopperContent
        className="extra"
        target="target"
        isOpen
        container="inline"
        modifiers={[
          {
            name: 'offset',
            options: {
              offset: [2, 2],
            },
          },
          {
            name: 'preventOverflow',
            options: {
              boundary: 'viewport',
            },
          },
        ]}
      >
        Yo!
      </PopperContent>,
    );

    expect(wrapper.find(Popper).props().modifiers).toContainEqual({
      name: 'offset',
      options: {
        offset: [2, 2],
      },
    });
    expect(wrapper.find(Popper).props().modifiers).toContainEqual({
      name: 'flip',
      enabled: true,
      options: {
        fallbackPlacements: undefined,
      },
    });
    expect(wrapper.find(Popper).props().modifiers).toContainEqual({
      name: 'preventOverflow',
      options: {
        boundary: 'viewport',
      },
    });

    wrapper.unmount();
  });

  it('should have data-popper-placement of auto by default', () => {
    const wrapper = mount(
      <PopperContent target="target" isOpen container="inline">
        Yo!
      </PopperContent>,
    );

    expect(wrapper.find('div[data-popper-placement="auto"]').exists()).toBe(
      true,
    );
  });

  it('should override data-popper-placement', () => {
    const wrapper = mount(
      <PopperContent placement="top" target="target" isOpen container="inline">
        Yo!
      </PopperContent>,
    );

    expect(wrapper.find('div[data-popper-placement="auto"]').exists()).toBe(
      false,
    );
    expect(wrapper.find('div[data-popper-placement="top"]').exists()).toBe(
      true,
    );
  });

  it('should allow for a placement prefix', () => {
    const wrapper = mount(
      <PopperContent
        placementPrefix="dropdown"
        target="target"
        isOpen
        container="inline"
      >
        Yo!
      </PopperContent>,
    );

    expect(wrapper.find('.dropdown-auto').exists()).toBe(true);
  });

  it('should allow for a placement prefix with custom placement', () => {
    const wrapper = mount(
      <PopperContent
        placementPrefix="dropdown"
        placement="top"
        target="target"
        isOpen
        container="inline"
      >
        Yo!
      </PopperContent>,
    );

    expect(wrapper.find('.dropdown-auto').exists()).toBe(true);
    expect(wrapper.find('div[data-popper-placement="top"]').exists()).toBe(
      true,
    );
  });

  it('should render custom tag for the popper', () => {
    const wrapper = mount(
      <PopperContent tag="main" target="target" isOpen container="inline">
        Yo!
      </PopperContent>,
    );

    expect(wrapper.getDOMNode().tagName.toLowerCase()).toBe('main');
  });

  it('should allow a function to be used as children', () => {
    const renderChildren = jest.fn();
    mount(
      <PopperContent target="target" isOpen>
        {renderChildren}
      </PopperContent>,
    );
    expect(renderChildren).toHaveBeenCalled();
  });

  it('should render children properly when children is a function', () => {
    const wrapper = mount(
      <PopperContent target="target" isOpen>
        {() => 'Yo!'}
      </PopperContent>,
    );

    expect(wrapper.text()).toBe('Yo!');
  });
});


text:
TEST_GROUP(groupEvents){};

TEST(groupEvents, testDefault)
{
    amici::simulateWithDefaultOptions();
}

TEST(groupEvents, testSimulation)
{
    amici::simulateVerifyWrite("/model_events/nosensi/");
}

TEST(groupEvents, testSensitivityForward)
{
    amici::simulateVerifyWrite("/model_events/sensiforward/");
}


text:
package org.jkiss.dbeaver.runtime;

import org.jkiss.dbeaver.Log;

import java.security.Provider;
import java.security.Security;

/**
 * Bouncy Castle linker
 */
public class SecurityProviderUtils {
    private static final Log log = Log.getLog(SecurityProviderUtils.class);

    public static final String BC_SECURITY_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider";

    private static String securityProvider = null;
    private static boolean registrationDone;

    public static void registerSecurityProvider() {
        if (!registrationDone) {
            try {
                if (securityProvider == null) {
                    registerSecurityProvider(BC_SECURITY_PROVIDER_CLASS);
                    if (securityProvider == null) {
                        log.debug("BouncyCastle not registered, using the default JCE provider");
                    }
                }
            } finally {
                registrationDone = true;
            }
        }
    }

    private static boolean registerSecurityProvider(String providerClassName) {
        Provider provider = null;
        try {
            Class<?> name = Class.forName(providerClassName);
            provider = (Provider) name.newInstance();
        } catch (Exception e) {
            log.debug("Can't find BC security provider. Use default JCE.");
        }

        if (provider == null) {
            return false;
        }

        try {
            if (Security.getProvider(provider.getName()) == null) {
                Security.addProvider(provider);
            }

            if (securityProvider == null) {
                securityProvider = provider.getName();
                log.debug("BounceCastle bundle found. Use JCE provider " + provider.getName());
                return true;
            }
        } catch (Exception e) {
            log.warn("Registration of Security Provider '" + providerClassName + "' unexpectedly failed", e);
        }
        return false;
    }

}


text:
//
//  ESArcProgressView+Animations.h
//  CircleDraw
//
//  Created by Bas van Kuijck on 11-03-15.
//  Copyright (c) 2015 e-sites. All rights reserved.
//

#import "ESArcProgressViewCore.h"
#include "easing.h"

typedef void (^ESArcProgressViewUpdateBlock)(CGFloat animationProgress);

@interface ESArcProgressView (Animations)

/**
 *	@author Bas van Kuijck <bas@e-sites.nl>
 *
 *	Animate to a given value with a duration of 1.0seconds and linear easing
 *
 *	@param toValue CGFloat (somewhere between 0.0 and 1.0f)
 *
 *	@since 1.5
 *  @date 10/03/2015
 */
- (void)animateTo:(CGFloat)toValue;

/**
 *	@author Bas van Kuijck <bas@e-sites.nl>
 *
 *	Animate to a given value with a given duration and a linear easing
 *
 *	@param toValue CGFloat (somewhere between 0.0 and 1.0f)
 *  @param duration NSTimeInterval Duration
 *
 *	@since 1.5
 *  @date 10/03/2015
 */
- (void)animateTo:(CGFloat)toValue withDuration:(NSTimeInterval)duration;

/**
 *	@author Bas van Kuijck <bas@e-sites.nl>
 *
 *	Animate to a given value with a duration and custom easing
 *  @see https://github.com/warrenm/AHEasing for possible easingFunction values
 *
 *	@param toValue        CGFloat
 *	@param duration       NSTimeInterval
 *	@param easingFunction AHEasingFunction
 *
 *	@since 1.5
 *  @date 10/03/2015
 */
- (void)animateTo:(CGFloat)toValue withDuration:(NSTimeInterval)duration withEasingFunction:(AHEasingFunction)easingFunction;

/**
 *	@author Bas van Kuijck <bas@e-sites.nl>
 *
 *	Animate to a given value with a duration and custom easing
 *  Every time a new progress is done the updateHandler will be called
 *  @see https://github.com/warrenm/AHEasing for possible easingFunction values
 *
 *	@param toValue        CGFloat
 *	@param duration       NSTimeInterval
 *	@param easingFunction AHEasingFunction
 *  @param updateHandler ESArcProgressViewUpdateBlock
 *
 *	@since 1.5
 *  @date 10/03/2015
 */
- (void)animateTo:(CGFloat)toValue withDuration:(NSTimeInterval)duration withEasingFunction:(AHEasingFunction)easingFunction withUpdateHandler:(ESArcProgressViewUpdateBlock)updateHandler;

/**
 *	@author Bas van Kuijck <bas@e-sites.nl>
 *
 *	Stops an active animation
 *
 *	@since 1.5
 *  @date 10/03/2015
 */
- (void)stopAnimation;

@end


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{{ site.title }}</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/motion-ui/1.1.1/motion-ui.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundicons/3.0.0/foundation-icons.css" />

    {{ content }}

Är du en hejare på något? Hör av dig!

{{ site.data.company.email }}

{{ site.data.company.phone }}

          {% if site.data.company.address != undefined %}

{{ site.data.company.address | replace: ',', '
'  }}

          {% endif %}

Crafted with love by incredible techies at Hejare 2017


text:
import json, os

from common import *

from test_asmjs import test_asmjs
from test_c     import test_c
from test_d     import test_d

def main( verbose = True ):

    result_li = []

    if verbose: print( os.linesep + '.' )
    result_li.extend( test_asmjs( verbose = verbose ) )

    if verbose: print( os.linesep + '.' )
    result_li.extend( test_c( verbose = verbose ) )

    if verbose: print( os.linesep + '.' )
    result_li.extend( test_d( verbose = verbose ) )

    s = summary( result_li )

    if verbose:
        print( os.linesep + '.' )
        print()
        print( '--- all done ---' )
        print( s[ MESSAGE ] )

    if s[ N_FAILURE ] > 0:
        if verbose: print( 'Failure(s):' )
        faili = filter( lambda x: not x[ OK ], result_li )
        if verbose: print( os.linesep.join( map( json.dumps, faili ) ) )

    return s

if __name__ == '__main__':
    main()


text:
/*!
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

/**
 * If the given text or resolved expression matches any text within the element, the matching text will be wrapped
 * with a class.
 *
 * Example:
 *
My text
 ==>
My text

 *
 *
{{ name }}

 * <input type="text" ng-model="searchTerm">
 */
(function () {
    angular.module('piwikApp.directive').directive('piwikAutocompleteMatched', piwikAutocompleteMatched);

    piwikAutocompleteMatched.$inject = ['piwik', '$sanitize'];

    function piwikAutocompleteMatched(piwik, $sanitize) {

        return {
            priority: 10, // makes sure to render after other directives, otherwise the content might be overwritten again see https://github.com/piwik/piwik/pull/8467
            link: function (scope, element, attrs) {
                var searchTerm;

                scope.$watch(attrs.piwikAutocompleteMatched, function (value) {
                    searchTerm = value;
                    updateText();
                });

                function updateText() {
                    if (!searchTerm || !element) {
                        return;
                    }

                    var content = piwik.helper.htmlEntities(element.text());
                    var startTerm = content.toLowerCase().indexOf(searchTerm.toLowerCase());

                    if (-1 !== startTerm) {
                        var word = content.substr(startTerm, searchTerm.length);
                        var escapedword = $sanitize(piwik.helper.htmlEntities(word));
                        content = content.replace(word, '' + escapedword + '');
                        element.html(content);
                    }
                }
            }
        };
    }
})();


text:
package com.tyrfing.games.tyrlib3.view.graphics.materials;

import com.tyrfing.games.tyrlib3.model.game.Color;
import com.tyrfing.games.tyrlib3.view.graphics.Mesh;
import com.tyrfing.games.tyrlib3.view.graphics.Program;
import com.tyrfing.games.tyrlib3.view.graphics.ProgramManager;
import com.tyrfing.games.tyrlib3.view.graphics.TextureManager;
import com.tyrfing.games.tyrlib3.view.graphics.TyrGL;
import com.tyrfing.games.tyrlib3.view.graphics.renderables.IBlendable;
import com.tyrfing.games.tyrlib3.view.graphics.renderer.OpenGLRenderer;
import com.tyrfing.games.tyrlib3.view.graphics.texture.Texture;
import com.tyrfing.games.tyrlib3.view.graphics.texture.TextureRegion;

/**
 * Material for rendering point sprites.
 * @author Sascha
 *
 */

public class PointSpriteMaterial extends Material implements IBlendable {

	private String textureName;
	private Texture texture;
	private Color color;
	private TextureRegion region;
	private boolean blending = true;

	public PointSpriteMaterial(String textureName, Color color) {
		program = ProgramManager.getInstance().getProgram("POINT_SPRITE");

		this.textureName = textureName;
		this.color = color;

		if (textureName != null) {
			texture = TextureManager.getInstance().getTexture(textureName);
		}

		init(0,3, "u_MVPMatrix", "a_Position");
	}

	public PointSpriteMaterial(String textureName, TextureRegion region, Color color) {
		program = ProgramManager.getInstance().getProgram("POINT_SHEET");

		this.textureName = textureName;
		this.color = color;
		this.region = region;

		if (textureName != null) {
			texture = TextureManager.getInstance().getTexture(textureName);
		}

		init(0,3, "u_MVPMatrix", "a_Position");
	}

	public void render(Mesh mesh, float[] modelMatrix) {
        super.render(mesh, modelMatrix);

		if (region != null ){
			int textureCoordPointSizeX = TyrGL.glGetUniformLocation(program.handle, "u_TextureCoordPointSizeX");
			TyrGL.glUniform1f(textureCoordPointSizeX, region.u2 - region.u1);

			int textureCoordPointSizeY = TyrGL.glGetUniformLocation(program.handle, "u_TextureCoordPointSizeY");
			TyrGL.glUniform1f(textureCoordPointSizeY, region.v2 - region.v1);

			int textureCoordIn = TyrGL.glGetUniformLocation(program.handle, "u_TextureCoordIn");
			TyrGL.glUniform2f(textureCoordIn, region.u1,region.v1);
		}

		int textureHandle = texture.getHandle();

		if (program.textureHandle != textureHandle) {

//
//			TyrGL.glEnableVertexAttribArray(textureUniformHandle);

		    // Set the active texture unit to texture unit 0.
			TyrGL.glActiveTexture(TyrGL.GL_TEXTURE0);

		    // Bind the texture to this unit.
			TyrGL.glBindTexture(TyrGL.GL_TEXTURE_2D, textureHandle);

		    // Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0.
			int textureUniformHandle = TyrGL.glGetUniformLocation(program.handle, "u_Texture");
			TyrGL.glUniform1i(textureUniformHandle, 0);

		    program.textureHandle = textureHandle;

		    OpenGLRenderer.setTextureFails(OpenGLRenderer.getTextureFails() + 1);

		}

		if (blending) {
			Program.blendEnable(TyrGL.GL_SRC_ALPHA, TyrGL.GL_ONE_MINUS_SRC_ALPHA);
		} else {
			Program.blendDisable();
		}
	}

	public void setBlending(boolean blending) {
		this.blending = blending;
	}

	public String getTextureName(){
		return textureName;
	}

	@Override
	public float getAlpha() {
		return color.a;
	}

	@Override
	public void setAlpha(float alpha) {
		this.color.a = alpha;
	}

	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public Material copy() {
		return new PointSpriteMaterial(textureName, color.copy());
	}

	public Texture getTexture() {
		return texture;
	}

	public TextureRegion getRegion() {
		return region;
	}

	public void setRegion(TextureRegion region) {
		this.region = region;
	}
}


text:
'use strict';

let User = require('./index').User;

module.exports = {
  // sign up a user
  create: function create(user) {
    return User.create(user).exec();
  },

  // get user
  getUserByName: function getUserByname(name) {
    return User
      .findOne({name: name})
      // create time stamp
      .addCreateAt()
      .exec();
  }
};