text:
/**
 * Tracking touch events and simulating click events on touch.
 * @extends {gui.SpiritTracker}
 */
gui.SpiritTouchTracker = gui.SpiritTracker.extend ( "gui.SpiritTouchTracker", {

	/**
	 * Add touch handler(s) of one or more of types:
	 * gui.SpiritTouch.HAND_START
	 * gui.SpiritTouch.HAND_MOVE
	 * gui.SpiritTouch.HAND_END
	 * gui.SpiritTouch.FINGER_START
	 * gui.SpiritTouch.FINGER_MOVE
	 * gui.SpiritTouch.FINGER_END
	 * @param {object} arg
	 * @returns {gui.SpiritTouchTracker}
	 */
	add : function ( arg ) {

		this._breakdown ( arg ).forEach ( function ( type ) {
			if ( this._addchecks ( type, [ "local" ])) {
				gui.SpiritTouch.handle ( type, this.spirit, true );
			}
		}, this );
		return this;
	},

	/**
	 * Remove touch handler(s).
	 * @param {object} arg
	 * @returns {gui.SpiritTouchTracker}
	 */
	remove : function ( arg ) {

		this._breakdown ( arg ).forEach ( function ( type ) {
			if ( this._removechecks ( type, [ "local" ])) {
				gui.SpiritTouch.handle ( type, this.spirit, false );
			}
		}, this );
		return this;
	},

	/**
	 * Add global touch handler(s).
	 * @param {object} arg
	 * @returns {gui.SpiritTouchTracker}
	 */
	addGlobal : function ( arg ) {

		this._breakdown ( arg ).forEach ( function ( type ) {
			if ( this._addchecks ( type, [ "global" ])) {
				console.error("TODO");
				//gui.SpiritTouch.addGlobal ( type, this );
			}
		}, this );
		return this;
	},

	/**
	 * Remove global touch handler(s).
	 * @param {object} arg
	 * @param {object} handler
	 * @returns {gui.SpiritTouchTracker}
	 */
	removeGlobal : function ( arg ) {

		this._breakdown ( arg ).forEach ( function ( type ) {
			if ( this._removechecks ( type, [ "global" ])) {
				console.error("TODO");
				//gui.SpiritTouch.removeGlobal ( type );
			}
		}, this );
		return this;
	},

	// THE REST OF THIS FILE IS ALL ABOUT FAST-CLICK BUTTONS .......................

	/**
	 * Make "click" dispatch on "touchup" for improved button responsivenes.
	 * @return {[type]} [description]
	 * @returns {gui.SpiritTouchTracker}
	 */
	toclick : function () {

		this.add ( gui.SpiritTouch.FINGER_START );
		this._toclick = true;
		return this;
	},

	/**
	 * Handle touch.
	 * @param {gui.SpiritTouch} touch
	 */
	ontouch : function ( touch ) {

		this.spirit.ontouch ( touch ); // when to do this?
		if ( this._toclick ) {
			switch ( touch.type ) {
				case gui.SpiritTouch.FINGER_START :
					this._touchdown ( touch );
					break;
				case gui.SpiritTouch.FINGER_MOVE :
					this._touchmove ( touch );
					break;
				case gui.SpiritTouch.FINGER_END :
					this._touchup ( touch );
					break;
			}
		}
	},

	// PRIVATES ...................................................................

	/**
	 * Touch-to-click?
	 * @type {boolean}
	 */
	_toclick : false,

	/**
	 * Touch down.
	 * @param {gui.SpiritTouch} touch
	 */
	_touchdown : function ( touch ) {

		if ( touch.hand.fingers.length === 1 ) {
			this.add ( gui.SpiritTouch.FINGER_END );
			this.add ( gui.SpiritTouch.FINGER_MOVE );
			this._mouseevent ( "mousedown", touch.event );
		}
	},

	/**
	 * Touch move. Move beoynd a set distance to cancel
	 * the click event; user appears to perform a drag.
	 * @param {gui.SpiritTouch} touch
	 */
	_touchmove : function ( touch ) {

		if ( touch.finger.distance () < gui.SpiritTouchTracker.CANCEL ) {
			this._mouseevent ( "mousemove", touch.event );
		} else {
			this._reset ();
		}
	},

	/**
	 * Touch up. Trigger a simulated click event
	 * and supress the non-simulated click event.
	 * @param {gui.SpiritTouch} touch
	 */
	_touchup : function ( touch ) {

		this._mouseevent ( "mouseup", touch.event );
		this._mouseevent ( "click", touch.event );
		this._noclick ( touch );
		this._reset ();
	},

	/**
	 * Dispatch simulated mouse event.
	 * @param {String} type
	 * @param {TouchEvent} e
	 */
	_mouseevent : function ( type, e ) {

		var win = this.spirit.window;
		var doc = this.spirit.document;
		var elm = this.spirit.element;

		var event = doc.createEvent ( "MouseEvent" );
		event.initMouseEvent (
				type, true, true, win, 1,
				e.screenX, e.screenY,
				e.clientX, e.clientY,
				e.ctrlKey, e.altKey,
				e.shiftKey, e.metaKey,
				0, null );
		elm.dispatchEvent ( event );
	},

	/**
	 * User agent will soon trigger a regular click event,
	 * causing handlers to fire twice. We terminate all click
	 * events in our general vicinity for at least one second.
	 * @param {gui.SpiritTouch} touch
	 */
	_noclick : function ( touch ) {

		var doc = this.spirit.document;
		var end = touch.finger.end;
		var pos = new gui.Position ( end.clientX, end.clientY );
		gui.SpiritTouchTracker.noclick ( doc, pos );
	},

	/**
	 * Reset setup.
	 */
	_reset : function () {

		this.remove ( gui.SpiritTouch.FINGER_END );
		this.remove ( gui.SpiritTouch.FINGER_MOVE );
	}

}, {}, { // STATICS ............................................................

	/**
	 * Maximum distance before a click session is considered a drag move.
	 * @type {number}
	 */
	CANCEL : 10,

	/**
	 * Size of the no click zone.
	 * @type {number}
	 */
	ZONE : 20,

	/**
	 * Temporarily conjure a no-click-zone at given position.
	 * @param {Document} doc
	 * @param {gui.Position} pos
	 */
	noclick : function ( doc, pos ) {

		console.log("1: " + pos.x + ": " + doc.title );

		this._zones.push ({ doc : doc, pos : pos });
		doc.addEventListener ( "click", gui.SpiritTouchTracker, true );
		var zones = this._zones;
		setTimeout ( function () {
			zones.shift ();
		}, 1000 );
	},

	/**
	 * Tracking no click zones.
	 * @type {Arra<object>}
	 */
	_zones : [],

	/**
	 * Enforce no click zone.
	 * @param {Event} e
	 */
	handleEvent : function ( e ) {

		console.log(Math.random())
		e.stopImmediatePropagation ();
		e.stopPropagation ();
		e.preventDefault ();

		if ( e.type === "click" ) {
			var x = e.clientX;
			var y = e.clientY;
			var z = this.ZONE;
			this._zones.forEach ( function ( zone ) {
				if ( zone.doc === e.currentTarget ) {
					if ( Math.abs ( zone.pos.x - x ) < z && Math.abs ( zone.pos.y - y ) < z ) {
						e.stopImmediatePropagation ();
						e.stopPropagation ();
						e.preventDefault ();
					}
				}
			});
		}
	}

});


text:
# Changelog

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.12.0](https://github.com/danibram/mocker-data-generator/compare/v2.10.0...v2.12.0) (2021-02-03)

### Features

-   **chore:** updated deps

## [2.10.0](https://github.com/danibram/mocker-data-generator/compare/v2.9.0...v2.10.0) (2020-10-13)

### Features

-   Merged Array Example: [#102](https://github.com/danibram/mocker-data-generator/pull/102)
-   Merged Generic Type for Generator: [#114](https://github.com/danibram/mocker-data-generator/pull/114)

## [2.9.0](https://github.com/danibram/mocker-data-generator/compare/v2.8.0...v2.9.0) (2020-09-04)

### Features

-   add buildSync method to Mocker class ([772b20d](https://github.com/danibram/mocker-data-generator/commit/772b20da6f9ccaba98f20a1361babe5f55810d78))
-   all deps updated!!

### Bug Fixes

-   **appveyor:** update matrix config to install defined node version ([703aa41](https://github.com/danibram/mocker-data-generator/commit/703aa41411b3813f3d1af6e79b6d2643a36dec56))
-   **docs-website:** added seed example ([d1fa143](https://github.com/danibram/mocker-data-generator/commit/d1fa143f20467cf69c87e5cc4a74657429550384))

## [2.8.0](https://github.com/danibram/mocker-data-generator/compare/v2.7.0...v2.8.0) (2020-05-13)

### Features

-   **chore:** easy publish as minor shortcut ([fd1a87b](https://github.com/danibram/mocker-data-generator/commit/fd1a87bfe444817b75af88c91398929fab91b83c))
-   **chore:** update chance and tslib, and some devDependencies ([59d0aea](https://github.com/danibram/mocker-data-generator/commit/59d0aea51fba7ef2e6b1ea153da4aa8007f07170))
-   **Mocker.seed:** add posibility to prepopulate the db. Thanks [@suspiciousfellow](https://github.com/suspiciousfellow) and [@marshallswain](https://github.com/marshallswain) for the idea and the code ([dfb2ad6](https://github.com/danibram/mocker-data-generator/commit/dfb2ad64fe002e4b55dfe71d1d65574d5054d6cc))
-   **Mocker.seed:** add tests ([7faafab](https://github.com/danibram/mocker-data-generator/commit/7faafab779af49434c47ac63631aea9cebbc9be7))
-   **Mocker.seed:** seed and schema and work together ([68970fc](https://github.com/danibram/mocker-data-generator/commit/68970fc3fe7a2072c99d58ed3b1ececd3b6909dd))

## [2.7.0](https://github.com/danibram/mocker-data-generator/compare/v2.6.5...v2.7.0) (2020-04-16)

### All deps updated!

## [2.6.6](https://github.com/danibram/mocker-data-generator/compare/v2.6.5...v2.6.6) (2018-09-18)

### Feature

Unique field in hasMany generator

### Bug Fixes

-   **errors:** hasMany added unique error

### All deps updated!

## [2.6.5](https://github.com/danibram/mocker-data-generator/compare/v2.6.4...v2.6.5) (2018-09-06)

### All deps updated!

## [2.6.4](https://github.com/danibram/mocker-data-generator/compare/v2.6.3...v2.6.4) (2018-05-08)

### Bug Fixes

-   **hasOne:** Issues with eval ([f1ab9e8](https://github.com/danibram/mocker-data-generator/commit/f1ab9e8))

## [2.6.3](https://github.com/danibram/mocker-data-generator/compare/v2.6.2...v2.6.3) (2018-05-08)

## [2.6.2](https://github.com/danibram/mocker-data-generator/compare/v2.6.1...v2.6.2) (2018-05-08)

### Bug!

-   Fixing bug related to _eval_!

## [2.6.1](https://github.com/danibram/mocker-data-generator/compare/v2.5.2...v2.6.1) (2018-03-20)

### Improvements!

-   Now I rework internal part of the generators to offer the posibility of avoid **eval** step, i used eval to offer the maximum flexibility, but now its optional, of course that without eval, is less flexible, but if it fits for your mock data right now you will gain **10x speed**, Awesome!
    Also it offers the posibility of use eval like in the older versions of mocker.

Welcome to the ludicrous speed! 🎉

## [2.5.2](https://github.com/danibram/mocker-data-generator/compare/v2.5.1...v2.5.2) (2018-01-17)

### Bug Fixes

-   **generation:** added fix when min = 0 in hasMany, now can produce empty array of data, by default is 1, so you have to specify minimum to 0 in order to have the chance to produce empty arrays ([7f97646](https://github.com/danibram/mocker-data-generator/commit/7f97646))

### All deps updated!

# [2.5.0](https://github.com/danibram/mocker-data-generator/compare/v2.4.9...v2.5.0) (2017-11-01)

### Breaking Changes!

-   Now the build method throws the error, in the case of the callback in a traditional style function **function(err, data)** in the case of promise style in the reject.

### Bug Fixes

-   **test:** separate gh-pages generation modules from the mocker modules for development, some test fails ([2cc421e](https://github.com/danibram/mocker-data-generator/commit/2cc421e))
-   Better error throwing and test covered ([20ca0a0](https://github.com/danibram/mocker-data-generator/commit/20ca0a0))

### Bug Fixes

-   **test:** separate gh-pages generation modules from the mocker modules for development, some test fails ([2cc421e](https://github.com/danibram/mocker-data-generator/commit/2cc421e))
-   Better error throwing and test covered ([20ca0a0](https://github.com/danibram/mocker-data-generator/commit/20ca0a0))

## [2.4.9](https://github.com/danibram/mocker-data-generator/compare/v2.4.7...v2.4.9) (2017-10-20)

### Features

-   Added browser build
-   Fixes in build to sync with gh-pages

## [2.4.5](https://github.com/danibram/mocker-data-generator/compare/v2.4.4...v2.4.5) (2017-10-20)

## [2.4.4](https://github.com/danibram/mocker-data-generator/compare/v2.4.3...v2.4.4) (2017-10-17)

### Bug Fixes

-   **fakerjs:** Better locale detector and better testing ([f05872d](https://github.com/danibram/mocker-data-generator/commit/f05872d))

## [2.4.3](https://github.com/danibram/mocker-data-generator/compare/v2.4.2...v2.4.3) (2017-10-16)

## [2.4.2](https://github.com/danibram/mocker-data-generator/compare/v2.4.1...v2.4.2) (2017-10-16)

## [2.4.1](https://github.com/danibram/mocker-data-generator/compare/v2.4.0...v2.4.1) (2017-10-16)

# [2.4.0](https://github.com/danibram/mocker-data-generator/compare/v2.2.1...v2.4.0) (2017-10-16)

### Bug Fixes

-   **builder:** fix tslint space identation ([b3f9f7c](https://github.com/danibram/mocker-data-generator/commit/b3f9f7c))

### Features

-   **fakerjs:** Added multilanguaje support ([0b94471](https://github.com/danibram/mocker-data-generator/commit/0b94471))
-   **fakerjs:** Added tests for multilang support ([5078d24](https://github.com/danibram/mocker-data-generator/commit/5078d24))
-   **fakerjs:** Updates on the readme ([b79e88f](https://github.com/danibram/mocker-data-generator/commit/b79e88f))

# [2.3.0](https://github.com/danibram/mocker-data-generator/compare/v2.2.1...v2.3.0) (2017-10-16)

### Bug Fixes

-   **builder:** fix tslint space identation ([b3f9f7c](https://github.com/danibram/mocker-data-generator/commit/b3f9f7c))

### Features

-   **fakerjs:** Added multilanguaje support ([0b94471](https://github.com/danibram/mocker-data-generator/commit/0b94471))
-   **fakerjs:** Added tests for multilang support ([5078d24](https://github.com/danibram/mocker-data-generator/commit/5078d24))
-   **fakerjs:** Updates on the readme ([b79e88f](https://github.com/danibram/mocker-data-generator/commit/b79e88f))

## [2.2.1](https://github.com/danibram/mocker-data-generator/compare/v2.2.0...v2.2.1) (2017-10-13)

### Bug Fixes

-   **linter:** trying to use supported tslint rule ([5edac70](https://github.com/danibram/mocker-data-generator/commit/5edac70))
-   **updates:** Update libs to last releases ([a6ce60b](https://github.com/danibram/mocker-data-generator/commit/a6ce60b))

# [2.2.0](https://github.com/danibram/mocker-data-generator/compare/v2.1.0...v2.2.0) (2017-06-14)

### Features

-   added min max for value generation randomly with tests. thanks [@jhkim-novavin](https://github.com/jhkim-novavin) ([5eaa6f4](https://github.com/danibram/mocker-data-generator/commit/5eaa6f4))

# [2.1.0](https://github.com/danibram/mocker-data-generator/compare/v2.0.2...v2.1.0) (2017-05-27)

### Features

-   Added a way to obtain actual array while the generation, [@zamnuts](https://github.com/zamnuts) suggestion ([2588a34](https://github.com/danibram/mocker-data-generator/commit/2588a34))
-   Added length on the array function generator, thanks [@zamnuts](https://github.com/zamnuts) ([1f17519](https://github.com/danibram/mocker-data-generator/commit/1f17519))
-   added PR #16 Add parameter to hasMany generator, thanks [@justinbarry](https://github.com/justinbarry) ([71d947f](https://github.com/danibram/mocker-data-generator/commit/71d947f))

## [2.0.2](https://github.com/danibram/mocker-data-generator/compare/v2.0.1...v2.0.2) (2017-05-24)

### Bug Fixes

-   **browserify:** fix browserify builds changing casual to browserify-casual ([de93262](https://github.com/danibram/mocker-data-generator/commit/de93262))

## [2.0.1](https://github.com/danibram/mocker-data-generator/compare/v2.0.0...v2.0.1) (2017-05-24)

### Changes

-   **fix:** tslib fix for ES5 builds
-   **updates:** updates on dependencies

# [2.0.0](https://github.com/danibram/mocker-data-generator/compare/v1.2.7...v2.0.0) (2017-03-18)

### Features

-   **build:** new build using Typescript, breaking change in imports, adapted import to be used with es6 ([6114eaf](https://github.com/danibram/mocker-data-generator/commit/6114eaf))

### OLD Release History

#### (1.2.7)

-   Fix little issue with array generators, now parse well the index inside, add a test for that
-   Fix string issue with fakerJs
-   Fixed babel polyfill issues
-   updates on dev packages

#### (1.2.2)

-   Better error management
-   Added eval methods
-   Update docs with the online mocker-api: https://mocker-api.herokuapp.com/

#### (1.2.1)

-   Start to parse better the errors

#### (1.2.0)

-   New internal reorganization
-   Added hasOne (related is deprecated) and hasMany
-   **_Breaking Change_**: related config is deprecated, instead of related use hasOne.

#### (1.1.1)

-   Added RandExpJs generator
-   Improve test system (I know im improving it! =P)
-   **_Breaking Change_**: the older versions aren´t compatible with this module, the way to generate the data are changed:
    #### (1.1.0)
-   Added casualJs
-   Added self option
-   Added db option
-   Added related option

#### (1.0.6)

-   Updated chance.js to 1.0

#### (1.0.5)

-   Added the concat option, and the strictConcat on Array generator.

#### (1.0.4)

-   Added on uniqueField two ways to generate the data
-   Starting to add errors

#### (1.0.3)

-   Fix Arrays
-   **_Breaking Change_**: the older versions aren´t compatible with this module, the way to generate the data are changed:

    ```javascript
    var cat = {
        name: {
            values: ['txuri', 'pitxi', 'kitty']
        }
    }
    var m = mocker()
        .schema('cat', cat, 10)
        .schema('cat2', cat, { uniqueField: 'name' })
        .build(function (data) {
            console.log(util.inspect(data, { depth: 10 }))
        })
    ```

#### (0.7.0)

-   **_Breaking Change_**: Added the posibility to enable the pluralize on the output entity. Now if you want to pluralize the output follow the example in the doc, **_by defatult is not anymore pluralized_**.

    Old call configuration:

    ```javascript
    var m = mocker(config)
    m.generate('user', 2)
        .then(m.generate('group', 2))
        .then(m.generate('conditionalField', 2))
        .then(function (data) {
            console.log(util.inspect(data, { depth: 10 }))
            //This returns an object
            // {
            //      user:[array of users],
            //      group: [array of groups],
            //      conditionalField: [array of conditionalFields]
            // }
        })
    ```

    New array configuration:

    ```javascript
    var m = mocker(config)
    m.generate('user', 2)
        .generate('group', 2)
        .generate('conditionalField', 2)
        .build(function (data) {
            console.log(util.inspect(data, { depth: 10 }))
            //This returns an object
            // {
            //      user:[array of users],
            //      group: [array of groups],
            //      conditionalField: [array of conditionalFields]
            // }
        })
    ```

#### (0.6.0)

-   **_Breaking Change_**: Added the posibility to enable the pluralize on the output entity. Now if you want to pluralize the output follow the example in the doc, **_by defatult is not anymore pluralized_**.

#### (0.5.0)

-   **_Breaking Change_**: Break Point with array config. Now is more clear.

    Old array configuration:

    ```javascript
        [{
            //Any generator
                //Faker
            faker: 'random.arrayElement(db.users)[userId]'
                //Chance
            chance: 'integer'
                //Function
            function: function (){ return /**/ }

        }, //Array config
        {length: 10, fixedLength: false}]
    ```

    New array configuration:

    ```javascript
        [{
            //Any generator
                //Faker
            faker: 'random.arrayElement(db.users)[userId]'
                //Chance
            chance: 'integer'
                //Function
            function: function (){ return /**/ }

            //Array config
            length: 10,
            fixedLength: false
        }]
    ```

#### (0.4.7)

-   Add virtual fields

#### (0.4.5)

-   Add incrementalId config
-   Some tweaks on dev config to start to use generators on typescript
-   Performance tweaks for large data generation

#### (0.4.1)

-   Show in console the errors. (I will improve this)
-   Add support to chanceJs, exactly like FakerJs (see "Model definition" **_Chance_**)

#### (0.3.0)

-   Fix errors on iteration over nested structures (new improved interator)
-   Added support to call more naturally to FackerJs fields (see "Model definition" **_Faker_**)

#### (0.2.2)

-   Added a pluralization function
-   Fixed a little issue with the roots schemas (now you can do really crazy things, see test/mocker.example.js)
-   Fix errors introduced in 0.2.0

#### (0.1.6)

-   Fix an error: (Clean initial data field)
-   Fix some memory errors adding inmutableJS for the model
-   Add new tests

#### (0.1.1)

-   Real Refractor of the code
-   Add support multi-level schemas
-   Add tests
-   Add travis support

#### (0.0.4)

-   First release i will update soon with tests and more examples, stay tuned!

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.web.reactive.handler;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.server.handler.ResponseStatusExceptionHandler;

/**
 * Common WebFlux exception handler that detects instances of
 * {@link org.springframework.web.server.ResponseStatusException}
 * (inherited from the base class) as well as exceptions annotated with
 * {@link ResponseStatus @ResponseStatus} by determining the HTTP status
 * for them and updating the status of the response accordingly.
 *
 * <p>If the response is already committed, the error remains unresolved
 * and is propagated.
 *
 * @author Juergen Hoeller
 * @author Rossen Stoyanchev
 * @since 5.0.5
 */
public class WebFluxResponseStatusExceptionHandler extends ResponseStatusExceptionHandler {

	@Override
	protected HttpStatusCode determineStatus(Throwable ex) {
		HttpStatusCode statusCode = super.determineStatus(ex);
		if (statusCode == null) {
			ResponseStatus ann = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
			if (ann != null) {
				statusCode = ann.code();
			}
		}
		return statusCode;
	}

}


text:
package com.cloud.network.element;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Set;

import javax.ejb.Local;

import org.apache.log4j.Logger;

import com.cloud.api.commands.DeleteCiscoNexusVSMCmd;
import com.cloud.api.commands.EnableCiscoNexusVSMCmd;
import com.cloud.api.commands.DisableCiscoNexusVSMCmd;
import com.cloud.api.commands.ListCiscoNexusVSMsCmd;
import com.cloud.api.response.CiscoNexusVSMResponse;
import com.cloud.deploy.DeployDestination;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.CiscoNexusVSMDeviceVO;
import com.cloud.network.CiscoNexusVSMDevice;
import com.cloud.network.CiscoNexusVSMDeviceManagerImpl;
import com.cloud.network.Network;
import com.cloud.network.PhysicalNetworkServiceProvider;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.dao.CiscoNexusVSMDeviceDao;
import com.cloud.utils.component.Inject;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.network.element.NetworkElement;
import com.cloud.offering.NetworkOffering;
import com.cloud.org.Cluster;
import com.cloud.utils.component.Manager;
import com.cloud.exception.ResourceInUseException;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.server.ManagementService;

@Local(value = NetworkElement.class)
public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl implements CiscoNexusVSMElementService, NetworkElement, Manager {

    private static final Logger s_logger = Logger.getLogger(CiscoNexusVSMElement.class);

    @Inject
    CiscoNexusVSMDeviceDao _vsmDao;

    @Override
    public Map<Service, Map<Capability, String>> getCapabilities() {
    	return null;
    }

    @Override
    public Provider getProvider() {
        return null;
    }

    @Override
    public boolean implement(Network network, NetworkOffering offering,
            DeployDestination dest, ReservationContext context)
            throws ConcurrentOperationException, ResourceUnavailableException,
            InsufficientCapacityException {
        return true;
    }

    @Override
    public boolean prepare(Network network, NicProfile nic,
            VirtualMachineProfile<? extends VirtualMachine> vm,
            DeployDestination dest, ReservationContext context)
            throws ConcurrentOperationException, ResourceUnavailableException,
            InsufficientCapacityException {
        return true;
    }

    @Override
    public boolean release(Network network, NicProfile nic,
            VirtualMachineProfile<? extends VirtualMachine> vm,
            ReservationContext context) throws ConcurrentOperationException,
            ResourceUnavailableException {
        return true;
    }

    @Override
    public boolean shutdown(Network network, ReservationContext context,
    		boolean cleanup) throws ConcurrentOperationException,
    		ResourceUnavailableException {
        return true;
    }

    @Override
    public boolean destroy(Network network)
            throws ConcurrentOperationException, ResourceUnavailableException {
        return true;
    }

    @Override
    public boolean isReady(PhysicalNetworkServiceProvider provider) {
        return true;
    }

    @Override
    public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider,
    		ReservationContext context) throws ConcurrentOperationException,
    		ResourceUnavailableException {
    	return true;
    }

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

    @Override
    public boolean verifyServicesCombination(Set<Service> services) {
    	return true;
    }

    @Override
    @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DELETE, eventDescription = "deleting VSM", async = true)
    public boolean deleteCiscoNexusVSM(DeleteCiscoNexusVSMCmd cmd) {
    	boolean result;
    	try {
    		result = deleteCiscoNexusVSM(cmd.getCiscoNexusVSMDeviceId());
    	} catch (ResourceInUseException e) {
    		s_logger.info("VSM could not be deleted");
    		// TODO: Throw a better exception here.
    		throw new CloudRuntimeException("Failed to delete specified VSM");
    	}
    	return result;
    }

    @Override
    @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_ENABLE, eventDescription = "deleting VSM", async = true)
    public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(EnableCiscoNexusVSMCmd cmd) {
    	CiscoNexusVSMDeviceVO result;
    	result = enableCiscoNexusVSM(cmd.getCiscoNexusVSMDeviceId());
    	return result;
    }

    @Override
    @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DISABLE, eventDescription = "deleting VSM", async = true)
    public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(DisableCiscoNexusVSMCmd cmd) {
    	CiscoNexusVSMDeviceVO result;
    	result = disableCiscoNexusVSM(cmd.getCiscoNexusVSMDeviceId());
    	return result;
    }

    @Override
    public List<CiscoNexusVSMDeviceVO> getCiscoNexusVSMs(ListCiscoNexusVSMsCmd cmd) {
    	// If clusterId is defined, then it takes precedence, and we will return
    	// the VSM associated with this cluster.

    	Long clusterId = cmd.getClusterId();
    	Long zoneId = cmd.getZoneId();
    	List<CiscoNexusVSMDeviceVO> result = new ArrayList<CiscoNexusVSMDeviceVO>();
    	if (clusterId != null && clusterId.longValue() != 0) {
    		// Find the VSM associated with this clusterId and return a list.
    		CiscoNexusVSMDeviceVO vsm = getCiscoVSMbyClusId(cmd.getClusterId());
    		if (vsm == null) {
        		throw new CloudRuntimeException("No Cisco VSM associated with specified Cluster Id");
        	}
    		// Else, add it to a list and return the list.
    		result.add(vsm);
    		return result;
    	}
    	// Else if there is only a zoneId defined, get a list of all vmware clusters
    	// in the zone, and then for each cluster, pull the VSM and prepare a list.
    	if (zoneId != null && zoneId.longValue() != 0) {
    		ManagementService ref = cmd.getMgmtServiceRef();
    		List<? extends Cluster> clusterList = ref.searchForClusters(zoneId, cmd.getStartIndex(), cmd.getPageSizeVal(), "VMware");

    		if (clusterList.size() == 0) {
    			throw new CloudRuntimeException("No VMWare clusters found in the specified zone!");
    		}
    		// Else, iterate through each vmware cluster, pull its VSM if it has one, and add to the list.
    		for (Cluster clus : clusterList) {
    			CiscoNexusVSMDeviceVO vsm = getCiscoVSMbyClusId(clus.getId());
    			if (vsm != null)
    				result.add(vsm);
    		}
    		return result;
    	}

    	// If neither is defined, we will simply return the entire list of VSMs
    	// configured in the management server.
    	// TODO: Is this a safe thing to do? Only ROOT admin can invoke this call.
    	result = _vsmDao.listAllVSMs();
    	return result;
    }

    @Override
    public CiscoNexusVSMResponse createCiscoNexusVSMResponse(CiscoNexusVSMDevice vsmDeviceVO) {
            CiscoNexusVSMResponse response = new CiscoNexusVSMResponse();
            response.setId(vsmDeviceVO.getId());
            response.setMgmtIpAddress(vsmDeviceVO.getipaddr());
            return response;
        }

    public CiscoNexusVSMResponse createCiscoNexusVSMDetailedResponse(CiscoNexusVSMDevice vsmDeviceVO) {
    	CiscoNexusVSMResponse response = new CiscoNexusVSMResponse();
    	response.setId(vsmDeviceVO.getId());
    	response.setDeviceName(vsmDeviceVO.getvsmName());
    	response.setDeviceState(vsmDeviceVO.getvsmDeviceState().toString());
    	response.setMgmtIpAddress(vsmDeviceVO.getipaddr());
    	// The following values can be null, so check for that.
    	if(vsmDeviceVO.getvsmConfigMode() != null)
    		response.setVSMConfigMode(vsmDeviceVO.getvsmConfigMode().toString());
    	if(vsmDeviceVO.getvsmConfigState() != null)
    		response.setVSMConfigState(vsmDeviceVO.getvsmConfigState().toString());
    	if(vsmDeviceVO.getvsmDeviceState() != null)
    		response.setVSMDeviceState(vsmDeviceVO.getvsmDeviceState().toString());
    	response.setVSMCtrlVlanId(vsmDeviceVO.getManagementVlan());
    	response.setVSMPktVlanId(vsmDeviceVO.getPacketVlan());
    	response.setVSMStorageVlanId(vsmDeviceVO.getStorageVlan());
    	return response;
    }

    @Override
    public String getPropertiesFile() {
    	return "cisconexusvsm_commands.properties";
    }
}


text:
<?php

class BattleNetAPI_Wow_Item_Set_Endpoint extends BattleNetAPI_Endpoint {
	function __construct( $params ) {
		if ( ! isset( $params['setId'] ) ) {
			throw new BattleNetAPI_Exception( 'The "/wow/item/set/" endpoint requires the parameter "setId".' );
		}

		$this->url = BattleNetAPI::getHost() . '/wow/item/set/' . $params['setId'];
	}
}


text:
/**
 ** Test JUnit collections.
 *
 * @author Ponkin Aleksey (mailto:ponkin.a.v@gmail.com)
 * @version $Id$
 * @since 0.1
 */

package ru.job4j.collections;


text: ACCOUNT_NAME = 'Sagemcom'


text:
module DataMapper
  class Property
    class Text < String
      length  65535
      lazy    true

      def primitive?(value)
        value.kind_of?(::String)
      end
    end # class Text
  end # class Property
end # module DataMapper


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/daluz.iml" filepath="$PROJECT_DIR$/.idea/daluz.iml" />
    </modules>
  </component>
</project>


text:
from __future__ import unicode_literals, print_function, absolute_import
from django.contrib.auth import get_user_model
from django.db.models.signals import m2m_changed
from django.dispatch import receiver

from reviewers import review_group_name
from reviewers.models import Reviewer

user_model = get_user_model()

@receiver(m2m_changed, sender=user_model.groups.through)
def register_reviews_handler(sender, **kwargs):
    action = kwargs.get("action")
    instance = kwargs.get("instance")
    if instance and action in ("post_add", "post_remove"):
        if review_group_name in instance.groups.values_list("name", flat=True):
            if not Reviewer.objects.filter(user=instance).exists():
                Reviewer.objects.create(user=instance)
        else:
            if Reviewer.objects.filter(user=instance).exists():
                Reviewer.objects.filter(user=instance).delete()


text:
package main

import (
	"bufio"
	"fmt"
	"github.com/korobool/nlp4go"
	"os"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)

	tokenizer := gonlp.NewSplitTokenizer(" ")

	posTagger, err := gonlp.NewPerceptronTagger(tokenizer, true, "")

	if err != nil {
		fmt.Fprintln(os.Stderr, "posTagger:", err)
	}

	for scanner.Scan() {
		line := scanner.Text()

		tags, _ := posTagger.Tag(line)

		for _, tag := range tags {
			fmt.Println(tag)
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Stylesheet</title>

  <link rel="stylesheet" href="stylesheets/asdf.css" media="screen" type="text/css" />
  <link rel="stylesheet" href="stylesheets/screen.css" media="screen" type="text/css" />


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe User do
  describe "issuer" do
    before(:each) do
      @issuer=User.issuer
    end

    it "should find issuer" do
      @issuer.should_not be_nil
    end

    it "should have 0 balance" do
      @issuer.balance.to_i.should==0
    end
  end

end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Egghead.io Angular JS tutorial</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/css/normalize.css">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/css/main.css">
    <link rel="stylesheet" href="app.css">
    <link rel="stylesheet" href="bower_components/foundation/css/foundation.css">

<input type="text" ng-model="model.title">
<input type="text" ng-model="model.content">

<zippy title="{{model.title}}">
    This is the {{model.content}}
</zippy>


text:
package org.gradle.tooling.internal.protocol.events;

/**
 * DO NOT CHANGE THIS INTERFACE. It is part of the cross-version protocol.
 *
 * @since 2.4
 */
public interface InternalTestFinishedProgressEvent extends InternalTestProgressEvent {
    /**
     * Returns the result of running the test.
     *
     * @return The test result
     */
    InternalTestResult getResult();
}


text:
#include <ctype.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "core/constants.h"
#include "core/common.h"
#include "core/install.h"
#include "core/keyword.h"
#include "core/search.h"
#include "renderplain.h"

typedef struct deen_cli_args deen_cli_args;
struct deen_cli_args {
	deen_bool version;
	deen_bool index;
	deen_bool trace_enabled;
	uint32_t result_count;
	uint8_t *search_expression;
	char *ding_filename;
};

static void deen_cli_init_args(deen_cli_args *args) {
	args->version = DEEN_FALSE;
	args->index = DEEN_FALSE;
	args->trace_enabled = DEEN_FALSE;
	args->result_count = DEEN_RESULT_SIZE_DEFAULT;
	args->search_expression = NULL;
	args->ding_filename = NULL;
}

static void deen_cli_syntax(char *binary_name) {
	char *binary_name_basename = basename(binary_name);
	printf("version %s\n",DEEN_VERSION);
	printf("%s [-h]\n", binary_name_basename);
	printf("%s [-v]\n", binary_name_basename);
	printf("%s [-t] [-i] <ding-file>\n", binary_name_basename);
	printf("%s [-t] [-c <result-count>] <search-term>\n", binary_name_basename);
	exit(1);
}

static void deen_cli_capture_args(deen_cli_args *args, int argc, char** argv) {
	int i;

	for (i = 1; i < argc; i++) {
		if ('-' == argv[i][0]) {

			if (2 != strlen(argv[i])) {
				deen_log_error_and_exit("unrecognized switch [%s]", argv[i]);
			}

			switch (argv[i][1]) {

				case 'h':
					deen_cli_syntax(argv[0]);
					break;

				case 'i':
					args->index = DEEN_TRUE;

					if (i == argc - 1) {
						deen_log_error_and_exit("expected a ding file to be specified");
					}

					args->ding_filename = argv[i + 1];
					i++;
					break;

				case 'v':
					args->version = DEEN_TRUE;
					break;

				case 't':
					args->trace_enabled = DEEN_TRUE;
					break;

				case 'c':
					if (i == argc - 1) {
						deen_log_error_and_exit("expected a count to be specified");
					}

					args->result_count = (uint32_t) atoi(argv[i + 1]);

					if (0 == args->result_count) {
						deen_log_error_and_exit("bad result count value [%s]", argv[i + 1]);
					}

					i++;
					break;

				default:
					deen_log_error_and_exit("unrecognized switch [%s]", argv[i]);
					break;

			}

		} else {
			args->search_expression = (uint8_t *) argv[i];

			if (i != argc - 1) {
				deen_log_error_and_exit("the search-term must be the last argument");
			}
		}
	}
}

static void deen_cli_validate_args(deen_cli_args *args) {
	if (args->index) {
		if (NULL != args->search_expression) {
			deen_log_error_and_exit("when indexing, search arguments are not allowed");
		}
	}
	else {
		if (
			DEEN_FALSE == args->version &&
			(NULL == args->search_expression || 0 == args->search_expression[0])) {
			deen_log_error_and_exit("a search expression was expected");
		}
	}
}

static deen_bool deen_cli_install_progress_cb(
	void* context,
	enum deen_install_state state,
	float progress) {
	deen_log_install_progress(state, progress);
	return DEEN_TRUE; // keep going
}

static void deen_cli_index(const char *filename) {
	char *root_dir = deen_root_dir();

	deen_install_from_path(
		root_dir,
		filename,
		NULL,
		deen_cli_install_progress_cb,
		NULL // no is cancelled function
	);

	free((void *) root_dir);
}

static void deen_cli_check_and_index(const char *filename) {
	switch (deen_install_check_for_ding_format(filename)) {

		case DEEN_INSTALL_CHECK_OK:
			DEEN_LOG_INFO0("the ding input file looks like valid data");
			deen_cli_index(filename);
			break;

		case DEEN_INSTALL_CHECK_IS_COMPRESSED:
			DEEN_LOG_ERROR0("the ding input file looks compressed; decompress it first");
			break;

		case DEEN_INSTALL_CHECK_IO_PROBLEM:
			DEEN_LOG_ERROR0("a problem has arisen processing the ding input file - io problem");
			break;

		case DEEN_INSTALL_CHECK_TOO_SMALL:
			DEEN_LOG_ERROR0("a problem has arisen processing the ding input file - too small");
			break;

		case DEEN_INSTALL_CHECK_BAD_FORMAT:
			DEEN_LOG_ERROR0("the input ding file looks malformed");
			break;

		default:
			deen_log_error_and_exit("illegal state; unknown check result");
			break;

	}
}

static void deen_cli_query(deen_cli_args *args) {
	deen_search_result *result;
	deen_search_context *context;
	char *root_dir = deen_root_dir();
	deen_keywords *keywords = deen_keywords_create();
	size_t search_expression_len = strlen((char *) args->search_expression);
	uint8_t *search_expression_upper = (uint8_t *) deen_emalloc(
		sizeof(uint8_t) * (search_expression_len + 1));

	search_expression_upper[search_expression_len] = 0;
	memcpy(
		search_expression_upper,
		args->search_expression,
		search_expression_len);

	deen_to_upper(search_expression_upper);

	DEEN_LOG_TRACE2("keywords; [%s] --> [%s]", args->search_expression, search_expression_upper);
	deen_keywords_add_from_string(keywords, search_expression_upper);

	// dump out the keywords for now
	deen_trace_log_keywords(keywords);

	// run the search

	context = deen_search_init(root_dir);

	if(NULL==context) {
		deen_log_error_and_exit("unable to create a search context");
	}

	result = deen_search(context, keywords, args->result_count);

	if (0 == result->total_count) {
		if (deen_keywords_adjust(keywords)) {
			DEEN_LOG_INFO0("no results found -> did adjust keywords");
			deen_trace_log_keywords(keywords);
			deen_search_result_free(result);
			result = deen_search(context, keywords, args->result_count);
		}
	}

    deen_render_plain(result, keywords);

    deen_search_result_free(result);
    deen_search_free(context);
    deen_keywords_free(keywords);

    free((void *) root_dir);
	free((void *) search_expression_upper);
}

int main(int argc, char** argv) {
	deen_cli_args args;

	if (1 == argc) {
		deen_cli_syntax(argv[0]);
	}

	// capture the argument inputs from the user.

	deen_cli_init_args(&args);
	deen_cli_capture_args(&args, argc, argv);
	deen_cli_validate_args(&args);

	if (args.version) {
		printf("%s\n", DEEN_VERSION);
	}

	if (args.trace_enabled) {
		deen_set_trace_enabled(DEEN_TRUE);
	}

	// now action the indexing.

	if (args.index) {
		deen_cli_check_and_index(args.ding_filename);
	} else {
		if (NULL != args.search_expression) {
			deen_cli_query(&args);
		}
	}

	return EXIT_SUCCESS;
}


text:
<?php

namespace peterrehm\gh\Command;

use peterrehm\gh\Helper\GitHelper;
use peterrehm\gh\Helper\TemplatingHelper;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class MergeCommand extends GitHubBaseCommand
{
    /**
     * {@inheritdoc}
     */
    public function configure()
    {
        $this
            ->setName('merge')
            ->setDescription('Merges the pull request given')
            ->addArgument('pr', InputArgument::REQUIRED, 'Pull Request number')
            ->addOption('force', null, InputOption::VALUE_NONE, 'Enforce the merge if PR is in unstable state')
            ->addOption('branch', null, InputOption::VALUE_REQUIRED, 'Target branch', 'master');

        parent::configure();
    }

    /**
     * {@inheritdoc}
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var GitHelper $gitHelper */
        $gitHelper = $this->getHelper('git');

        /** @var QuestionHelper $questionHelper */
        $questionHelper = $this->getHelper('question');

        $branch = $input->getOption('branch');

        // fetch the PR information
        $client = $this->getClient();
        $pr = $client->pullRequest()->show($input->getOption('username'), $input->getOption('repository'), $input->getArgument('pr'));
        $commits = $client->pullRequest()->commits($input->getOption('username'), $input->getOption('repository'), $input->getArgument('pr'));

        $gitHelper->ensureRemoteConfiguration($input->getOption('username'), $pr['base']['repo']['clone_url']);

        // Skip if PR is already merged
        if (true === $pr['merged']) {
            $output->writeln('<error>Pull request has been merged already.</error>');
            return;
        }

        // If there are conflicts they have to be resolved manually
        if (false === $pr['mergeable']) {
            $output->writeln('<error>Pull request is not mergeable. Please rebase the PR and fix the conflicts.</error>');
            return;
        }

        $question = new ChoiceQuestion(
            'Please select the PR type:',
            array('feature', 'bug', 'minor')
        );

        $prType = $questionHelper->ask($input, $output, $question);
        $question = new ConfirmationQuestion(sprintf('Merge <info>%s</info> PR <info>#%s</info> "<info>%s</info>" by <info>%s</info> into <info>(%s)</info>? [y/n] ', $prType, $pr['number'], $pr['title'], $pr['user']['login'], $branch), false);

        if (!$questionHelper->ask($input, $output, $question)) {
            return;
        }

        // by default merges should only be possible if the mergeable state is clean which
        // means that there are no conflicts by CI
        if ('unstable' === $pr['mergeable_state'] && $input->hasOption('force') === false) {
            $output->writeln('<error>PR is not in clean state. Fix the CI errors or use the --force option.</error>');
            return;
        }

        /** @var TemplatingHelper $templatingHelper */
        $templatingHelper = $this->getHelper('templating');
        $commitMessage = $templatingHelper->render(
            'commit_message.tpl.twig',
            array('prType' => $prType, 'pr' => $pr, 'commits' => $commits)
        );

        $merged = $gitHelper->mergeRemote($input->getOption('username'), $branch, $input->getArgument('pr'), $commitMessage);

        // check if the PR has been merged
        if (false === $merged) {
            $output->writeln('<error>The pull request could not be merged.</error>');
            return;
        }

        $pr = $client->pullRequest()->show($input->getOption('username'), $input->getOption('repository'), $input->getArgument('pr'));

        // In case of a rebase the PR might not be closed, so close automatically
        if (false === $pr['merged']) {
            $client->pullRequest()->update($input->getOption('username'), $input->getOption('repository'), $input->getArgument('pr'), ['state' => 'closed']);
        }

        $output->writeln('The pull request has been merged successfully.');
    }
}


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

<title>com.centurylink.mdw.services (MDW 6 API JavaDocs)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.centurylink.mdw.services

Interfaces

AssetServices

CollaborationServices

DesignServices

EventServices

RequestServices

RulesServices

SolutionServices

StagingServices

SystemServices

TaskServices

TestingServices

UserServices

WorkflowServices

Classes

ConfigurationHelper

MessageServices

OfflineMonitorTrigger

ServiceLocator

Enums

SystemServices.SysInfoType

Exceptions

EventException

ProcessException

UserException


text:
namespace GeekLearning.Domain.AspnetCore
{
    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.Extensions.Logging;
    using System.Collections.Generic;

    public class DomainUserFilter : ActionFilterAttribute
    {
        private readonly IEnumerable<IIdentityDomain> identityDomains;
        private readonly ILogger<DomainUserFilter> logger;

        public DomainUserFilter(
            ILogger<DomainUserFilter> logger,
            IEnumerable<IIdentityDomain> identityDomains)
        {
            this.logger = logger;
            this.identityDomains = identityDomains;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.HttpContext.User == null
                   || context.HttpContext.User.Identity == null
                   || !context.HttpContext.User.Identity.IsAuthenticated)
            {
                foreach (var domain in this.identityDomains)
                {
                    domain.AsAnonymous();
                }
            }
            else
            {
                var principal = context.HttpContext.User;
                foreach (var domain in this.identityDomains)
                {
                    domain.As(principal);
                }
            }
        }
    }
}


text:
<?php

namespace Mcwork\Fs;

/**
 * Copy operation file system model
 *
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 *
 */
class Copy extends AbstractFs
{

    /**
     * Name of the folder or files to copy in fs
     *
     * @var string
     */
    private $copyItems = false;

    /**
     * Name of copy destination
     *
     * @var string
     */
    private $destination;

    /**
     * Create a new directory
     */
    public function copy()
    {
        return $this->copyDirectory(array(
            array(
                'value' => $this->getCopyItems()
            )
        ), $this->getDestination(), $this->getEntity(), $this->getFsCurrent());
    }

    /**
     *
     * @return the $copyItems
     */
    public function getCopyItems()
    {
        return $this->copyItems;
    }

    /**
     * Set items to copy in the fs
     *
     * @param multiple $copyItems
     */
    public function setCopyItems($copyItems)
    {
        $this->copyItems = $copyItems;
    }

    /**
     *
     * @return the $destination
     */
    public function getDestination()
    {
        return $this->destination;
    }

    /**
     *
     * @param string $destination
     */
    public function setDestination($destination)
    {
        $this->destination = $destination;
    }
}


text:
import React, { Component, PropTypes } from 'react';

var styles = {
  label: {
    WebkitUserSelect: 'none',
    cursor: 'default',
    fontFamily: '"San Francisco", "Helvetica Neue", "Lucida Grande", Arial, sans-serif',
    fontSize: '13px',
    whiteSpace: 'nowrap'
  },

  rowLabel: {
    textAlign: 'right',
    marginRight: '12px'
  }
};

class LabelOSX extends Component {
  static propTypes = {
    children: PropTypes.oneOfType([PropTypes.string, PropTypes.element, PropTypes.array]),
    style: PropTypes.object,
    color: PropTypes.string,
    row: PropTypes.any,
    form: PropTypes.any,
    align: PropTypes.string,
    visible: PropTypes.bool,
    display: PropTypes.bool
  };

  constructor(props) {
    super();
    this.state = { visible: props.visible !== false, display: props.display !== false };
  }

  componentDidMount() {
    if (this.props.row && this.props.form) {
      this.props.form.registerLabel(this);
    }
  }

  render() {
    const { children, style, color, row, form, align, display, visible, ...props } = this.props;

    let componentStyle = { ...styles.label, ...style }
    let componentColor = color;
    if (componentColor) {
      switch (componentColor) {
      case 'red': componentColor = '#fd2700'; break;
      }
      componentStyle = { ...componentStyle, color: componentColor }
    }

    if (row) {
      componentStyle = { ...componentStyle, ...styles.rowLabel }
    }

    if (align) {
      componentStyle = { ...componentStyle, textAlign: align }
    }

    componentStyle = {
      ...componentStyle,
      visibility: this.state.visible ? 'visible' : 'hidden',
      display: this.state.display ? 'block' : 'none'
    }

    return (
      <div
        ref="label"
        style={componentStyle}
        {...props}
      >
        {children}
      </div>
    );
  }
}

export default LabelOSX;


text:
import {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLInt,
  GraphQLBoolean,
  GraphQLString,
  GraphQLList,
} from 'graphql'
import mount from 'koa-mount'
import graphqlHTTP from 'koa-graphql'
import convert from 'koa-convert'
import { every, filter, flow, isFunction, map } from 'lodash'

let data = require('./data.json')
let idCounter = data.length

// TODO: debugger
const log = fn => (
  isFunction(fn)
    ? (...args) => (result => log(result))(fn(...args))
    : console.log(fn) || fn
)

const todoType = new GraphQLObjectType({
  name: 'Todo',
  fields: {
    id: { type: GraphQLInt },
    completed: { type: GraphQLBoolean },
    text: { type: GraphQLString },
  },
})

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'QueryTodos',
    fields: {
      getTodos: {
        type: new GraphQLList(todoType),
        resolve: flow(() => data, log),
      },
    },
  }),
  mutation: new GraphQLObjectType({
    name: 'UpdateTodo',
    fields: {
      addTodo: {
        type: new GraphQLList(todoType),
        args: {
          text: { type: GraphQLString },
        },
        resolve: flow((_, { text }) =>
          (data = [...data, { id: idCounter++, text, completed: false }]), log
        ),
      },
      completeTodo: {
        type: new GraphQLList(todoType),
        args: {
          id: { type: GraphQLInt },
        },
        resolve: flow((_, { id }) =>
          (data = map(data, todo =>
            (todo.id === id ? { ...todo, completed: !todo.completed } : todo)
          )), log
        ),
      },
      completeAll: {
        type: new GraphQLList(todoType),
        resolve: flow(() => {
          const areAllMarked = every(data, todo => todo.completed)
          return (data = map(data, todo => ({
            ...todo,
            completed: !areAllMarked,
          })))
        }, log),
      },
      editTodo: {
        type: new GraphQLList(todoType),
        args: {
          id: { type: GraphQLInt },
          text: { type: GraphQLString },
        },
        resolve: flow((_, { id, text }) =>
          (data = map(data, todo => (todo.id === id ? { ...todo, text } : todo))), log
        ),
      },
      deleteTodo: {
        type: new GraphQLList(todoType),
        args: {
          id: { type: GraphQLInt },
        },
        resolve: flow((_, { id }) =>
          (data = filter(data, todo => todo.id !== id)), log
        ),
      },
      clearCompleted: {
        type: new GraphQLList(todoType),
        resolve: flow(() =>
          (data = filter(data, todo => !todo.completed)), log
        ),
      },
    },
  }),
})

export default () => mount('/api', convert(graphqlHTTP({ schema, graphiql: true })))


text:
class Course::Assessment::Submission < ActiveRecord::Base
  include Workflow
  acts_as_experience_points_record

  after_save :auto_grade_submission, if: :submitted?

  workflow do
    state :attempting do
      event :finalise, transitions_to: :submitted
    end
    state :submitted do
      event :unsubmit, transitions_to: :attempting
      event :publish, transitions_to: :graded
    end
    state :graded
  end

  belongs_to :assessment, inverse_of: :submissions

  # @!attribute [r] answers
  #   The answers associated with this submission. There can be more than one answer per submission,
  #   this is because every answer is saved over time. Use the {.latest} scope of the answers if
  #   only the latest answer for each question is desired.
  has_many :answers, class_name: Course::Assessment::Answer.name, inverse_of: :submission do
    include Course::Assessment::Submission::AnswersConcern
  end
  has_many :multiple_response_answers,
           through: :answers, inverse_through: :answer, source: :actable,
           source_type: Course::Assessment::Answer::MultipleResponse.name
  has_many :text_response_answers,
           through: :answers, inverse_through: :answer, source: :actable,
           source_type: Course::Assessment::Answer::TextResponse.name
  has_many :programming_answers,
           through: :answers, inverse_through: :answer, source: :actable,
           source_type: Course::Assessment::Answer::Programming.name

  # @!attribute [r] graders
  #   The graders associated with this submission.
  has_many :graders, through: :answers, class_name: User.name

  accepts_nested_attributes_for :answers

  # @!attribute [r] submitted_at
  #   Gets the time the submission was submitted.
  #   @return [Time]
  calculated :submitted_at, (lambda do
    Course::Assessment::Answer.where do
      course_assessment_answers.submission_id == course_assessment_submissions.id
    end.select { max(course_assessment_answers.submitted_at) }
  end)

  # @!attribute [r] grade
  #   Gets the grade of the current submission.
  #   @return [Fixnum]
  calculated :grade, (lambda do
    Course::Assessment::Answer.where do
      course_assessment_answers.submission_id == course_assessment_submissions.id
    end.select { sum(course_assessment_answers.grade) }
  end)

  # @!attribute [r] graded_at
  #   Gets the time the submission was graded.
  #   @return [Time]
  calculated :graded_at, (lambda do
    Course::Assessment::Answer.where do
      course_assessment_answers.submission_id == course_assessment_submissions.id
    end.select { max(course_assessment_answers.graded_at) }
  end)

  # @!method self.by_user(user)
  #   Finds all the submissions by the given user.
  #   @param [User] user The user to filter submissions by
  scope :by_user, (lambda do |user|
    joins { experience_points_record.course_user }.
      where { experience_points_record.course_user.user == user }
  end)

  # @!method self.ordered_by_date
  #   Orders the submissions by date of creation. This defaults to reverse chronological order
  #   (newest submission first).
  scope :ordered_by_date, ->(direction = :desc) { order(created_at: direction) }

  alias_method :finalise=, :finalise!
  alias_method :publish=, :publish!

  # Creates an Auto Grading job for this submission. This saves the submission if there are pending
  # changes.
  #
  # @return [Course::Assessment::Submission::AutoGradingJob] The job instance.
  def auto_grade!
    AutoGradingJob.perform_later(self)
  end

  protected

  # Handles the finalisation of a submission.
  #
  # This finalises all the answers as well.
  def finalise(_ = nil)
    answers.each(&:finalise!)
  end

  # Handles the grading of a submission.
  #
  # This grades all the answers as well.
  def publish(_ = nil)
    answers.each do |answer|
      answer.publish! if answer.submitted?
    end
  end

  private

  # Queues the submission for auto grading, after the submission has changed to the submitted state.
  def auto_grade_submission
    return unless workflow_state_changed?

    auto_grade!
  end
end


text:
package org.apache.drill.exec.work.fragment;

import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.ops.ExecutorFragmentContext;
import org.apache.drill.exec.proto.BitControl.FragmentStatus;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.proto.UserBitShared.FragmentState;
import org.apache.drill.exec.proto.UserBitShared.MinorFragmentProfile;
import org.apache.drill.exec.proto.helper.QueryIdHelper;
import org.apache.drill.exec.rpc.control.ControlTunnel;

import java.util.concurrent.atomic.AtomicReference;

/**
 * The status reporter is responsible for receiving changes in fragment state and propagating the status back to the
 * Foreman either through a control tunnel or locally.
 */
public class FragmentStatusReporter implements AutoCloseable {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FragmentStatusReporter.class);

  protected final ExecutorFragmentContext context;

  protected final AtomicReference<DrillbitEndpoint> foremanDrillbit;

  public FragmentStatusReporter(final ExecutorFragmentContext context) {
    this.context = context;
    this.foremanDrillbit = new AtomicReference<>(context.getForemanEndpoint());
  }

  /**
   * Returns a {@link FragmentStatus} with the given state. {@link FragmentStatus} has additional information like
   * metrics, etc. that is gathered from the {@link ExecutorFragmentContext}.
   *
   * @param state the state to include in the status
   * @return the status
   */
  FragmentStatus getStatus(final FragmentState state) {
    return getStatus(state, null);
  }

  private FragmentStatus getStatus(final FragmentState state, final UserException ex) {
    final FragmentStatus.Builder status = FragmentStatus.newBuilder();
    final MinorFragmentProfile.Builder b = MinorFragmentProfile.newBuilder();
    context.getStats().addMetricsToStatus(b);
    b.setState(state);
    if (ex != null) {
      final boolean verbose = context.getOptions().getOption(ExecConstants.ENABLE_VERBOSE_ERRORS_KEY).bool_val;
      b.setError(ex.getOrCreatePBError(verbose));
    }
    status.setHandle(context.getHandle());
    b.setMemoryUsed(context.getAllocator().getAllocatedMemory());
    b.setMinorFragmentId(context.getHandle().getMinorFragmentId());
    status.setProfile(b);
    return status.build();
  }

  /**
   * Reports the state change to the Foreman. The state is wrapped in a {@link FragmentStatus} that has additional
   * information like metrics, etc. This additional information is gathered from the {@link ExecutorFragmentContext}.
   * NOTE: Use {@link #fail} to report state change to {@link FragmentState#FAILED}.
   *
   * @param newState the new state
   */
  void stateChanged(final FragmentState newState) {
    final FragmentStatus status = getStatus(newState, null);
    logger.info("{}: State to report: {}", QueryIdHelper.getQueryIdentifier(context.getHandle()), newState);
    switch (newState) {
      case AWAITING_ALLOCATION:
      case CANCELLATION_REQUESTED:
      case CANCELLED:
      case FINISHED:
      case RUNNING:
        sendStatus(status);
        break;
      case SENDING:
        // no op.
        break;
      case FAILED:
        // shouldn't get here since fail() should be called.
      default:
        throw new IllegalStateException(String.format("Received state changed event for unexpected state of %s.", newState));
    }
  }

  /**
   * Sends status to remote Foreman node using Control Tunnel or to Local Foreman bypassing
   * Control Tunnel and using WorkEventBus.
   *
   * @param status
   */
  void sendStatus(final FragmentStatus status) {

    DrillbitEndpoint foremanNode = foremanDrillbit.get();

    if (foremanNode == null) {
      logger.warn("{}: State {} is not reported as {} is closed", QueryIdHelper.getQueryIdentifier(context.getHandle()), status.getProfile().getState(), this);
      return;
    }

    // Send status for both local and remote foreman node via Tunnel. For local there won't be any network connection
    // created and it will be submitted locally using LocalControlConnectionManager
    final ControlTunnel tunnel = context.getController().getTunnel(foremanNode);
    tunnel.sendFragmentStatus(status);
  }

  /**
   * {@link FragmentStatus} with the {@link FragmentState#FAILED} state is reported to the Foreman. The
   * {@link FragmentStatus} has additional information like metrics, etc. that is gathered from the
   * {@link ExecutorFragmentContext}.
   *
   * @param ex the exception related to the failure
   */
  void fail(final UserException ex) {
    final FragmentStatus status = getStatus(FragmentState.FAILED, ex);
    sendStatus(status);
  }

  @Override
  public void close() {
    final DrillbitEndpoint foremanNode = foremanDrillbit.getAndSet(null);
    if (foremanNode != null) {
      logger.debug("Closing {}", this);
    } else {
      logger.warn("{} was already closed", this);
    }
  }
}


text:
/*! @license Firebase v4.3.1
Build: rev-b4fe95f
Terms: https://firebase.google.com/terms/ */

'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.StatsReporter = undefined;

var _obj = require('../../../utils/obj');

var _util = require('../util/util');

var _StatsListener = require('./StatsListener');

// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
// seconds to try to ensure the Firebase connection is established / settled.
var FIRST_STATS_MIN_TIME = 10 * 1000; /**
                                      * Copyright 2017 Google Inc.
                                      *
                                      * Licensed under the Apache License, Version 2.0 (the "License");
                                      * you may not use this file except in compliance with the License.
                                      * You may obtain a copy of the License at
                                      *
                                      *   http://www.apache.org/licenses/LICENSE-2.0
                                      *
                                      * Unless required by applicable law or agreed to in writing, software
                                      * distributed under the License is distributed on an "AS IS" BASIS,
                                      * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                                      * See the License for the specific language governing permissions and
                                      * limitations under the License.
                                      */

var FIRST_STATS_MAX_TIME = 30 * 1000;
// We'll continue to report stats on average every 5 minutes.
var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
/**
 * @constructor
 */
var StatsReporter = function () {
    /**
     * @param collection
     * @param server_
     */
    function StatsReporter(collection, server_) {
        this.server_ = server_;
        this.statsToReport_ = {};
        this.statsListener_ = new _StatsListener.StatsListener(collection);
        var timeout = FIRST_STATS_MIN_TIME + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
        (0, _util.setTimeoutNonBlocking)(this.reportStats_.bind(this), Math.floor(timeout));
    }
    StatsReporter.prototype.includeStat = function (stat) {
        this.statsToReport_[stat] = true;
    };
    StatsReporter.prototype.reportStats_ = function () {
        var _this = this;
        var stats = this.statsListener_.get();
        var reportedStats = {};
        var haveStatsToReport = false;
        (0, _obj.forEach)(stats, function (stat, value) {
            if (value > 0 && (0, _obj.contains)(_this.statsToReport_, stat)) {
                reportedStats[stat] = value;
                haveStatsToReport = true;
            }
        });
        if (haveStatsToReport) {
            this.server_.reportStats(reportedStats);
        }
        // queue our next run.
        (0, _util.setTimeoutNonBlocking)(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
    };
    return StatsReporter;
}();
exports.StatsReporter = StatsReporter;
//# sourceMappingURL=StatsReporter.js.map


text:
function Reddit(url, type) {

	var STR_REDDITBASE = 'http://www.reddit.com'
	this.getPosts = function(callback) {
		var xhr = Titanium.Network.createHTTPClient();

		xhr.onload = function() {
			var parsedJson = JSON.parse(this.responseText);
			if(parsedJson && parsedJson.data && parsedJson.data.children) {
				var items = [];
				for(var i = 0, j = parsedJson.data.children.length; i < j; i++) {
					var postData = parsedJson.data.children[i].data;
					items.push({
						title : postData.title,
						url : STR_REDDITBASE + postData.permalink,
						id : postData.id,
						commentCount : postData.num_comments,
						points : postData.score,
						time : postData.created_utc,
						timetype : 'timestamp',
						user : postData.author,
						thumbnail : postData.thumbnail,
						details : (type==='proggit')?postData.domain:postData.subreddit
					});
				};
				Ti.API.log(items);
				callback.call(this, items);
			}
		};
		// open the client
		xhr.open('GET', url);

		// send the data
		xhr.send();

	};
};

module.exports = Reddit;


text:
    <button class="btn btn-warning btn-lg btn-login requestback" ui-sref="customerRequest">

      Back
    </button>

{{customerActorCtrl.actor.name}}

Basic Info

{{customerActorCtrl.actor.basicinfo}}

Branch

{{branch}}

Description

{{customerActorCtrl.actor.description}}


text:
'use strict';
angular.module('myApp.timer', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/timer', {
    templateUrl: 'timer/timer.html',
    controller: 'timerCtrl'
  });
}])

.controller('timerCtrl', [ '$scope', '$timeout', 'settingsService', '$mdDialog', 'addCustomService', function($scope, $timeout, settingsService, $mdDialog, addCustomService) {
	$scope.fade = true;
    $scope.times = [
		{value : 25, name : "25 (Work Period)"},
		{value : 5, name : "5 (Short Break Period)"},
		{value : 10, name :"10 (Long Break Period)"}
	];

	$scope.paused = true;

	$scope.startButton = "Start";

	$scope.workTime = $scope.times[0];
	$scope.counter = $scope.workTime.value * 60;
	$scope.remainingMinutes = Math.floor($scope.counter / 60);
	$scope.remainingSeconds = $scope.counter - $scope.remainingMinutes * 60;
	if ($scope.remainingSeconds == 0)
		$scope.remainingSeconds = "00";

    $scope.onTimeout = function(){
        $scope.counter--;
        $scope.remainingMinutes = Math.floor($scope.counter / 60);
		$scope.remainingSeconds = $scope.counter - $scope.remainingMinutes * 60;
        if ($scope.counter > 0) {
            mytimeout = $timeout($scope.onTimeout,1000);
        }
        else {
        	$scope.playAudio();
            if ($scope.workTime == $scope.times[0]){
            	$scope.workTime = $scope.times[1];
            	$scope.counter = $scope.workTime.value * 60;
            	$scope.remainingMinutes = Math.floor($scope.counter / 60);
				$scope.remainingSeconds = $scope.counter - $scope.remainingMinutes * 60;
				if ($scope.remainingSeconds == 0)
					$scope.remainingSeconds = "00";
            }
            else{
            	$scope.workTime = $scope.times[0];
            	$scope.counter = $scope.workTime.value * 60;
            	$scope.remainingMinutes = Math.floor($scope.counter / 60);
				$scope.remainingSeconds = $scope.counter - $scope.remainingMinutes * 60;
				if ($scope.remainingSeconds == 0)
					$scope.remainingSeconds = "00";
            }
        }
    }
    var mytimeout;

    $scope.pause= function(){
    	$timeout.cancel(mytimeout);
    	$scope.paused = true;
    	$scope.startButton = "Start"
    }

    $scope.resume= function(){
    	mytimeout = $timeout($scope.onTimeout,1000);
    	$scope.paused = false;
    	$scope.startButton = "Pause"
    }

    $scope.startOrResume= function(){
    	if($scope.paused == true){
    		$scope.resume()
    	}
    	else{
    		$scope.pause();
    	}
    }

    $scope.reset= function(time){
        $scope.pause()
        $scope.workTime=time;
        $scope.counter = $scope.workTime.value * 60;
        $scope.resume()
    }

    $scope.addCustom= function(ev){
        $mdDialog.show({
          controller: DialogController,
          templateUrl: 'addCustomDialog.html',
          parent: angular.element(document.body),
          targetEvent: ev,
          clickOutsideToClose:true,
          fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
        })
        .then(function(){
            $scope.submitCustom();
        });
    }

    //controller for add custom time dialog
    function DialogController($scope, $mdDialog, settingsService) {
        $scope.hide = function() {
            $mdDialog.hide();
        };

        $scope.cancel = function() {
            $mdDialog.cancel();
        };

        $scope.confirm = function() {
            $scope.setNewCustomName()
            $scope.setNewCustomTime();
            $mdDialog.hide();
        };

        $scope.getNewCustomName = function(){
            return addCustomService.getNewCustomName();
        }

        $scope.getNewCustomTime = function(){
            return addCustomService.getNewCustomTime();
        }

        $scope.setNewCustomName = function(){
            return addCustomService.setNewCustomName($scope.newCustomName);
        }

        $scope.setNewCustomTime = function(){
            return addCustomService.setNewCustomTime($scope.newCustomTime);
        }

        //Range function for the time selector from 1-60minutes
        $scope.Range = function(start, end) {
            var result = [];
            for (var i = start; i <= end; i++) {
                result.push(i);
            }
            return result;
        }

        $scope.newCustomName = $scope.getNewCustomName();
        $scope.newCustomTime = $scope.getNewCustomTime();

    }

    $scope.newCustomName = ""; //set to default for safety
    $scope.newCustomTime = 1;

    $scope.submitCustom= function(){
        $scope.newCustomName = addCustomService.getNewCustomName();
        $scope.newCustomTime = addCustomService.getNewCustomTime();
    	$scope.times.push(
    		{value : $scope.newCustomTime,
    			name : $scope.newCustomTime.toString() + " ("+ $scope.newCustomName + ")"})
    	$scope.newCustomName = ""; //return to default
    	$scope.newCustomTime = 1;
        addCustomService.setNewCustomTime($scope.newCustomTime); //reset to defaults in service
        addCustomService.setNewCustomName($scope.newCustomName);
    	$scope.workTime = $scope.times[$scope.times.length-1]; //set selected time to newly added custom time
    }

    $scope.getAudioVolume = function(){
    	return settingsService.getAudioVolume();
    }

    $scope.getSoundFile = function(){
        return settingsService.getSoundFile();
    }

    $scope.playAudio = function() {
        var audio = new Audio($scope.getSoundFile());
        audio.volume = $scope.getAudioVolume();
        audio.play();
    };
}]);


text:
<?php

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 *
 * @author Aurora Voje <aurora.voje@jbv.no>
 */
$lang['noPrefix']              = 'Hvilke klasser (adskilt med komma) bør eksluderes fra å ha prefiks "wrap_"?';
$lang['restrictedClasses']     = 'begrens bruk av plugin til klasser adskilt med komma';
$lang['restrictionType']       = 'restriksjonstype, spesifiserer om de ovenforstående klassene skal inkluderes eller ekskluderes';
$lang['restrictionType_o_0']   = 'vis alle klasser bortsett fra de ovenforstående';
$lang['restrictionType_o_1']   = 'begrens til kun ovenforstående klasser og ingen fler';
$lang['syntaxDiv']             = 'Hvilken syntaks bør brukes i verktøylinjen valg for blokkomkransning?';
$lang['syntaxSpan']            = 'Hvilken syntaks bør brukes i verktøylinjen valg for omkransning på en linje?';
$lang['darkTpl']               = 'Optimer farger for mørke maler?';


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="widget_base_width" content="74">
    <meta name="widget_base_height" content="71">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="gridster_disable" content="1">
    <meta name="longpoll" content="1">
    <meta name="debug" content="2">

    <link rel="stylesheet" href="lib/jquery.gridster.min.css" />
    <link rel="stylesheet" href="css/fhem-tablet-ui.css" />
    <link rel="stylesheet" href="css/fhem-mobil-ui.css" />
    <link rel="stylesheet" href="lib/font-awesome.min.css" />
    <link rel="stylesheet" href="lib/jquery.toast.min.css" />

    <title>FHEM-Tablet-UI-mobil</title>

Temps

Lights

Windows

Sounds


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

		<title>testpage</title>
		<meta name="description" content="" />
		<meta name="author" content="System Crasher" />

		<meta name="viewport" content="width=device-width; initial-scale=1.0" />

		<link rel="shortcut icon" href="/favicon.ico" />
		<link rel="apple-touch-icon" href="/apple-touch-icon.png" />


text:
package com.seifernet.chatclient.mail;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import org.jboss.logging.Logger;

import com.seifernet.chatclient.util.Definitions;

/**
 * Mail messenger class
 *
 * @author Seifer ( Cuauhtemoc Herrera Muñoz )
 * @version 1.0.0
 * @since 1.0.0
 */
public class Messenger {

	@Resource( mappedName=Definitions.MAIL_SESSION_CONTEXT )
	private Session session;
	private Logger logger = Logger.getLogger( Messenger.class );

	/**
	 * Sends a message via SMTP
	 *
	 * @param messageData - The message data
	 */
	public void sendMail( com.seifernet.chatclient.mail.Message messageData ) {
		MimeMessage message = null;

		try{
			message = new MimeMessage( session );
			message.setFrom( messageData.getFrom( ) );
			message.addRecipient( Message.RecipientType.TO, messageData.getTo( ) );
			message.setHeader( "Content-Type", Definitions.CONTENT_PLAIN_TEXT + "; charset=\"" + Definitions.UTF8_CHARSET + "\"" );
			message.setSubject( messageData.getSubject( ) );
			message.setText( messageData.getContent( ) );
			Transport.send( message );
		} catch ( MessagingException e) {
			logger.error( "Unable to send email ERROR:MAIL" );
		}
	}
}


text:
layout: post
title: "Centos 安装 Docker"
description: ""
category: 技术
tags: ["Centos", "Docker"]
published: true
---

## 安装 Docker

```bash
sudo yum install -y yum-utils device-mapper-persistent-data lvm2

sudo yum-config-manager --add-repo https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce.repo

sudo yum install docker-ce -y
```

启动

```bash
sudo systemctl start docker
```

开机启动

```bash
sudo systemctl enable docker
```

## 安装 docker-compose

```bash
yum install -y epel-release

yum install -y docker-compose
```


text:
package net.sourceforge.plantuml.posimo;

public interface Moveable {

	void moveSvek(double deltaX, double deltaY);

}


text:
package com.lapms.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lapms.entity.PersonThymeleafTest;

@Controller
public class ThymeleafTestController {

	@RequestMapping("/index")
	public String index(Model model){
		PersonThymeleafTest single = new PersonThymeleafTest("aa",11);

		List<PersonThymeleafTest> people = new ArrayList<PersonThymeleafTest>();
		PersonThymeleafTest p1 = new PersonThymeleafTest("xx",11);
		PersonThymeleafTest p2 = new PersonThymeleafTest("yy",22);
		PersonThymeleafTest p3 = new PersonThymeleafTest("zz",33);
		people.add(p1);
		people.add(p2);
		people.add(p3);

		model.addAttribute("singlePerson", single);
		model.addAttribute("people", people);

		return "index";
	}
}


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

public class BaseAndroidPopup : MonoBehaviour {

	public string title;
	public string message;

	public event Action<AndroidDialogResult> ActionComplete = delegate{};

	//--------------------------------------
	// INITIALIZE
	//--------------------------------------

	//--------------------------------------
	//  PUBLIC METHODS
	//--------------------------------------

	//--------------------------------------
	//  GET/SET
	//--------------------------------------

	//--------------------------------------
	//  EVENTS
	//--------------------------------------

	public void onDismissed(string data) {
		ActionComplete(AndroidDialogResult.CLOSED);
		Destroy(gameObject);
	}

	protected void DispatchAction(AndroidDialogResult res) {
		ActionComplete(res);
	}

	//--------------------------------------
	//  PRIVATE METHODS
	//--------------------------------------

	//--------------------------------------
	//  DESTROY
	//--------------------------------------

}


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

<TITLE>
ScriptRunnerHelper (Apache Ant API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.tools.ant.util.ScriptRunnerHelper class">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.tools.ant.util

Class ScriptRunnerHelper

java.lang.Object
  org.apache.tools.ant.util.ScriptRunnerHelper

public class ScriptRunnerHelper
extends java.lang.Object

A class to help in creating, setting and getting script runners.

Constructor Summary

ScriptRunnerHelper()

Method Summary

 void
add(ResourceCollection resource)

          Add any source resource.

 void
addText(java.lang.String text)

          Add script text.

 Path
createClasspath()

          Classpath to be used when searching for classes and resources.

 java.lang.String
getLanguage()

          Get the language.

 ScriptRunnerBase
getScriptRunner()

          Create and set text on a script.

 void
setClassLoader(java.lang.ClassLoader loader)

          Used when called by scriptdef.

 void
setClasspath(Path classpath)

          Set the classpath to be used when searching for classes and resources.

 void
setClasspathRef(Reference r)

          Set the classpath by reference.

 void
setLanguage(java.lang.String language)

          Defines the language (required).

 void
setManager(java.lang.String manager)

          Defines the script manager - defaults to "auto".

 void
setProjectComponent(ProjectComponent component)

          Set the project component associated with this helper.

 void
setSetBeans(boolean setBeans)

          Set the setbeans attribute.

 void
setSrc(java.io.File file)

          Load the script from an external file ; optional.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ScriptRunnerHelper

public ScriptRunnerHelper()

Method Detail

setProjectComponent

public void setProjectComponent(ProjectComponent component)

Set the project component associated with this helper.

Parameters:
component - the project component that owns this helper.

getScriptRunner

public ScriptRunnerBase getScriptRunner()

Create and set text on a script.

Returns:
the created or reused script runner.

createClasspath

public Path createClasspath()

Classpath to be used when searching for classes and resources.

Returns:
an empty Path instance to be configured by Ant.

setClasspath

public void setClasspath(Path classpath)

Set the classpath to be used when searching for classes and resources.

Parameters:
classpath - an Ant Path object containing the search path.

setClasspathRef

public void setClasspathRef(Reference r)

Set the classpath by reference.

Parameters:
r - a Reference to a Path instance to be used as the classpath
          value.

setSrc

public void setSrc(java.io.File file)

Load the script from an external file ; optional.

Parameters:
file - the file containing the script source.

addText

public void addText(java.lang.String text)

Add script text.

Parameters:
text - a component of the script text to be added.

setManager

public void setManager(java.lang.String manager)

Defines the script manager - defaults to "auto".

Parameters:
manager - the scripting manager - "bsf" or "javax" or "auto"

setLanguage

public void setLanguage(java.lang.String language)

Defines the language (required).

Parameters:
language - the scripting language name for the script.

getLanguage

public java.lang.String getLanguage()

Get the language.

Returns:
the scripting language.

setSetBeans

public void setSetBeans(boolean setBeans)

Set the setbeans attribute.
 If this is true, <script> will create variables in the
 script instance for all
 properties, targets and references of the current project.
 It this is false, only the project and self variables will
 be set.
 The default is true.

Parameters:
setBeans - the value to set.

setClassLoader

public void setClassLoader(java.lang.ClassLoader loader)

Used when called by scriptdef.

Parameters:
loader - the loader used by scriptdef.

add

public void add(ResourceCollection resource)

Add any source resource.

Parameters:
resource - source of script
Since:

Ant 1.7.1

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
"""Customized base ModelAdmin classes"""

from django.contrib import admin
from storybase.fields import ShortTextField
from storybase.widgets import AdminLongTextInputWidget

class StorybaseModelAdmin(admin.ModelAdmin):
    """
    Base class for ModelAdmin classes in this project

    Correctly sets the widget for our text field class in the Django
    Admin.  It seems like this is the only place you can do it, though
    it would be nice to do it with the field definition.

    Also provides a prefix_inlines attribute that allows us to show some
    inlines before the rest of the fields rather than after (the default)

    """
    # List of classes listed in ModelAdmin.inlines that should have their
    # form shown before the model's non-inline fields rahter than after
    # Useful for translations
    prefix_inline_classes = []

    formfield_overrides = {
        ShortTextField: {'widget': AdminLongTextInputWidget},
    }

    def add_view(self, request, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['prefix_inline_classes'] = self.prefix_inline_classes
        return super(StorybaseModelAdmin, self).add_view(request, form_url,
           extra_context=extra_context)

    def change_view(self, request, object_id, extra_context=None):
        extra_context = extra_context or {}
        extra_context['prefix_inline_classes'] = self.prefix_inline_classes
        return super(StorybaseModelAdmin, self).change_view(request, object_id,
           extra_context=extra_context)

class StorybaseStackedInline(admin.StackedInline):
    """Custom version of StackedInline

    This sets the widget for ShortTextField fields to the customized
    wider version.  It also provides a method to let us display some
    inlines before non-inline model fields and some after.

    """
    formfield_overrides = {
        ShortTextField: {'widget': AdminLongTextInputWidget},
    }

    def type(self):
        """ Get the class name of this inline

        Django's templates don't let us access attributes that start
        with '__', so we need to wrap it in a method.  This is used
        to check whether the an inline form should be shown before or
        after the other fields.

        """
        return self.__class__.__name__

class Select2StackedInline(admin.StackedInline):
    """
    Stacked inline that allows for using Select2 for the select widget

    The heavy lifting is performed by additional JavaScript in the template.

    """
    template = 'admin/edit_inline/select2_stacked.html'

    class Media:
        css = {
            "all": ("js/libs/select2/select2.css",)
        }
        js = ("js/admin/init.js", "js/libs/select2/select2.js",
              "js/admin/select_filters.js")

def obj_title(obj):
    """ Callable to display an object title in the Django admin

    This is needed because title isn't an attribute of the Story or
    Section models, it's an attribute of the translation class.

    """
    if obj.title:
        return obj.title
    else:
        return str(obj)
obj_title.short_description = 'Title'

def toggle_featured(modeladmin, request, queryset):
    featured_field_name = 'on_homepage'
    # In Django 1.5, we could use an F() object to update this in a single
    # query. See https://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model
    for obj in queryset:
        featured = getattr(obj, featured_field_name)
        setattr(obj, featured_field_name, not featured)
        obj.save()
toggle_featured.short_description = "Toggle the featured on homepage status"


text:
'use strict';
/**
 * TXT export
 */

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

const Changeset = require('../../static/js/Changeset');
const attributes = require('../../static/js/attributes');
const padManager = require('../db/PadManager');
const _analyzeLine = require('./ExportHelper')._analyzeLine;

// This is slightly different than the HTML method as it passes the output to getTXTFromAText
const getPadTXT = async (pad, revNum) => {
  let atext = pad.atext;

  if (revNum !== undefined) {
    // fetch revision atext
    atext = await pad.getInternalRevisionAText(revNum);
  }

  // convert atext to html
  return getTXTFromAtext(pad, atext);
};

// This is different than the functionality provided in ExportHtml as it provides formatting
// functionality that is designed specifically for TXT exports
const getTXTFromAtext = (pad, atext, authorColors) => {
  const apool = pad.apool();
  const textLines = atext.text.slice(0, -1).split('\n');
  const attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text);

  const props = ['heading1', 'heading2', 'bold', 'italic', 'underline', 'strikethrough'];
  const anumMap = {};
  const css = '';

  props.forEach((propName, i) => {
    const propTrueNum = apool.putAttrib([propName, true], true);
    if (propTrueNum >= 0) {
      anumMap[propTrueNum] = i;
    }
  });

  const getLineTXT = (text, attribs) => {
    const propVals = [false, false, false];
    const ENTER = 1;
    const STAY = 2;
    const LEAVE = 0;

    // Use order of tags (b/i/u) as order of nesting, for simplicity
    // and decent nesting.  For example,
    // Just bold Bold and italics Just italics
    // becomes
    // Just bold Bold and italics Just italics
    const taker = Changeset.stringIterator(text);
    const assem = Changeset.stringAssembler();

    let idx = 0;

    const processNextChars = (numChars) => {
      if (numChars <= 0) {
        return;
      }

      const ops = Changeset.deserializeOps(Changeset.subattribution(attribs, idx, idx + numChars));
      idx += numChars;

      for (const o of ops) {
        let propChanged = false;

        for (const a of attributes.decodeAttribString(o.attribs)) {
          if (a in anumMap) {
            const i = anumMap[a]; // i = 0 => bold, etc.

            if (!propVals[i]) {
              propVals[i] = ENTER;
              propChanged = true;
            } else {
              propVals[i] = STAY;
            }
          }
        }

        for (let i = 0; i < propVals.length; i++) {
          if (propVals[i] === true) {
            propVals[i] = LEAVE;
            propChanged = true;
          } else if (propVals[i] === STAY) {
            // set it back
            propVals[i] = true;
          }
        }

        // now each member of propVal is in {false,LEAVE,ENTER,true}
        // according to what happens at start of span
        if (propChanged) {
          // leaving bold (e.g.) also leaves italics, etc.
          let left = false;

          for (let i = 0; i < propVals.length; i++) {
            const v = propVals[i];

            if (!left) {
              if (v === LEAVE) {
                left = true;
              }
            } else if (v === true) {
              // tag will be closed and re-opened
              propVals[i] = STAY;
            }
          }

          const tags2close = [];

          for (let i = propVals.length - 1; i >= 0; i--) {
            if (propVals[i] === LEAVE) {
              // emitCloseTag(i);
              tags2close.push(i);
              propVals[i] = false;
            } else if (propVals[i] === STAY) {
              // emitCloseTag(i);
              tags2close.push(i);
            }
          }

          for (let i = 0; i < propVals.length; i++) {
            if (propVals[i] === ENTER || propVals[i] === STAY) {
              propVals[i] = true;
            }
          }
          // propVals is now all {true,false} again
        } // end if (propChanged)

        let chars = o.chars;
        if (o.lines) {
          // exclude newline at end of line, if present
          chars--;
        }

        const s = taker.take(chars);

        // removes the characters with the code 12. Don't know where they come
        // from but they break the abiword parser and are completly useless
        // s = s.replace(String.fromCharCode(12), "");

        // remove * from s, it's just not needed on a blank line..  This stops
        // plugins from being able to display * at the beginning of a line
        // s = s.replace("*", ""); // Then remove it

        assem.append(s);
      } // end iteration over spans in line

      const tags2close = [];
      for (let i = propVals.length - 1; i >= 0; i--) {
        if (propVals[i]) {
          tags2close.push(i);
          propVals[i] = false;
        }
      }
    };
    // end processNextChars

    processNextChars(text.length - idx);
    return (assem.toString());
  };
  // end getLineHTML

  const pieces = [css];

  // Need to deal with constraints imposed on HTML lists; can
  // only gain one level of nesting at once, can't change type
  // mid-list, etc.
  // People might use weird indenting, e.g. skip a level,
  // so we want to do something reasonable there.  We also
  // want to deal gracefully with blank lines.
  // => keeps track of the parents level of indentation

  const listNumbers = {};
  let prevListLevel;

  for (let i = 0; i < textLines.length; i++) {
    const line = _analyzeLine(textLines[i], attribLines[i], apool);
    let lineContent = getLineTXT(line.text, line.aline);

    if (line.listTypeName === 'bullet') {
      lineContent = `* ${lineContent}`; // add a bullet
    }

    if (line.listTypeName !== 'number') {
      // We're no longer in an OL so we can reset counting
      for (const key of Object.keys(listNumbers)) {
        delete listNumbers[key];
      }
    }

    if (line.listLevel > 0) {
      for (let j = line.listLevel - 1; j >= 0; j--) {
        pieces.push('\t'); // tab indent list numbers..
        if (!listNumbers[line.listLevel]) {
          listNumbers[line.listLevel] = 0;
        }
      }

      if (line.listTypeName === 'number') {
        /*
        * listLevel == amount of indentation
        * listNumber(s) == item number
        *
        * Example:
        * 1. foo
        *  1.1 bah
        * 2. latte
        *  2.1 latte
        *
        * To handle going back to 2.1 when prevListLevel is lower number
        * than current line.listLevel then reset the object value
        */
        if (line.listLevel < prevListLevel) {
          delete listNumbers[prevListLevel];
        }

        listNumbers[line.listLevel]++;
        if (line.listLevel > 1) {
          let x = 1;
          while (x <= line.listLevel - 1) {
            // if it's undefined to avoid undefined.undefined.1 for 0.0.1
            if (!listNumbers[x]) listNumbers[x] = 0;
            pieces.push(`${listNumbers[x]}.`);
            x++;
          }
        }
        pieces.push(`${listNumbers[line.listLevel]}. `);
        prevListLevel = line.listLevel;
      }

      pieces.push(lineContent, '\n');
    } else {
      pieces.push(lineContent, '\n');
    }
  }

  return pieces.join('');
};

exports.getTXTFromAtext = getTXTFromAtext;

exports.getPadTXTDocument = async (padId, revNum) => {
  const pad = await padManager.getPad(padId);
  return getPadTXT(pad, revNum);
};


text:
using System;
using Newtonsoft.Json.Linq;
using Skybrud.Essentials.Common;
using Skybrud.Essentials.Http;
using Skybrud.Social.GitHub.Http;
using Skybrud.Social.GitHub.Models.Issues;

namespace Skybrud.Social.GitHub.Options.Issues.Comments {

    /// <summary>
    /// Class representing the options for adding a comment to a GitHub issue.
    /// </summary>
    public class GitHubAddIssueCommentOptions : GitHubHttpRequestOptions {

        #region Properties

        /// <summary>
        /// Mandatory: Gets or sets the username (login) of the owner of the repository.
        /// </summary>
        public string Owner { get; set; }

        /// <summary>
        /// Mandatory: Gets or sets the slug of the repository.
        /// </summary>
        public string Repository { get; set; }

        /// <summary>
        /// Gets or sets the number of the issue to which the comment should be added.
        /// </summary>
        public int Number { get; set; }

        /// <summary>
        /// Gets or sets the Markdown-based body of the comment.
        /// </summary>
        /// <see>
        ///     <cref>https://guides.github.com/features/mastering-markdown/</cref>
        /// </see>
        public string Body { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance with default options.
        /// </summary>
        public GitHubAddIssueCommentOptions() { }

        /// <summary>
        /// Initializes a new instance based on the specified <paramref name="owner"/>, <paramref name="repository"/>,
        /// <paramref name="number"/> and <paramref name="body"/>.
        /// </summary>
        /// <param name="owner">The username (login) of the owner of the repository.</param>
        /// <param name="repository">The slug of the repository.</param>
        /// <param name="number">The number of the issue.</param>
        /// <param name="body">The Markdown-based body of the comment.</param>
        public GitHubAddIssueCommentOptions(string owner, string repository, int number, string body) {
            Owner = owner;
            Repository = repository;
            Number = number;
            Body = body;
        }

        /// <summary>
        /// Initializes a new instance based on the specified <paramref name="issue"/> and <paramref name="body"/>.
        /// </summary>
        /// <param name="issue">The issue to which the comment will be added.</param>
        /// <param name="body">The Markdown-based body of the comment.</param>
        public GitHubAddIssueCommentOptions(GitHubIssue issue, string body) {
            if (issue == null) throw new ArgumentNullException(nameof(issue));
            Owner = issue.Repository.Owner.Login;
            Repository = issue.Repository.Name;
            Number = issue.Number;
            Body = body;
        }

        #endregion

        #region Member methods

        /// <summary>
        /// Returns a new <see cref="IHttpRequest"/> instance for this options instance.
        /// </summary>
        /// <returns>An instance of <see cref="IHttpRequest"/>.</returns>
        public override IHttpRequest GetRequest() {

            // Validate required parameters
            if (string.IsNullOrWhiteSpace(Owner)) throw new PropertyNotSetException(nameof(Owner));
            if (string.IsNullOrWhiteSpace(Repository)) throw new PropertyNotSetException(nameof(Repository));
            if (Number == 0) throw new PropertyNotSetException(nameof(Number));
            if (string.IsNullOrWhiteSpace(Body)) throw new PropertyNotSetException(nameof(Body));

            // Generate the payload for the request body
            JObject body = new JObject {
                {"body", Body}
            };

            // Initialize the request
            return HttpRequest
                .Post($"/repos/{Owner}/{Repository}/issues/{Number}/comments", body)
                .SetAcceptHeader(MediaTypes);

        }

        #endregion

    }

}