text:
==========
Quickstart
==========

Using a tapioca package
=======================

**Yes, you are in the right place**

There is a good chance you found this page because you clicked a link from some python package called **tapioca-SOMETHING**. Well, welcome! You are in the right place, this page will teach you the basics of how to use the package that sent you here. If you didn't arrive here from other package, please keep reading, the concepts learned here applies to any tapioca-**package** available.

What's tapioca?
===============

**tapioca** is a *API wrapper maker*. It helps Python developers creating packages for APIs (like the :ref:`Facebook Graph API <flavour-facebook>` or the :ref:`Twitter REST API <flavour-twitter>`. You can find a full list of available API packages made with tapioca :doc:`here <flavours>`.

All wrappers made with tapioca follow a simple interaction pattern that works uniformly so once you learn how tapioca works you will be able to work with any tapioca package available.

Getting started
===============

We will use ``tapioca-facebook`` as example to guide us through tapioca concepts.
Lets install ``tapioca-facebook``:

.. code-block:: bash

	$ pip install tapioca-facebook

To better experience tapioca, we will also use iPython:

.. code-block:: bash

	$ pip install ipython

Lets explore!

Go to  `https://developers.facebook.com/tools/explorer/ <https://developers.facebook.com/tools/explorer/>`_, click "Get Access Token", select all "User Data Permissions" and "Extended Permissions" and click "Get Access Token". This will give you a temporary access token to play with Facebook API. In case it expires, just generate a new one.

TapiocaClient object
====================

This is how you initialize your tapioca client:

.. code-block:: python

	from tapioca_facebook import Facebook

	api = Facebook(access_token='{your_genereated_access_token}')

If you are using iPython, you can now list available endpoints by typing ``api.`` and pressing ``tab``.

.. code-block:: python

	>>> api.
	api.user_likes                  api.page_blocked                 api.page_locations
	api.page_statuses                api.user_applications_developer  api.user_friends
	api.user_invitable_friends       api.user_photos                  api.user_videos
	api.object                       api.page_conversations           api.page_milestones
	...

Resources
---------

Those are the available endpoints for the facebook API. As we can see there is one called: ``user_likes``, lets take a closer look.

Type ``api.user_likes?`` and press ``enter``

.. code-block:: python

	In [3]: api.user_likes?
	...
	Docstring:
	Automatic generated __doc__ from resource_mapping.
	Resource: {id}/likes
	Docs: https://developers.facebook.com/docs/graph-api/reference/v2.2/user/likes

As we can see, ``user_likes`` resource requires an ``id`` to be passed to the url. Lets do it:

.. code-block:: python

	api.user_likes(id='me')

Fetching data
-------------

To request current user likes, its easy:

.. code-block:: python

	likes = api.user_likes(id='me').get()

To print the returned data do:

.. code-block:: python

	In [9]: likes().data
	OUT [9]: {
		'data': [...],
		'paging': {...}
	}

Exploring data
--------------

We can also explore the returned data using the iPython ``tab`` auto-complete

.. code-block:: python

	In [9]: likes.
	likes.data    likes.paging

Iterating over data
-------------------

You can iterate over returned data:

.. code-block:: python

	likes = api.user_likes(id='me').get()

	for like in likes.data:
		print(like.id().data)

Items passed to the ``for`` loop will be wrapped in tapioca so you still have access to all features.

TapiocaClientExecutor object
============================

Whenever you make a "call" on a ``TapiocaClient`` it will return to you an ``TapiocaClientExecutor`` object. You will use the executor every time you want to perform an action over data you possess.

An example was when we filled url params for the ``user_like`` resource (calling it and passing the argument ``id='me'``). In this new object you will find many methods to help you play with the data available.

Here is the list of the methods available in a ``TapiocaClientExecutor``:

Making requests
---------------

Tapioca uses `requests <http://docs.python-requests.org/en/latest/>`_ library to make requests, so http methods will work just the same (get()/post()/put()/delete()/head()/options()). The only difference is that we don't need to pass a url since tapioca will take care of this.

.. code-block:: python

	likes = api.user_likes(id='me').get()

**URL params**

To pass querystring parameters in the url, your can use the ```params``` parameter:

.. code-block:: python

	likes = api.user_likes(id='me').get(
		params={'limit': 5})

This will return only 5 results.

**Body data**

If you need to pass data in the body of your request, you can use the ```data``` parameter. For example, lets post a message to a facebook wall:

.. code-block:: python

	# this will only work if you have a post to wall permission
	api.user_feed(id='me').post(
		data={'message': 'I love tapiocas!! S2'})

Please read `requests <http://docs.python-requests.org/en/latest/>`_ for more detailed information about how to use HTTP methods.

Accessing raw data
------------------

Use ``data`` to return data contained in the Tapioca object.

.. code-block:: python

	>>> likes = api.user_likes(id='me').get()
	>>> likes().data
	{
		'data': [...],
		'paging': {...}
	}
	>>> this will print only the array contained
	>>> # in the 'data' field of the response
	>>> likes.data().data
	>>> [...]

Dynamically fetching pages
-------------------------

Many APIs use paging concept to provide large amounts of data. This way data is returned in multiple requests avoiding a single long request.
Tapioca is built to provide an easy way to access paged data using ``pages()`` method:

.. code-block:: python

	likes = api.user_likes(id='me').get()

	for like in likes().pages():
		print(like.name().data

This will keep fetching user likes until there are none left. Items passed to the ``for`` loop will be wrapped in tapioca so you still have access to all features.

This method also accepts ``max_pages`` and ``max_items`` parameters. If both parameters are used, the for loop will stop after ``max_pages`` are fetched or ``max_items`` are yielded, witch ever comes first:

.. code-block:: python

	for item in resp().pages(max_pages=2, max_items=40):
		print(item)
	# in this example, the for loop will stop after two pages are fetched or 40 items are yielded,
	# witch ever comes first.

Accessing wrapped data attributes
---------------------------------

It's possible to access wrapped data attributes on executor. For example it's possible to reverse a wrapped list:

.. code-block:: python

	likes = api.user_likes(id='me').get()

	likes_list = likes.data
	likes_list().reverse()
	# items in the likes_list are now in reverse order
	# but still wrapped in a tapioca object

Opening documentation in the browser
------------------------------------

If you are accessing a resource, you can call ``open_docs`` to open resource documentation in browser:

.. code-block:: python

	api.user_likes().open_docs()

Opening any link in the browser
-------------------------------

Whenever the data contained in Tapioca object is a URL, you can open it in browser by using the ``open_in_browser()`` method.


text:
package net.mindengine.blogix.markup;

public interface Markup {

    String apply(String unformatedText);
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';
describe('mark with regular expression', function() {
  var $ctx1, $ctx2, errorThrown, ret;
  beforeEach(function(done) {
    loadFixtures('regexp/main.html');

    $ctx1 = $('.regexp > div:first-child');
    $ctx2 = $('.regexp > div:last-child');
    errorThrown = false;
    ret = new Mark($ctx1[0]).markRegExp(/Lor[^]?m/gmi, {
      'done': function() {
        try {
          new Mark($ctx2[0]).markRegExp(/(Lor)([^]?m)/gmi, {
            'done': function() {
              // timeout, otherwise "ret =" will not be executed
              setTimeout(function() {
                done();
              }, 50);
            }
          });
        } catch (e) {
          errorThrown = true;
          done();
        }
      }
    });
  });

  it('should wrap matches', function() {
    expect($ctx1.find('mark')).toHaveLength(4);
  });
  it('should silently ignore groups in regular expressions', function() {
    expect($ctx2.find('mark')).toHaveLength(4);
    expect(errorThrown).toBe(false);
  });
  it('should return an object with further methods', function() {
    expect(ret instanceof Mark).toBe(true);
    expect(typeof ret.mark).toBe('function');
    expect(typeof ret.unmark).toBe('function');
    expect(typeof ret.markRegExp).toBe('function');
  });
});


text:
Recovers a primary or mirror segment instance that has been marked as down \(if mirroring is enabled\).

## Synopsis

```
gprecoverseg [[-p <new_recover_host>[,...]] | -i <recover_config_file>] [-d <master_data_directory>]
             [-b <segment_batch_size>] [-B <batch_size>] [-F [-s]] [-a] [-q]
	      [--hba-hostnames <boolean>]
             [--no-progress] [-l <logfile_directory>]

gprecoverseg -r

gprecoverseg -o <output_recover_config_file>
             [-p <new_recover_host>[,...]]

gprecoverseg -? | -h | --help

gprecoverseg -v | --verbose

gprecoverseg --version
```

## Description

In a system with mirrors enabled, the `gprecoverseg` utility reactivates a failed segment instance and identifies the changed database files that require resynchronization. Once `gprecoverseg` completes this process, the system goes into `Not in Sync` mode until the recovered segment is brought up to date. The system is online and fully operational during resynchronization.

During an incremental recovery \(the `-F` option is not specified\), if `gprecoverseg` detects a segment instance with mirroring deactivated in a system with mirrors activated, the utility reports that mirroring is deactivated for the segment, does not attempt to recover that segment instance, and continues the recovery process.

A segment instance can fail for several reasons, such as a host failure, network failure, or disk failure. When a segment instance fails, its status is marked as `d` \(down\) in the Greenplum Database system catalog, and its mirror is activated in `Not in Sync` mode. In order to bring the failed segment instance back into operation again, you must first correct the problem that made it fail in the first place, and then recover the segment instance in Greenplum Database using `gprecoverseg`.

**Note:** If incremental recovery was not successful and the down segment instance data is not corrupted, contact VMware Support.

Segment recovery using `gprecoverseg` requires that you have an active mirror to recover from. For systems that do not have mirroring enabled, or in the event of a double fault \(a primary and mirror pair both down at the same time\) — you must take manual steps to recover the failed segment instances and then perform a system restart to bring the segments back online. For example, this command restarts a system.

```
gpstop -r
```

By default, a failed segment is recovered in place, meaning that the system brings the segment back online on the same host and data directory location on which it was originally configured. In this case, use the following format for the recovery configuration file \(using `-i`\).

```
<failed_host_address>|<port>|<data_directory>
```

In some cases, this may not be possible \(for example, if a host was physically damaged and cannot be recovered\). In this situation, `gprecoverseg` allows you to recover failed segments to a completely new host \(using `-p`\), on an alternative data directory location on your remaining live segment hosts \(using `-s`\), or by supplying a recovery configuration file \(using `-i`\) in the following format. The word <SPACE\> indicates the location of a required space. Do not add additional spaces.

```
<failed_host_address>|<port>|<data_directory><SPACE>
<recovery_host_address>|<port>|<data_directory>

```

See the `-i` option below for details and examples of a recovery configuration file.

The `gp_segment_configuration` system catalog table can help you determine your current segment configuration so that you can plan your mirror recovery configuration. For example, run the following query:

```
=# SELECT dbid, content, address, port, datadir
   FROM gp_segment_configuration
   ORDER BY dbid;
```

The new recovery segment host must be pre-installed with the Greenplum Database software and configured exactly the same as the existing segment hosts. A spare data directory location must exist on all currently configured segment hosts and have enough disk space to accommodate the failed segments.

The recovery process marks the segment as up again in the Greenplum Database system catalog, and then initiates the resynchronization process to bring the transactional state of the segment up-to-date with the latest changes. The system is online and available during `Not in Sync` mode.

## Options

-a \(do not prompt\)
:   Do not prompt the user for confirmation.

-b segment\_batch\_size
:   The maximum number of segments per host to operate on in parallel. Valid values are `1` to `128`. If not specified, the utility will start recovering up to 64 segments in parallel on each host.

-B batch\_size
:   The number of hosts to work on in parallel. If not specified, the utility will start working on up to 16 hosts in parallel. Valid values are `1` to `64`.

-d master\_data\_directory
:   Optional. The master host data directory. If not specified, the value set for `$MASTER_DATA_DIRECTORY` will be used.

-F \(full recovery\)
:   Optional. Perform a full copy of the active segment instance in order to recover the failed segment. The default is to only copy over the incremental changes that occurred while the segment was down.

    **Warning:** A full recovery deletes the data directory of the down segment instance before copying the data from the active \(current primary\) segment instance. Before performing a full recovery, ensure that the segment failure did not cause data corruption and that any host segment disk issues have been fixed.

    Also, for a full recovery, the utility does not restore custom files that are stored in the segment instance data directory even if the custom files are also in the active segment instance. You must restore the custom files manually. For example, when using the `gpfdists` protocol \(`gpfdist` with SSL encryption\) to manage external data, client certificate files are required in the segment instance `$PGDATA/gpfdists` directory. These files are not restored. For information about configuring `gpfdists`, see [Encrypting gpfdist Connections](../../security-guide/topics/Encryption.html).

    Use the `-s` option to output a new line once per second for each segment. Alternatively, use the `--no-progress` option to completely deactivate progress reports.

--hba-hostnames boolean
:   Optional. Controls whether this utility uses IP addresses or host names in the `pg_hba.conf` file when updating this file with addresses that can connect to Greenplum Database. When set to 0 -- the default value -- this utility uses IP addresses when updating this file. When set to 1, this utility uses host names when updating this file. For consistency, use the same value that was specified for `HBA_HOSTNAMES` when the Greenplum Database system was initialized. For information about how Greenplum Database resolves host names in the `pg_hba.conf` file, see [Configuring Client Authentication](../../admin_guide/client_auth.html).

-i recover\_config\_file
:   Specifies the name of a file with the details about failed segments to recover.

    Each line in the config file specifies a segment to recover. This line can have one of two formats. In the event of in-place \(incremental\) recovery, enter one group of pipe-delimited fields in the line. For example:

    ```
    failedAddress|failedPort|failedDataDirectory
    ```

    For recovery to a new location, enter two groups of fields separated by a space in the line. The required space is indicated by <SPACE\>. Do not add additional spaces.

    ```
    failedAddress|failedPort|failedDataDirectory<SPACE>newAddress|
    newPort|newDataDirectory
    ```

    **Note:** Lines beginning with `#` are treated as comments and ignored.

    **Examples**

    **In-place \(incremental\) recovery of a single mirror**

    ```
    sdw1-1|50001|/data1/mirror/gpseg16
    ```

    **Recovery of a single mirror to a new host**

    ```
    sdw1-1|50001|/data1/mirror/gpseg16<SPACE>sdw4-1|50001|/data1/recover1/gpseg16
    ```

    **Obtaining a Sample File**

    You can use the `-o` option to output a sample recovery configuration file to use as a starting point. The output file lists the currently invalid segments and their default recovery location. This file format can be used with the `-i` option for in-place \(incremental\) recovery.

-l logfile\_directory
:   The directory to write the log file. Defaults to `~/gpAdminLogs`.

-o output\_recover\_config\_file
:   Specifies a file name and location to output a sample recovery configuration file. This file can be edited to supply alternate recovery locations if needed. The following example outputs the default recovery configuration file:

    ```
    $ gprecoverseg -o /home/gpadmin/recover_config_file
    ```

-p new\_recover\_host\[,...\]
:   Specifies a new host outside of the currently configured Greenplum Database array on which to recover invalid segments.

:   The new host must have the Greenplum Database software installed and configured, and have the same hardware and OS configuration as the current segment hosts \(same OS version, locales, `gpadmin` user account, data directory locations created, ssh keys exchanged, number of network interfaces, network interface naming convention, and so on\). Specifically, the Greenplum Database binaries must be installed, the new host must be able to connect password-less with all segments including the Greenplum master, and any other Greenplum Database specific OS configuration parameters must be applied.

:   **Note:** In the case of multiple failed segment hosts, you can specify the hosts to recover with a comma-separated list. However, it is strongly recommended to recover one host at a time. If you must recover more than one host at a time, then it is critical to ensure that a double fault scenario does not occur, in which both the segment primary and corresponding mirror are offline.

-q \(no screen output\)
:   Run in quiet mode. Command output is not displayed on the screen, but is still written to the log file.

-r \(rebalance segments\)
:   After a segment recovery, segment instances may not be returned to the preferred role that they were given at system initialization time. This can leave the system in a potentially unbalanced state, as some segment hosts may have more active segments than is optimal for top system performance. This option rebalances primary and mirror segments by returning them to their preferred roles. All segments must be valid and resynchronized before running `gprecoverseg -r`. If there are any in progress queries, they will be cancelled and rolled back.

-s \(sequential progress\)
:   Show `pg_basebackup` or `pg_rewind` progress sequentially instead of in-place. Useful when writing to a file, or if a tty does not support escape sequences. The default is to show progress in-place.

--no-progress
:   Suppresses progress reports from the `pg_basebackup` or `pg_rewind` utility. The default is to display progress.

-v \| --verbose
:   Sets logging output to verbose.

--version
:   Displays the version of this utility.

-? \| -h \| --help
:   Displays the online help.

## Examples

**Example 1: Recover Failed Segments in Place**

Recover any failed segment instances in place:

```
$ gprecoverseg
```

**Example 2: Rebalance Failed Segments If Not in Preferred Roles**

First, verify that all segments are up and running, reysynchronization has completed, and there are segments **not** in preferred roles:

```
$ gpstate -e
```

Then, if necessary, rebalance the segments:

```
$ gprecoverseg -r
```

**Example 3: Recover Failed Segments to a Separate Host**

Recover any failed segment instances to a newly configured new segment host:

```
$ gprecoverseg -i <recover_config_file>
```

## See Also

[gpstart](gpstart.html), [gpstop](gpstop.html)


text:
**JUMP** is a library that facilitates writing **simple multiplayer games** using **[Unity 3D]**
and **[Photon Unity Networking]**.

I was working on a multiplayer game and found myself in trouble trying to handle events from
Unity and Photon at the same time; ending up with fragile code - so I worked to
streamline and simplify the scenario and build a reusable library.

Out of the box, **JUMP** Provides:
- A simple flow for connecting to the server, matchmaking and starting a multiplayer game
- Authoritative local Server (using Photon Master Client)
- Streamlined Client-Server communication
- Custom Client Commands and Server Snapshots
- Sample Project and Prefabs to get started in 5 minutes
- Full source code access and great customization.

#### Current Version
[0.3.0] - 2016-11-13 - Adding offline bots support!

For details, see [Changelog](https://raw.githubusercontent.com/MaurGi/JUMP/master/CHANGELOG.md)

### Table of Content
#### Table of Content
* **[How To Install](#how-to-install)**
* **[Scenario](#scenario)**
* **[Object Model](#object-model)**
* **[(NEW!!) Offline Bots](#offline-bots)**
* **[DiceRoller Sample](#diceroller-sample)**
* **[Testing JUMP](#testing-jump)**
* **[Features to Add](#features-to-add)**
* **[License](#license)**

# How to Install
You can get the source code here or download **JUMP** from the [Unity Asset Store][JUMPAsset].

#### Prerequisites
**JUMP** works with [Unity 5](https://unity3d.com/5) and requires [Photon PUN](https://www.assetstore.unity3d.com/en/#!/content/1786) to function properly:

1. Install [Photon PUN Free](https://www.assetstore.unity3d.com/en/#!/content/1786) or [Photon PUN+](https://www.assetstore.unity3d.com/en/#!/content/12080)
2. Configure your Photon Application ID - see [Initial Setup](https://doc.photonengine.com/en/pun/current/getting-started/initial-setup)

For more information about configuring PUN, see [PUN Setup](https://doc.photonengine.com/en/pun/current/getting-started/initial-setup).

> Note: JUMP was tested with Unity version 5.3.4 and Photon PUN Free version 1.67

#### Option 1: Unity Asset Store
The [Unity Asset Store][JUMPAsset] package includes the [DiceRoller](#diceroller-sample) sample project.

* Download **JUMP** from the [Unity Asset Store][JUMPAsset].
* Add all the scenes in the `DiceRollerSample/` to the Unity build
* Open the `DiceRollerConnection` scene and start Unity.
* The DiceRoller sample should go to the Matchmake scene in connected mode.

> Note: To test multiplayer games in Unity, you will need to run two copies of the game, so that they can connect to each other. The best way, is to build a copy of the game (File/Build & Run) for one player and start Unity debugging for the second player. See this Unity [forum post](http://answers.unity3d.com/questions/214802/how-to-test-your-multiplayer-game.html) for more details.

#### Option 2: From GitHub source code
In alternative to use the Asset store, you can create a folder in the unity project (under Assets) and copy all the files from the `JUMP Multiplayer\` folder.
Then you can use the [Object Model](#object-model) and the prefabs.

# Scenario
The scenario supported by JUMP is very simple and designed with mobile multiplayer games in mind:
* [Two Players networking](#two-players-networking)
* [Basic matchmaking](#basic-matchmaking)
* [Streamlined UI flow](#streamlined-ui-flow)
* [Custom server](#custom-server)
* [Client-Server communication](#client-server-communication)

#### Two Players networking
JUMP automates building Photon game rooms, easy.

*Note:* While it supports more than two players, we tested JUMP with the two players scenario

#### Basic Matchmaking
JUMP uses Photon [Random Matchmaking](https://doc.photonengine.com/en/realtime/current/reference/matchmaking-and-lobby) without the use of the Photon Lobby making the UI and the object model much simpler to use compared to the use of the Lobby.

#### Streamlined UI flow
JUMP supports up to five different Unity scenes:
* Connection
* Home Page (Master)
* [Room] Waiting for players
* [Room] Playing the game

*Note:* support for multiple levels can be added to the Playing the game scene.

![](https://raw.githubusercontent.com/MaurGi/JUMP/master/Doc/UIFlow.png)

#### Custom Server
JUMP cannot provide a dedicated remote server using [Photon Unity Networking] or [Photon Cloud], so it uses the **Host** model, where one of the clients also hosts the Game Server (sometimes called **Local Server**)

Photon provides support for this with the concept of [Master Client].

#### Client-Server Communication
JUMP supports the concept of an Authoritative or Semi-Authoritative server using a Command/Snapshot Client-Server communication:
* The Client sends Commands to the Server
* The Server sends Snapshot to the Client

The model is similar to the one explained by [Fast Paced Multiplayer] [Gambetta], but we use the term **Command** instead of Actions and **Snapshot** instad of New State

![](https://raw.githubusercontent.com/MaurGi/JUMP/master/Doc/ClientServer.png)

> The slanted lines indicate that there is lag between the client and server communication, see [Fighting Latency on Call of Duty III] [CallOfDuty]

While it is possible to optimize the client/server communication in terms of reliability and space utilized with delta compression of snapshots and queues of commands, JUMP simply uses
[Photon Reliable UDP](https://doc.photonengine.com/en/onpremise/current/getting-started/photon-server-intro) to communicate, it is a good balance of reliability and ease-of-use.

#### References
JUMP Multiplayer with (Semi)Authoritative Server model is based on lots of literature on multiplayer games:
* [Fast Paced Multiplayer] [Gambetta]  (Gambetta)
* [What every programmer needs to know about game networking](http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/) (Gaffer on Games)
* [Fighting Latency on Call of Duty Black Ops III] [CallOfDuty]  (GDC 2016)
* [Building a Peer-to-Peer Multiplayer Networked Game](http://gamedevelopment.tutsplus.com/tutorials/building-a-peer-to-peer-multiplayer-networked-game--gamedev-10074)
* [Unity3D Multiplayer Game Development](http://www.pepwuper.com/unity3d-multiplayer-game-development-unity-networking-photon-and-ulink-comparison/)
* [How can I make a peer-to-peer multiplayer game?](http://gamedev.stackexchange.com/questions/3887/how-can-i-make-a-peer-to-peer-multiplayer-game/3891#3891)
* [Unity Networking](http://docs.unity3d.com/Manual/UNetConcepts.html)

---

## Object Model
See **[Object Model](Doc/JUMPObjectModel.md#object-model)**

## Offline Bots
See **[Offline Bots](Doc/OfflineBots.md#offline-bots)**

## DiceRoller Sample
See **[DiceRoller Sample](Doc/DiceRollerSample.md#diceroller-sample)**

## Testing JUMP
See **[Testing JUMP](Doc/MiscDoc.md#testing-jump)**

## Features to Add
See **[Features to Add](Doc/MiscDoc.md#features-to-add)**

# License

Unless stated otherwise all works are Copyright © 2016 [Juiced Team LLC.](http://www.juicedteam.com)

And licensed under the [MIT License](https://raw.githubusercontent.com/MaurGi/JUMP/master/LICENSE.txt)

### Donate
If you want to donate, you can simply [purchase the JUMP package in the Unity Asset Store][JUMPAsset].

### Contribute
We are not ready to accept pull requests at the time, we are considering that for the future.
If you are interested in contributing, file a bug and we will consider your request.
All contributions will be voluntary and will grant no rights, compensation or license, you will retain the rights to reuse your code.

### Attribution
Photon, Photon Engine, PUN: ©2016 [Exit Games](https://www.photonengine.com)®

Unity 3D, Unity Engine: ©2016 [Unity Technologies](http://unity.com)

[Unity 3D]: <http://unity3d.com/unity>
[Photon Unity Networking]: <http://www.photonengine.com/PUN>
[Photon Cloud]: <http://www.photonengine.com/en-US/Realtime>
[Master Client]: <http://doc.photonengine.com/en/pun/current/tutorials/tutorial-marco-polo>
[Photon Lobby]: <http://doc.photonengine.com/en/realtime/current/reference/matchmaking-and-lobby>
[Gambetta]:<http://www.gabrielgambetta.com/fpm1.html>
[TODOPicture]:<https://upload.wikimedia.org/wikipedia/commons/2/21/OpenGL_Tutorial_TODO.png>
[CallOfDuty]:<http://schedule.gdconf.com/session/fighting-latency-on-call-of-duty-black-ops-iii>
[JUMPAsset]:<http://u3d.as/uRe>


text:
(function () {
    angular.module("sputnikControllers").controller("segmentEffortController", ['$scope', 'stravaSegmentResource', function ($scope, stravaSegmentResource) {
        stravaSegmentResource.get({segmentId: $scope.segmentEffort.segmentId}).$promise.then(assignSegment);

        function assignSegment(segment) {
            $scope.segment = segment;
        }
    }]);
})();


text: package protoparse


text:
package org.apache.roller.ui.authoring.struts.formbeans;

import org.apache.struts.action.ActionForm;

/**
 * @struts.form name="memberPermissionsForm"
 * @author Dave M Johnson
 */
public class MemberPermissionsForm extends ActionForm
{
    private String websiteId;
    public String getWebsiteId()
    {
        return websiteId;
    }
    public void setWebsiteId(String websiteId)
    {
        this.websiteId = websiteId;
    }
}


text:
using gfx::ViewConfiguration;

namespace ui {
namespace {
// This was the minimum tap/press size used on Android before the new gesture
// detection pipeline.
const float kMinGestureBoundsLengthDips = 24.f;

// This value is somewhat arbitrary, but provides a reasonable maximum
// approximating a large thumb depression.
const float kMaxGestureBoundsLengthDips = kMinGestureBoundsLengthDips * 4.f;

class GestureConfigurationAndroid : public GestureConfiguration {
 public:
  ~GestureConfigurationAndroid() override {
  }

  static GestureConfigurationAndroid* GetInstance() {
    return Singleton<GestureConfigurationAndroid>::get();
  }

 private:
  GestureConfigurationAndroid() : GestureConfiguration() {
    float raw_pixel_to_dip_ratio = 1.f / gfx::Screen::GetNativeScreen()
                                       ->GetPrimaryDisplay()
                                       .device_scale_factor();
    set_double_tap_timeout_in_ms(ViewConfiguration::GetDoubleTapTimeoutInMs());
    set_gesture_begin_end_types_enabled(false);
    set_long_press_time_in_ms(ViewConfiguration::GetLongPressTimeoutInMs());
    set_max_distance_between_taps_for_double_tap(
        ViewConfiguration::GetDoubleTapSlopInPixels() * raw_pixel_to_dip_ratio);
    set_max_fling_velocity(
        ViewConfiguration::GetMaximumFlingVelocityInPixelsPerSecond() *
        raw_pixel_to_dip_ratio);
    set_max_gesture_bounds_length(kMaxGestureBoundsLengthDips);
    set_max_touch_move_in_pixels_for_click(
        ViewConfiguration::GetTouchSlopInPixels() * raw_pixel_to_dip_ratio);
    set_min_fling_velocity(
        ViewConfiguration::GetMinimumFlingVelocityInPixelsPerSecond() *
        raw_pixel_to_dip_ratio);
    set_min_gesture_bounds_length(kMinGestureBoundsLengthDips);
    set_min_pinch_update_span_delta(0.f);
    set_min_scaling_span_in_pixels(
        ViewConfiguration::GetMinScalingSpanInPixels() *
        raw_pixel_to_dip_ratio);
    set_min_scaling_touch_major(
        ViewConfiguration::GetMinScalingTouchMajorInPixels() *
        raw_pixel_to_dip_ratio);
    set_show_press_delay_in_ms(ViewConfiguration::GetTapTimeoutInMs());
    set_span_slop(ViewConfiguration::GetTouchSlopInPixels() * 2.f *
                  raw_pixel_to_dip_ratio);
  }

  friend struct DefaultSingletonTraits<GestureConfigurationAndroid>;
  DISALLOW_COPY_AND_ASSIGN(GestureConfigurationAndroid);
};

}  // namespace

// Create a GestureConfigurationAura singleton instance when using Android.
GestureConfiguration* GestureConfiguration::GetInstance() {
  return GestureConfigurationAndroid::GetInstance();
}

}  // namespace ui


text:
package log

import "github.com/bitrise-io/go-utils/colorstring"

// Severity ...
type Severity uint8

const (
	errorSeverity Severity = iota
	warnSeverity
	normalSeverity
	infoSeverity
	doneSeverity
	debugSeverity
)

type severityColorFunc colorstring.ColorfFunc

var (
	doneSeverityColorFunc   severityColorFunc = colorstring.Greenf
	infoSeverityColorFunc   severityColorFunc = colorstring.Bluef
	normalSeverityColorFunc severityColorFunc = colorstring.NoColorf
	debugSeverityColorFunc  severityColorFunc = colorstring.Magentaf
	warnSeverityColorFunc   severityColorFunc = colorstring.Yellowf
	errorSeverityColorFunc  severityColorFunc = colorstring.Redf
)

var severityColorFuncMap = map[Severity]severityColorFunc{
	doneSeverity:   doneSeverityColorFunc,
	infoSeverity:   infoSeverityColorFunc,
	normalSeverity: normalSeverityColorFunc,
	debugSeverity:  debugSeverityColorFunc,
	warnSeverity:   warnSeverityColorFunc,
	errorSeverity:  errorSeverityColorFunc,
}


text:
require 'test_helper'
require 'ostruct'

class UserTest < ActiveSupport::TestCase
  test "should be able to filter repos by permission" do
    user = users :macaullyjames
    default = user.repos
    owner = user.repos(permission: :owner)
    admin = user.repos(permission: :admin)
    push = user.repos(permission: :push)
    pull = user.repos(permission: :pull)

    assert_not_empty default
    assert_equal default, owner

    assert_empty owner - admin
    assert_empty admin - push
    assert_empty push - pull
    assert_operator owner.count, :<, admin.count
    assert_operator admin.count, :<, push.count
    assert_operator push.count, :<, pull.count
  end
end


text:
<?php
/* $Id: session.inc.php 10422 2007-06-05 16:32:49Z lem9 $ */
// vim: expandtab sw=4 ts=4 sts=4:
/**
 * session handling
 *
 * @todo    add failover or warn if sessions are not configured properly
 * @todo    add an option to use mm-module for session handler
 * @see     http://www.php.net/session
 * @uses    session_name()
 * @uses    session_start()
 * @uses    ini_set()
 * @uses    version_compare()
 * @uses    PHP_VERSION
 */

// verify if PHP supports session, die if it does not

if (!@function_exists('session_name')) {
    $cfg = array('DefaultLang'           => 'en-iso-8859-1',
                 'AllowAnywhereRecoding' => false);
    // Loads the language file
    require_once('./libraries/select_lang.lib.php');
    // Displays the error message
    // (do not use & for parameters sent by header)
    header('Location: ' . (defined('PMA_SETUP') ? '../' : '') . 'error.php'
            . '?lang='  . urlencode($available_languages[$lang][2])
            . '&dir='   . urlencode($text_dir)
            . '&type='  . urlencode($strError)
            . '&error=' . urlencode(sprintf($strCantLoad, 'session')));
    exit();
} elseif (ini_get('session.auto_start') == true && session_name() != 'phpMyAdmin') {
    $_SESSION = array();
    if (isset($_COOKIE[session_name()])) {
        PMA_removeCookie(session_name());
    }
    session_unset();
    @session_destroy();
}

// disable starting of sessions before all settings are done
// does not work, besides how it is written in php manual
//ini_set('session.auto_start', 0);

// session cookie settings
session_set_cookie_params(0, PMA_Config::getCookiePath() . '; HttpOnly',
    '', PMA_Config::isHttps());

// cookies are safer
ini_set('session.use_cookies', true);

// but not all user allow cookies
ini_set('session.use_only_cookies', false);
ini_set('session.use_trans_sid', true);
ini_set('url_rewriter.tags',
    'a=href,frame=src,input=src,form=fakeentry,fieldset=');
//ini_set('arg_separator.output', '&');

// delete session/cookies when browser is closed
ini_set('session.cookie_lifetime', 0);

// warn but dont work with bug
ini_set('session.bug_compat_42', false);
ini_set('session.bug_compat_warn', true);

// use more secure session ids (with PHP 5)
if (version_compare(PHP_VERSION, '5.0.0', 'ge')
  && substr(PHP_OS, 0, 3) != 'WIN') {
    ini_set('session.hash_function', 1);
    ini_set('session.hash_bits_per_character', 6);
}

// some pages (e.g. stylesheet) may be cached on clients, but not in shared
// proxy servers
session_cache_limiter('private');

// start the session
// on some servers (for example, sourceforge.net), we get a permission error
// on the session data directory, so I add some "@"

// See bug #1538132. This would block normal behavior on a cluster
//ini_set('session.save_handler', 'files');

$session_name = 'phpMyAdmin';
@session_name($session_name);
// strictly, PHP 4 since 4.4.2 would not need a verification
if (version_compare(PHP_VERSION, '5.1.2', 'lt')
 && isset($_COOKIE[$session_name])
 && eregi("\r|\n", $_COOKIE[$session_name])) {
    die('attacked');
}

if (! isset($_COOKIE[$session_name])) {
    // on first start of session we will check for errors
    // f.e. session dir cannot be accessed - session file not created
    ob_start();
    $r = session_start();
    $session_error = ob_get_contents();
    ob_end_clean();
    if ($r !== true || ! empty($session_error)) {
        setcookie($session_name, '', 1);
        $cfg = array('DefaultLang'           => 'en-iso-8859-1',
                     'AllowAnywhereRecoding' => false);
        // Loads the language file
        require_once './libraries/select_lang.lib.php';
        // Displays the error message
        // (do not use & for parameters sent by header)
        header('Location: ' . (defined('PMA_SETUP') ? '../' : '') . 'error.php'
                . '?lang='  . urlencode($available_languages[$lang][2])
                . '&dir='   . urlencode($text_dir)
                . '&type='  . urlencode($strError)
                . '&error=' . urlencode($strSessionStartupErrorGeneral));
        exit();
    }
} else {
    @session_start();
}

/**
 * Token which is used for authenticating access queries.
 * (we use "space PMA_token space" to prevent overwriting)
 */
if (!isset($_SESSION[' PMA_token '])) {
    $_SESSION[' PMA_token '] = md5(uniqid(rand(), true));
}

/**
 * tries to secure session from hijacking and fixation
 * should be called before login and after successfull login
 * (only required if sensitive information stored in session)
 *
 * @uses    session_regenerate_id() to secure session from fixation
 * @uses    session_id()            to set new session id
 * @uses    strip_tags()            to prevent XSS attacks in SID
 * @uses    function_exists()       for session_regenerate_id()
 */
function PMA_secureSession()
{
    // prevent session fixation and XSS
    if (function_exists('session_regenerate_id')) {
        session_regenerate_id(true);
    } else {
        session_id(strip_tags(session_id()));
    }
}
?>


text:
var async = require('async');
var moment = require('moment');
var request = require('request');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var AWS = require('aws-sdk');

var sqsconfig = {
    apiVersion: '2012-11-05',
    region: process.env.AWS_REGION,
    accessKeyId: process.env.AWS_ACCESS_KEY_ID || undefined,
    secretAccessKey: process.env.AWS_SECRET_KEY_ID || undefined,
}

var sqs = new AWS.SQS(sqsconfig);

function SQSToWebhook(options) {

    EventEmitter.call(this);

    //trackk the total number of messages in flight at
    //the same time so we don't run out of resources
    this.totalMessagesInFlight = 0;

    this.options = options || {};

}

util.inherits(SQSToWebhook, EventEmitter);

var start = SQSToWebhook.prototype.start = function start(options, done) {
    done = done || function() {};
    var self = this;

    self.receiveMessagesCurrentlyExecuting = 0;
    self.shouldStop = false;

    self.options = {
        maxMessagesInFlight: options.maxMessagesInFlight || self.options.maxMessagesInFlight || 1,
        queueUrl: options.queueUrl || self.options.queueUrl,
        webhookUrl: options.webhookUrl || self.options.webhookUrl || "success",
        headers: options.headers || self.options.headers || {},
        linearSecondDelayPerSecondSinceCreation: options.linearSecondDelayPerSecondSinceCreation || self.options.linearSecondDelayPerSecondSinceCreation || 1.0
    }

    if (!self.options.queueUrl) throw new Error("Must provide a queueUrl.");
    if (!self.options.webhookUrl) throw new Error("Must provide a webhookUrl.");
    if (typeof self.options.queueUrl === "string") self.options.queueUrl = [self.options.queueUrl];

    self.emit('starting', self.options);

    self.options.queueUrl.map(function(queueUrl) {
        self.tendril(queueUrl);
    });

}

var stop = SQSToWebhook.prototype.stop = function stop(done) {
    done = done || function() {};
    var self = this;

    self.shouldStop = true;
    if (self.receiveMessagesCurrentlyExecuting == 0) return done();

    setImmediate(function() {
        self.stop(done);
    });

}

var callWebhook = SQSToWebhook.prototype.callWebhook = function callWebhook(message, done) {
    done = done || function() {};
    var self = this;

    var params = {
        url: message.Body.webhookUrl || self.options.webhookUrl,
        headers: self.options.headers,
        method: "POST",
        json: true,
        body: message.Body
    };

    self.emit('request', {
        message: message,
        params: params,
    });

    if (params.url == "succeed") {

        self.emit('response', {
            message: message,
            body: message.Body
        });

        return done(null, null);
    }

    if (params.url == "fail") {

        self.emit('requesterror', {
            message: message,
            params: params,
            err: new Error("simulated failure"),
        });

        return done(new Error("simulated failure"));
    }

    request(params, function(err, response, body) {
        if (body && body.message) err = new Error(body.message);

        if (err) {

            self.emit('requesterror', {
                message: message,
                params: params,
                err: err,
            });

            return done(err);

        }
        self.emit('response', {
            message: message,
            body: body
        });

        return done(null, body);

    });

}

var tendril = SQSToWebhook.prototype.tendril = function tendril(queueUrl, done) {
    done = done || function() {};

    var self = this;

    var headroom = self.options.maxMessagesInFlight - this.totalMessagesInFlight;

    if (!headroom) {
        //we are out of headroom, try again in 1 second
        !self.shouldStop && setTimeout(function() {
            self.tendril(queueUrl, done);
        }, 1000);
        return;
    }

    self.emit('polling', {
        queueUrl: queueUrl,
        headroom: headroom
    });

    //chack to make sure there are not multiple threads running
    if (self.receiveMessagesCurrentlyExecuting) {
        console.log("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEERROR multiple threads running");
    }

    self.receiveMessagesCurrentlyExecuting += 1;
    this.receiveMessages(queueUrl, headroom, function(err, messages) {

        async.each(messages, function(message, done) {

            self.totalMessagesInFlight += 1;

            self.callWebhook(message, function(err, body) {

                if (err) {
                    self.changeMessageVisibility(message);
                } else {
                    self.emit('messagecomplete', {
                        message: message,
                    });
                    self.deleteMessage(message);
                }

                self.totalMessagesInFlight -= 1;

                return;

            });

        });

        self.receiveMessagesCurrentlyExecuting -= 1;

        //try again, waiting a bit if there was an error or no messages
        !self.shouldStop && setTimeout(function() {
            self.tendril(queueUrl, done)
        }, err ? 1000 : 0);

    });

}

var deleteMessage = SQSToWebhook.prototype.deleteMessage = function deleteMessage(message, done) {
    done = done || function() {};
    var self = this;
    if (message.deleted) return done(null, message);

    var params = {
        QueueUrl: message.queueUrl,
        ReceiptHandle: message.ReceiptHandle,
    };

    self.emit('deletemessage', {
        message: message,
        params: params,
    });

    sqs.deleteMessage(params, function(err) {
        if (err) {
            self.emit('deletemessageerror', {
                message: message,
                params: params,

                err: err
            });
            return done(err);
        }
        message.deleted = true;
        return done(null, message);
    });

}

var queueMessage = SQSToWebhook.prototype.queueMessage = function queueMessage(message, done) {
    done = done || function() {};
    var self = this;

    var params = {
        QueueUrl: message.queueUrl,
        MessageBody: JSON.stringify(message.Body),
    };

    if (message.Attributes && message.Attributes.ApproximateFirstReceived) {
        params.DelaySeconds = Math.abs(moment().diff(message.Attributes.ApproximateFirstReceived, 'seconds'));
    }

    self.emit('queuemessage', {
        message: message,
        params: params,
    });

    sqs.sendMessage(params, function(err, result) {

        if (err) {
            self.emit('queuemessageerror', {
                message: message,
                params: params,
                err: err
            });
            //wait for a second and try again
            !self.shouldStop && setTimeout(function() {
                self.queueMessage(message, done)
            }, 1000)
            return;
        }

        self.emit('queuemessagecomplete', {
            message: message,
            params: params,
            result: result,
        });

        return done(null, message);

    });

}

var changeMessageVisibility = SQSToWebhook.prototype.changeMessageVisibility = function changeMessageVisibility(message, done) {
    done = done || function() {};
    var self = this;

    var params = {
        QueueUrl: message.queueUrl,
        ReceiptHandle: message.ReceiptHandle,
        VisibilityTimeout: 1
    };

    if (message.Attributes && message.Attributes.ApproximateFirstReceived) {
        params.VisibilityTimeout = 1 + Math.abs(moment().diff(message.Attributes.ApproximateFirstReceived, 'seconds'));
    }

    self.emit('changevisibility', {
        params: params,
        message: message,
    });

    sqs.changeMessageVisibility(params, function(err, data) {
        if (err) {
            //there was an error changing the visibility, probably we are hittim some limits
            self.emit('changevisibilityerror', {
                params: params,
                message: message,
                err: err
            });
            self.queueMessage(message, function() {
                //queuemessage will keep trying until it succeeds
                //then we can delete this one
                self.deleteMessage(message, done);
            });
            return;
        }

        return done(null, message);
    });

}

var getQueueSize = SQSToWebhook.prototype.getQueueSize = function getQueueSize(queueUrl, done) {
    done = done || function() {};
    var self = this;

    var params = {
        QueueUrl: queueUrl,
        AttributeNames: [
            'ApproximateNumberOfMessages',
            'ApproximateNumberOfMessagesNotVisible',
            'ApproximateNumberOfMessagesDelayed',
        ]
    };
    sqs.getQueueAttributes(params, function(err, data) {
        if (err) return done(err);
        return done(null, (Number(data.Attributes.ApproximateNumberOfMessages) || 0) + (Number(data.Attributes.ApproximateNumberOfMessagesDelayed) || 0) + (Number(data.Attributes.ApproximateNumberOfMessagesNotVisible) || 0));
    });

}

var receiveMessages = SQSToWebhook.prototype.receiveMessages = function receiveMessages(queueUrl, numberOfMessages, done) {
    done = done || function() {};
    var self = this;

    var params = {
        QueueUrl: queueUrl,
        MaxNumberOfMessages: Math.min(numberOfMessages, 10),
        VisibilityTimeout: 10,
        WaitTimeSeconds: 1,
        AttributeNames: ['ApproximateFirstReceiveTimestamp'],
    };

    self.emit('receivemessage', {
        params: params,
    });

    sqs.receiveMessage(params, function(err, data) {

        data = data || {
            Messages: []
        };

        data.Messages = data.Messages || [];

        data.Messages = data.Messages.map(function(msg) {
            msg.queueUrl = queueUrl;
            msg.Body = JSON.parse(msg.Body);
            msg.Attributes.ApproximateFirstReceived = new Date(0);
            msg.Attributes.ApproximateFirstReceived.setUTCSeconds(msg.Attributes.ApproximateFirstReceiveTimestamp / 1000);
            return msg;
        });

        if (err) {

            self.emit('receivemessageerror', {
                params: params,
                err: err
            });

            return done(err);

        }

        self.emit('messagesreceived', {
            params: params,
            messages: data.Messages,
            messageCount: data.Messages.length,
        });

        return done(null, data.Messages);

    });
}

module.exports = SQSToWebhook;


text:
<?php

set_include_path(
  get_include_path() . PATH_SEPARATOR .
  realpath(dirname(__FILE__)) . '/../lib'
);

require_once "Braintree.php";
require_once "Braintree/CreditCardNumbers/CardTypeIndicators.php";
require_once "Braintree/CreditCardDefaults.php";

function integrationMerchantConfig()
{
    Braintree_Configuration::environment('development');
    Braintree_Configuration::merchantId('integration_merchant_id');
    Braintree_Configuration::publicKey('integration_public_key');
    Braintree_Configuration::privateKey('integration_private_key');
}

function testMerchantConfig()
{
    Braintree_Configuration::environment('development');
    Braintree_Configuration::merchantId('test_merchant_id');
    Braintree_Configuration::publicKey('test_public_key');
    Braintree_Configuration::privateKey('test_private_key');
}

integrationMerchantConfig();

date_default_timezone_set("UTC");

class Braintree_TestHelper
{
    public static function defaultMerchantAccountId()
    {
        return 'sandbox_credit_card';
    }

    public static function nonDefaultMerchantAccountId()
    {
        return 'sandbox_credit_card_non_default';
    }

    public static function nonDefaultSubMerchantAccountId()
    {
        return 'sandbox_sub_merchant_account';
    }

    public static function threeDSecureMerchantAccountId()
    {
        return 'three_d_secure_merchant_account';
    }

    public static function createViaTr($regularParams, $trParams)
    {
        $trData = Braintree_TransparentRedirect::transactionData(
            array_merge($trParams, array("redirectUrl" => "http://www.example.com"))
        );
        return Braintree_TestHelper::submitTrRequest(
            TransparentRedirect::url(),
            $regularParams,
            $trData
        );
    }

    public static function submitTrRequest($url, $regularParams, $trData)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_HEADER, true);
        // curl_setopt($curl, CURLOPT_VERBOSE, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array_merge($regularParams, array('tr_data' => $trData))));
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        preg_match('/Location: .*\?(.*)/i', $response, $match);
        return trim($match[1]);
    }

    public static function suppressDeprecationWarnings()
    {
        set_error_handler("Braintree_TestHelper::_errorHandler", E_USER_NOTICE);
    }

    static function _errorHandler($errno, $errstr, $errfile, $errline)
    {
        if (preg_match('/^DEPRECATED/', $errstr) == 0) {
            trigger_error('Unknown error received: ' . $errstr, E_USER_ERROR);
        }
    }

    public static function includes($collection, $targetItem)
    {
        foreach ($collection AS $item) {
            if ($item->id == $targetItem->id) {
                return true;
            }
        }
        return false;
    }

    public static function assertPrintable($object)
    {
        " " . $object;
    }

    public static function settle($transactionId)
    {
        Braintree_Http::put('/transactions/' . $transactionId . '/settle');
    }

    public static function settlementDecline($transactionId)
    {
        Braintree_Http::put('/transactions/' . $transactionId . '/settlement_decline');
    }

    public static function settlementPending($transactionId)
    {
        Braintree_Http::put('/transactions/' . $transactionId . '/settlement_pending');
    }

    public static function escrow($transactionId)
    {
        Braintree_Http::put('/transactions/' . $transactionId . '/escrow');
    }

    public static function create3DSVerification($merchantAccountId, $params)
    {
        $response = Braintree_Http::post('/three_d_secure/create_verification/' . $merchantAccountId, array(
            'threeDSecureVerification' => $params
        ));
        return $response['threeDSecureVerification']['threeDSecureToken'];
    }

    public static function nowInEastern()
    {
        $eastern = new DateTimeZone('America/New_York');
        $now = new DateTime('now', $eastern);
        return $now->format('Y-m-d');
    }

    public static function decodedClientToken($params=array()) {
        $encodedClientToken = Braintree_ClientToken::generate($params);
        return base64_decode($encodedClientToken);
    }
}


text:
package com.cloud.api.command.user.autoscale;

import com.cloud.acl.RoleType;
import com.cloud.api.APICommand;
import com.cloud.api.ApiConstants;
import com.cloud.api.BaseListProjectAndAccountResourcesCmd;
import com.cloud.api.Parameter;
import com.cloud.api.response.AutoScaleVmProfileResponse;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.ServiceOfferingResponse;
import com.cloud.api.response.TemplateResponse;
import com.cloud.api.response.ZoneResponse;
import com.cloud.network.as.AutoScaleVmProfile;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@APICommand(name = "listAutoScaleVmProfiles", description = "Lists autoscale vm profiles.", responseObject = AutoScaleVmProfileResponse.class, entityType = {AutoScaleVmProfile
        .class},
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ListAutoScaleVmProfilesCmd extends BaseListProjectAndAccountResourcesCmd {
    public static final Logger s_logger = LoggerFactory.getLogger(ListAutoScaleVmProfilesCmd.class.getName());

    private static final String s_name = "listautoscalevmprofilesresponse";

    // ///////////////////////////////////////////////////
    // ////////////// API parameters /////////////////////
    // ///////////////////////////////////////////////////

    @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, description = "the ID of the autoscale vm profile")
    private Long id;

    @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, description = "the templateid of the autoscale vm profile")
    private Long templateId;

    @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = ServiceOfferingResponse.class, description = "list profiles by service offering " +
            "id", since = "4.4")
    private Long serviceOffId;

    @Parameter(name = ApiConstants.OTHER_DEPLOY_PARAMS, type = CommandType.STRING, description = "the otherdeployparameters of the autoscale vm profile")
    private String otherDeployParams;

    @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, since = "4.4", description = "availability zone for the auto deployed " +
            "virtual machine")
    private Long zoneId;

    @Parameter(name = ApiConstants.FOR_DISPLAY, type = CommandType.BOOLEAN, description = "list resources by display flag; only ROOT admin is eligible to pass this parameter",
            since = "4.4", authorized = {RoleType.Admin})
    private Boolean display;

    // ///////////////////////////////////////////////////
    // ///////////////// Accessors ///////////////////////
    // ///////////////////////////////////////////////////

    public Long getId() {
        return id;
    }

    public Long getTemplateId() {
        return templateId;
    }

    public String getOtherDeployParams() {
        return otherDeployParams;
    }

    public Long getServiceOfferingId() {
        return serviceOffId;
    }

    public Long getZoneId() {
        return zoneId;
    }

    @Override
    public Boolean getDisplay() {
        if (display != null) {
            return display;
        }
        return super.getDisplay();
    }

    // ///////////////////////////////////////////////////
    // ///////////// API Implementation///////////////////
    // ///////////////////////////////////////////////////

    @Override
    public void execute() {
        final List<? extends AutoScaleVmProfile> autoScaleProfiles = _autoScaleService.listAutoScaleVmProfiles(this);
        final ListResponse<AutoScaleVmProfileResponse> response = new ListResponse<>();
        final List<AutoScaleVmProfileResponse> responses = new ArrayList<>();
        if (autoScaleProfiles != null) {
            for (final AutoScaleVmProfile autoScaleVmProfile : autoScaleProfiles) {
                final AutoScaleVmProfileResponse autoScaleVmProfileResponse = _responseGenerator.createAutoScaleVmProfileResponse(autoScaleVmProfile);
                autoScaleVmProfileResponse.setObjectName("autoscalevmprofile");
                responses.add(autoScaleVmProfileResponse);
            }
        }
        response.setResponses(responses);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    }

    @Override
    public String getCommandName() {
        return s_name;
    }
}


text:
"""Fetch a variety of acoustic metrics from The Echo Nest.
"""
import time
import logging
import socket
import os
import tempfile
from string import Template
import subprocess

from beets import util, config, plugins, ui
import pyechonest
import pyechonest.song
import pyechonest.track

log = logging.getLogger('beets')

# If a request at the EchoNest fails, we want to retry the request RETRIES
# times and wait between retries for RETRY_INTERVAL seconds.
RETRIES = 10
RETRY_INTERVAL = 10

DEVNULL = open(os.devnull, 'wb')
ALLOWED_FORMATS = ('MP3', 'OGG', 'AAC')

# The attributes we can import and where to store them in beets fields.
ATTRIBUTES = {
    'energy':       'energy',
    'liveness':     'liveness',
    'speechiness':  'speechiness',
    'acousticness': 'acousticness',
    'danceability': 'danceability',
    'valence':      'valence',
    'tempo':        'bpm',
}
# We also use echonest_id (song_id) and echonest_fingerprint to speed up
# lookups.
ID_KEY = 'echonest_id'
FINGERPRINT_KEY = 'echonest_fingerprint'

def _splitstrip(string, delim=u','):
    """Split string (at commas by default) and strip whitespace from the
    pieces.
    """
    return [s.strip() for s in string.split(delim)]

def diff(item1, item2, attributes):
    result = 0.0
    for attr in attributes:
        try:
            result += abs(
                float(item1.get(attr, None)) -
                float(item2.get(attr, None))
            )
        except TypeError:
            result += 1.0
    return result

def similar(lib, src_item, threshold=0.15):
    for item in lib.items():
        if item.path != src_item.path:
            d = diff(item, src_item, ATTRIBUTES.values())
            if d < threshold:
                print(u'{1:2.2f}: {0}'.format(item.path, d))

class EchonestMetadataPlugin(plugins.BeetsPlugin):
    def __init__(self):
        super(EchonestMetadataPlugin, self).__init__()
        self.config.add({
            'auto':    True,
            'apikey':  u'NY2KTZHQ0QDSHBAP6',
            'codegen': None,
            'upload':  True,
            'convert': True,
        })
        self.config.add(ATTRIBUTES)

        pyechonest.config.ECHO_NEST_API_KEY = \
            config['echonest']['apikey'].get(unicode)

        if config['echonest']['codegen']:
            pyechonest.config.CODEGEN_BINARY_OVERRIDE = \
                config['echonest']['codegen'].get(unicode)

        if self.config['auto']:
            self.import_stages = [self.imported]

    def _echofun(self, func, **kwargs):
        """Wrapper for requests to the EchoNest API.  Will retry up to
        RETRIES times and wait between retries for RETRY_INTERVAL
        seconds.
        """
        for i in range(RETRIES):
            try:
                result = func(**kwargs)
            except pyechonest.util.EchoNestAPIError as e:
                if e.code == 3:
                    # reached access limit per minute
                    time.sleep(RETRY_INTERVAL)
                elif e.code == 5:
                    # specified identifier does not exist
                    # no use in trying again.
                    log.debug(u'echonest: {0}'.format(e))
                    return None
                else:
                    log.error(u'echonest: {0}'.format(e.args[0][0]))
                    return None
            except (pyechonest.util.EchoNestIOError, socket.error) as e:
                log.warn(u'echonest: IO error: {0}'.format(e))
                time.sleep(RETRY_INTERVAL)
            except Exception as e:
                # there was an error analyzing the track, status: error
                log.debug(u'echonest: {0}'.format(e))
                return None
            else:
                break
        else:
            # If we exited the loop without breaking, then we used up all
            # our allotted retries.
            raise ui.UserError(u'echonest request failed repeatedly')
            return None
        return result

    def _pick_song(self, songs, item):
        """Helper method to pick the best matching song from a list of songs
        returned by the EchoNest.  Compares artist, title and duration.  If
        the artist and title match and the duration difference is <= 1.0
        seconds, it's considered a match.
        """
        if not songs:
            log.debug(u'echonest: no songs found')
            return

        pick = None
        min_dist = item.length
        for song in songs:
            if song.artist_name.lower() == item.artist.lower() \
                    and song.title.lower() == item.title.lower():
                dist = abs(item.length - song.audio_summary['duration'])
                if dist < min_dist:
                    min_dist = dist
                    pick = song
        if min_dist > 2.5:
            return None
        return pick

    def _flatten_song(self, song):
        """Given an Echo Nest song object, return a flat dict containing
        attributes we care about. If song is None, return None.
        """
        if not song:
            return
        values = dict(song.audio_summary)
        values['id'] = song.id
        return values

    # "Profile" (ID-based) lookup.

    def profile(self, item):
        """Do a lookup on the EchoNest by MusicBrainz ID.
        """
        # Use an existing Echo Nest ID.
        if ID_KEY in item:
            enid = item[ID_KEY]

        # Look up the Echo Nest ID based on the MBID.
        else:
            if not item.mb_trackid:
                log.debug(u'echonest: no ID available')
                return
            mbid = 'musicbrainz:track:{0}'.format(item.mb_trackid)
            track = self._echofun(pyechonest.track.track_from_id,
                                  identifier=mbid)
            if not track:
                log.debug(u'echonest: lookup by MBID failed')
                return
            enid = track.song_id

        # Use the Echo Nest ID to look up the song.
        songs = self._echofun(pyechonest.song.profile, ids=enid,
                buckets=['id:musicbrainz', 'audio_summary'])
        return self._flatten_song(self._pick_song(songs, item))

    # "Search" (metadata-based) lookup.

    def search(self, item):
        """Search the item at the EchoNest by artist and title.
        """
        songs = self._echofun(pyechonest.song.search, title=item.title,
                              results=100, artist=item.artist,
                              buckets=['id:musicbrainz', 'tracks',
                                       'audio_summary'])
        return self._flatten_song(self._pick_song(songs, item))

    # "Identify" (fingerprinting) lookup.

    def fingerprint(self, item):
        """Get the fingerprint for this item from the EchoNest.  If we
        already have a fingerprint, return it and don't calculate it
        again.
        """
        if FINGERPRINT_KEY in item:
            return item[FINGERPRINT_KEY]

        try:
            res = self._echofun(pyechonest.util.codegen,
                                filename=item.path.decode('utf-8'))
        except Exception as e:
            # Frustratingly, the pyechonest library raises a plain Exception
            # when the command is not found.
            log.debug(u'echonest: codegen failed: {0}'.format(e))
            return

        if not res or 'code' not in res[0] or not res[0]['code']:
            log.debug(u'echonest: no fingerprint returned')
            return
        code = res[0]['code']

        log.debug(u'echonest: calculated fingerprint')
        item[FINGERPRINT_KEY] = code
        return code

    def identify(self, item):
        """Try to identify the song at the EchoNest.
        """
        code = self.fingerprint(item)
        if not code:
            return

        songs = self._echofun(pyechonest.song.identify, code=code)
        if not songs:
            log.debug(u'echonest: no songs found for fingerprint')
            return

        return self._flatten_song(max(songs, key=lambda s: s.score))

    # "Analyze" (upload the audio itself) method.

    def convert(self, item):
        """Converts an item in an unsupported media format to ogg.  Config
        pending.
        This is stolen from Jakob Schnitzers convert plugin.
        """
        fd, dest = tempfile.mkstemp(u'.ogg')
        os.close(fd)
        source = item.path

        log.info(u'echonest: encoding {0} to {1}'.format(
            util.displayable_path(source),
            util.displayable_path(dest),
        ))

        # Build up the FFmpeg command line.
        # FIXME: use avconv?
        command = u'ffmpeg -i $source -y -acodec libvorbis -vn -aq 2 $dest'
        opts = []
        for arg in command.split():
            arg = arg.encode('utf-8')
            opts.append(Template(arg).substitute(source=source, dest=dest))

        # Run the command.
        try:
            subprocess.check_call(opts, close_fds=True, stderr=DEVNULL)
        except (OSError, subprocess.CalledProcessError) as exc:
            log.debug(u'echonest: encode failed: {0}'.format(exc))
            util.remove(dest)
            return

        log.info(u'echonest: finished encoding {0}'.format(
            util.displayable_path(source))
        )
        return dest

    def analyze(self, item):
        """Upload the item to the EchoNest for analysis. May require to
        convert the item to a supported media format.
        """
        # Get the file to upload (either by using the file directly or by
        # transcoding it first).
        source = item.path
        if item.format not in ALLOWED_FORMATS:
            if config['echonest']['convert']:
                source = self.convert(item)
                if not source:
                    log.debug(u'echonest: failed to convert file')
                    return
            else:
                return

        # Upload the audio file.
        log.info(u'echonest: uploading file, please be patient')
        track = self._echofun(pyechonest.track.track_from_filename,
                              filename=source)
        if not track:
            log.debug(u'echonest: failed to upload file')
            return

        # Sometimes we have a track but no song. I guess this happens for
        # new / unverified songs. We need to "extract" the audio_summary
        # from the track object manually.  I don't know why the
        # pyechonest API handles tracks (merge audio_summary to __dict__)
        # and songs (keep audio_summary in an extra attribute)
        # differently.
        # Maybe a patch for pyechonest could help?

        # First get the (limited) metadata from the track in case
        # there's no associated song.
        from_track = {}
        for key in ATTRIBUTES:
            try:
                from_track[key] = getattr(track, key)
            except AttributeError:
                pass
        from_track['duration'] = track.duration

        # Try to look up a song for the full metadata.
        try:
            song_id = track.song_id
        except AttributeError:
            return from_track
        songs = self._echofun(pyechonest.song.profile,
                              ids=[song_id], track_ids=[track.id],
                              buckets=['audio_summary'])
        if songs:
            pick = self._pick_song(songs, item)
            if pick:
                return self._flatten_song(pick)
        return from_track  # Fall back to track metadata.

    # Shared top-level logic.

    def fetch_song(self, item):
        """Try all methods to get a matching song object from the
        EchoNest. If no method succeeds, return None.
        """
        # There are four different ways to get a song. Each method is a
        # callable that takes the Item as an argument.
        methods = [self.profile, self.search]
        if config['echonest']['codegen']:
            methods.append(self.identify)
        if config['echonest']['upload']:
            methods.append(self.analyze)

        # Try each method in turn.
        for method in methods:
            song = method(item)
            if song:
                log.debug(
                    u'echonest: got song through {0}: {1} - {2} [{3}]'.format(
                        method.__name__,
                        item.artist,
                        item.title,
                        song['duration'],
                    )
                )
                return song

    def apply_metadata(self, item, values, write=False):
        """Copy the metadata from the dictionary of song information to
        the item.
        """
        # Update each field.
        for k, v in values.iteritems():
            if k in ATTRIBUTES:
                field = ATTRIBUTES[k]
                log.debug(u'echonest: metadata: {0} = {1}'.format(field, v))
                if field == 'bpm':
                    item[field] = int(v)
                else:
                    item[field] = v
        if 'id' in values:
            enid = values['id']
            log.debug(u'echonest: metadata: {0} = {1}'.format(ID_KEY, enid))
            item[ID_KEY] = enid

        # Write and save.
        if write:
            item.write()
        item.store()

    # Automatic (on-import) metadata fetching.

    def imported(self, session, task):
        """Import pipeline stage.
        """
        for item in task.imported_items():
            song = self.fetch_song(item)
            if song:
                self.apply_metadata(item, song)

    # Explicit command invocation.

    def requires_update(self, item):
        """Check if this item requires an update from the EchoNest (its
        data is missing).
        """
        for field in ATTRIBUTES.values():
            if not item.get(field):
                return True
        log.info(u'echonest: no update required')
        return False

    def commands(self):
        fetch_cmd = ui.Subcommand('echonest',
            help='Fetch metadata from the EchoNest')
        fetch_cmd.parser.add_option('-f', '--force', dest='force',
            action='store_true', default=False,
            help='(re-)download information from the EchoNest')

        def fetch_func(lib, opts, args):
            self.config.set_args(opts)
            write = config['import']['write'].get(bool)
            for item in lib.items(ui.decargs(args)):
                log.info(u'echonest: {0} - {1}'.format(item.artist,
                        item.title))
                if self.config['force'] or self.requires_update(item):
                    song = self.fetch_song(item)
                    if song:
                        self.apply_metadata(item, song, write)

        fetch_cmd.func = fetch_func

        sim_cmd = ui.Subcommand('echosim', help='show related files')

        def sim_func(lib, opts, args):
            self.config.set_args(opts)
            for item in lib.items(ui.decargs(args)):
                similar(lib, item)

        sim_cmd.func = sim_func

        return [fetch_cmd, sim_cmd]


text:
{-# LANGUAGE RecordWildCards #-}

-- | A version of `Numeric.SGD.Sparse` extended with momentum.

module Numeric.SGD.Sparse.Momentum
( SgdArgs (..)
, sgdArgsDefault
, Para
, sgd
, module Numeric.SGD.Sparse.Grad
, module Numeric.SGD.DataSet
) where

import           Control.Monad (forM_)
-- import qualified System.Random as R
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import qualified Control.Monad.Primitive as Prim

import           Numeric.SGD.Sparse.Grad
import           Numeric.SGD.DataSet

-- | SGD parameters controlling the learning process.
data SgdArgs = SgdArgs
    { -- | Size of the batch
      batchSize :: Int
    -- | Regularization variance
    , regVar    :: Double
    -- | Number of iterations
    , iterNum   :: Double
    -- | Initial gain parameter
    , gain0     :: Double
    -- | After how many iterations over the entire dataset
    -- the gain parameter is halved
    , tau       :: Double
    }

-- | Default SGD parameter values.
sgdArgsDefault :: SgdArgs
sgdArgsDefault = SgdArgs
    { batchSize = 50
    , regVar    = 10
    , iterNum   = 10
    , gain0     = 0.25
      -- Without momentum I would rather go for '1', but with momentum the
      -- gradient gets significantly larger.
    , tau       = 5
    }

-- | The gamma parameter which drives momentum.
--
-- TODO: put in SgdArgs.
--
gamma :: Double
gamma = 0.9

-- | Vector of parameters.
type Para       = U.Vector Double

-- | Type synonym for mutable vector with Double values.
type MVect      = UM.MVector (Prim.PrimState IO) Double

-- | A stochastic gradient descent method.
-- A notification function can be used to provide user with
-- information about the progress of the learning.
sgd
    :: SgdArgs                  -- ^ SGD parameter values
    -> (Para -> Int -> IO ())   -- ^ Notification run every update
    -> (Para -> x -> Grad)      -- ^ Gradient for dataset element
    -> DataSet x                -- ^ DataSet
    -> Para                     -- ^ Starting point
    -> IO Para                  -- ^ SGD result
sgd SgdArgs{..} notify mkGrad dataset x0 = do

  putStrLn $ "Running momentum!"

  -- A vector for the momentum gradient
  momentum <- UM.new (U.length x0)

  -- A worker vector for computing the actual gradients
  u <- UM.new (U.length x0)

  doIt momentum u 0 =<< U.thaw x0

  where
    -- Gain in k-th iteration.
    gain k = (gain0 * tau) / (tau + done k)

    -- Number of completed iterations over the full dataset.
    done :: Int -> Double
    done k
        = fromIntegral (k * batchSize)
        / fromIntegral (size dataset)

    -- Regularization (Guassian prior) parameter
    regularizationParam = regCoef
      where
        regCoef = iVar ** coef
        iVar = 1.0 / regVar
        coef = fromIntegral (size dataset)
             / fromIntegral batchSize

    doIt momentum u k x

      | done k > iterNum = do
        frozen <- U.unsafeFreeze x
        notify frozen k
        return frozen

      | otherwise = do

        -- Sample the dataset
        batch <- randomSample batchSize dataset

        -- NEW: comment out
        -- -- Apply regularization to the parameters vector.
        -- scale (regularization k) x

        -- Freeze mutable vector of parameters. The frozen version is
        -- then supplied to external mkGrad function provided by user.
        frozen <- U.unsafeFreeze x
        notify frozen k

        -- Compute the gradient and put it in `u`
        let grad = parUnions (map (mkGrad frozen) batch)
        addUp grad u

        -- Apply regularization to `u`
        applyRegularization regularizationParam x u

        -- Scale the gradient
        scale (gain k) u

        -- Compute the new momentum
        updateMomentum gamma momentum u

        x' <- U.unsafeThaw frozen
        momentum `addTo` x'
        doIt momentum u (k+1) x'

-- | Compute the new momentum (gradient) vector.
applyRegularization
  :: Double -- ^ Regularization parameter
  -> MVect  -- ^ The parameters
  -> MVect  -- ^ The current gradient
  -> IO ()
applyRegularization regParam params grad = do
  forM_ [0 .. UM.length grad - 1] $ \i -> do
    x <- UM.unsafeRead grad i
    y <- UM.unsafeRead params i
    UM.unsafeWrite grad i $ x - regParam * y

-- | Compute the new momentum (gradient) vector.
updateMomentum
  :: Double -- ^ The gamma parameter
  -> MVect  -- ^ The previous momentum
  -> MVect  -- ^ The scaled current gradient
  -> IO ()
updateMomentum gammaCoef momentum grad = do
  forM_ [0 .. UM.length momentum - 1] $ \i -> do
    x <- UM.unsafeRead momentum i
    y <- UM.unsafeRead grad i
    UM.unsafeWrite momentum i (gammaCoef * x + y)

-- | Add up all gradients and store results in normal domain.
addUp :: Grad -> MVect -> IO ()
addUp grad v = do
    UM.set v 0
    forM_ (toList grad) $ \(i, x) -> do
        y <- UM.unsafeRead v i
        UM.unsafeWrite v i (x + y)

-- | Scale the vector by the given value.
scale :: Double -> MVect -> IO ()
scale c v = do
  forM_ [0 .. UM.length v - 1] $ \i -> do
    y <- UM.unsafeRead v i
    UM.unsafeWrite v i (c * y)

-- | Apply gradient to the parameters vector, that is add the first vector to
-- the second one.
addTo :: MVect -> MVect -> IO ()
addTo w v = do
  forM_ [0 .. UM.length v - 1] $ \i -> do
    x <- UM.unsafeRead v i
    y <- UM.unsafeRead w i
    UM.unsafeWrite v i (x + y)


text:
package pingis.services;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import pingis.entities.Task;
import pingis.entities.TmcUserDto;
import pingis.entities.User;
import pingis.repositories.UserRepository;
import pingis.services.entity.UserService;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {UserService.class})
public class UserServiceTest {

  private static final int TEST_USER_ID = 1;
  private static final String TEST_USER_NAME = "Test_user1";
  private static final int TEST_USER_LEVEL = 3;

  private static final int TEST_USER2_ID = 2;
  private static final String TEST_USER2_NAME = "Test_user2";
  private static final int TEST_USER2_LEVEL = 5;

  @Autowired
  UserService userService;

  @MockBean
  private UserRepository userRepositoryMock;

  private User testUser;
  private User testUser2;
  private ArgumentCaptor<User> userCaptor;

  @Before
  public void setUp() {
    testUser = new User(TEST_USER_ID, TEST_USER_NAME, TEST_USER_LEVEL);
    testUser2 = new User(TEST_USER2_ID, TEST_USER2_NAME, TEST_USER2_LEVEL);
    userCaptor = ArgumentCaptor.forClass(User.class);
  }

  @Test
  public void testSaveOneUser() {
    userService.save(testUser);
    verify(userRepositoryMock, times(1)).save(userCaptor.capture());
    assertThat(userCaptor.getValue()).isEqualTo(testUser);
  }

  @Test
  public void testSimpleSaveAndFindOneUserFind() {
    userService.save(testUser);
    userService.findByName(testUser.getName());
    verify(userRepositoryMock, times(1)).save(userCaptor.capture());
    verify(userRepositoryMock, times(1)).findByName(userCaptor.getValue().getName());
    verifyNoMoreInteractions(userRepositoryMock);

    User oneUser = userCaptor.getValue();

    assertThat(oneUser.getName()).isEqualTo(testUser.getName());
    assertThat(oneUser.getId()).isEqualTo(testUser.getId());
    assertThat(oneUser.getPoints()).isEqualTo(testUser.getPoints());
  }

  @Test
  public void testSimpleFindAllUsers() {
    userService.save(testUser);

    List<User> testUsers = new ArrayList<User>();
    testUsers.add(testUser);

    when(userRepositoryMock.findAll()).thenReturn(testUsers);
    List<User> found = userService.findAll();

    verify(userRepositoryMock, times(1)).findAll();
    assertEquals(found.size(), testUsers.size());
  }

  @Test
  public void testfindAllUsersWithTwoUsers() {
    userService.save(testUser);
    userService.save(testUser2);

    List<User> testUsers = new ArrayList<User>();
    testUsers.add(testUser);
    testUsers.add(testUser2);

    when(userRepositoryMock.findAll()).thenReturn(testUsers);
    List<User> found = userService.findAll();

    verify(userRepositoryMock, times(1)).findAll();
    assertEquals(found.size(), testUsers.size());
  }

  @Test
  public void testSimpleFindAlltWithMultipleInputUsers() {
    userService.save(testUser);
    userService.save(testUser2);

    List<User> testUsers = new ArrayList<User>();
    testUsers.add(testUser);
    testUsers.add(testUser2);

    when(userRepositoryMock.findAll()).thenReturn(testUsers);
    List<User> found = userService.findAll();

    verify(userRepositoryMock, times(1)).findAll();
    assertEquals(found.size(), testUsers.size());

    assertThat(found.get(0).getName()).isEqualTo(testUser.getName());
    assertThat(found.get(1).getName()).isEqualTo(testUser2.getName());
  }

  @Test
  public void testSimpleDeleteOneUser() {
    userService.save(testUser);
    verify(userRepositoryMock, times(1)).save(userCaptor.capture());

    userService.delete(userCaptor.getValue());
    verify(userRepositoryMock).delete(userCaptor.getValue());

    boolean userExists = userService.contains(userCaptor.getValue().getId());
    assertFalse(userExists);
  }

  @Test
  public void testSimpleDeleteMultipleUsers() {

    userService.save(testUser);
    userService.save(testUser2);
    verify(userRepositoryMock, times(2)).save(userCaptor.capture());

    List<User> capturedUsers = userCaptor.getAllValues();

    int userIndex = 0;

    userService.delete(testUser);
    verify(userRepositoryMock, times(1)).delete(capturedUsers.get(userIndex));

    userService.delete(testUser2);
    verify(userRepositoryMock, times(1)).delete(capturedUsers.get(++userIndex));
    verifyNoMoreInteractions(userRepositoryMock);
  }

  @Test
  public void testContains() {
    when(userRepositoryMock.existsById(testUser.getId())).thenReturn(true);
    userService.save(testUser);

    boolean contains = userService.contains(testUser.getId());
    verify(userRepositoryMock).existsById(testUser.getId());
    assertThat(contains).isTrue();
  }

  @Test
  public void testContainsWithTwoUsers() {
    when(userRepositoryMock.existsById(testUser.getId())).thenReturn(true);
    when(userRepositoryMock.existsById(testUser2.getId())).thenReturn(true);

    userService.save(testUser);
    userService.save(testUser2);

    boolean contains = userService.contains(testUser.getId());
    boolean contains2 = userService.contains(testUser2.getId());

    verify(userRepositoryMock).existsById(testUser.getId());
    verify(userRepositoryMock).existsById(testUser2.getId());
    assertThat(contains && contains2).isTrue();
  }

  @Test
  public void testDeleteMultipleWithTwo() {
    List<User> delUsers = Arrays.asList(testUser, testUser2);

    userService.save(testUser);
    userService.save(testUser2);

    userService.deleteMultiple(delUsers);
    verify(userRepositoryMock).delete(testUser);
    verify(userRepositoryMock).delete(testUser2);
  }

  @Test
  public void testInitializeUserWithOauthUser() {
    TmcUserDto user = generateOauthTestUser();
    userService.initializeUser(user);
    verify(userRepositoryMock).save(userCaptor.capture());
    assertThat(userCaptor.getValue().getName()).isEqualTo(user.getName());
    assertThat(userCaptor.getValue().getId()).isEqualTo(Long.parseLong(user.getId()));
    assertThat(userCaptor.getValue().getPoints()).isEqualTo(1);
    assertThat(userCaptor.getValue().isAdministrator()).isEqualTo(user.isAdministrator());
  }

  @Test
  public void testHandleUnknownOAuthUser() {
    TmcUserDto oauthUser1 = new TmcUserDto();
    Long randomUserId = new Random(Long.MAX_VALUE).nextLong();
    String randomUserIdString = Long.toString(randomUserId);

    oauthUser1.setAdministrator(true);
    oauthUser1.setName(TEST_USER2_NAME);
    oauthUser1.setId(randomUserIdString);

    when(userRepositoryMock.findById(Long.parseLong(randomUserIdString)))
            .thenReturn(Optional.empty());
    when(userRepositoryMock.save(userCaptor.capture())).thenReturn(testUser2);
    User newUser = userService.handleOAuthUserAuthentication(oauthUser1);

    ArgumentCaptor<Long> capturedId = ArgumentCaptor.forClass(Long.class);

    verify(userRepositoryMock).findById(capturedId.capture());
    verify(userRepositoryMock, times(1)).save(userCaptor.capture());

    assertThat(newUser).isNotNull();
    assertThat(newUser.getName()).isEqualTo(TEST_USER2_NAME);
    assertThat(userCaptor.getValue().getId()).isEqualTo((Long.parseLong(randomUserIdString)));
  }

  @Test
  public void testHandleKnownOAuthUser() {
    userService.save(testUser);
    verify(userRepositoryMock).save(userCaptor.capture());

    when(userRepositoryMock.findById((long) TEST_USER_ID)).thenReturn(Optional.of(testUser));

    TmcUserDto user = generateOauthTestUser();
    User newUser = userService.handleOAuthUserAuthentication(user);

    ArgumentCaptor<Long> capturedId = ArgumentCaptor.forClass(Long.class);

    verify(userRepositoryMock).findById(capturedId.capture());
    verify(userRepositoryMock).save(testUser);
    assertThat(newUser).isEqualTo(testUser);
    assertThat(capturedId.getValue()).isEqualTo((long) TEST_USER_ID);
  }

  private TmcUserDto generateOauthTestUser() {
    TmcUserDto user = new TmcUserDto();
    user.setAdministrator(true);
    user.setName(TEST_USER_NAME);
    user.setId(Long.toString(TEST_USER_ID));

    return user;
  }

  @Test
  public void testHandleKnownUser() {
    userService.save(testUser);
    verify(userRepositoryMock).save(userCaptor.capture());

    when(userRepositoryMock.findByName(testUser.getName())).thenReturn(userCaptor.getValue());
    User newUser = userService.handleUserAuthenticationByName(TEST_USER_NAME);
    assertThat(newUser).isEqualTo(testUser);
  }

  @Test
  public void testHandleUnknownUser() {
    when(userRepositoryMock.findByName(testUser2.getName())).thenReturn(null);
    when(userRepositoryMock.save(testUser2)).thenReturn(testUser2);
    User newUser = userService.handleUserAuthenticationByName(testUser2.getName());

    assertThat(newUser).isNotNull();
    assertThat(newUser.getName()).isEqualTo(testUser2.getName());
    assertThat(newUser.getId()).isExactlyInstanceOf(Long.class);
  }

  public void testLevels() {
    assertEquals(0, userService.getLevel(500));
    assertEquals(1, userService.getLevel(1000));
    assertEquals(1, userService.getLevel(1400));
    assertEquals(2, userService.getLevel(2100));
    assertEquals(20, userService.getLevel(20010));
    assertEquals(Task.LEVEL_MAX_VALUE, userService.getLevel(Integer.MAX_VALUE));
  }
}


text:
Dev::Util.require_tree Pathname(__dir__).join('subcommand')
Dev::Util.require_tree Pathname(__dir__).join('command')

module Dev
  class CLI < Thor
    desc 'project SUBCOMMAND ...ARGS', 'manage your dockerized projects'
    subcommand 'project', Subcommand::Project

    desc 'stage SUBCOMMAND ...ARGS', 'manage the current project stage'
    subcommand 'stage', Subcommand::Stage

    desc 'config SUBCOMMAND ...ARGS', 'configure this development system'
    subcommand 'config', Subcommand::Config

    def self.dispatch(*args, &block)
      super(*args, &block)
    rescue StandardError => exception
      Dev.logger.error(exception)
      exit(1)
    end
  end
end


text:
using UnityEngine;
using System;

namespace QFramework.Experimental
{
    [CreateAssetMenu(fileName = "soGameObject", menuName = "soVariables/soGameObject", order = 1)]
    public class SOGameObject : ScriptableVariable, ISerializationCallbackReceiver
    {
        //Float value
        [NonSerialized]
        public GameObject value;

        //When the game starts, the starting value we use (so we can reset if need be)
        [SerializeField]
        private GameObject startingValue = null;

        /// <summary>
        /// Set sGameObject value
        /// </summary>
        /// <param name="_value"></param>
        public void SetValue(GameObject _value)
        {
            value = _value;
        }

        /// <summary>
        /// Set value to another sGameObject value
        /// </summary>
        /// <param name="_value"></param>
        public void SetValue(SOGameObject _value)
        {
            value = _value.value;
        }

        /// <summary>
        /// Recieve callback after unity deseriallzes the object
        /// </summary>
        public void OnAfterDeserialize()
        {
            value = startingValue;
        }

        public void OnBeforeSerialize() { }

        /// <summary>
        /// Reset the value to it's inital value if it's resettable
        /// </summary>
        public override void ResetValue()
        {
            value = startingValue;
        }
    }
}


text:
layout: post
title: Luminance Noise
categories: vidéo analogique
tags: [Analog, Video, Luminance, Noise, Cable, Cleaning]
lang: Français
---

Luminance noise manifests itself in a video picture as light white noise. It may be the result of electronic failure, recording in low-light, worn or poorly coated tape stock, transmission of a video signal over cables that are too long, over-enhancement of the video signal, or dirty record or playback heads. Color video or black and white video can both contain luminance noise.

## Can it be fixed?

If the video output has been properly adjusted for playback and there is no cabling or media issues, then the noise is inherent to the source and is not remediable.


text:
layout: article
title: "Chloe, 22 months"
excerpt: "PaperFaces portrait of my daughter Chloe drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-chloe-winter-lg.jpg
  teaser: paperfaces-chloe-winter-teaser.jpg
  thumb: paperfaces-chloe-winter-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53, blend, black and white, bokeh, twins]
---

Just like [her sister]({% post_url /paperfaces/2014-06-23-everly-autumn-portrait %}), *Chlo-worm's* hair can't be tamed.

The more I draw with Paper, the clearer it becomes that I don't really have a set process. Sometimes I start with a rough outline that I continuously erase and refine. Other times I jump right to the darks and work backwards towards the light.

{% include paperfaces-boilerplate-4.html %}

Work in progress screen captures Made with Paper.