text:
;(function(root) {

	'use strict';

	var namespace = {};

	;
(function(namespace) {

	'use strict';

	/**
	 * Augments the window object with a
	 * module and a require property to
	 * emulate CommonJS in the browser.
	 * @param  {Object} appRoot The object to use as the root object for your 'modules' reqistered with kwire.
	 * @param  {Object} globalShadow An object to shadow the global object for testing purposes.
	 */
	function kwire(appRoot, globalShadow) {
		appRoot = appRoot == null ? {} : appRoot;
		globalShadow = globalShadow || window;

		if (typeof appRoot !== 'object') {
			throw 'root object must be an object.'
		}

		if (isServerSide() ||
			isUsingRequireJS() ||
			rootIsAlreadyConfigured(globalShadow)) {
			return;
		}

		globalShadow.module = {
			set exports(value) {
				if (value === undefined) {
					throw 'module not defined.';
				}
				if (value === null) { // null or undefined.
					return;
				}
				if (!value.hasOwnProperty('_path_')) {
					throw '_path_ own-property must be present on modules registered with kwire.';
				}

				if (typeof value._path_ !== 'string') {
					throw '_path_ own-property must be a string.';
				}

				appRoot[value._path_] = value;
			}
		};

		/**
		 * cb is optional.
		 */
		globalShadow.require = function(value, cb) {
			var valueIsArray = Array.isArray(value);
			if (value == null) {
				throw 'value not defined.'
			}
			if (typeof value !== 'string' && !valueIsArray) {
				throw 'value must be a string or an array.'
			}

			if (cb) {
				if (!valueIsArray) {
					return cb(appRoot[value]);
				}

				return cb.apply(null, value.map(function(v) {
					return appRoot[v];
				}));
			}

			var result = appRoot[value];

			return result === undefined ? globalShadow[camelify(value)] : result;
		};

	}

	function camelify(str) {
		return str.replace(/(\-([^-]{1}))/g, function(match, $1, $2) {
			return $2.toUpperCase();
		});
	}

	function isServerSide() {
		return (typeof exports === 'object') && module;
	}

	function isUsingRequireJS() {
		return (typeof define === 'function') && define.amd;
	}

	function rootIsAlreadyConfigured(globalShadow) {
		return (globalShadow.module && globalShadow.require);
	}

	kwire.camelify = camelify;
	namespace.kwire = kwire;

}(namespace));

	if ((typeof exports === 'object') && module) {
		module.exports = namespace; // CommonJS
	} else if ((typeof define === 'function') && define.amd) {
		define(function() {
			return namespace;
		}); // AMD
	} else {
		root.kwire = namespace.kwire; // Browser
	}

}(this));

;(function(root) {

	'use strict';

	var namespace = {};

	;
(function(namespace) {

	'use strict';

	/**
	 * Expects an arguments object, followed by zero or more
	 * string arguments, corresponding to argument names.
	 * If a single argument is supplied, then all arguments
	 * are verified to be defined. If more than one argument
	 * is supplied, then the arguments corresponding to indices
	 * that do not contain an '_' (underscore) are checked to
	 * be defined.
	 * @param  {Arguments} args  The arguments object to check.
	 * @return {undefined}
	 */
	function need(args) {
		var argsArray, restArgs;

		if (!args) {
			return args;
		}

		argsArray = Array.prototype.slice.call(args);
		restArgs = Array.prototype.slice.call(arguments, 1);

		if (isArgumentObject(args)) {
			return argCheck(argsArray, restArgs);
		}

		return objectCheck(args, restArgs);
	}

	function argCheck(args, restArgs) {
		var iterator, reduceFn;

		iterator = restArgs.length ? restArgs : args;
		reduceFn = iterator === args ? undefinedCheck : unneededCheck.bind(null, args);

		iterator.reduce(reduceFn, null);
	}

	function objectCheck(o, restArgs) {
		var iterator, reduceFn;

		iterator = restArgs.length ? restArgs : Object.keys(o);
		reduceFn = undefinedCheckIn.bind(null, o);

		iterator.reduce(reduceFn, null);
	}

	function undefinedCheckIn(o, p, c) {
		if (o[c] === undefined) {
			throw c + ' not defined.';
		}
	}

	function unneededCheck(args, p, c, i) {
		if (c === '_') {
			return;
		}

		if (args[i] === undefined) {
			throw c + ' not defined.';
		}
	}

	function undefinedCheck(p, c, i) {
		if (c === undefined) {
			throw 'argument not defined.';
		}
	}

	function isArgumentObject(item) {
		return Object.prototype.toString.call(item) === '[object Arguments]';
	}

	namespace.need = need;

}(namespace));

	if ((typeof exports === 'object') && module) {
		module.exports = namespace; // CommonJS
	} else if ((typeof define === 'function') && define.amd) {
		define(function() {
			return namespace;
		}); // AMD
	} else {
		root.niid = namespace; // Browser
	}

}(this));

;(function(root) {

	'use strict';

	var namespace = {};

	;(function(namespace) {

	'use strict';

	function noop() {}

	noop.truthy = function() {
		return true;
	};

	noop.falsy = function() {
		return false;
	};

	noop.exception = function(str) {
		throw str;
	};

	namespace.noopaam = noop;

}(namespace));

	if ((typeof exports === 'object') && module) {
		module.exports = namespace.noopaam; // CommonJS
	} else if ((typeof define === 'function') && define.amd) {
		define(function() {
			return namespace.noopaam;
		}); // AMD
	} else {
		root.noopaam = namespace.noopaam; // Browser
	}

}(this));

;(function(root) {

	'use strict';

	var namespace = {};

	;(function(namespace) {

	'use strict';

	/**
	 * Partially apply a function.
	 * @param  {Function} fn      The function to partially apply.
	 * @return {Function}         The partially applied function.
	 */
	function partial(fn) {
		var args;

		if (typeof fn !== 'function') {
			throw 'First argument must be a function.';
		}

		if (arguments.length <= 1) {
			return fn;
		}

		args = Array.prototype.slice.call(arguments, 1);

		return function() {
			return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
		}
	}

	/**
	 * Partially apply a function, but ensure the returned function has an arity of one.
	 * @param  {Function} fn      The function to partially apply.
	 * @return {Function}         The partially applied function.
	 */
	function partialWithArityOfOne(fn) {
		var args = arguments;

		return function(a) {
			return partial.apply(this, args).apply(this, arguments);
		};
	}

	namespace.partial = partial;
	namespace.partial1 = partialWithArityOfOne;

}(namespace));

	if ((typeof exports === 'object') && module) {
		module.exports = namespace; // CommonJS
	} else if ((typeof define === 'function') && define.amd) {
		define(function() {
			return namespace;
		}); // AMD
	} else {
		root.partialApplication = namespace; // Browser
	}

}(this));

;(function(root) {

	'use strict';

	var namespace = {};

	;(function(namespace) {

	'use strict';

	function rest(fn, args) {
		return Array.prototype.slice.call(args, fn.length);
	}

	function spread(fn, arr, target) {
		return fn.apply((target || this), arr);
	}

	namespace.rest = rest;
	namespace.spread = spread;

}(namespace));

	if ((typeof exports === 'object') && module) {
		module.exports = namespace; // CommonJS
	} else if ((typeof define === 'function') && define.amd) {
		define(function() {
			return namespace;
		}); // AMD
	} else {
		root.sprest = namespace; // Browser
	}

}(this));

;(function(root) {

	'use strict';

	var namespace = {};

	;(function(namespace) {

	'use strict';

	var mixFn = (function() {
		return isES5() ? mixIntoObjectES5 : mixIntoObjectES3;
	}());

	/**
	 * Accepts an object and zero or more objects.
	 * Returns the function, modified so that the
	 * methods on the supplied objects are present
	 * on the function's prototype.
	 */
	function mix(target) {
		var objs = Array.prototype.slice.call(arguments, 1);

		switch (typeof target) {
			case 'function':
				mixFn(target.prototype, objs);
				return target;
			case 'object':
				return mixFn(target, objs);
		}

		return target;
	}

	function mixIntoObjectES3(target, objs) {
		var i, key, o;

		for (i = 0; i < objs.length; i++) {
			o = objs[i];

			if(o == null) { // null or undefined
				continue;
			}

			for (key in o) {
				if (!o.hasOwnProperty(key)) {
					continue;
				}

				target[key] = o[key];
			}
		}

		return target;
	}

	function mixIntoObjectES5(target, objs) {
		objs.forEach(function(o) {
			if(o == null) { // null or undefined
				return;
			}
			Object.keys(o).forEach(function(k) {
				var descriptor = Object.getOwnPropertyDescriptor(o, k);
				descriptor.configurable = true;
				Object.defineProperty(target, k, descriptor);
			});
		});

		return target;
	}

	function isES5() {
		return Object.getOwnPropertyDescriptor && Array.prototype.forEach;
	}

	namespace.mix = mix;

}(namespace));

	if ((typeof exports === 'object') && module) {
		module.exports = namespace; // CommonJS
	} else if ((typeof define === 'function') && define.amd) {
		define(function() {
			return namespace;
		}); // AMD
	} else {
		root.mixx = namespace; // Browser
	}

}(this));

;(function(root) {
  'use strict';

  var namespace = {};

  kwire(namespace); // Configure window in browser for CommonJS module syntax.

  /* global require, module */
;(function() {

	'use strict';

	var mix = require('mixx').mix;
	var need = require('niid').need;
	var partial = require('partial-application').partial;
	var spread = require('sprest').spread;
	var rest = require('sprest').rest;

	var transitionHelper = {};

	var defaultOptions = Object.freeze({
		statefulObject: undefined,
		machine: undefined,
		targetState: undefined,
	});

	transitionHelper.triggerTransition = function triggerTransition(options) {
		need(options = mix({}, defaultOptions, options));

		if (options.machine.currentState.value === options.targetState.value &&
			!options.machine.permitSelfTransition) {
			throw 'self transition exception';
		}

		if (options.machine.finalState && options.machine.currentState.value === options.machine.finalState.value) {
			throw 'final state transition exception';
		}

		if (options.machine.currentState.value === options.targetState.value &&
			options.machine.bypassTransitionBehaviorForSelfTransition) {
			return;
		}

		return performTransition(options,
			getTransition(options),
			rest(triggerTransition, arguments));
	};

	function performTransition(options, transition, restArgs) {
		if (transition &&
			spread(partial(transition.condition, options.targetState, options.statefulObject), restArgs)) {
			return runTransitionSteps(options, restArgs, transition);
		}

		if (!options.machine.parent) {
			throw 'invalid state transition. current: ' +
			options.machine.currentState.value + ' target: ' + options.targetState.value;
		}

		return spread(partial(options.machine.parent.triggerTransition, options.targetState), restArgs);
	}

	function runTransitionSteps(options, restArgs, transition) {
		var result;

		spread(options.machine.currentState.exitAction, restArgs);
		result = spread(partial(transition.transitionAction, options), restArgs);
		spread(options.targetState.entryAction, restArgs);
		options.machine.currentState = options.targetState;

		return result;
	}

	function getTransition(options) {
		return options.machine.transitions
			.find(function(t) {
				return t.startStates.some(function(s) {
					return s.value === options.machine.currentState.value;
				}) && t.endStates.some(function(e) {
					return e.value === options.targetState.value;
				});
			});
	}

	transitionHelper._path_ = './transition-helper';

	module.exports = transitionHelper;

}());

  /* global require, module */
;(function() {

	'use strict';

	var mix = require('mixx').mix;
	var need = require('niid').need;
	var partial = require('partial-application').partial;
	var spread = require('sprest').spread;
	var rest = require('sprest').rest;

	var transitionHelper = require('./transition-helper');

	var defaultOptions = Object.freeze({
		name: undefined,
		transitions: undefined,
		initialState: undefined,
		finalState: null,
		parentMachine: null,
		permitSelfTransition: true,
		bypassTransitionBehaviorForSelfTransition: false
	});

	function Machine(options) {
		need(options = mix({}, defaultOptions, options), 'name', 'transitions', 'initialState');

		mix(this, options); // Add `options` directly to `this`.

		this.currentState = this.initialState;
		this.children = {};

		if (this.parentMachine) {
			this.parentMachine.children[this.name] = this;
		}
	}

	Machine.prototype.triggerTransition = function triggerTransition(options) {
		need(options = mix({
			machine: this
		}, options), 'statefulObject', 'targetState');

		return spread(partial(transitionHelper.triggerTransition, options),
			rest(triggerTransition, arguments));
	};

	Machine._path_ = './machine';

	module.exports = Machine;

}());

  /* global require, module */
;(function() {

	'use strict';

	var noop = require('noopaam');

	var state = {
		value: null, // Used for equality checks.
		entryAction: noop,
		exitAction: noop,
	};

	state._path_ = './state';

	module.exports = state;

}());

  /* global require, module */
;(function() {

	'use strict';

	var need = require('niid').need;
	var partial = require('partial-application').partial;
	var spread = require('sprest').spread;
	var rest = require('sprest').rest;

	/**
	 * Expects a property named `machine`.
	 * @type {Object}
	 */
	var stateful = {

		get parentState() {
			return this.machine.parentState;
		},

		get currentState() {
			return this.machine.currentState;
		},

		/**
		 * `cb` is passed `transitionActionStatus`, so that
		 * this can be used by client code.
		 */
		triggerTransition: function triggerTransition(options) {
			need(options, 'targetState');

			var transitionActionStatus;

			transitionActionStatus = spread(partial(this.machine.triggerTransition, {
					statefulObject: this,
					targetState: options.targetState
				}),
				rest(triggerTransition, arguments), this.machine);
			options.cb && options.cb(transitionActionStatus);

			return this;
		}

	};

	stateful._path_ = './stateful';

	module.exports = stateful;

}());

  /* global module */
;(function() {

	'use strict';

	var transitionActionStatus = {
		NOT_RUN: 1,
		SUCCESS: 2,
		FAILED: 3,
	};

	transitionActionStatus._path_ = './transition-action-status';

	module.exports = transitionActionStatus;

}());

  /* global require, module */
;(function() {

	'use strict';

	var mix = require('mixx').mix;
	var need = require('niid').need;
	var noop = require('noopaam');

	var defaultOptions = Object.freeze({
		startStates: undefined,
		endStates: undefined,
		condition: noop.truthy,
		transitionAction: noop.truthy
	});

	function Transition(options) {
		need(options = mix({}, defaultOptions, options), 'startStates', 'endStates');

		mix(this, options);
	}

	Transition._path_ = './transition';

	module.exports = Transition;

}());

  if ((typeof exports === 'object') && module) {
    module.exports = namespace; // CommonJS
  } else if ((typeof define === 'function') && define.amd) {
    define(function() {
      return namespace;
    }); // AMD
  } else {
    root.eventApi = namespace; // Browser
  }
}(this));


text:
This example will go through all of the major uses of Forge Networking Remastered. You will learn the basic building blocks required to build any online multiplayer game using Forge Networking Remastered (FNR).

## Introduction

The game we will be creating for this example is very simple. We will have two or more players that can see each other as capsules and we will have a volume (trigger), in this trigger if our player activates it (triggers it) then it will spawn a sphere to the center of the map that will have a rigidbody and random x and z force. Note that the trigger will need to be destroyed when the ball is spawned in order to prevent it from spawning more than one sphere. When the sphere is collided with y the player, then the sphere is destroyed and we add a point to the player who touched the sphere.

## Very First Step

The first step before adding any networking to your game is to identify where the critical points to add networking will be. Below is a list of information we know that will need to be sent across the network in order for the game to play as expected on all connections.

* Spawn player
* Sync player positions
* Sync player names
* Destroy trigger after touch
* Spawn sphere
* Sync sphere position
* Change sphere velocity on spawn
* Add points for colliding with sphere
* Change sphere position after collision

Next we can go through each of our required network fields and determine which ones should be done with an RPC, network instantiate, network destroy, and which ones should be done by synchronizing a variable.

* **Instantiate** Spawn player
* **Variable** Sync player positions
* **RPC** Sync player names
* **Destroy** Remove trigger after touch
* **Instantiate** Spawn sphere
* **Variable** Sync sphere position
* **RPC** Change sphere velocity on spawn
* **RPC** Show the last person who got the ball
* **RPC** Change sphere position and velocity after collision

By doing this we are easily able to see what we should do next when we move onto the Network Contract Wizard (NCW).

## Setup the Game

Next, before we setup our networking logic, we will want to setup our base game and all of it's objects and prefabs (No scripting yet).

First we will create the basic world for our players to run around in.

1. Create folder:  Scenes
2. Create folder:  Scripts
3. Create folder:  Prefabs
4. Create folder:  Materials
5. Create a new scene
6. Delete the **Main Camera**
7. Save your scene as a new scene into **Scenes** folder
8. Create a material in **Materials** folder
    1. Name:  Trigger
    2. Color:  0, 255, 0, 128
    3. Set Rendering Mode to Transparent
9. Create a material in **Materials** folder
    1. Name:  GameBall
    2. Color:  0, 0, 255, 255 Do the following in the Scene we just created.

1. Create a cube:
    1. Position:  0, 0, 0
    2. Rotation:  0, 0, 0
    3. Scale:  25, 0.1, 25
    4. Name:  Floor
2. Create a cube
    1. Position:  -12.5, 5, 0
    2. Rotation:  0, 0, 0
    3. Scale:  0.1, 10, 25
    4. Name:  Left Wall
3. Create a cube
    1. Position:  12.5, 5, 0
    2. Rotation:  0, 0, 0
    3. Scale:  0.1, 10, 25
    4. Name:  Right Wall
4. Create a cube
    1. Position:  0, 5, -12.5
    2. Rotation:  0, 0, 0
    3. Scale:  25, 10, 0.1
    4. Name:  Front Wall
5. Create a cube
    1. Position:  0, 5, 12.5
    2. Rotation:  0, 0, 0
    3. Scale:  25, 10, 0.1
    4. Name:  Back Wall
6. Create a cube
    1. Position:  7.5, 5, 7.5
    2. Rotation:  0, 0, 0
    3. Scale:  10, 10, 10
    4. Name:  Start Trigger
    5. Set Material to the **Trigger** material we created
    6. Check the **Is Trigger** box in the box collider component on this object
7. Create a sphere
    1. Position:  0, 10, 0
    2. Rotation: 0, 0, 0
    3. Scale:  1, 1, 1
    4. Name:  GameBall
    5. Set Material to the **GameBall** material we created
    6. Add a **Rigidbody** component
    7. Save as a Prefab in the **Prefabs** folder
    8. Delete from scene
8. Create an empty Game Object
    1. Position:  0, 0, 0
    2. Rotation:  0, 0, 0
    3. Scale:  1, 1, 1
    4. Name:  Game Logic
9. Select the menu item **Game Object>UI>Text**
    1. The **Text** that is created in the **Hierarchy**
    2. Rename it to **Last Scored**
    3. Change the **Text** field to be empty
    4. Set the **Anchor Preset** to **Top Left** _(this is the one with the top left being highlighted in the anchor image)_ e.  Set the **Pivot X** to 0
    5. Set the **Pivot Y** to 1
    6. Set **Pos X** to 0
    7. Set **Pos Y** to 0
    8. Set **Pos Z** to 0
    9. Set **Width** to 500
11. Save the scene

Now we have completed the setup for our game, let's setup our **Build Settings**

1. Open Build Settings from **File>Build Settings** (Ctrl + Shift + B on windows)
2. Add **MultiplayerMenu** scene as the 0th scene index
3. Add your newly saved scene as the 1st index
4. Click **Player Settings...**
5. Turn on **Run In Background**

Now all that is left to do is setup our **Player** prefab and then we will be ready to jump into setting up our network.

1. In Unity select **Assets>Import Package>Characters**
2. Click the Import button
3. Open the **Standard Assets>Characters>FirstPersonCharacter>Prefabs** directory
4. Drag the **FPSController** prefab into the scene
5. Rename the prefab to **Player**
6. Add a **Mesh Filter** component
7. Add a **Mesh Renderer** component
8. Select the **Capsule** as the **Mesh** in the **MeshFilter** component
9. Open the **Materials** drop down in the **Mesh Renderer**
10. Select **Default-Material** in **Element 0**
11. Add a **Sphere Collider**
    1. Set **Y** to -0.5
    2. Set **Radius** to 0.5
12. Add another **Sphere Collider**
    1. Set **Y** to 0.5
    2. Set **Radius** to 0.5
13. Drag the **Player** GameObject from the **Hierarchy** into the **Prefabs** folder that we made in the beginning
14. Delete the **Player** Game Object from the scene
15. Save the project

The reason we are adding 2 sphere Colliders is because (at the time of this writing) the Character Controller is not reliable for detecting collisions. You have to "rub" up on the object a bit before it is detected. By adding the sphere colliders to our character, this issue will be resolved.

Now you are ready to start setting up your network contract using the **Network Contract Wizard**.

## Network Contract Wizard

The Network Contract Wizard (NCW) is responsible for creating the blueprint of the network communication. We will use this UI to setup the basic classes, fields, and remote procedure calls needed for our network communication. To get started, open the Network Contract Wizard UI by going to **Window>Forge Networking>Network Contract Wizard** within Unity. In this window you will be presented with all the current network classes.

If you included the **Bearded Man Studios Inc** examples folder then you should see a couple pre-made options initially.

Now let's get started on making the network contract for our simple game:

1. Click the **Create** button
2. Type in **Player** into the name box
3. Click the **Add Field** button
    1. Type **position** into the text box
    2. Select the drop down
    3. Select **VECTOR3** from the options
    4. Click the **Interpolate** button and leave the value at **0.15**
4. Click the **Add RPC** button
    1. Type **UpdateName** into the text field
    2. Open the **Arguments** cascade
        1.Click the ![add-button](https://raw.githubusercontent.com/BeardedManStudios/ForgeNetworkingRemastered/develop/docs/mkdocs/docs/images/add.png "Add Button") button
        2. Type **newName** into the text field
        3. Click the drop down iv.  Select **STRING** from the drop down
5. Click **Save & Compile**

What this will do is create and modify some classes in the **Generated** folder of your project. Before we continue to add the other network contracts, let's setup our **Player** class.

1. Open the **Scripts** folder
2. Create a new C# script named **Player**
3. Open the **Prefabs** folder and select the **Player** prefab
4. Click **Add Component**
5. Add the **Player** script to the prefab
6. Select the **Scripts** folder
7. Open the **Player.cs** script you just created
8. Insert the following code

### Player.cs**
```csharp
// We use this namespace as it is where our PlayerBehavior was generated using BeardedManStudios.Forge.Networking;
using BeardedManStudios.Forge.Networking.Generated;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

// We extend PlayerBehavior which extends NetworkBehavior which extends MonoBehaviour
public class Player : PlayerBehavior
{
	private string[] nameParts = new string[] { "crazy", "cat", "dog", "homie", "bobble", "mr", "ms", "mrs", "castle", "flip", "flop" };

	public string Name { get; private set; }

	protected override void NetworkStart()
	{
		base.NetworkStart();

		if (!networkObject.IsOwner)
		{
			// Don't render through a camera that is not ours
			// Don't listen to audio through a listener that is not ours
			transform.GetChild(0).gameObject.SetActive(false);

			// Don't accept inputs from objects that are not ours
			GetComponent<FirstPersonController>().enabled = false;

			// There is no reason to try and simulate physics since the position is
			// being sent across the network anyway
			Destroy(GetComponent<Rigidbody>());
		}

		// Assign the name when this object is setup on the network
		ChangeName();
	}

	public void ChangeName()
	{
		// Only the owning client of this object can assign the name
		if (!networkObject.IsOwner)
		return;
		// Get a random index for the first name
		int first = Random.Range(0, nameParts.Length - 1);
		// Get a random index for the last name
		int last = Random.Range(0, nameParts.Length - 1);

		// Assign the name to the random selection
		Name = nameParts[first] + " " + nameParts[last];

		// Send an RPC to let everyone know what the name is for this player
		// We use "AllBuffered" so that if people come late they will get the
		// latest name for this object
		// We pass in "Name" for the args because we have 1 argument that is to
		// be a string as it is set in the NCW
		networkObject.SendRpc(RPC_UPDATE_NAME, Receivers.AllBuffered, Name);
	}

	// Default Unity update method
	private void Update()
	{
		// Check to see if we are the owner of this player
		if (!networkObject.IsOwner)
		{
			// If we are not the owner then we set the position to the
			// position that is syndicated across the network for this player
			transform.position = networkObject.position;
			return;
		}

		// When our position changes the networkObject.position will detect the
		// change based on this assignment automatically, this data will then be
		// syndicated across the network on the next update pass for this networkObject
		networkObject.position = transform.position;
	}

	// Override the abstract RPC method that we made in the NCW
	public override void UpdateName(RpcArgs args)
	{
		// Since there is only 1 argument and it is a string we can safely
		// cast the first argument to a string knowing that it is going to
		// be the name for this player
		Name = args.GetNext<string>();
	}
}
```

This is all the code we need to allow for all of the connections to see the movement of the players. The next thing we need is to be able to actually instantiate our **Player** prefab since it will not be in the scene at the start of the game. To do this let's open the **NCW** window again.

1. Click the **Create** button
2. Type in **GameLogic** in the name box
3. Click the **Add RPC** button
    1. Type **PlayerScored** into the text field
    2. Open the **Arguments** cascade
        1. Click the ![add-button](https://raw.githubusercontent.com/BeardedManStudios/ForgeNetworkingRemastered/develop/docs/mkdocs/docs/images/add.png "Add Button") button
        2. Type **playerName** into the text field
        3. Click the drop down iv.  Select **STRING** from the drop down
4. Click **Save & Compile**

What this will do is create and modify some classes in the **Generated** folder of your project. Before we continue to add the other network contracts, let's setup our **GameLogic** class.

1. Open the **Scripts** folder
2. Create a new C# script named **GameLogic**
3. Select the **Game Logic** Game Object from the **Hierarchy** of our previously saved scene
4. Click **Add Component**
5. Add the **GameLogic** script to the Game Object
6. Select the **Scripts** folder
7. Open the **GameLogic.cs** script you just created
8. Insert the following code

### GameManager.cs
```csharp
// We use this namespace as it is where our GameLogicBehavior was generated
using BeardedManStudios.Forge.Networking.Generated;
using BeardedManStudios.Forge.Networking.Unity;
using UnityEngine;
using UnityEngine.UI;

// We extend GameLogicBehavior which extends NetworkBehavior which extends MonoBehaviour
public class GameLogic : GameLogicBehavior
{
	public Text scoreLabel;
	private void Start()
	{
		// This will be called on every client, so each client will essentially instantiate
		// their own player on the network. We also pass in the position we want them to spawn at
		NetworkManager.Instance.InstantiatePlayer(position: new Vector3(0, 5, 0));
	}

	// Override the abstract RPC method that we made in the NCW
	public override void PlayerScored(RpcArgs args)
	{
		// Since there is only 1 argument and it is a string we can safely
		// cast the first argument to a string knowing that it is going to
		// be the name for the scoring player
		string playerName = args.GetNext<string>();

		// Update the UI to show the last player that scored
		scoreLabel.text = "Last player to score was: " + playerName;
	}
}
```

Now we are able to not only spawn the player, but we are also able to print out the last player that scored to the screen. Talking about scoring, we possibly want to get the ball rolling (if you would excuse the expression) and instantiate the **ball** and serialize it's position to all the clients. However just before that, lets fill out our scoreLabel object on our **Game Logic** Game Object.

1. Select the **Game Logic** from the **hierarchy**
2. Drag the **Last Scored** UI Game Object from the **hierarchy** to the **Score Label** field on the **GameLogic** script

Okay, now we are actually ready to make the ball now! So let's start by opening up the **NCW** window once again.

1. Click the **Create** button
2. Type in **GameBall** into the name box
3. Click the **Add Field** button
    1. Type **position** into the text box
    2. Select the drop down
    3. Select **VECTOR3** from the options
    4. Click the **Interpolate** button and leave the value at **0.15**
4. Click **Save & Compile**

What this will do is create and modify some classes in the **Generated** folder of your project. Before we continue to add the other network contracts, let's setup our **GameBall** class.

1. Open the **Scripts** folder
2. Create a new C# script named **GameBall**
3. Open the **Prefabs** folder and select the **GameBall** prefab
4. Click **Add Component**
5. Add the **GameBall** script to the prefab
6. Select the **Scripts** folder
7. Open the **GameBall.cs** script you just created
8. Insert the following code

### GameBall.cs
```csharp
// We use this namespace as it is where our BallBehavior was generated
using BeardedManStudios.Forge.Networking;
using BeardedManStudios.Forge.Networking.Generated;
using BeardedManStudios.Forge.Networking.Unity;
using UnityEngine;

// We extend BallBehavior which extends NetworkBehavior which extends MonoBehaviour
public class GameBall : GameBallBehavior
{
	private Rigidbody rigidbodyRef;
	private GameLogic gameLogic;

	private void Awake()
	{
		rigidbodyRef = GetComponent<Rigidbody>();
		gameLogic = FindObjectOfType<GameLogic>();
	}

	// Default Unity update method
	private void Update()
	{
		// Check to see if we are the owner of this ball
		if (!networkObject.IsOwner)
		{
			// If we are not the owner then we set the position to the
			// position that is syndicated across the network for this ball
			transform.position = networkObject.position;
			return;
		}

		// When our position changes the networkObject.position will detect the
		// change based on this assignment automatically, this data will then be
		// syndicated across the network on the next update pass for this networkObject
		networkObject.position = transform.position;
	}

	public void Reset()
	{
		// Move the ball to 0, 10, 0
		transform.position = Vector3.up * 10;

		// Reset the velocity for this object to zero
		rigidbodyRef.velocity = Vector3.zero;

		// Create a random force to apply to this object between 300 to 500 or -300 to -500
		Vector3 force = new Vector3(0, 0, 0);
		force.x = Random.Range(300, 500);
		force.z = Random.Range(300, 500);

		// Randomly invert along the number line by 50%
		if (Random.value < 0.5f)
			force.x *= -1;

		if (Random.value < 0.5f)
			force.z *= -1;

		// Add the random force to the ball
		rigidbodyRef.AddForce(force);
	}

	private void OnCollisionEnter(Collision c)
	{
		// We are making this authoritative by only
		// allowing the server to call it
		if (!networkObject.IsServer)
			return;

		// Only move if a player touched the ball
		if (c.GetComponent<Player>() == null)
			return;

		// Call an RPC on the Game Logic to print the player's name as the last
		// player to touch the ball
		gameLogic.networkObject.SendRpc(GameLogicBehavior.RPC_PLAYER_SCORED, Receivers.All,

		c.GetComponent<Player>().Name);

		// Reset the ball
		Reset();
	}
}
```

With the ball complete, we are finally ready to move onto the last script that we will need to create, the behavior for the trigger that starts the whole game!

1. Open the **Scripts** folder
2. Create a new C# script named **GameTrigger**
3. Select the **Start Trigger** Game Object from the **Hierarchy** of our previously saved scene
4. Click **Add Component**
5. Add the **GameTrigger** script to the Game Object
6. Select the **Scripts** folder
7. Open the **GameTrigger.cs** script you just created
8. Insert the following code

### GameTrigger.cs
```csharp
using BeardedManStudios.Forge.Networking.Unity;
using UnityEngine;

public class GameTrigger : MonoBehaviour
{
	private bool started;

	private void Update()
	{
		// If the game started we will remove this trigger from the scene
		if (FindObjectOfType<GameBall>() != null)
			Destroy(gameObject);
	}

	private void OnTriggerEnter(Collider c)
	{
		// Since we added 2 sphere colliders to the player, we need to
		// make sure to only trigger this 1 time
		if (started)
			return;

		// Only allow the server player to start the game so that the
		// server is the owner of the ball, otherwise if a client is the
		// owner of the ball, if they disconnect, the ball will be destroyed
		if (!NetworkManager.Instance.IsServer)
			return;

		Player player = c.GetComponent<Player>();

		if (player == null)
			return;

		started = true;

		// We need to create the ball on the network
		GameBall ball = NetworkManager.Instance.InstantiateGameBall() as GameBall;

		// Reset the ball position and give it a random velocity
		ball.Reset();

		// We no longer need this trigger, the game has started
		Destroy(gameObject);
	}
}
```

**Finalization of our game!**

Now that we have finished all of the network code, we need to tell Forge what prefabs are suppose to be instantiated when we make those **NetworkManager.Instance.Instantiat...** calls.

1. Open **Bearded Man Studios Inc>Prefabs**
2. Select the prefab named **NetworkManager**
3. Locate the various empty fields in the **NetworkManager** component that is attached to this prefab
4. In the **GameBall Network Object** array field, put the **GameBall** prefab from the **Prefabs** folder as the **Element 0** (0th index)
5. In the **Player Network Object** array field, put the **Player** prefab from the **Prefabs** folder as the **Element 0** (0th index)

## Congratulations

You have completed the steps for this tutorial. All that is left is to build, run and test it out. To do this just build the project as you normally would do within the Unity Editor.

1. Build the project
2. Run 2 instances of the project
3. Select **Host** in one instance
4. Click **Connect** in the second instance
5. You may be prompted to allow access to the application on the firewall, which you will need to accept

## Troubleshooting

**Getting a null reference exception?**

The most common user errors with this part of the documentation are:

- Forgot to turn on Run in Background*
- Tried pressing the play button in the scene and not loading the Multiplayer Menu scene first
- Not setting up the multiplayer menu scene as index 0 and the demo scene as index 1

redpajama_set_name: RedPajamaGithub


text:
/* $Id$ */

package org.apache.fop.visual;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.io.IOUtils;

import org.apache.batik.ext.awt.image.GraphicsUtil;
import org.apache.batik.ext.awt.image.renderable.Filter;
import org.apache.batik.ext.awt.image.spi.ImageTagRegistry;
import org.apache.batik.util.ParsedURL;

/**
 * Helper class to visually compare two bitmap images.
 *

 * This class was created by extracting reusable code from
 * org.apache.batik.test.util.ImageCompareText (Apache Batik)
 * into this separate class.
 *

 * TODO Move as utility class to XML Graphics Commons when possible
 */
public final class BitmapComparator {

    private BitmapComparator() {
    }

    /**
     * Builds a new BufferedImage that is the difference between the two input images
     * @param ref the reference bitmap
     * @param gen the newly generated bitmap
     * @return the diff bitmap
     */
    public static BufferedImage buildDiffImage(BufferedImage ref,
                                               BufferedImage gen) {
        BufferedImage diff = new BufferedImage(ref.getWidth(),
                                               ref.getHeight(),
                                               BufferedImage.TYPE_INT_ARGB);
        WritableRaster refWR = ref.getRaster();
        WritableRaster genWR = gen.getRaster();
        WritableRaster dstWR = diff.getRaster();

        boolean refPre = ref.isAlphaPremultiplied();
        if (!refPre) {
            ColorModel     cm = ref.getColorModel();
            cm = GraphicsUtil.coerceData(refWR, cm, true);
            ref = new BufferedImage(cm, refWR, true, null);
        }
        boolean genPre = gen.isAlphaPremultiplied();
        if (!genPre) {
            ColorModel     cm = gen.getColorModel();
            cm = GraphicsUtil.coerceData(genWR, cm, true);
            gen = new BufferedImage(cm, genWR, true, null);
        }

        int w = ref.getWidth();
        int h = ref.getHeight();

        int [] refPix = null;
        int [] genPix = null;
        for (int y = 0; y < h; y++) {
            refPix = refWR.getPixels(0, y, w, 1, refPix);
            genPix = genWR.getPixels(0, y, w, 1, genPix);
            for (int i = 0; i < refPix.length; i++) {
                // val = ((genPix[i] - refPix[i]) * 5) + 128;
                int val = ((refPix[i] - genPix[i]) * 10) + 128;
                if ((val & 0xFFFFFF00) != 0) {
                    if ((val & 0x80000000) != 0) {
                        val = 0;
                    } else {
                        val = 255;
                    }
                }
                genPix[i] = val;
            }
            dstWR.setPixels(0, y, w, 1, genPix);
        }

        if (!genPre) {
            ColorModel cm = gen.getColorModel();
            cm = GraphicsUtil.coerceData(genWR, cm, false);
        }

        if (!refPre) {
            ColorModel cm = ref.getColorModel();
            cm = GraphicsUtil.coerceData(refWR, cm, false);
        }

        return diff;
    }

    /**
     * Builds a combined image that places a number of images next to each other for
     * manual, visual comparison.
     * @param images the array of bitmaps
     * @return the combined image
     */
    public static BufferedImage buildCompareImage(BufferedImage[] images) {
        BufferedImage cmp = new BufferedImage(
                images[0].getWidth() * images.length,
                images[0].getHeight(), BufferedImage.TYPE_INT_ARGB);

        Graphics2D g = cmp.createGraphics();
        g.setPaint(Color.white);
        g.fillRect(0, 0, cmp.getWidth(), cmp.getHeight());
        int lastWidth = 0;
        for (int i = 0; i < images.length; i++) {
            if (lastWidth > 0) {
                g.translate(lastWidth, 0);
            }
            if (images[i] != null) {
                g.drawImage(images[i], 0, 0, null);
                lastWidth = images[i].getWidth();
            } else {
                lastWidth = 20; //Maybe add a special placeholder image instead later
            }
        }
        g.dispose();

        return cmp;
    }

    /**
     * Builds a combined image that places two images next to each other for
     * manual, visual comparison.
     * @param ref the reference image
     * @param gen the actual image
     * @return the combined image
     */
    public static BufferedImage buildCompareImage(BufferedImage ref,
            BufferedImage gen) {
        return buildCompareImage(new BufferedImage[] {ref, gen});
    }

    /**
     * Loads an image from a URL
     * @param url the URL to the image
     * @return the bitmap as BufferedImage
     * TODO This method doesn't close the InputStream opened by the URL.
     */
    public static BufferedImage getImage(URL url) {
        ImageTagRegistry reg = ImageTagRegistry.getRegistry();
        Filter filt = reg.readURL(new ParsedURL(url));
        if (filt == null) {
            return null;
        }

        RenderedImage red = filt.createDefaultRendering();
        if (red == null) {
            return null;
        }

        BufferedImage img = new BufferedImage(red.getWidth(),
                                              red.getHeight(),
                                              BufferedImage.TYPE_INT_ARGB);
        red.copyData(img.getRaster());

        return img;
    }

    /**
     * Loads an image from a URL
     * @param bitmapFile the bitmap file
     * @return the bitmap as BufferedImage
     */
    public static BufferedImage getImage(File bitmapFile) {
        try {
            InputStream in = new java.io.FileInputStream(bitmapFile);
            try {
                in = new java.io.BufferedInputStream(in);

                ImageTagRegistry reg = ImageTagRegistry.getRegistry();
                Filter filt = reg.readStream(in);
                if (filt == null) {
                    return null;
                }

                RenderedImage red = filt.createDefaultRendering();
                if (red == null) {
                    return null;
                }

                BufferedImage img = new BufferedImage(red.getWidth(),
                                                      red.getHeight(),
                                                      BufferedImage.TYPE_INT_ARGB);
                red.copyData(img.getRaster());
                return img;
            } finally {
                IOUtils.closeQuietly(in);
            }
        } catch (IOException e) {
            return null;
        }
    }

}


text:
pub enum Direction {
    Up = 1,
    Down = 0,
}

/// A command to send to the hardware
pub enum Command {

    /// An internal command
    #[doc(hidden)]
    __Internal,

    /// Move the box either up or down
    MoveBox(Direction),

    /// Enable or disable lights
    Lighting(bool),

    /// Turn page, sending spine width
    FlipPage(u8),
}

impl Command {

    /// Encode a command into a byte array
    pub fn encode(self) -> Vec<u8> {
        use Command::*;
        match self {
            MoveBox(dir) => vec![0b00000010, dir as u8],
            Lighting(state) => vec![0b00000100, state as u8],
            FlipPage(spine) => vec![0b00001000, spine],
            _ => unreachable!() // panic on "__Internal"
        }
    }
}

#[derive(Debug)]
pub enum Status {
    Cool,
    Error(u8),
}

impl From<u8> for Status {
    fn from(code: u8) -> Self {
        match code {
            0 => Status::Cool,
            err => Status::Error(err),
        }
    }
}

/// Ab abstraction over responses sent by the hardware
///
/// If no payload was present `payload` is an empty vector
#[derive(Debug)]
pub struct Response {
    status: Status,
    payload: Vec<u8>,
}

impl Response {
    /// Pass a lambda that returns a byte via reads
    pub fn build<F>(mut req_byte: F) -> Option<Self>
    where
        F: FnMut() -> Option<u8>,
    {
        let status = req_byte()?.into();
        let len = req_byte()?;

        let payload = (0..len).map(|_| req_byte()).fold(Some(Vec::new()), |mut vec, byte| {
            match (&mut vec, byte) {
                (Some(ref mut v), Some(b)) => v.push(b),
                _ => return None,
            };

            vec
        })?;

        Some(Self { status, payload })
    }
}


text:
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Backend.Interfaces;
using Backend.ViewModels.Authentication;
using Portal.Common.IoC;
using Portal.Web.Models;

namespace Backend.Web.Controllers
{
    public class AuthController : BaseController
    {

        #region Instances Variables

        private readonly IAuthentication authenticationLogic = IoC.Instance.Resolve<IAuthentication>();

        #endregion
        // GET: Auth
        [HttpGet]
        public ActionResult Login()
        {
            if (this.Request.IsAuthenticated)
            {
                return this.RedirectToAction("Index", "Home");
            }

            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
                {
                    return this.View();
                }

                var response = this.authenticationLogic.Login(request.Username, request.Password);

                if (response != null)
                {
                    var formAuthCookie = new HttpCookie(response.FormsAuthCookieName, response.FormsAuthCookieValue);
                    this.Response.Cookies.Add(formAuthCookie);

                    return this.RedirectToAction("Index", "Home");
                }

                var error = "username or password is incorrect";
                if (response != null && !string.IsNullOrEmpty(response.Message))
                {
                    error = response.Message;
                }

                this.ModelState.AddModelError("Username", error);
                return this.View();
            }
            catch (Exception ex)
            {
                return this.View();
            }
        }

        public ActionResult LogOff()
        {
            if (!this.Request.IsAuthenticated)
            {
                return this.RedirectToAction("Index", "Home");
            }

            var user = this.User;

            FormsAuthentication.SignOut();

            return this.RedirectToAction("Index", "Home");
        }
    }
}


text:
Promise based mongo driver built on mongojs

[![Build Status](https://img.shields.io/travis/then/then-mongo/master.svg)](https://travis-ci.org/then/then-mongo)
[![Dependency Status](https://img.shields.io/david/then/then-mongo.svg)](https://david-dm.org/then/then-mongo)
[![NPM version](https://img.shields.io/npm/v/then-mongo.svg)](https://www.npmjs.com/package/then-mongo)

## Installation

    npm install then-mongo

## Usage

Emulates the [offical mongo api](https://docs.mongodb.org/manual/reference/method/) as far as is possible, except that the result of every operation is a promise, rather than being synchronous.

```js
var mongo = require('then-mongo');
var db = mongo('connection-string', ['collectionA', 'collectionB']);

db.collectionA.find().skip(5).limit(10)
  .done(function (results) {
    console.dir(results);
  });
```

## API

Exports a function `connect(connectionString, collections?, options?)` and returns an instance of [Database](docs/database.md).  If you pass in a list of collection names, then you can access each [Collection](docs/collection.md) as a property of the [Database](docs/database.md) instance.

## License

  MIT


text:
describe("SpinalTap.Persistence", function() {
  describe("load", function() {
    it("extends the provided options with defaultLoadOptions and passes them to $.ajax", function() {
      spyOn(SpinalTap.Persistence, 'defaultLoadOptions').andReturn({base: "opts"});
      spyOn(SpinalTap.$, 'ajax').andReturn("ajaxed");

      var result = SpinalTap.Persistence.load("record", {more: "opts"});
      expect(result).toEqual("ajaxed");
      expect(SpinalTap.Persistence.defaultLoadOptions).toHaveBeenCalledWith("record");
      expect(SpinalTap.$.ajax).toHaveBeenCalledWith({base: "opts", more: "opts"});
    });
  });

  describe("defaultLoadOptions", function() {
    it("gets the url of a model", function() {
      var model = new SpinalTap.Model({url: "dummy://url"});

      var result = SpinalTap.Persistence.defaultLoadOptions(model);
      expect(result).toEqual({url: "dummy://url", dataType: "json"});
    });

    it("gets the url of a record", function() {
      var record = new SpinalTap.Model({url: "dummy://url"}).newRecord({id: 123});

      var result = SpinalTap.Persistence.defaultLoadOptions(record);
      expect(result).toEqual({url: "dummy://url/123", dataType: "json"});
    });
  });

  describe("save", function() {
    beforeEach(function() {
      record = new SpinalTap.Model({url: "dummy://url"}).newRecord({id: 123});
    });

    it("extends the provided options with defaultSaveOptions and passes them to $.ajax", function() {
      spyOn(SpinalTap.Persistence, 'defaultSaveOptions').andReturn({base: "opts"});
      spyOn(SpinalTap.$, 'ajax').andReturn("ajaxed");

      var result = SpinalTap.Persistence.save(record, {more: "opts"});
      expect(result).toEqual("ajaxed");
      expect(SpinalTap.Persistence.defaultSaveOptions).toHaveBeenCalledWith(record);
      expect(SpinalTap.$.ajax).toHaveBeenCalledWith({base: "opts", more: "opts"});
    });

    it("triggers a beforeSave event", function() {
      spyOn(SpinalTap.$, 'ajax');

      var triggered;
      record.registerEvents({beforeSave: function() { triggered = true; }});

      var result = SpinalTap.Persistence.save(record, {more: "opts"});
      expect(triggered).toEqual(true);
    });
  });

  describe("defaultSaveOptions", function() {
    var record;

    beforeEach(function() {
      record = new SpinalTap.Model({url: "dummy://url"}).newRecord({id: 123});
    });

    it("uses POST for a new record", function() {
      record.a.id = null;
      var result = SpinalTap.Persistence.defaultSaveOptions(record);
      expect(result.url).toEqual("dummy://url");
      expect(result.method).toEqual("POST");
    });

    it("uses PUT for an existing record", function() {
      var result = SpinalTap.Persistence.defaultSaveOptions(record);
      expect(result.url).toEqual("dummy://url/123");
      expect(result.method).toEqual("PUT");
    });

    it("gets the saveable attributes and runs them through attributesToWire", function() {
      spyOn(record, "getSaveableAttributes").andReturn("gsa");
      spyOn(record, "attributesToWire").andReturn("wired");

      var result = SpinalTap.Persistence.defaultSaveOptions(record);
      expect(result.data).toEqual("wired");
      expect(record.attributesToWire).toHaveBeenCalledWith("gsa");
    });

    it("sets dataType to json", function() {
      var result = SpinalTap.Persistence.defaultSaveOptions(record);
      expect(result.dataType).toEqual("json");
    });
  });
});


text:
using System;
using System.Net;

namespace Nowin
{
    public interface ITransportLayerHandler : ILayerHandler
    {
        ITransportLayerCallback Callback { set; }
        void PrepareAccept();
        void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint);

        // length==-1 for connection closed
        void FinishReceive(byte[] buffer, int offset, int length);
        void FinishSend(Exception exception);
    }
}


text:
<?php
namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class EmailType extends AbstractType
{
    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email')
            ->add('submit', 'submit');
    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['data_class' => 'AppBundle\Model\Email']);
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'app_email';
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: gseidel
 * Date: 2020-06-11
 * Time: 22:35
 */

namespace Enhavo\Bundle\DoctrineExtensionBundle\Metadata\Provider;

use Enhavo\Bundle\DoctrineExtensionBundle\Metadata\Metadata;
use Enhavo\Bundle\DoctrineExtensionBundle\Metadata\Reference;
use Enhavo\Component\Metadata\Exception\ProviderException;
use Enhavo\Component\Metadata\Metadata as BaseMetata;
use Enhavo\Component\Metadata\ProviderInterface;

class ReferenceProvider implements ProviderInterface
{
    public function provide(BaseMetata $metadata, $normalizedData)
    {
        if(!$metadata instanceof Metadata) {
            throw ProviderException::invalidType($metadata, Metadata::class);
        }

        if(array_key_exists('reference', $normalizedData) && is_array($normalizedData['reference'])) {
            foreach($normalizedData['reference'] as $name => $referenceData) {
                if(!is_array($referenceData)) {
                    throw ProviderException::definitionMissing($metadata, ['idField', 'nameField']);
                } elseif(!array_key_exists('nameField', $referenceData)) {
                    throw ProviderException::definitionMissing($metadata, 'nameField');
                } elseif(!array_key_exists('idField', $referenceData)) {
                    throw ProviderException::definitionMissing($metadata, 'idField');
                }
                $metadata->addReference(new Reference($name, $referenceData['nameField'], $referenceData['idField']));
            }
        }
    }
}


text:
$.oip = $.oip || {}
$.oip.ajax = $.oip.ajax || {}

$.oip.ajax.getCities = function(pattern, callback) {

    if (pattern != '')
    {
        $.oip.ajax.get(('show_cities'), { _format: 'json' },
            { s: pattern, small: true }, callback);
    }
}

$.oip.ajax.getJSON = function(route, route_params, data, callback) {
    $.get(
        Routing.generate(route, route_params),
        data,
        function(data)
        {
            callback(data);
        }, 'json');
}

$.oip.ajax.get = function(route, route_params, data, callback) {
    $.get(
        Routing.generate(route, route_params),
        data,
        function(data)
        {
            callback(data);
        });
}

$.oip.ajax.postJSON = function(route, route_params, data, callback) {
    $.post(
        Routing.generate(route, route_params),
        data,
        function(data)
        {
            callback(data);
        },
        'json');
}

$.oip.ajax.post = function(route, route_params, data, callback) {
    $.post(
        Routing.generate(route, route_params),
        data,
        function(data)
        {
            callback(data);
        });
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.forbesdigital</groupId>
		<artifactId>dummyArtifact</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>

	<artifactId>dummyArtifact-war</artifactId>
	<name>Dummy Project WAR</name>
	<packaging>war</packaging>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<skip>true</skip>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<webResources>
						<resource>
							<filtering>true</filtering>
							<directory>src/main/webapp/WEB-INF</directory>
							<targetPath>WEB-INF</targetPath>
							<includes>
								<include>sun-web.xml</include>
								<include>web.xml</include>
							</includes>
							<excludes>
								<exclude>pages/**</exclude>
							</excludes>
						</resource>
					</webResources>
				</configuration>
			</plugin>
		</plugins>

		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
	</build>

	<dependencies>
		<dependency>
			<groupId>com.forbesdigital</groupId>
			<artifactId>dummyArtifact-ejb</artifactId>
			<version>${project.version}</version>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
		</dependency>

		<dependency>
			<groupId>org.glassfish.jersey.media</groupId>
			<artifactId>jersey-media-json-jackson</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.reflections</groupId>
			<artifactId>reflections</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
	</dependencies>
</project>


text:
Read and write to users recent plays on Last.fm.

## Installation

    npm install lastfm

## Usage

    var LastFmNode = require('lastfm').LastFmNode;

    var lastfm = new LastFmNode({
      api_key: 'apikey',    // sign-up for a key at http://www.last.fm/api
      secret: 'secret',
      useragent: 'appname/vX.X MyApp' // optional. defaults to lastfm-node.
    });

## Documentation

### LastFmRequest

    lastfm.request(method, options);

Returns a `LastFmRequest` instance.

Send request to Last.fm. Requests automatically include the API key and are signed and/or sent via POST as described in the Last.fm API documentation.

Methods:

Accepts any Last.fm API method name, eg "artist.getInfo".

Options:

All options are passed through to Last.fm with the exception of the following.

- *write*

        Force request to act as a write method. Write methods are signed and sent via POST. Useful for new methods not yet recognised by lastfm-node.

- *signed*

        Force request to be signed. See Last.fm API docs for signature details. Useful for new methods not yet recognised by lastfm-node.

- *handlers*

        Default event handlers to attach to the request object on creation.

Events:

- *success(json)*

        JSON response from Last.fm

- *error(error)*

        Ruh-roh. Either a error returned by Last.fm or a transmission error.

### RecentTracksStream

    lastfm.stream(username);

Returns: a `RecentTracksStream` instance

Methods:

- *start()*

        Start streaming recent track info.

- *stop()*

        Stop streaming recent track info.

- *isStreaming()*

        Boolean. True is nowplaying/recent track data is being actively fetched.

- *on(event, listener)*

        Adds a listener for the specified event.

- *removeListener(event, listener)*

        Removes the listener for the specified event.

Options:

- *autostart*

        Start streaming automatically. Defaults to false.

- *handlers*

        Default event handlers to attach to the request object on creation.

Events:

- *lastPlayed(track)*

        The user's last scrobbled track.

- *nowPlaying(track)*

        Track the user is currently listening to.

- *scrobbled(track)*

        Now playing track has been scrobbled.

- *stoppedPlaying(track)*

        User stopped listening to current track.

- *error(error)*

        Ruh-roh.

### LastFmSession

    lastfm.session([user], [key]);

Returns: a `LastFmSession` instance.

If no key is supplied then the authorise() method must be used before the session can be used to make authenticated calls. See the last.fm API documentation for more info.

Public properties:

- *user*

        The username of the Last.fm user associated with the session.

- *key*

        The session key. Either passed in or generated using authorise().

Methods:

- *authorise(token, [options])*

        Authorises user with Last.fm api. See last.fm documentation. Options argument has handlers property that has default event handlers to attach to the LastFmSession instance.

- *on(event, handler)*

        Adds a listener for the specified event.

- *removeListener(event, handler)*

        Removes the listener for the specified event.

- *isAuthorised()*

        Returns true if the session has been authorised or a key was specified in the constructor.

Events:

- *authorised(session)*

        Authorisation of session was successful.
        Note: Only emitted after a call to authorise(). Keys supplied in the constructor are assumed to be valid.

- *error(track, error)*

        Ruh-roh.

### LastFmUpdate

    lastfm.update(method, session, options);

Returns a `LastFmUpdate` instance.

Valid methods are 'nowplaying' and 'scrobble'.

An authorised `LastFmSession` instance is required to make a successful update.

If a scrobble request receives an 11 (service offline), 16 (temporarily unavailable) or 29 (rate limit exceeded) error code from Last.fm then the request is automatically retried until it is permanently rejected or accepted. The first retry attempt is made after 10 seconds with subsequent requests delayed by 30 seconds, 1 minute, 5 minutes, 15 minutes and then every 30 minutes.

Options:

Accepts all parameters used by track.updateNowPlaying and user.scrobble (see Last.Fm API) as well as:

- *track*

        Track for nowplaying and scrobble requests. Uses same format as returned by `RecentTracksStream` events.

- *timestamp*

        Required for scrobble requests. Timestamp is in unix time (seconds since 01-01-1970 and is in UTC time).

- *handlers*

        Default event handlers to attach to the request object on creation.

Events:

- *success(track)*

       Update request was successful.

- *retrying(retry)*

       Scrobble request was not successful but will be retried after a delay. Retry object contains the following properties:
       `delay` - The time in milliseconds before the request will be retried.
       `error` - The error code returned by the Last.fm API.
       `message` - The error message returned by the Last.fm API.

- *error(track, error)*

        Ruh-roh.

### LastFmInfo

    lastfm.info(itemtype, [options]);

Returns: a `LastFmInfo` instance.

Gets extended info about specified item.

Public properties:

- *itemtype*

        Any Last.fm item with a getInfo method. eg user, track, artist, etc.

Options:

- *handlers*

        Event handlers to attach to object at creation.

- *various*

       Params as specified in Last.fm API, eg user: "username"

Special cases:

When requesting track info the `track` param can be either the track name or a track object as returned by `RecentTracksStream`.

## Example

    var LastFmNode = require('lastfm').LastFmNode;

    var lastfm = new LastFmNode({
      api_key: 'abc',
      secret: 'secret'
    });

    var trackStream = lastfm.stream('username');

    trackStream.on('lastPlayed', function(track) {
      console.log('Last played: ' + track.name);
    });

    trackStream.on('nowPlaying', function(track) {
      console.log('Now playing: ' + track.name);
    });

    trackStream.on('scrobbled', function(track) {
      console.log('Scrobbled: ' + track.name);
    });

    trackStream.on('stoppedPlaying', function(track) {
      console.log('Stopped playing: ' + track.name);
    });

    trackStream.on('error', function(error) {
      console.log('Error: '  + error.message);
    });

    trackStream.start();

    var session = lastfm.session();
    session.authorise(token, {
       handlers: {
          authorised: function(session) {
             lastfm.update('nowplaying', session, { track: track } );
             lastfm.update('scrobble', session, { track: track, timestamp: 12345678 });
          }
       }
    });

    var request = lastfm.request("artist.getInfo", {
        artist: "The Mae Shi",
        handlers: {
            success: function(data) {
                console.log("Success: " + data);
            },
            error: function(error) {
                console.log("Error: " + error.message);
            }
        }
    });

## Influences

Heavily drawn from technoweenie's twitter-node
http://github.com/technoweenie/twitter-node

## Contributors

* Garret Wilkin (garrettwilkin) - http://geethink.com
* Uwe L. Korn (xhochy) - http://xhochy.com
* Max Kueng (maxkueng) - http://maxkueng.com


text:
require 'spec_helper'

describe ExpenseGroup do
  let(:group) { FactoryBot.create(:expense_group) }

  it "can be created by the factory" do
    expect(group).to be_valid
  end

  it "must have a name" do
    group.group_name = nil
    expect(group).not_to be_valid
  end

  it "must have a visible setting of true or false" do
    group.visible = nil
    expect(group).to be_invalid

    group.visible = true
    expect(group).to be_valid
  end

  it "cannot have both the info_page_id and info_url set" do
    group.info_page = FactoryBot.create(:page)
    group.info_url = "http://www.google.com"
    expect(group).to be_invalid
  end

  it "can have the info_page_id set" do
    group.info_page = FactoryBot.create(:page)
    expect(group).to be_valid
  end

  it "has a nice to_s" do
    expect(group.to_s).to eq(group.group_name)
  end

  it "onlies list the visible groups" do
    @group2 = FactoryBot.create(:expense_group, visible: true)
    group # reference to build it
    described_class.visible == [group]
  end

  it "defaults to not required" do
    group = described_class.new
    expect(group.competitor_required).to eq(false)
    expect(group.noncompetitor_required).to eq(false)
  end

  it "requires that the 'required' fields be set" do
    group.competitor_required = nil
    expect(group).to be_invalid

    group.competitor_required = false
    group.noncompetitor_required = nil
    expect(group).to be_invalid
  end

  describe "with expense_items" do
    before do
      @item2 = FactoryBot.create(:expense_item, expense_group: group)
      @item1 = FactoryBot.create(:expense_item, expense_group: group)
      @item2.update_attribute(:position, 2)
    end

    it "orders the items by position" do
      expect(group.expense_items).to eq([@item1, @item2])
    end
  end

  describe "with multiple expense groups" do
    before do
      group.position = 1
      group.visible = false
      group.save
      @group3 = FactoryBot.create(:expense_group)
      @group2 = FactoryBot.create(:expense_group)
      @group4 = FactoryBot.create(:expense_group)
      @group3.update(position: 3)
    end

    it "lists them in order" do
      expect(described_class.all).to eq([group, @group2, @group3, @group4])
    end

    it "lists the 'visible' ones in order" do
      expect(described_class.visible).to eq([@group2, @group3, @group4])
    end
  end
end


text:
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

# [2.0.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.11.0...v2.0.0) (2021-03-18)

### Bug Fixes

- Fixed React strict mode warnings by upgrading to new React context API and removing legacy refs ([#624](https://github.com/clauderic/react-sortable-hoc/pull/624)). Since the new context API was introduced in React ^16.3.0, the peer dependencies had to be upgraded accordingly.
- Check if event is cancellable before calling `event.preventDefault()` [#752](https://github.com/clauderic/react-sortable-hoc/pull/752).
- Fix touch events being lost by listening to event.target on mobile [#586](https://github.com/clauderic/react-sortable-hoc/pull/586).
- Added `disableAutoscroll` prop to PropType definitions [#755](https://github.com/clauderic/react-sortable-hoc/pull/755).

### Dependencies

- Updated minimum peer dependencies for `react` and `react-dom` to ^16.3.0. Added ^17.0.0 to list of supported peer dependencies.

# [1.11.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.10.1...v1.11.0) (2020-01-20)

### Bug Fixes

- clear autoscroller when autoscroll is disabled ([#604](https://github.com/clauderic/react-sortable-hoc/issues/604)) ([3fd83f9](https://github.com/clauderic/react-sortable-hoc/commit/3fd83f9))
- Fix UMD path ([#611](https://github.com/clauderic/react-sortable-hoc/pull/611)) ([f61331d](https://github.com/clauderic/react-sortable-hoc/commit/f61331d))

### Features

- Add CSS Grid grid-gap support ([#657](https://github.com/clauderic/react-sortable-hoc/issues/657)) ([4efcaa2](https://github.com/clauderic/react-sortable-hoc/commit/4efcaa2))

## [1.10.1](https://github.com/clauderic/react-sortable-hoc/compare/v1.10.0...v1.10.1) (2019-08-22)

### Bug Fixes

- PropType definition for keyCodes was incorrect ([eaf5070](https://github.com/clauderic/react-sortable-hoc/commit/eaf5070))

# [1.10.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.9.1...v1.10.0) (2019-08-22)

### Bug Fixes

- don't spread the keysToOmit parameter in omit util ([#563](https://github.com/clauderic/react-sortable-hoc/issues/563)) ([1c69772](https://github.com/clauderic/react-sortable-hoc/commit/1c69772))
- Fix broken UMD build ([#587](https://github.com/clauderic/react-sortable-hoc/issues/587)) ([6cb7750](https://github.com/clauderic/react-sortable-hoc/commit/6cb7750))
- remove browser field with umd bundle ([#541](https://github.com/clauderic/react-sortable-hoc/issues/541)) ([d3b30fd](https://github.com/clauderic/react-sortable-hoc/commit/d3b30fd)

### Features

- Add keyCodes prop to configure the keyboard shortcuts ([#588](https://github.com/clauderic/react-sortable-hoc/issues/588)) ([4c6d8dd](https://github.com/clauderic/react-sortable-hoc/commit/4c6d8dd))

## [1.9.1](https://github.com/clauderic/react-sortable-hoc/compare/v1.9.0...v1.9.1) (2019-04-24)

### Bug Fixes

- do not copy canvas context if it has neither width nor height ([#530](https://github.com/clauderic/react-sortable-hoc/issues/530)) ([3808437](https://github.com/clauderic/react-sortable-hoc/commit/3808437))
- pass isKeySorting to onSortOver and updateBeforeSortStart handler props ([#531](https://github.com/clauderic/react-sortable-hoc/issues/531)) ([763fd33](https://github.com/clauderic/react-sortable-hoc/commit/763fd33)

# [1.9.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.8.3...v1.9.0) (2019-04-23)

### Bug Fixes

- issue with radio input name collision when cloning helper ([5337c97](https://github.com/clauderic/react-sortable-hoc/commit/5337c97))

### Features

- add support for keyboard sorting ([#501](https://github.com/clauderic/react-sortable-hoc/issues/501)) ([439b92f](https://github.com/clauderic/react-sortable-hoc/commit/439b92f))
- prevent sort start on contentEditable target ([d64c8cf](https://github.com/clauderic/react-sortable-hoc/commit/d64c8cf))

## [1.8.3](https://github.com/clauderic/react-sortable-hoc/compare/v1.8.2...v1.8.3) (2019-03-20)

### Bug Fixes

- issue with windowAsScrollContainer and translation offsets ([0391e62](https://github.com/clauderic/react-sortable-hoc/commit/0391e62))

### Features

- Add disableAutoscroll prop ([#484](https://github.com/clauderic/react-sortable-hoc/issues/484)) ([7845e76](https://github.com/clauderic/react-sortable-hoc/commit/7845e76))
- added helperContainer prop ([286eff4](https://github.com/clauderic/react-sortable-hoc/commit/286eff4))
- allow helperContainer prop to be a function returning an HTMLElement ([#489](https://github.com/clauderic/react-sortable-hoc/issues/489)) ([f4a9b4a](https://github.com/clauderic/react-sortable-hoc/commit/f4a9b4a))
- Detect scroll container automatically ([#507](https://github.com/clauderic/react-sortable-hoc/issues/507)) ([6572921](https://github.com/clauderic/react-sortable-hoc/commit/6572921))

## [1.8.2](https://github.com/clauderic/react-sortable-hoc/compare/v1.8.1...v1.8.2) (2019-03-19)

### Bug Fixes

- issue with getComputedStyle and getScrollingParent ([b104249](https://github.com/clauderic/react-sortable-hoc/commit/b104249))

## [1.8.1](https://github.com/clauderic/react-sortable-hoc/compare/v1.8.0...v1.8.1) (2019-03-18)

### Bug Fixes

- issue with cloning canvas context of dragged items ([#512](https://github.com/clauderic/react-sortable-hoc/issues/512)) ([4df34ad](https://github.com/clauderic/react-sortable-hoc/commit/4df34ad))

# [1.8.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.1.0...v1.8.0) (2019-03-18)

### Bug Fixes

- added prop-types to peerDependencies ([0e855c5](https://github.com/clauderic/react-sortable-hoc/commit/0e855c5))
- copy canvas content into cloned node ([43ad122](https://github.com/clauderic/react-sortable-hoc/commit/43ad122))
- get updated index after updateBeforeSortStart ([4471a0a](https://github.com/clauderic/react-sortable-hoc/commit/4471a0a))
- helperContainer PropType definition broke server-side rendering ([#471](https://github.com/clauderic/react-sortable-hoc/issues/471)) ([c0eef97](https://github.com/clauderic/react-sortable-hoc/commit/c0eef97))
- lock axis story should not use lockToContainerEdges ([db1d3a9](https://github.com/clauderic/react-sortable-hoc/commit/db1d3a9))
- omit disableAutoscroll prop ([#502](https://github.com/clauderic/react-sortable-hoc/issues/502)) ([e994e73](https://github.com/clauderic/react-sortable-hoc/commit/e994e73))
- omit spreading helperContainer prop ([#497](https://github.com/clauderic/react-sortable-hoc/issues/497)) ([12bafdf](https://github.com/clauderic/react-sortable-hoc/commit/12bafdf))
- overflow bug while dragging an item upwards in a grid ([1a2c87e](https://github.com/clauderic/react-sortable-hoc/commit/1a2c87e))
- replace process.env.NODE_ENV in UMD builds ([16135df](https://github.com/clauderic/react-sortable-hoc/commit/16135df))
- update helperContainer prop type definition ([#491](https://github.com/clauderic/react-sortable-hoc/issues/491)) ([fd30383](https://github.com/clauderic/react-sortable-hoc/commit/fd30383))
- updated the behaviour of disabled elements ([bd3d041](https://github.com/clauderic/react-sortable-hoc/commit/bd3d041))
- virtualized collection grid bug ([a57975c](https://github.com/clauderic/react-sortable-hoc/commit/a57975c))

### Features

- Add disableAutoscroll prop ([#484](https://github.com/clauderic/react-sortable-hoc/issues/484)) ([7845e76](https://github.com/clauderic/react-sortable-hoc/commit/7845e76))
- added helperContainer prop ([286eff4](https://github.com/clauderic/react-sortable-hoc/commit/286eff4))
- allow helperContainer prop to be a function returning an HTMLElement ([#489](https://github.com/clauderic/react-sortable-hoc/issues/489)) ([f4a9b4a](https://github.com/clauderic/react-sortable-hoc/commit/f4a9b4a))
- Detect scroll container automatically ([#507](https://github.com/clauderic/react-sortable-hoc/issues/507)) ([6572921](https://github.com/clauderic/react-sortable-hoc/commit/6572921))

## [1.7.1](https://github.com/clauderic/react-sortable-hoc/compare/v1.1.0...v1.7.1) (2019-03-06)

### Bug Fixes

- updated the behaviour of disabled elements ([bd3d041](https://github.com/clauderic/react-sortable-hoc/commit/bd3d041))

# [1.7.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.1.0...v1.7.0) (2019-03-06)

### Bug Fixes

- updated the behaviour of disabled elements ([bd3d041](https://github.com/clauderic/react-sortable-hoc/commit/bd3d041))

## [1.6.1](https://github.com/clauderic/react-sortable-hoc/compare/v1.6.0...v1.6.1) (2019-02-11)

### Bug Fixes

- omit disableAutoscroll prop ([#502](https://github.com/clauderic/react-sortable-hoc/issues/502)) ([e994e73](https://github.com/clauderic/react-sortable-hoc/commit/e994e73))

# [1.6.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.5.3...v1.6.0) (2019-02-07)

### Features

- Add disableAutoscroll prop ([#484](https://github.com/clauderic/react-sortable-hoc/issues/484)) ([7845e76](https://github.com/clauderic/react-sortable-hoc/commit/7845e76))

## [1.5.4](https://github.com/clauderic/react-sortable-hoc/compare/v1.5.3...v1.5.4) (2019-02-07)

### Bug Fixes

- overflow bug while dragging an item upwards in a grid ([1a2c87e](https://github.com/clauderic/react-sortable-hoc/commit/1a2c87e))
- virtualized collection grid bug ([a57975c](https://github.com/clauderic/react-sortable-hoc/commit/a57975c))

## [1.5.3](https://github.com/clauderic/react-sortable-hoc/compare/v1.1.0...v1.5.3) (2019-01-25)

### Bug Fixes

- omit spreading helperContainer prop on WrappedComponent ([#497](https://github.com/clauderic/react-sortable-hoc/issues/497)) ([12bafdf](https://github.com/clauderic/react-sortable-hoc/commit/12bafdf))

## [1.5.2](https://github.com/clauderic/react-sortable-hoc/compare/v1.5.1...v1.5.2) (2019-01-22)

### Bug Fixes

- invalid helperContainer PropType definition ([#493](https://github.com/clauderic/react-sortable-hoc/issues/493)) ([dc1d18f](https://github.com/clauderic/react-sortable-hoc/commit/dc1d18f))

## [1.5.1](https://github.com/clauderic/react-sortable-hoc/compare/v1.5.0...v1.5.1) (2019-01-22)

### Bug Fixes

- update helperContainer prop type definition ([#491](https://github.com/clauderic/react-sortable-hoc/issues/491)) ([fd30383](https://github.com/clauderic/react-sortable-hoc/commit/fd30383))

# [1.5.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.4.0...v1.5.0) (2019-01-22)

### Features

- allow helperContainer prop to be a function returning an HTMLElement ([f4a9b4a](https://github.com/clauderic/react-sortable-hoc/commit/f4a9b4a))

# [1.4.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.3.0...v1.4.0) (2019-01-10)

### Bug Fixes

- Fix CommonJS and UMD builds by using Rollup and Babel to generate the bundles ([#474](https://github.com/clauderic/react-sortable-hoc/issues/474))

# [1.3.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.2.0...v1.3.0) (2019-01-08)

### Bug Fixes

- helperContainer PropType definition broke server-side rendering ([#471](https://github.com/clauderic/react-sortable-hoc/issues/471)) ([c0eef97](https://github.com/clauderic/react-sortable-hoc/commit/c0eef97))

# [1.2.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.1.0...v1.2.0) (2019-01-08)

### Features

- added helperContainer prop ([286eff4](https://github.com/clauderic/react-sortable-hoc/commit/286eff4))

# [1.1.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.0.0...v1.1.0) (2019-01-07)

### Features

- added updateBeforeSortStart prop ([162857b](https://github.com/clauderic/react-sortable-hoc/commit/162857b))

# [1.0.0](https://github.com/clauderic/react-sortable-hoc/compare/v0.8.4...v1.0.0) (2019-01-07)

### BREAKING CHANGES

- The UMD release no longer includes babel-polyfill, you will need to include your own polyfills in order to support older browsers.

# 0.8.4

- Fix a bug when you use SortableHandle and distance prop [#447](https://github.com/clauderic/react-sortable-hoc/pull/447)

# 0.8.3

- Fix: TouchEvent is undefined in certain browsers, such as Safari [#382](https://github.com/clauderic/react-sortable-hoc/issues/382)

# 0.8.1

- Fix scrolling issues on mobile with anchor tag elements [#380](https://github.com/clauderic/react-sortable-hoc/pull/380)
- Update TypeScript type definition for ContainerGetter to accept Promises that return HTMLElements

# 0.8.0

- Allow `getContainer` to return a promise. This is useful when the container node is rendered by a parent component, since `componentDidMount` fires backwards (from child to parent) [#155](https://github.com/clauderic/react-sortable-hoc/pull/155/)

# 0.7.4

- Fix typo in getLockPixelOffset helper

# 0.7.3

- Fix issues with distance and pressThreshold props on mobile [#378](https://github.com/clauderic/react-sortable-hoc/pull/378)

# 0.7.2

- Fix issues with TypeScript type definitions

# 0.7.1

- Provide TypeScript type definitions out of the box [#377](https://github.com/clauderic/react-sortable-hoc/pull/377)
- Fix potential issues with calling `removeEventListeners` on `componentWillUnmount` if the container node has already unmounted [#376](https://github.com/clauderic/react-sortable-hoc/pull/376)

# 0.7.0

- [Breaking change] Removed lodash dependency. For users wishing to support Internet Explorer, a [polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#Polyfill) for Array.prototype.find will be required
- Added `onSortOver` prop that gets invoked when sorting over an element [#278](https://github.com/clauderic/react-sortable-hoc/pull/278)
- Fix `useWindowAsScrollContainer` [#306](https://github.com/clauderic/react-sortable-hoc/pull/306)

# 0.6.8

Update react and react-dom peerdependency requirements for React 16+ [#283](https://github.com/clauderic/react-sortable-hoc/pull/283). Thanks [@jnsdls](https://github.com/jnsdls)!

# 0.6.7

Fixes issues with Jest Snapshot testing trying to serialize the `window` object and running out of memory [#249](https://github.com/clauderic/react-sortable-hoc/issues/249). Thanks [@cameronmcefee](https://github.com/cameronmcefee)!

# 0.6.6

Fixes an issue with Internet Explorer 11 introduced in `0.6.5` [#248](https://github.com/clauderic/react-sortable-hoc/pull/248). Thanks [@humiston](https://github.com/humiston)!

# 0.6.5

Fixes the position of the sortable helper when the page is scrolled [#213](https://github.com/clauderic/react-sortable-hoc/pull/213)

# 0.6.4

Fix: when cloning the element that is being sorted, we no longer update the value of cloned file inputs [#232](https://github.com/clauderic/react-sortable-hoc/pull/232)

# 0.6.3

Fixes issues caused by a disabled SortableElement being moved when `distance` is set to a value other than `0`

# 0.6.2

Use `prop-types` package for PropType validation for compatibility with React ^15.5

# 0.6.1

Tweak: default to `pointerEvents: none` on sortable helper, this way the underlying view can still be scrolled using the trackpad/mousewheel while sorting [#160](https://github.com/clauderic/react-sortable-hoc/pull/160)

# 0.6.0

Feature: added `pressThreshold` prop to make `pressDelay` fault tolerant [#159](https://github.com/clauderic/react-sortable-hoc/pull/159)

# 0.5.0

Tweak: `button` elements are now included in the default `shouldCancelStart` implementation [#142](https://github.com/clauderic/react-sortable-hoc/pull/142).
Fix: Omit `getHelperDimensions` before passing down props in `SortableContainer`

# 0.4.12

Fix: This release fixes some issues caused by the `onSortEnd` callback being invoked before `setState` [#82](https://github.com/clauderic/react-sortable-hoc/issues/82).

# 0.4.10

Fix: This version fixes issues with nested `SortableContainer` elements using drag handles from also dragging their parent [#112](https://github.com/clauderic/react-sortable-hoc/issues/112), #127(https://github.com/clauderic/react-sortable-hoc/pull/127). Thanks [@DeadHeadRussell](https://github.com/DeadHeadRussell)!

# 0.4.9

Fix: This release fixes a bug introduced in `0.4.8` caused by calling the `forEach` method directly on a NodeList, which is undefined in a number of browsers [#125](https://github.com/clauderic/react-sortable-hoc/issues/125)

# 0.4.8

Fix: Added logic to ensure that `select`, `input` and `textarea` fields in `SortableElement` always retain their `value` when the element is cloned (this happens when sorting begins) [#122](https://github.com/clauderic/react-sortable-hoc/issues/122) [#123](https://github.com/clauderic/react-sortable-hoc/pull/123). Thanks [@tomasztomys](https://github.com/tomasztomys)!

# 0.4.7

Fix: This release fixes a bug in Firefox caused by active anchor tags preventing mousemove events from being fired [#118](https://github.com/clauderic/react-sortable-hoc/issues/118)

# 0.4.5

Fix: getHelperDimensions height was not being used (Thanks [@SMenigat](https://github.com/SMenigat)!)

# 0.4.4

Tweak: cherry-picking lodash methods instead of importing the entire bundle (slipped by in a PR, thanks for pointing this out [@arackaf](https://github.com/arackaf)!)

# 0.4.3

Fixes an edge-case bug in Firefox where window.getComputedStyle() returns null inside an iframe with `display: none` [#106](https://github.com/clauderic/react-sortable-hoc/pull/106). Thanks [@funnel-mark](https://github.com/funnel-mark)!

# 0.4.2

Fixes an issue when attempting to sort items while rapidly moving the mouse. By setting an immediate timer, we move the cancel event to the tail of the timer queue, and ensure that it is fired after the pressTimer [#80](https://github.com/clauderic/react-sortable-hoc/pull/80). Thanks [@v0lkan](https://github.com/v0lkan)!

# 0.4.0

- Fix a timing issue in Chrome caused by setTimeout [#71](https://github.com/clauderic/react-sortable-hoc/pull/71)
- Private props are no longer passed down to the wrapped component [#98](https://github.com/clauderic/react-sortable-hoc/pull/98)

# 0.3.0

Added grid support for elements of equal widths / heights [#4](https://github.com/clauderic/react-sortable-hoc/issues/4) [#86](https://github.com/clauderic/react-sortable-hoc/pull/86). Huge shout-out to [@richmeij](https://github.com/richmeij) for making this happen!

# 0.2.0

Add a `getHelperDimensions` prop to control SortableHelper size [#83](https://github.com/clauderic/react-sortable-hoc/issues/83). Thanks [@nervetattoo](https://github.com/nervetattoo)!

# 0.1.1

Added `touchCancel` listener to properly handle canceled touches [#73](https://github.com/clauderic/react-sortable-hoc/pull/73)

# 0.1.0

- Force `box-sizing: border-box` on sortable helper [#67](https://github.com/clauderic/react-sortable-hoc/issues/67)
- Support changing an item's collection prop on the fly [#66](https://github.com/clauderic/react-sortable-hoc/pull/66)

# 0.0.11

Utilize babel-plugin-transform-runtime to utilize `babelHelpers` without them being required in application code [#45](https://github.com/clauderic/react-sortable-hoc/issues/45)

# 0.0.10

The `arrayMove` helper no longer mutates the array, it now returns a new array [#61](https://github.com/clauderic/react-sortable-hoc/issues/61)

# 0.0.9

Server-side rendering bugfix: safeguard against `document` being undefined [#59](https://github.com/clauderic/react-sortable-hoc/pull/59)

# 0.0.8

- Added `distance` prop ([#35](https://github.com/clauderic/react-sortable-hoc/issues/35))
- Added a `shouldCancelStart` ([#47](https://github.com/clauderic/react-sortable-hoc/issues/47), [#36](https://github.com/clauderic/react-sortable-hoc/issues/36), [#41](https://github.com/clauderic/react-sortable-hoc/issues/41)) prop to programatically cancel sorting before it begins.
- Prevent right click from causing sort start ([#46](https://github.com/clauderic/react-sortable-hoc/issues/46))

# 0.0.7

Fixes server-side rendering (window undefined) ([#39](https://github.com/clauderic/react-sortable-hoc/issues/39))

# 0.0.6

- Added support for a custom container ([#37](https://github.com/clauderic/react-sortable-hoc/issues/37))
- Fix changing disable property while receiving props ([#34](https://github.com/clauderic/react-sortable-hoc/issues/34))


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('orders', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='order',
            name='date',
            field=models.DateTimeField(default=datetime.datetime(2015, 2, 10, 19, 13, 13, 194674, tzinfo=utc), auto_now_add=True),
            preserve_default=False,
        ),
    ]


text:
import GetConnection

testBucketName = "testtest"

if __name__ == '__main__':
    s3 = GetConnection.getConnection()
    # use the access control policy
    # by default, user ID is same with the DisplayName
    response = s3.put_bucket_acl(
        AccessControlPolicy={
            'Grants': [
                {
                    'Grantee': {
                        'ID': 'obuser-1',
                        'Type': 'CanonicalUser',
                        'DisplayName': 'obuser-1',
                    },
                    'Permission': 'FULL_CONTROL',
                },
            ],
            'Owner': {
                'DisplayName': 'obuser-1',
                'ID': 'obuser-1'
            }
        },
        Bucket=testBucketName,
    )

    # response: class dict
        # ResponseMetadata: class dict
            # RequestId
            # HTTPStatusCode
            # ...
        # Owner: dict
        # Grants: list of grant dict
    response = s3.get_bucket_acl(
        Bucket=testBucketName
    )

    print("owner info: " + str(response["Owner"]))
    print("grants info: " + str(response["Grants"]))

    # simple switch for one user one time
    response = s3.put_bucket_acl(
        # GrantFullControl='string',
        # GrantReadACP='string',
        # GrantWrite='string',
        # GrantWriteACP='string',
        GrantRead='id=obuser-1',
        Bucket=testBucketName
    )

    response = s3.get_bucket_acl(
        Bucket=testBucketName
    )

    print("owner info: " + str(response["Owner"]))
    print("grants info: " + str(response["Grants"]))


text:
using System;
using System.Threading.Tasks;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Tests.Integ.Framework;
using Telegram.Bot.Types;
using Xunit;

namespace Telegram.Bot.Tests.Integ.Getting_Updates
{
    [Collection(Constants.TestCollections.GettingUpdates)]
    [TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)]
    public class GettingUpdatesTests
    {
        ITelegramBotClient BotClient => _fixture.BotClient;

        readonly TestsFixture _fixture;

        public GettingUpdatesTests(TestsFixture fixture) => _fixture = fixture;

        [OrderedFact("Should pass API Token test with valid token")]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetMe)]
        public async Task Should_Pass_Test_Api_Token()
        {
            bool result = await BotClient.TestApiAsync();

            Assert.True(result);
        }

        [OrderedFact(
            "Should throw HttpRequestException with \"404 (Not Found)\" error when malformed API Token is provided"
        )]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetMe)]
        public async Task Should_Fail_Test_Api_Token()
        {
            ITelegramBotClient botClient = new TelegramBotClient("0:1this_is_an-invalid-token_for_tests");

            ApiRequestException exception = await Assert.ThrowsAsync<ApiRequestException>(() =>
                botClient.TestApiAsync()
            );

            Assert.IsType<ApiRequestException>(exception);
            Assert.Equal(404, exception.ErrorCode);
            Assert.Equal("Not Found", exception.Message);
        }

        [OrderedFact("Should fail API Token test with invalid token")]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetMe)]
        public async Task Should_Test_Bad_BotToken()
        {
            ITelegramBotClient botClient = new TelegramBotClient("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11");
            bool result = await botClient.TestApiAsync();

            Assert.False(result);
        }

        [OrderedFact("Should get bot user info")]
        [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.GetMe)]
        public async Task Should_Get_Bot_User()
        {
            User botUser = await BotClient.GetMeAsync();

            Assert.NotNull(botUser);
            Assert.NotNull(botUser.Username);
            Assert.True(botUser.IsBot);
            Assert.EndsWith("bot", botUser.Username!, StringComparison.OrdinalIgnoreCase);
        }
    }
}


text:
function g = newDomain(g, newDom)
%NEWDOMAIN   Change of domain of a CHEBFUN.
%  NEWDOMAIN(G, DOM) returns the CHEBFUN G but moved to the domain DOM. This is
%  done with a linear map. DOM may be a vector of length G.ends, or a two-vector
%  (in which case all breakpoints are scaled by the same amount).

% Copyright 2014 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% [TODO]: Unbounded domains.

% Current breakpoints:
oldDom = g.domain;

if ( numel(newDom) == numel(oldDom) )
    % All new breakpoints are given!
elseif ( numel(newDom) == 2 )
    % Scale breakpoints:
    c = oldDom(1);
    d = oldDom(end);
    a = newDom(1);
    b = newDom(2);
    newDom = (b - a)*(oldDom - c)/(d - c) + a;
else
    error('CHEBFUN:CHEBFUN:newDomain:numints', 'Inconsistent domains.');
end

for k = 1:numel(g.funs)
    % Update the domains of each of the funs:
    g.funs{k} = changeMap(g.funs{k}, newDom(k:k+1));
end

% Update the CHEBFUN:
g.domain = newDom;

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SiteManager.Core.Websites
{
    public enum Status
    {
        Starting = 0,
        Started = 1,
        Stopping = 2,
        Stopped = 3,
        Unknown = 4
    }
}


text:
package com.nosleep.githubclient.datalayer.services.branches;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Commit {

    @SerializedName("sha")
    @Expose
    private String sha;
    @SerializedName("url")
    @Expose
    private String url;

    /**
     * @return The sha
     */
    public String getSha() {
        return sha;
    }

    /**
     * @param sha The sha
     */
    public void setSha(String sha) {
        this.sha = sha;
    }

    /**
     * @return The url
     */
    public String getUrl() {
        return url;
    }

    /**
     * @param url The url
     */
    public void setUrl(String url) {
        this.url = url;
    }

}


text:
import * as Scrivito from 'scrivito'

Scrivito.provideEditingConfig('SwipeBlocksItemWidget', {
  title: 'Block'

})