text:
<?php

App::uses('Security', 'Utility');
App::uses('UsersAppModel', 'Users.Model');
App::uses('SearchableBehavior', 'Search.Model/Behavior');
App::uses('SluggableBehavior', 'Utils.Model/Behavior');

class User extends UsersAppModel {

	public $name = 'User';

	public $virtualFields = array(
		'comment_count' => 'SELECT COUNT(*) FROM comments as Comment where Comment.user_id = User.id'
	);

	public $findMethods = array(
		'search' => true
	);

	public $filterArgs = array(
		'username' => array('type' => 'like'),
		'email' => array('type' => 'value')
	);

	public $displayField = 'username';

	public $emailTokenExpirationTime = 86400;

	public $validationDomain = 'users';

	public $validate = array(
		'username' => array(
			'required' => array(
				'rule' => array('notEmpty'),
				'required' => true, 'allowEmpty' => false,
				'message' => 'Please enter a username.'
			)
			/*,
			'alpha' => array(
				'rule' => array('alphaNumeric'),
				'message' => 'The username must be alphanumeric.'
			),
			'unique_username' => array(
				'rule' => array('isUnique', 'username'),
				'message' => 'This username is already in use.'
			),
			'username_min' => array(
				'rule' => array('minLength', '3'),
				'message' => 'The username must have at least 3 characters.'
			) */
		),
		'email' => array(
			'isValid' => array(
				'rule' => 'email',
				'required' => true,
				'message' => 'Please enter a valid email address.'
			),
			'isUnique' => array(
				'rule' => array('isUnique', 'email'),
				'message' => 'This email is already in use.'
			)
		),
		'password' => array(
			'too_short' => array(
				'rule' => array('minLength', '6'),
				'message' => 'The password must have at least 6 characters.'
			),
			'required' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter a password.'
			)
		),
		'temppassword' => array(
			'rule' => 'confirmPassword',
			'message' => 'The passwords are not equal, please try again.'
		),
		'tos' => array(
			'rule' => array('custom','[1]'),
			'message' => 'You must agree to the terms of use.'
		)
	);

	public function __construct($id = false, $table = null, $ds = null) {
		$this->_setupBehaviors();
		$this->_setupValidation();
		parent::__construct($id, $table, $ds);
	}

	protected function _setupBehaviors() {
		if (CakePlugin::loaded('Search') && class_exists('SearchableBehavior')) {
			$this->actsAs[] = 'Search.Searchable';
		}

		if (CakePlugin::loaded('Utils') && class_exists('SluggableBehavior') && Configure::read('Users.disableSlugs') !== true) {
			$this->actsAs['Utils.Sluggable'] = array(
				'label' => 'username',
				'method' => 'multibyteSlug'
			);
		}
	}

/**
 * Setup validation rules
 *
 * @return void
 */
	protected function _setupValidation() {
		$this->validatePasswordChange = array(
			'new_password' => $this->validate['password'],
			'confirm_password' => array(
				'required' => array('rule' => array('compareFields', 'new_password', 'confirm_password'), 'required' => true, 'message' => __d('users', 'The passwords are not equal.'))),
			'old_password' => array(
				'to_short' => array('rule' => 'validateOldPassword', 'required' => true, 'message' => __d('users', 'Invalid password.'))
			)
		);
	}

	public function hash($string, $type = null, $salt = false) {
		return Security::hash($string, $type, $salt);
	}

	public function confirmPassword($password = null) {
		if ((isset($this->data[$this->alias]['password']) && isset($password['temppassword']))
			&& !empty($password['temppassword'])
			&& ($this->data[$this->alias]['password'] === $password['temppassword'])) {
			return true;
		}
		return false;
	}

	public function confirmEmail($email = null) {
		if ((isset($this->data[$this->alias]['email']) && isset($email['confirm_email']))
			&& !empty($email['confirm_email'])
			&& (strtolower($this->data[$this->alias]['email']) === strtolower($email['confirm_email']))) {
				return true;
		}
		return false;
	}

/**
 * Checks the token for email verification
 *
 * @param string $token
 * @return array
 */
	public function checkEmailVerfificationToken($token = null) {
		$result = $this->find('first', array(
			'contain' => array(),
			'conditions' => array(
				$this->alias . '.email_verified' => null,
				$this->alias . '.email_token' => $token),
			'fields' => array(
				'id', 'email', 'email_token_expires', 'role')
			)
		);

		if (empty($result)) {
			return false;
		}

		return $result;
	}

/**
 * Verifies a users email by a token that was sent to him via email and flags the user record as active
 *
 * @param string $token The token that wa sent to the user
 * @throws RuntimeException
 * @return array On success it returns the user data record
 */
	public function verifyEmail($token = null) {
		$user = $this->checkEmailVerfificationToken($token);

		if ($user === false) {
			throw new RuntimeException(__d('users', 'Invalid token, please check the email you were sent, and retry the verification link.'));
		}

		$expires = strtotime($user[$this->alias]['email_token_expires']);
		if ($expires < time()) {
			throw new RuntimeException(__d('users', 'The token has expired.'));
		}

		$data[$this->alias]['active'] = 1;
		$user[$this->alias]['email_verified'] = 1;
		$user[$this->alias]['email_token'] = null;
		$user[$this->alias]['email_token_expires'] = null;

		$user = $this->save($user, array(
			'validate' => false,
			'callbacks' => false
		));
		$this->data = $user;
		return $user;
	}

/**
 * Updates the last activity field of a user
 *
 * @param string $userId User id
 * @param string $field Default is "last_action", changing it allows you to use this method also for "last_login" for example
 * @return boolean True on success
 */
	public function updateLastActivity($userId = null, $field = 'last_action') {
		if (!empty($userId)) {
			$this->id = $userId;
		}
		if ($this->exists()) {
			return $this->saveField($field, date('Y-m-d H:i:s', time()));
		}
		return false;
	}

/**
 * Checks if an email is in the system, validated and if the user is active so that the user is allowed to reste his password
 *
 * @param array $postData post data from controller
 * @return mixed False or user data as array on success
 */
	public function passwordReset($postData = array()) {
		$user = $this->find('first', array(
			'contain' => array(),
			'conditions' => array(
				$this->alias . '.active' => 1,
				$this->alias . '.email' => $postData[$this->alias]['email'])));

		if (!empty($user) && $user[$this->alias]['email_verified'] == 1) {
			$sixtyMins = time() + 43000;
			$token = $this->generateToken();
			$user[$this->alias]['password_token'] = $token;
			$user[$this->alias]['email_token_expires'] = date('Y-m-d H:i:s', $sixtyMins);
			$user = $this->save($user, false);
			$this->data = $user;
			return $user;
		} elseif (!empty($user) && $user[$this->alias]['email_verified'] == 0) {
			//$this->invalidate('email', __d('users', 'This Email Address exists but was never validated.'));
			$this->data = $user;
			return $user;
		} else {
			$this->invalidate('email', __d('users', 'This Email Address does not exist in the system.'));
		}

		return false;
	}

/**
 * Checks the token for a password change
 *
 * @param string $token Token
 * @return mixed False or user data as array
 */
	public function checkPasswordToken($token = null) {
		$user = $this->find('first', array(
			'contain' => array(),
			'conditions' => array(
				$this->alias . '.active' => 1,
				$this->alias . '.password_token' => $token,
				$this->alias . '.email_token_expires >=' => date('Y-m-d H:i:s'))));
		if (empty($user)) {
			return false;
		}
		return $user;
	}

/**
 * Changes the validation rules for the User::resetPassword() method
 *
 * @return array Set of rules required for the User::resetPassword() method
 */
	public function setUpResetPasswordValidationRules() {
		return array(
			'new_password' => $this->validate['password'],
			'confirm_password' => array(
				'required' => array(
					'rule' => array('compareFields', 'new_password', 'confirm_password'),
					'message' => __d('users', 'The passwords are not equal.')
				)
			)
		);
	}

/**
 * Resets the password
 *
 * @param array $postData Post data from controller
 * @return boolean True on success
 */
	public function resetPassword($postData = array()) {
		$result = false;

		$tmp = $this->validate;
		$this->validate = $this->setUpResetPasswordValidationRules();

		$this->set($postData);
		if ($this->validates()) {
			$this->data[$this->alias]['password'] = $this->hash($this->data[$this->alias]['new_password'], null, true);
			$this->data[$this->alias]['password_token'] = null;
			$result = $this->save($this->data, array(
				'validate' => false,
				'callbacks' => false)
			);
		}

		$this->validate = $tmp;
		return $result;
	}

/**
 * Changes the password for a user
 *
 * @param array $postData Post data from controller
 * @return boolean True on success
 */
	public function changePassword($postData = array()) {
		$this->validate = $this->validatePasswordChange;

		$this->set($postData);
		if ($this->validates()) {
			$this->data[$this->alias]['password'] = $this->hash($this->data[$this->alias]['new_password'], null, true);
			$this->save($postData, array(
				'validate' => false,
				'callbacks' => false));
			return true;
		}
		return false;
	}

/**
 * Validation method to check the old password
 *
 * @param array $password
 * @throws OutOfBoundsException
 * @return boolean True on success
 */
	public function validateOldPassword($password) {
		if (!isset($this->data[$this->alias]['id']) || empty($this->data[$this->alias]['id'])) {
			if (Configure::read('debug') > 0) {
				throw new OutOfBoundsException(__d('users', '$this->data[\'' . $this->alias . '\'][\'id\'] has to be set and not empty'));
			}
		}

		$currentPassword = $this->field('password', array($this->alias . '.id' => $this->data[$this->alias]['id']));
		return $currentPassword === $this->hash($password['old_password'], null, true);
	}

/**
 * Validation method to compare two fields
 *
 * @param mixed $field1 Array or string, if array the first key is used as fieldname
 * @param string $field2 Second fieldname
 * @return boolean True on success
 */
	public function compareFields($field1, $field2) {
		if (is_array($field1)) {
			$field1 = key($field1);
		}

		if (isset($this->data[$this->alias][$field1]) && isset($this->data[$this->alias][$field2]) &&
			$this->data[$this->alias][$field1] == $this->data[$this->alias][$field2]) {
			return true;
		}
		return false;
	}

/**
 * Returns all data about a user
 *
 * @param string|integer $slug user slug or the uuid of a user
 * @param string $field
 * @throws NotFoundException
 * @return array
 */
	public function view($slug = null, $field = 'slug') {
		$user = $this->find('first', array(
			'contain' => array(),
			'conditions' => array(
				'OR' => array(
					$this->alias . '.' . $field => $slug,
					$this->alias . '.' . $this->primaryKey => $slug),
				$this->alias . '.active' => 1,
				$this->alias . '.email_verified' => 1)));

		if (empty($user)) {
			throw new NotFoundException(__d('users', 'The user does not exist.'));
		}

		return $user;
	}

/**
 * Finds an user simply by email
 *
 * Used by the following methods:
 *  - checkEmailVerification
 *  - resendVerification
 *
 * Override it as needed, to add additional models to contain for example
 *
 * @param string $email
 * @return array
 */
	public function findByEmail($email = null) {
		return $this->find('first', array(
			'contain' => array(),
			'conditions' => array(
				$this->alias . '.email' => $email,
			)
		));
	}

/**
 * Checks if an email is already verified and if not renews the expiration time
 *
 * @param array $postData the post data from the request
 * @param boolean $renew
 * @return bool True if the email was not already verified
 */
	public function checkEmailVerification($postData = array(), $renew = true) {
		$user = $this->findByEmail($postData[$this->alias]['email']);

		if (empty($user)) {
			$this->invalidate('email', __d('users', 'Invalid Email address.'));
			return false;
		}

		if ($user[$this->alias]['email_verified'] == 1) {
			$this->invalidate('email', __d('users', 'This email is already verified.'));
			return false;
		}

		if ($user[$this->alias]['email_verified'] == 0) {
			if ($renew === true) {
				$user[$this->alias]['email_token_expires'] = $this->emailTokenExpirationTime();
				$this->save($user, array(
					'validate' => false,
					'callbacks' => false,
				));
			}
			$this->data = $user;
			return true;
		}
	}

/**
 * Registers a new user
 *
 * Options:
 * - bool emailVerification : Default is true, generates the token for email verification
 * - bool removeExpiredRegistrations : Default is true, removes expired registrations to do cleanup when no cron is configured for that
 * - bool returnData : Default is true, if false the method returns true/false the data is always available through $this->User->data
 *
 * @param array $postData Post data from controller
 * @param mixed should be array now but can be boolean for emailVerification because of backward compatibility
 * @return mixed
 */
	public function register($postData = array(), $options = array()) {
		$Event = new CakeEvent(
			'Users.Model.User.beforeRegister',
			$this,
			array(
				'data' => $postData,
				'options' => $options
			)
		);

		$this->getEventManager()->dispatch($Event);
		if ($Event->isStopped()) {
			return $Event->result;
		}

		if (is_bool($options)) {
			$options = array('emailVerification' => $options);
		}

		$defaults = array(
			'emailVerification' => true,
			'removeExpiredRegistrations' => true,
			'returnData' => true);
		extract(array_merge($defaults, $options));

		$postData = $this->_beforeRegistration($postData, $emailVerification);

		if ($removeExpiredRegistrations) {
			$this->_removeExpiredRegistrations();
		}

		$this->set($postData);
		if ($this->validates()) {
			$postData[$this->alias]['password'] = $this->hash($postData[$this->alias]['password'], 'sha1', true);
			$this->create();
			$this->data = $this->save($postData, false);
			$this->data[$this->alias]['id'] = $this->id;

			$Event = new CakeEvent(
				'Users.Model.User.afterRegister',
				$this,
				array(
					'data' => $this->data,
					'options' => $options
				)
			);

			$this->getEventManager()->dispatch($Event);

			if ($Event->isStopped()) {
				return $Event->result;
			}

			if ($returnData) {
				return $this->data;
			}
			return true;
		}
		return false;
	}

/**
 * Resends the verification if the user is not already validated or invalid
 *
 * @param array $postData Post data from controller
 * @return mixed False or user data array on success
 */
	public function resendVerification($postData = array()) {
		if (!isset($postData[$this->alias]['email']) || empty($postData[$this->alias]['email'])) {
			$this->invalidate('email', __d('users', 'Please enter your email address.'));
			return false;
		}

		$user = $this->findByEmail($postData[$this->alias]['email']);

		if (empty($user)) {
			$this->invalidate('email', __d('users', 'The email address does not exist in the system'));
			return false;
		}

		if ($user[$this->alias]['email_verified'] == 1) {
			$this->invalidate('email', __d('users', 'Your account is already authenticated.'));
			return false;
		}

		if ($user[$this->alias]['active'] == 0) {
			$this->invalidate('email', __d('users', 'Your account is disabled.'));
			return false;
		}

		$user[$this->alias]['email_token'] = $this->generateToken();
		$user[$this->alias]['email_token_expires'] = $this->emailTokenExpirationTime();

		return $this->save($user, false);
	}

/**
 * Returns the time the email verification token expires
 *
 * @return string
 */
	public function emailTokenExpirationTime() {
		return date('Y-m-d H:i:s', time() + $this->emailTokenExpirationTime);
	}

/**
 * Generates a password
 *
 * @param int $length Password length
 * @return string
 */
	public function generatePassword($length = 10) {
		srand((double)microtime() * 1000000);
		$password = '';
		$vowels = array("a", "e", "i", "o", "u");
		$cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
							"cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl");
		for ($i = 0; $i < $length; $i++) {
			$password .= $cons[mt_rand(0, 31)] . $vowels[mt_rand(0, 4)];
		}
		return substr($password, 0, $length);
	}

/**
 * Generate token used by the user registration system
 *
 * @param int $length Token Length
 * @return string
 */
	public function generateToken($length = 10) {
		$possible = '0123456789abcdefghijklmnopqrstuvwxyz';
		$token = "";
		$i = 0;

		while ($i < $length) {
			$char = substr($possible, mt_rand(0, strlen($possible) - 1), 1);
			if (!stristr($token, $char)) {
				$token .= $char;
				$i++;
			}
		}
		return $token;
	}

/**
 * Optional data manipulation before the registration record is saved
 *
 * @param array post data array
 * @param boolean Use email generation, create token, default true
 * @return array
 */
	protected function _beforeRegistration($postData = array(), $useEmailVerification = true) {
		if ($useEmailVerification == true) {
			$postData[$this->alias]['email_token'] = $this->generateToken();
			$postData[$this->alias]['email_token_expires'] = date('Y-m-d H:i:s', time() + 86400);
		} else {
			$postData[$this->alias]['email_verified'] = 1;
		}
		$postData[$this->alias]['active'] = 1;
		$defaultRole = Configure::read('Users.defaultRole');
		if ($defaultRole) {
			$postData[$this->alias]['role'] = $defaultRole;
		} else {
			$postData[$this->alias]['role'] = 'registered';
		}
		return $postData;
	}

/**
 * Returns the search data - Requires the CakeDC Search plugin to work
 *
 * @param string $state Find State
 * @param string $query Query options
 * @param array|string $results Result data
 * @throws MissingPluginException
 * @return array
 * @link https://github.com/CakeDC/search
 */
	protected function _findSearch($state, $query, $results = array()) {
		if (!class_exists('SearchableBehavior')) {
			throw new MissingPluginException(array('plugin' => 'Utils'));
		}

		if ($state == 'before') {
			$this->Behaviors->load('Containable', array(
				'autoFields' => false)
			);
			$results = $query;

			if (empty($query['search'])) {
				$query['search'] = '';
			}

			$by = $query['by'];
			$like = '%' . $query['search'] . '%';

			switch ($by) {
				case 'username':
					$results['conditions'] = Hash::merge(
						$query['conditions'],
						array($this->alias . '.username LIKE' => $like));
					break;
				case 'email':
					$results['conditions'] = Hash::merge(
						$query['conditions'],
						array($this->alias . '.email LIKE' => $like));
					break;
				case 'any':
					$results['conditions'] = Hash::merge(
						$query['conditions'],
						array('OR' => array(
							array($this->alias . '.username LIKE' => $like),
							array($this->alias . '.email LIKE' => $like))));
					break;
				case '' :
					$results['conditions'] = $query['conditions'];
					break;
				default :
					$results['conditions'] = Hash::merge(
						$query['conditions'],
						array($this->alias . '.username LIKE' => $like));
					break;
			}

			if (isset($query['operation']) && $query['operation'] == 'count') {
				$results['fields'] = array('COUNT(DISTINCT ' . $this->alias . '.id)');
			}

			return $results;
		} elseif ($state == 'after') {
			if (isset($query['operation']) && $query['operation'] == 'count') {
				if (isset($query['group']) && is_array($query['group']) && !empty($query['group'])) {
					return count($results);
				}
				return $results[0][0]['COUNT(DISTINCT ' . $this->alias . '.id)'];
			}
			return $results;
		}
	}

/**
 * Customized paginateCount method
 *
 * @param array $conditions Find conditions
 * @param int $recursive Recursive level
 * @param array $extra Extra options
 * @return array
 */
	public function paginateCount($conditions = array(), $recursive = 0, $extra = array()) {
		$parameters = compact('conditions');
		if ($recursive != $this->recursive) {
			$parameters['recursive'] = $recursive;
		}
		if (isset($extra['type']) && isset($this->findMethods[$extra['type']])) {
			$extra['operation'] = 'count';
			return $this->find($extra['type'], array_merge($parameters, $extra));
		} else {
			return $this->find('count', array_merge($parameters, $extra));
		}
	}

/**
 * Adds a new user, to be called from admin like user roles or interfaces
 *
 * This method is not sending any email like the register() method, its simply
 * adding a new user record and sets a default role.
 *
 * The difference to register() is that this method here is intended to be used
 * by admins to add new users without going through all the registration logic
 *
 * @param array post data, should be Controller->data
 * @return boolean True if the data was saved successfully.
 */
	public function add($postData = null) {
		if (!empty($postData)) {
			$this->data = $postData;
			if ($this->validates()) {
				if (empty($postData[$this->alias]['role'])) {
					if (empty($postData[$this->alias]['is_admin'])) {
						$defaultRole = Configure::read('Users.defaultRole');
						if ($defaultRole) {
							$postData[$this->alias]['role'] = $defaultRole;
						} else {
							$postData[$this->alias]['role'] = 'registered';
						}
					} else {
						$postData[$this->alias]['role'] = 'admin';
					}
				}
				$postData[$this->alias]['password'] = $this->hash($postData[$this->alias]['password'], 'sha1', true);
				$this->create();
				$result = $this->save($postData, false);
				if ($result) {
					$result[$this->alias][$this->primaryKey] = $this->id;
					$this->data = $result;
					return true;
				}
			}
		}
		return false;
	}

/**
 * Edits an existing user
 *
 * When saving a password it get hashed if the field is present AND not empty
 *
 * @param string $userId User ID
 * @param array $postData controller post data usually $this->data
 * @throws NotFoundException
 * @return mixed True on successfully save else post data as array
 */
	public function edit($userId = null, $postData = null) {
		$user = $this->getUserForEditing($userId);
		$this->set($user);
		if (!empty($postData)) {
			$this->set($postData);
			if ($this->validates()) {
				if (!empty($this->data[$this->alias]['password'])) {
					$this->data[$this->alias]['password'] = $this->hash($this->data[$this->alias]['password'], 'sha1', true);
				}
				$result = $this->save(null, false);
				if ($result) {
					$this->data = $result;
					return true;
				}
			} else {
				return $postData;
			}
		}
	}

/**
 * Gets the user data that needs to be edited
 *
 * Override this method and inject the conditions you need
 *
 * @var mixed $userId
 * @var array $options
 * @return array $user
 * @throws NotFoundException
 */
	public function getUserForEditing($userId = null, $options = array()) {
		$defaults = array(
			'contain' => array(),
			'conditions' => array(
				$this->alias . '.id' => $userId
			)
		);
		$options = Hash::merge($defaults, $options);

		$user = $this->find('first', $options);

		if (empty($user)) {
			throw new NotFoundException(__d('users', 'Invalid User'));
		}

		return $user;
	}

/**
 * Removes all users from the user table that are outdated
 *
 * Override it as needed for your specific project
 *
 * @return void
 */
	protected function _removeExpiredRegistrations() {
		$this->deleteAll(array(
			$this->alias . '.email_verified' => 0,
			$this->alias . '.email_token_expires <' => date('Y-m-d H:i:s'))
		);
	}

/**
 * Returns a CakeEmail object
 *
 * @return object CakeEmail instance
 * @link http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
 */
	public function getMailInstance() {
		$emailConfig = Configure::read('Users.emailConfig');
		if ($emailConfig) {
			return new CakeEmail($emailConfig);
		}
		return new CakeEmail('default');
	}

	// this is for comments the user makes
	public $hasMany = array(
		'Comment' => array(
			'className' => 'Comment',
			'foreignKey' => 'user_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		),
		'CommentsUser' => array(
			'className' => 'CommentsUser',
			'foreignKey' => 'user_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

//and this is for the interaction the user has with comments

	public $hasAndBelongsToMany = array(
		'Comment' => array(
			'className' => 'User',
			'joinTable' => 'comments_users',
			'foreignKey' => 'comment_id',
			'associationForeignKey' => 'user_id',
			'unique' => 'keepExisting',
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'finderQuery' => '',
		)
	);
}


text:
namespace Ranger
{
    /// <summary>
    /// Helper class for results returned by Google APIs
    /// </summary>
    public class TextValuePair
    {
        public string text;
        public int value;

        public TextValuePair()
        {
            text = string.Empty;
            value = -1;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Config;

use Symfony\Component\Config\Resource\ResourceInterface;

/**
 * Interface for ResourceCheckers.
 *
 * When a ResourceCheckerConfigCache instance is checked for freshness, all its associated
 * metadata resources are passed to ResourceCheckers. The ResourceCheckers
 * can then inspect the resources and decide whether the cache can be considered
 * fresh or not.
 *
 * @author Matthias Pigulla <mp@webfactory.de>
 * @author Benjamin Klotz <bk@webfactory.de>
 */
interface ResourceCheckerInterface
{
    /**
     * Queries the ResourceChecker whether it can validate a given
     * resource or not.
     *
     * @return bool True if the ResourceChecker can handle this resource type, false if not
     */
    public function supports(ResourceInterface $metadata);

    /**
     * Validates the resource.
     *
     * @param int $timestamp The timestamp at which the cache associated with this resource was created
     *
     * @return bool True if the resource has not changed since the given timestamp, false otherwise
     */
    public function isFresh(ResourceInterface $resource, $timestamp);
}


text:
pub mod debug;
/// ELF File Support
pub mod elf;
/// Event input
pub mod event;
/// Get slice implementation
pub mod get_slice;
/// Kernel memory allocation
pub mod memory;
/// Paging (x86)
#[cfg(target_arch = "x86")]
#[path="paging-i386.rs"]
pub mod paging;
/// Paging (x86_64)
#[cfg(target_arch = "x86_64")]
#[path="paging-x86_64.rs"]
pub mod paging;
/// A module for parsing paths
pub mod parse_path;
/// A module for parsing IP related string
pub mod parse_ip;
/// A module for pseudorandom generator
pub mod random;
/// A module for time
pub mod time;
/// String to number
pub mod to_num;


text:
<!DOCTYPE html>
<html>
<head>
<title>Simple Assignment</title>

</head>

<body>
<script src="animals.js" type="text/javascript"></script>
</body>
</html>


text:
package com.rwxlicai.fragment;

import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rwxlicai.R;
import com.rwxlicai.activity.Borrow_getTenderRecord_Activity;
import com.rwxlicai.activity.Crash_regionActivity;
import com.rwxlicai.activity.Profile_InfoManager_Activity;
import com.rwxlicai.activity.Profile_ManagerActivity;
import com.rwxlicai.activity.Profile_RedPacketsManager_Activity;
import com.rwxlicai.activity.User_bankCardIdentityActivity;
import com.rwxlicai.activity.User_realIdentity;
import com.rwxlicai.net.NetCallBack;
import com.rwxlicai.net.RwxHttpClient;
import com.rwxlicai.net.RwxUrlFactory;
import com.rwxlicai.utils.Config;
import com.rwxlicai.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by xuebing on 15/12/29.
 */
public class ProfileFragment extends Fragment {

    @InjectView(R.id.profile_img)
    CircleImageView profile_img;
    @InjectView(R.id.profile_manager)
    View profile_manager;
    @InjectView(R.id.invest)
    View invest;
    @InjectView(R.id.crash)
    View crash;
    @InjectView(R.id.redPackge)
    View redPackge;
    @InjectView(R.id.info)
    View info;
    @InjectView(R.id.profile_name)
    TextView profile_name;
    @InjectView(R.id.profile_total)
    TextView profile_total;
    @InjectView(R.id.profile_gain)
    TextView profile_gain;
    @InjectView(R.id.profile_balance)
    TextView profile_balance;

    private static int CAMERA_REQUEST_CODE = 1;
    private static int GALLERY_REQUEST_CODE = 2;
    private static int CROP_REQUEST_CODE = 3;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    protected ImageLoader imageLoader;

    private Bitmap bm;
    private Uri bmUri;
    private File tempFile;
    private String uri;
    private String availableMoney;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.profile_fragment, null);
        ButterKnife.inject(this, view);
        imageLoader = ImageLoader.getInstance();
        userCenter();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        imageLoader.displayImage(Config.getCachedPortrait(getActivity()), profile_img);
        profile_name.setText(Config.getCachedPhone(getActivity()));
    }

    @OnClick({R.id.profile_img, R.id.profile_manager,R.id.invest,R.id.crash,R.id.redPackge,R.id.info})
    public void clickAction(View view) {
        switch (view.getId()) {
            case R.id.info:
                startActivity(new Intent(getActivity(), Profile_InfoManager_Activity.class));
                break;
            case R.id.crash:
                if (Config.getAuth(getActivity())){
                    Intent crash = new Intent(getActivity(), Crash_regionActivity.class);
                    startActivity(crash);
                }else {
                    if (Config.getRealNameState(getActivity()) == "2"){
                        startActivity(new Intent(getActivity(), User_bankCardIdentityActivity.class));
                    }else {
                        startActivity(new Intent(getActivity(), User_realIdentity.class));
                    }
                }

                break;
            case R.id.redPackge: //红包管理
                startActivity(new Intent(getActivity(), Profile_RedPacketsManager_Activity.class));
//                startActivity(new Intent(getActivity(), User_bankCardIdentityActivity.class));
                break;
            case R.id.invest: //投资管理
//                startActivity(new Intent(getActivity(), User_realIdentity.class));
                Intent intent = new Intent(getActivity(), Borrow_getTenderRecord_Activity.class);
                startActivity(intent);
                break;
            case R.id.profile_manager:
                startActivity(new Intent(getActivity(), Profile_ManagerActivity.class));
                break;
            case R.id.profile_img:
                final String[] arrayFruit = new String[]{"拍照", "从相册选"};
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setItems(arrayFruit, new DialogClickListener()
                        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).create();
                Window window = alertDialog.getWindow();
                window.setGravity(Gravity.BOTTOM);
                window.setWindowAnimations(R.style.dialogstyle);
                alertDialog.show();
                break;
            default:
                break;
        }
    }

    private void userCenter(){
        RwxHttpClient.ClientTokenPost(getActivity(), RwxUrlFactory.BASE_URL + RwxUrlFactory.userCenter, null, new NetCallBack() {
            @Override
            public void onMzbSuccess(String result) {
                try {
                    JSONObject obj = new JSONObject(result);
                    Gson gson = new Gson();
                    if (obj.getInt("code") == 0) {
                        JSONObject data = obj.getJSONObject("result");
                        availableMoney = data.getString("availableMoney");

                        Config.cachedAvailableMoney(getActivity(),availableMoney);
                        profile_total.setText(data.getString("allMoney"));
                        profile_gain.setText(data.getString("getInterest"));
                        profile_balance.setText(availableMoney);
                    } else {
                        Toast.makeText(getActivity(),obj.getString("message"),Toast.LENGTH_SHORT);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onMzbFailues(Throwable arg0) {
                Toast.makeText(getActivity(), arg0.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    class DialogClickListener implements DialogInterface.OnClickListener {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case 0:
                    //从相机获取
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用,可用进行存储
                    if (hasSdcard()) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                    }
                    startActivityForResult(intent, CAMERA_REQUEST_CODE);
                    break;
                case 1:
                    // 激活系统图库,选择一张图片
                    Intent mintent = new Intent(Intent.ACTION_PICK);
                    mintent.setType("image/*");
                    startActivityForResult(mintent, GALLERY_REQUEST_CODE);
                default:
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (hasSdcard()) {
                tempFile = new File(Environment.getExternalStorageDirectory(),
                        PHOTO_FILE_NAME);
                crop(Uri.fromFile(tempFile));
            } else {
                ToastUtils.showToast(getActivity(), "未找到存储卡,无法存储照片!", Toast.LENGTH_LONG);
            }
        } else if (requestCode == GALLERY_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Uri uri;
            uri = data.getData();
            Uri fileUri = convertUri(uri);
            crop(fileUri);
        } else if (requestCode == CROP_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Bundle extras = data.getExtras();
            if (extras == null) {
                return;
            }
            bm = extras.getParcelable("data");
            profile_img.setImageBitmap(bm);
            bmUri = saveBitmap(bm);
            Config.cachedPortrait(getActivity(), bmUri.toString());
            updateAvatar();
        }
    }

    /**
     * 剪切图片
     *
     * @param uri
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例,1:1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri,false:返回uri
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    private Uri convertUri(Uri uri) {
        InputStream is = null;
        try {
            is = getActivity().getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Uri saveBitmap(Bitmap bm) {

        File img = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);

        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private void updateAvatar() {
        RequestParams params1 = new RequestParams();
        File file = new File(bmUri.getPath());
        try {
            params1.put("file", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        RwxHttpClient.ClientTokenPost(getActivity(), RwxUrlFactory.BASE_URL + RwxUrlFactory.updateAvatar, params1, new NetCallBack() {

            @Override
            public void onMzbSuccess(String result) {
                try {
                    JSONObject obj = new JSONObject(result);
                    if (obj.getInt("code") == 0) {
                        Toast.makeText(getActivity(),obj.getString("message"),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity(),obj.getString("message"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onMzbFailues(Throwable arg0) {
                Toast.makeText(getActivity(),"查看网络连接!",Toast.LENGTH_SHORT).show();
            }
        });
    }
}


text:
        Order
        Place Order For New Drugs

 Home

Stock

Panadol

Order

Order History

                        <button type="button" class="btn btn-box-tool" data-widget="collapse">
                        </button>

 24th of June 2016
                                Pending

 20th of May 2014

 24th of June 2016

 24th of June 2016 Cancelled

Order Information

                        <button type="button" class="btn btn-box-tool" data-widget="collapse">
                        </button>

                            Order Quantity
                            <input type="text" class="form-control" placeholder="Enter Order Quantity">

Compose New Message

                        <input class="form-control" placeholder="To:">

                        <input class="form-control" placeholder="Subject:">

                        <textarea id="compose-textarea" class="form-control" style="height: 300px">

                        </textarea>

                        <button type="submit" class="btn btn-primary"> Send</button>

                    <button type="reset" class="btn btn-default"> Discard</button>


text:
/**
 ************ BLUE ROUTER - Roter powered by Bluebird promises. **************
 * Basic synatx:
 * const br = require('blue-router');
 * var context = {uri: '/register/john?x=abc&y=123'};
 * var route = '/register/:name';
 * br(context).when(route).then().catch();
 */

/*For browser side scripting include <script src="bluebird.js"></script>*/
const BPromise = require('bluebird') || Promise;

/**
 * Blue Route debugger.
 * @param  {Boolean} optsDebug - true | false
 * @param  {String} msg        - debug message
 * @return {Void}
 */
var bluedebug = function (optsDebug, msg) {
    'use strict';
    if (optsDebug) {
        console.log(msg);
    }
};

/**
 * URI parser
 * @param  {String} uri - /register/john?x=abc&y=123  (uri === context.uri)
 * @return {Object} - {path: '/register/john', pathBase: '/register', querystring: 'x=abc&y=123'}
 *
 * Notice:
 * 1. When route is '/register/:name/:age' and uri is /register/john/23?x=abc&y=123 then uriParsed = {path: '/register/john/23', pathBase: '/register', querystring: 'x=abc&y=123'}
 * 2. When route is '/register/john/55' and uri is /register/john/55?x=abc&y=123 then uriParsed = {path: '/register/john/55', pathBase: '/register/john/55', querystring: 'x=abc&y=123'} (path == pathBase on EXACT MATCH)
 */
var uriParser = function (uri, route) {
    'use strict';
    var uriDivided = uri.split('?');

    var path = uriDivided[0];
    var querystring = uriDivided[1];

    //get pathBase
    var pathBase = '';
    if (route.indexOf('/:') !== -1) {//route has parameter definition /register/:name/:age
        var pathParts = path.split('/');
        var routeParts = route.split('/');

        // console.log('--pathParts: ', pathParts);
        // console.log('--routeParts: ', routeParts);

        //find how many parameters route has
        var routeParameters = routeParts.filter(function (routePart) {
            return (routePart.indexOf(':') === 0); // ':name'
        });

        //remove parameter parts from pathParts
        // console.log('--routeParameters.length', routeParameters.length);
        pathParts.splice(-routeParameters.length, routeParameters.length); //removing last routeParameters.length elements and result is ['', 'register']

        // console.log('--pathParts: ', pathParts);

        pathBase = pathParts.join('/');

    } else {
        pathBase = path;
    }

    var uriParsed = {
        path: path,
        pathBase: pathBase,
        querystring: querystring
    };

    return uriParsed;
};

/**
 * get route without parameter part. For example /register/:name/:age -> /register
 * @param  {String} route  - /register/:name/:age
 * @return {String}       - /register
 */
var extractRouteBase = function (route) {
    'use strict';

    var routeParts = route.split('/'); // [ '', register', ':name', ':age' ]

    var routeBaseArr = routeParts.map(function (routePart) {
        if (routePart.indexOf(':') === -1) {
            return routePart;
        }
    });

    //remove empty elements from array
    routeBaseArr = routeBaseArr.filter(function (elem) {
        return !!elem;
    });

    var routeBase = routeBaseArr.join('/'); // /register/

    return '/' + routeBase;
};

/**
 * Create query object of querystring. x=abc&y=123&z=true -> {x: 'abc', y: 123, z: true}
 * @param  {String} querystring - x=abc&y=123&z=true
 * @return {Object}             - {x: 'abc', y: 123, z: true}
 */
var getQuery = function (querystring) {
    'use strict';
    var queryArr = querystring.split('&');
    var queryObj = {};
    var qs, property, value;
    queryArr.forEach(function (elem) {
        qs = elem.split('=');
        property = qs[0];
        value = qs[1];

        //convert string into number
        if (!isNaN(value) && value.indexOf('.') === -1) { //integer 12
            value = parseInt(value, 10);
        } else if (!isNaN(value) && value.indexOf('.') !== -1) { //float 12.35
            value = parseFloat(value);
        }

        //convert string into boolean
        if (value === 'true' || value === 'false') {
            value = JSON.parse(value);
        }

        queryObj[property] = value;
    });

    return queryObj;
};

/**
 * Create parameters object. For example /register/:name AND /register/john -> {name: 'john'}
 * @param  {String} uriPath  - /register/john
 * @param  {String} route - /register/:name
 * @return {Object} - parameters
 */
var getParameters = function (uriPath, route) {
    'use strict';
    var routeParts = route.split('/'); // ['', 'register', ':name']
    var uriPathParts = uriPath.split('/'); // ['', 'register', 'john']

    var params = {};

    routeParts.forEach(function (routePart, index) {
        if (routePart.indexOf(':') === 0) {
            routePart = routePart.slice(1); //remove :

            var value = uriPathParts[index];

            //convert string into number
            if (!isNaN(value) && value.indexOf('.') === -1) { //integer 12
                value = parseInt(value, 10);
            } else if (!isNaN(value) && value.indexOf('.') !== -1) { //float 12.35
                value = parseFloat(value);
            }

            //convert string into boolean
            if (value === 'true' || value === 'false') {
                value = JSON.parse(value);
            }
            params[routePart] = value;
        }
    });

    return params;
};

//array of promises
var promises = [];

var router = function (ctx) {
    'use strict';

    return {

        when: function (route) {
            bluedebug(ctx.opts.debug, '+++++++uri: ' + ctx.uri + '\n+++++route: ' + route);

            if (!ctx.req) {
                ctx.req = {};
            }

            //add trailing slash if doesnt exist  ( register/john -> /register/john )
            if (route.indexOf('/') !== 0) {
                route = '/' + route;
            }
            if (ctx.uri.indexOf('/') !== 0) {
                ctx.uri = '/' + ctx.uri;
            }

            //remove ending slash if exist  ( /register/john/ -> /register/john )
            //because we want to match route='/register/john' and uri='/register/john/'
            if (ctx.uri.lastIndexOf('/') === ctx.uri.length - 1) {
                ctx.uri = ctx.uri.slice(0, -1);
            }
            if (route.lastIndexOf('/') === route.length - 1) {
                route = route.slice(0, -1);
            }

            //get route base /register/:name/:age -> /register/
            var routeBase = extractRouteBase(route);
            bluedebug(ctx.opts.debug, '+routeBase: ' + routeBase);

            //parse uri {path: '/register/john', querystring: 'x=abc&y=123'}
            var uriParsed = uriParser(ctx.uri, route);
            if (uriParsed.path.lastIndexOf('/') === uriParsed.path.length - 1) {
                uriParsed.path = uriParsed.path.slice(0, -1); //remove ending slash
            }
            bluedebug(ctx.opts.debug, '+uriParsed.path: ' + uriParsed.path + ' +uriParsed.pathBase: ' + uriParsed.pathBase + ' +uriParsed.querystring: ' + uriParsed.querystring);

            //get number of uri and route parts
            var numUriPathParts = uriParsed.path.split('/').length;
            var numRouteParts = route.split('/').length;

            //regular expression matching
            var routeBaseReg = new RegExp('^' + routeBase + '$', 'i');
            var regExpMatch = uriParsed.pathBase.match(routeBaseReg);
            bluedebug(ctx.opts.debug, '+routeBaseReg: ' + routeBaseReg + ' +uriParsed.pathBase: ' + uriParsed.pathBase + ' =====regExpMatch: ' + JSON.stringify(regExpMatch));

            //matching uri and route
            var promis;
            if ((route === uriParsed.path || !!regExpMatch) && route.indexOf('/:') === -1) { //exact match '/register/john' === '/register/john'
                !!regExpMatch
                    ? bluedebug(ctx.opts.debug, '+EXACT MATCH - REGEXP\n')
                    : bluedebug(ctx.opts.debug, '+EXACT MATCH\n');

                //get query object x=abc&y=123&z=true -> {x: 'abc', y: 123, z: true}
                if (!!uriParsed.querystring) {
                    ctx.req.query = getQuery(uriParsed.querystring);
                }

                //debug
                bluedebug(ctx.opts.debug, '++ctx.req.body: ' + JSON.stringify(ctx.req.body));
                bluedebug(ctx.opts.debug, '++ctx.req.params: ' + JSON.stringify(ctx.req.params));
                bluedebug(ctx.opts.debug, '++ctx.req.query: ' + JSON.stringify(ctx.req.query));

                promis = BPromise.resolve(ctx);
                promises.push(promis);

            } else if ((uriParsed.path.indexOf(routeBase) !== -1 || !!regExpMatch) && route.indexOf('/:') !== -1 && numUriPathParts === numRouteParts) { //param match '/register/john' === '/register/:name'
                !!regExpMatch
                    ? bluedebug(ctx.opts.debug, '+PARAM MATCH - REGEXP\n')
                    : bluedebug(ctx.opts.debug, '+PARAM MATCH\n');

                //get query object x=abc&y=123&z=true -> {x: 'abc', y: 123, z: true}
                if (!!uriParsed.querystring) {
                    ctx.req.query = getQuery(uriParsed.querystring);
                }

                //get param object /register/:name AND /register/john -> {name: 'john'}
                var params = getParameters(uriParsed.path, route);
                ctx.req.params = params;

                //debug
                bluedebug(ctx.opts.debug, '++ctx.req.body: ' + JSON.stringify(ctx.req.body));
                bluedebug(ctx.opts.debug, '++ctx.req.params: ' + JSON.stringify(ctx.req.params));
                bluedebug(ctx.opts.debug, '++ctx.req.query: ' + JSON.stringify(ctx.req.query));
                bluedebug(ctx.opts.debug, '\n');

                promis = BPromise.resolve(ctx);
                promises.push(promis);

            } else { //no match
                bluedebug(ctx.opts.debug, '+NO MATCH\n');
                promis = new BPromise(function(resolve, reject) {}); // retain promise in pending state
                promises.push(promis);
            }

            // console.log('\nroute:: ', route);
            // console.log('promis.isFulfilled():: ', promis.isFulfilled());
            // console.log('promis.isRejected():: ', promis.isRejected());
            // console.log('promis.isPending():: ', promis.isPending());
            // console.log('\n\n');

            return promis;
        }, //when

        /* Execute on each URI */
        do: function () {
            return BPromise.resolve(ctx);
        }, //do

        /* Execute when no URI matches against route */
        notfound: function () {

            //find is there any of promises fulfilled
            var tf = false;
            promises.forEach(function (promise) {
                tf = tf || promise.isFulfilled();
            });

            promises = []; //reset

            var p;
            if (!tf) {//if none of routes are not matched against URI
                bluedebug(ctx.opts.debug, '++NOTFOUND: ' + ctx.uri);
                p = BPromise.resolve(ctx);
            } else {//if one route (at least) is matched against URI
                p = new BPromise(function(resolve, reject) {}); // retain promise in pending state
            }
            return p;

        } //notfound

    };

};

/**
 * Add redirect function to bluebird promise.
 * @param  {String} newRoute - redirection route
 * @return {Promise}
 */
BPromise.prototype.redirect = function (newRoute) {
    'use strict';
    // console.log(promises); //all promises before redirect() usage

    var promisRedirection = BPromise.resolve(this)
        .then(function (ctx) {
            bluedebug(ctx.opts.debug, '++REDIRECT TO:' + newRoute);
            return BPromise.resolve(ctx);
        });

    return promisRedirection;
};

//browser (global var)
blue_router = router;

//nodejs or browserify
module.exports = router;


text:
import React, { PropTypes } from 'react';
import ImageSliderItem from './ImageSliderItem';
import itemTypes from './itemTypes';
import { DropTarget } from 'react-dnd';
const styles = {
  container : {
    border: '1px solid black',
    padding : '10px',
    marginTop : '10px',
    minHeight : '100px'
  }
};

const cardTarget = {
  drop(props, monitor, component) {
    const dragIndex = monitor.getItem().order;
    const hoverIndex = props.order;
    const dragLocale = monitor.getItem().locale;
    const hoverLocale = props.locale;

    if(hoverLocale !== dragLocale){
      console.log('we do the action !');
      props.handleMoveItem(dragIndex, dragLocale, hoverIndex, hoverLocale);
    }
  },
  hover(props, monitor, component){
  },
};

@DropTarget(itemTypes.CARD, cardTarget, (connectDragSource, monitor) => ({
  connectDropTarget: connectDragSource.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop(),
  item: monitor.getItem()
}))
class ImageSliderItemList extends React.Component{
  constructor(props){
    super(props);
  }

  _renderImageSliderItems = () => {
    const { items, handleRemoveItem, locale } = this.props;
    const itemList = [];

    items.map((item, i) => {
      const { name, order, value, id, image } = item;
      if (item !== undefined) {
        itemList.push(
          <ImageSliderItem
            name={name}
            order={i}
            value={value}
            locale={locale}
            handleRemoveItem={handleRemoveItem}
            handleMoveItem={this._handleMoveItem}
            image={image}
            id={id}/>
        )
      }
    });
    return itemList;
  };

  _handleMoveItem = (dragIndex,dragLocale, hoverIndex, hoverLocale) => {
    const { handleMoveItem } = this.props;
    handleMoveItem(dragIndex, dragLocale, hoverIndex, hoverLocale);
  };

  render(){
    const { connectDropTarget } = this.props;
    return connectDropTarget(
      <div style={styles.container}>
        {this._renderImageSliderItems()}
      </div>
    )
  }
}
ImageSliderItemList.propTypes = {
  items : PropTypes.array.isRequired,
  handleRemoveItem : PropTypes.func.isRequired,
  handleMoveItem: PropTypes.func.isRequired,
  connectDropTarget : PropTypes.func.isRequired
};

export default ImageSliderItemList;


text:
package com.hearthsim.card.basic.minion;

import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.MinionBattlecryInterface;
import com.hearthsim.event.effect.EffectCharacter;
import com.hearthsim.event.effect.EffectCharacterHeal;

public class GuardianOfKings extends Minion implements MinionBattlecryInterface {

    private static final EffectCharacter effect = new EffectCharacterHeal(6);

    public GuardianOfKings() {
        super();
    }

    /**
     * Battlecry: Restore 6 Health to your Hero
     */
    @Override
    public EffectCharacter getBattlecryEffect() {
        return GuardianOfKings.effect;
    }
}


text:
package ana1;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

public class General2 {
    private static final String DESTINATION1 = "queue/aufgabe6Queue1";
    private static final String DESTINATION2 = "queue/aufgabe6Queue2";
    private static final String DESTINATION3 = "queue/aufgabe6Queue3";
    private static final String USER = "guest";
    private static final String PASSWORD = "guest";
    private String[] Werte = new String[3];
    private int i = 0;

    public General2() {

    }

    public static Context getInitialContext() throws NamingException {
        Properties props = new Properties();
        props.put("java.naming.factory.initial",
            "org.jnp.interfaces.NamingContextFactory");
        props.put("java.naming.provider.url", "jnp://localhost:1099");
        props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
        props.put("jnp.socket.Factory", "org.jnp.interfaces.TimedSocketFactory");
        Context context = new InitialContext(props);
        return context;
    }

    public static void main(String[] args) throws Exception {
        General2 general2 = new General2();
        general2.ersteRunde();
        general2.zweiteRundeZuGen1();
        general2.zweiteRundeZuGen3();
        general2.vergleich();
    }

    public void ersteRunde() throws NamingException, JMSException {

        Context ctx = getInitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx
            .lookup("ConnectionFactory");
        Queue queue = (Queue) ctx.lookup(DESTINATION2);
        QueueConnection connection = factory.createQueueConnection(USER,
            PASSWORD);
        QueueSession session = connection.createQueueSession(false,
            Session.AUTO_ACKNOWLEDGE);
        QueueReceiver receiver = session.createReceiver(queue);
        connection.start();
        System.out.println("Auf Nachricht warten ...");

        TextMessage nachricht = (TextMessage) receiver.receive();
        for (int i = 0; i < 20; i++) {
            TextMessage nachricht2 = (TextMessage) receiver.receive();
        }

        Werte[0] = nachricht.getText();
        System.out.println("Kommander sagt: " + Werte[0]);
        receiver.close();
        session.close();
        connection.close();
    }

    public void zweiteRundeZuGen1() throws JMSException, NamingException {
        Context ctx2 = getInitialContext();
        QueueConnectionFactory factory2 = (QueueConnectionFactory) ctx2
            .lookup("ConnectionFactory");
        Queue queue2 = (Queue) ctx2.lookup(DESTINATION2);
        QueueConnection connection2 = factory2.createQueueConnection(USER,
            PASSWORD);
        QueueSession session2 = connection2.createQueueSession(false,
            Session.AUTO_ACKNOWLEDGE);
        QueueReceiver receiver2 = session2.createReceiver(queue2);
        connection2.start();
        System.out.println("Auf Nachricht warten ...");

        TextMessage nachricht = (TextMessage) receiver2.receive();
        Werte[1] = nachricht.getText();
        System.out.println("General 1 sagt: " + Werte[1]);
        Queue tempQueue2 = (Queue) nachricht.getJMSReplyTo();
        TextMessage antwort = session2.createTextMessage();
        antwort.setText(Werte[0]);
        QueueSender sender2 = session2.createSender(tempQueue2);
        System.out.println("Ich an General 1 schicke: " + antwort.getText());
        try {
            sender2.send(antwort);
        } finally {
            sender2.close();
            receiver2.close();
            session2.close();
            connection2.close();
        }
    }

    public void zweiteRundeZuGen3() throws JMSException, NamingException {
        Context ctx3 = getInitialContext();
        QueueConnectionFactory factory3 = (QueueConnectionFactory) ctx3.lookup("ConnectionFactory");
        Queue queue3 = (Queue) ctx3.lookup(DESTINATION3);
        QueueConnection connection3 = null;
        QueueSession session3 = null;
        TemporaryQueue tempQueue3 = null;
        QueueSender sender3 = null;
        QueueReceiver receiver3 = null;

        try {
            connection3 = factory3.createQueueConnection(USER, PASSWORD);
            session3 = connection3.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            // temporäre Queue für die Antwort erzeugen
            tempQueue3 = session3.createTemporaryQueue();
            sender3 = session3.createSender(queue3);
            receiver3 = session3.createReceiver(tempQueue3);
            connection3.start();

            TextMessage request = session3.createTextMessage();
            request.setText(Werte[0]);
            request.setJMSReplyTo(tempQueue3);
            sender3.send(request);
            System.out.println("Zweite Runde. An General3:" + Werte[0]);
            System.out.println("auf Antwort warten");
            TextMessage response = (TextMessage) receiver3.receive();
            Werte[2] = response.getText();
            System.out.println("Dritter General meldet: " + Werte[2]);
        } finally {
            sender3.close();
            receiver3.close();
            tempQueue3.delete();
            session3.close();
            connection3.close();
        }
    }

    public void vergleich() {
        for (int i = 0; i < 3; i++) {
            System.out.println(i + Werte[i]);
        }
    }
}


text:
namespace iv {
namespace lv5 {
namespace runtime {

// 15.15.2.1 WeakMap(iterable = [])
// 15.15.3.1 new WeakMap (iterable = [])
JSVal WeakMapConstructor(const Arguments& args, Error* e);

// 15.15.5.2 WeakMap.prototype.clear()
JSVal WeakMapClear(const Arguments& args, Error* e);

// 15.15.5.3 WeakMap.prototype.delete(key)
JSVal WeakMapDelete(const Arguments& args, Error* e);

// 15.15.5.4 WeakMap.prototype.get(key)
JSVal WeakMapGet(const Arguments& args, Error* e);

// 15.15.5.5 WeakMap.prototype.has(key)
JSVal WeakMapHas(const Arguments& args, Error* e);

// 15.15.5.6 WeakMap.prototype.set(key, value)
JSVal WeakMapSet(const Arguments& args, Error* e);

} } }  // namespace iv::lv5::runtime
#endif  // IV_LV5_RUNTIME_WEAK_MAP_H_


text:
package java.lang.ref;

/**
 * WeakReference objects are used to detect referents which are no longer
 * visible.
 *
 * @since 1.2
 */
public class WeakReference<T> extends Reference<T> {

    /**
     * Constructs a new instance of this class.
     *
     * @param r referent to track.
     */
    public WeakReference(T r) {
        super();
        initReference(r);
    }

    /**
     * Constructs a new instance of this class.
     *
     * @param r referent to track.
     * @param q queue to register to the reference object with.
     */
    public WeakReference(T r, ReferenceQueue<? super T> q) {
        super();
        initReference(r, q);
    }
}


text:
unless $".find { |lib| lib =~ /RMath\.so|RMath\.rb/ }
  # Load RMath normally.
  begin
    require 'RMath.so'
  rescue LoadError
    # RMath.so does not exist. Require plain version.
    require 'RMath.rb'
  end
end
include RMath

# Test::Unit
require 'test/unit'

# Test cases
require 'test/test_RVec3.rb'
require 'test/test_RVec4.rb'
require 'test/test_RQuat.rb'
require 'test/test_RMtx3.rb'
require 'test/test_RMtx4.rb'


text:
<?php

namespace Slashx\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Slashx\AdminBundle\Entity\Album;
use Slashx\AdminBundle\Form\AlbumType;

/**
 * Album controller.
 *
 * @Route("/album")
 */
class AlbumController extends Controller
{
    /**
     * Lists all Album entities.
     *
     * @Route("/", name="album")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $request = $this->getRequest();
        $id = $request->query->get('id');

        $entities = null;
        if ($id==null)
        {
        	$entities = $em->getRepository('SlashxAdminBundle:Album')->findAll();
        }else
        {
        	$papillon = $em->getRepository('SlashxAdminBundle:Papillon')->find($id);

        	$entities = array();
        	$entities[]=$papillon->getAlbum();

        }

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Creates a new Album entity.
     *
     * @Route("/", name="album_create")
     * @Method("POST")
     * @Template("SlashxAdminBundle:Album:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new Album();
        $form = $this->createForm(new AlbumType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

           return $this->redirect($this->generateUrl('album'));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to create a new Album entity.
     *
     * @Route("/new", name="album_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Album();
        $form   = $this->createForm(new AlbumType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Album entity.
     *
     * @Route("/{id}", name="album_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SlashxAdminBundle:Album')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Album entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Album entity.
     *
     * @Route("/{id}/edit", name="album_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SlashxAdminBundle:Album')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Album entity.');
        }

        $editForm = $this->createForm(new AlbumType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Album entity.
     *
     * @Route("/{id}", name="album_update")
     * @Method("PUT")
     * @Template("SlashxAdminBundle:Album:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('SlashxAdminBundle:Album')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Album entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new AlbumType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('album'));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Album entity.
     *
     * @Route("/{id}", name="album_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('SlashxAdminBundle:Album')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Album entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('album'));
    }

    /**
     * Creates a form to delete a Album entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
namespace perfetto {
class SharedMemoryArbiter;
}  // namespace perfetto

namespace tracing {

// This class represents the perfetto producer endpoint which is used for
// producers to talk to the Perfetto service. It also provides methods to
// interact with the shared memory buffer by binding and creating TraceWriters.
//
// In addition to the PerfettoProducers' pure virtual methods, subclasses must
// implement the remaining methods of the ProducerEndpoint interface.
class COMPONENT_EXPORT(TRACING_CPP) PerfettoProducer {
 public:
  explicit PerfettoProducer(base::tracing::PerfettoTaskRunner*);

  virtual ~PerfettoProducer();

  // Setup the shared memory buffer and data sources for startup tracing.
  // Returns false on failure. Can be called on any thread.
  bool SetupStartupTracing(const base::trace_event::TraceConfig&,
                           bool privacy_filtering_enabled);

  // Schedules the startup tracing timeout if active.
  void OnThreadPoolAvailable();

  // See SharedMemoryArbiter::CreateStartupTraceWriter.
  std::unique_ptr<perfetto::TraceWriter> CreateStartupTraceWriter(
      uint16_t target_buffer_reservation_id);

  // See SharedMemoryArbiter::BindStartupTargetBuffer. Should be called on the
  // producer's task runner.
  virtual void BindStartupTargetBuffer(
      uint16_t target_buffer_reservation_id,
      perfetto::BufferID startup_target_buffer);

  // See SharedMemoryArbiter::AbortStartupTracingForReservation. Should be
  // called on the producer's task runner.
  virtual void AbortStartupTracingForReservation(
      uint16_t target_buffer_reservation_id);

  // Used by the DataSource implementations to create TraceWriters
  // for writing their protobufs, and respond to flushes.
  //
  // Should only be called while a tracing session is active and a
  // SharedMemoryArbiter exists.
  //
  // Virtual for testing.
  virtual std::unique_ptr<perfetto::TraceWriter> CreateTraceWriter(
      perfetto::BufferID target_buffer,
      perfetto::BufferExhaustedPolicy =
          perfetto::BufferExhaustedPolicy::kDefault);

  // Returns the SharedMemoryArbiter if available.
  // TODO(eseckler): Once startup tracing v2 is available in Chrome, this could
  // become GetSharedMemoryArbiter() instead.
  virtual perfetto::SharedMemoryArbiter* MaybeSharedMemoryArbiter() = 0;

  // Informs the PerfettoProducer a new Data Source was added. This instance
  // will also be found in |data_sources| having just be inserted before this
  // method is called by PerfettoTracedProcess. This enables the
  // PerfettoProducer to perform initialization on new data sources.
  virtual void NewDataSourceAdded(
      const PerfettoTracedProcess::DataSourceBase* const data_source) = 0;

  // Returns true if this PerfettoProducer is currently tracing.
  virtual bool IsTracingActive() = 0;

  static void DeleteSoonForTesting(
      std::unique_ptr<PerfettoProducer> perfetto_producer);

  // In tests, PerfettoProducers may leak between tests, but their task sequence
  // may become invalid (e.g. TaskEnvironment is destroyed). This resets the
  // PerfettoProducer's sequence checker, so that it can later be rebound to a
  // new test's sequence. Note that this only resets the producer's sequence
  // checker - and there may be other sequence checkers elsewhere, e.g. in
  // PosixSystemProducer's socket (which would fail on disconnect if the system
  // producer's sequence is reset while it is connected).
  void ResetSequenceForTesting();

  void set_startup_tracing_timeout_for_testing(base::TimeDelta timeout) {
    startup_tracing_timeout_ = timeout;
  }

 protected:
  friend class MockProducerHost;

  // May be called on any thread.
  virtual bool SetupSharedMemoryForStartupTracing() = 0;

  // The PerfettoProducer subclass should call this once the startup tracing
  // session was taken over by the tracing service.
  // TODO(eseckler): Consider refactoring this into e.g. a delegate interface.
  void OnStartupTracingComplete();

  bool IsStartupTracingActive();

  // TODO(crbug.com/839071): Find a good compromise between performance and
  // data granularity (mainly relevant to running with small buffer sizes
  // when we use background tracing) on Android.
#if BUILDFLAG(IS_ANDROID)
  static constexpr size_t kSMBPageSizeBytes = 4 * 1024;
#else
  static constexpr size_t kSMBPageSizeBytes = 32 * 1024;
#endif

  // TODO(crbug.com/839071): Figure out a good buffer size.
  static constexpr size_t kDefaultSMBSizeBytes = 4 * 1024 * 1024;

  // TODO(lri): replace this constant with its version in the client library,
  // when we move over.
  //
  // This value for SharedMemoryArbiter's batch_commits_duration_ms was
  // determined by load testing, using the script at
  // https://chromium-review.googlesource.com/c/chromium/src/+/1835498. The
  // effects of various delays on the overhead of tracing in Chrome
  // can be seen at https://screenshot.googleplex.com/KgsJshNCFKq. See commit
  // 2fc0474d9 and crbug.com/1029298 for more context.
  //
  // Note that since this value is non-zero, it could lead to loss of batched
  // data at the end of a tracing session. The producer should enable
  // asynchronous stopping of datasources and should flush the accumulated
  // commits while a datasource is being stopped.
  static constexpr uint32_t kShmArbiterBatchCommitDurationMs = 1000;

  base::tracing::PerfettoTaskRunner* task_runner();

  size_t GetPreferredSmbSizeBytes();

  SEQUENCE_CHECKER(sequence_checker_);

 private:
  void MaybeScheduleStartupTracingTimeout();
  void OnStartupTracingTimeout();

  // If a startup tracing session is not taken over by the service after this
  // delay, the startup session will be aborted and its data lost. This is to
  // catch situations where e.g. a subprocess is spawned with startup tracing
  // flags, but the tracing session got disabled in the service while it was
  // initializing (in which case, the tracing service will not tell the
  // subprocess to start tracing after it connects).
  base::TimeDelta startup_tracing_timeout_ = base::Seconds(60);

  const raw_ptr<base::tracing::PerfettoTaskRunner> task_runner_;

  std::atomic<bool> startup_tracing_active_{false};

  // NOTE: Weak pointers must be invalidated before all other member variables.
  base::WeakPtrFactory<PerfettoProducer> weak_ptr_factory_{this};
};
}  // namespace tracing
#endif  // SERVICES_TRACING_PUBLIC_CPP_PERFETTO_PERFETTO_PRODUCER_H_


text:
/**
   * Module dependencies
   */
var util = require('util'),
actionUtil = require('./helpers/actionUtil');

/**
   * Find One Record
   *
   * get /:modelIdentity/:id
   *
   * An API call to find and return a single model instance from the data adapter
   * using the specified id.
   *
   * Required:
   * @param {Integer|String} id  - the unique id of the particular instance you'd like to look up *
   *
   * Optional:
   * @param {String} callback - default jsonp callback param (i.e. the name of the js function returned)
   */

module.exports = function findOneRecord(req, res){

	var Model = actionUtil.parseModel(req, this.modelName);
	var pk = actionUtil.requirePk(req);
	var self = this;

	var query = Model.findOne(pk);

	var opts = _.defaults({}, this.getQueryConfiguration(req, 'findOne'), {
		populate: true
	});

	if(opts.populate){
		if(_.isArray(opts.populate)){
			_.each(opts.populate, function(populate){
				query = query.populate(populate);
			});
		} else {
			query = actionUtil.populateEach(query, req);
		}
	}

	query.exec(function found(err, model){
		if(err) {return res.serverError(err);}

		if(!model) {return res.notFound('No record found with the specified `id`.');}

		self.canRead(req, model, function(err, value){
			if(err){return res.serverError(err);}

			if(!self.authorizer.isRequestAuthorized(req)){return res.notFound('No record found with the specified `id`.');}

			if(!value){return res.forbidden({
				error: 'You are not authorized to view this ' + Model.globalId
			});}

			self.beforeRead(req, model, function(err, model){
				if(err){return res.serverError(err);}

				if(!model){
					return res.ok(null);
				}

				if(sails.hooks.pubsub && req.isSocket) {
					Model.subscribe(req, model);
					actionUtil.subscribeDeep(req, model);
				}

				self.export(req, model, function(err, modelJSON){
					if(err){return res.serverError(err);}
					self.afterRead(req, model, function(err){
						if(err){return res.serverError(err);}

						res.ok(modelJSON);
					});
				});
			});
		});
	});

};


text:
python D:\dev\www\lib\closure\library\closure\bin\build\closurebuilder.py ^
   		--root D:\dev\www\lib\closure\library ^
   		--root ..\.. ^
   		--namespace ag ^
        --namespace PrimerPairFinderOdometer ^
   		--output_mode compiled ^
   		--compiler_jar D:\dev\www\lib\closure\compiler\compiler.jar ^
        > PrimerPairFinder-speedtest-simple.js
::        --compiler_flags="--compilation_level=ADVANCED_OPTIMIZATIONS" > PrimerPairFinder-speedtest-advanced.js


text:
"use strict";

const chalk = require("chalk");
const figures = require("figures");
const inquirer = require("inquirer");
const replaceInFile = require("replace-in-file");
const fss = require("@absolunet/fss");

const LOCAL = fss.realpath(".");
const NWAYO = `${LOCAL}/nwayo`;
const CONFIG_ORIGINAL = `${NWAYO}/nwayo.yaml`;
const BUNDLE = `${NWAYO}/bundles/site/site.yaml`;
const CONFIG = `${LOCAL}/nwayo.yaml`;

const ROOT = fss.realpath(__dirname);
const BOILERPLATE = `${ROOT}/boilerplate`;
const PACKAGE = fss.readJson(`${ROOT}/package.json`);

const echo = console.log; // eslint-disable-line no-console

const error = (message) => {
	console.error(chalk.red(`\n  ${figures.cross} ${message}`)); // eslint-disable-line no-console
	process.exit(); // eslint-disable-line node/no-process-exit, unicorn/no-process-exit
};

class GrowProject {
	async cli() {
		if (fss.exists(NWAYO)) {
			error(`There is already a 'nwayo' folder`);
		}

		if (fss.exists(CONFIG)) {
			error(`There is already a 'nwayo.yaml' file`);
		}

		const { projectId } = await inquirer.prompt([
			{
				name: "projectId",
				message: `What is your project's id ?`,
				type: "input",
				validate: (id) => {
					if (id.length >= 3) {
						if (/^(?<kebab1>[a-z][a-z0-9]*)(?<kebab2>-[a-z0-9]+)*$/u.test(id)) {
							return true;
						}

						return "The project id must be kebab-case";
					}

					return "The project id must be at least 3 characters long";
				},
			},
		]);

		echo(chalk.blue(`\n${figures.play} Generating project ${figures.ellipsis}`));

		// Duplicate boilerplate
		fss.copy(BOILERPLATE, NWAYO);
		fss.rename(`${NWAYO}/-gitignore`, `${NWAYO}/.gitignore`);

		// Configuration
		const config = fss.readYaml(CONFIG_ORIGINAL);
		fss.writeYaml(CONFIG, config);
		fss.remove(CONFIG_ORIGINAL);

		// Bundle
		const bundle = fss.readYaml(BUNDLE);
		bundle.output.konstan = "../pub/build";
		bundle.output.build = "../pub/build";
		fss.writeYaml(BUNDLE, bundle);

		// Change project name
		await replaceInFile({
			files: [`${NWAYO}/package.json`, `${NWAYO}/vendor/package.json`],
			from: "PROJECT_NAME",
			to: projectId,
		});

		// Confirmation
		echo(`
${chalk.green(`${figures.tick} ${chalk.bold(projectId)} via nwayo ${PACKAGE.version} created!`)}

  1. If not already present, install nwayo CLI via ${chalk.yellow("npm i -g @absolunet/nwayo-cli")}
  2. Run ${chalk.yellow("npm install")} in the nwayo root folder
  3. Run ${chalk.yellow("nwayo rebuild")} in the nwayo root folder
  4. Enjoy !
		`);
	}
}

module.exports = new GrowProject();


text:
import os
import time,datetime
from cStringIO import StringIO
import platform
import pymysql
import uuid
import tornado.web
from PIL import Image

import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
from webmodules.basehandler import BaseHandler
from webmodules.system_management import api as paramApi
import common.hanzi_to_pinyin.pinyin as pinyin

par1 = os.path.dirname(os.path.dirname(__file__))  # 获得page.py所在的目录--person_management
par2 = os.path.dirname(par1)  ##获得person_management所在的目录--modules
server_abspath = os.path.abspath(par2)  # 返回modules所在目录规范的绝对路径--E:\gd_facerecognize\server
# 判断当前操作系统
if platform.system() == "Windows":
    join_str = '\\'
elif platform.system() == "Linux":
    join_str = '/'

# 提交新增
class addItem(BaseHandler):
    def post(self):
        # 获取参数
        realname = self.get_argument('inputName')
        age = int(self.get_argument('inputAge'))
        sex = int(self.get_argument('inputSex'))
        flag = self.get_argument('hid_flag')
        if flag == 'handler':
            img_path = str(self.get_argument('hid_imgPath'))
            # 获取文件系统的地址
            file_url = str(paramApi.get_sys_param(self, 'fileServer'))
            frontfaceUrl = img_path.replace(file_url, '')
        else:
            file_metas = self.request.files['file_frontface']  # 上传的正面照
            # 上传至文件服务器
            rec = self.upload(file_metas[0]['body'], 'jpg')
            if rec['Status'] == 'Upload successed.':
                frontfaceUrl = rec['Remote file_id']

        # path = upload_file(realname, file_metas, 'add', '')
        # frontfaceUrl = path['file_path'][path['file_path'].find('personPhotos'):].replace(join_str, '/')
        # photosFolder = path['folder_path'][path['folder_path'].find('personPhotos'):].replace(join_str, '/')
        photosFolder = ''
        # 游标设置为字典类型
        self.cur = self.mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
        newId = uuid.uuid1()
        sql = "insert into facerecognize.person_train VALUES  \
              ('%s', '%s', 12, '%s', %d, %d, '%s', '%s')" % \
               (newId, realname, '80%', sex, age, frontfaceUrl, photosFolder)
        self.cur.execute(sql)
        self.mysql_conn.commit()

        # 若是人脸抓拍处理,更新处理状态
        if flag == 'handler':
            strH = "addNewPerson"
            handlerId = self.get_argument('hid_handlerId')
            sql2 = "UPDATE facerecognize.face_checked set is_handled = %d, " \
                  " handled_result = '%s'  " \
                  "WHERE id = '%s' " \
                  % (1, strH, handlerId)
            self.cur.execute(sql2)
            self.mysql_conn.commit()

        self.cur.close()
        self.mysql_conn.close()

        self.finish({
            'msg': 'ok',
            'data':{'personId':str(newId)},
        })

# 提交编辑
class editItem(BaseHandler):
    def post(self):
        # 用JQuery实现表单提交,获取参数
        personId = self.get_argument('personId')
        realname = self.get_argument('inputName')
        age = int(self.get_argument('inputAge'))
        sex = int(self.get_argument('inputSex'))
        oldName = self.get_argument('oldName')
        # 游标设置为字典类型
        self.cur = self.mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
        # 上传图片
        if len(self.request.files) == 0: # 没有上传正面照
            # if oldName != realname:
            #     path = upload_file(realname, '', 'edit', oldName)
            #     folder_path = path['folder_path'][path['folder_path'].find('personPhotos'):].replace(join_str, '/')
            #     new_folder_path = folder_path.replace(path['old_name'], path['new_name'])
            #     sql = "UPDATE facerecognize.person_train set `name` = '%s',sex = %d, age = '%d', photos_folder = '%s', " \
            #           " pic_url = REPLACE ( pic_url, '%s', '%s' ) " \
            #           "WHERE id = %d" \
            #         % (realname, sex, age, new_folder_path, path['old_name'], path['new_name'], personId )
            #     # print '没有上传正面照'
            # else: # 没有修改名称
            #     sql = "UPDATE facerecognize.person_train set sex = %d, age = '%d' WHERE id = %d" \
            #           % (sex, age, personId)
            #     # print '没有修改名称'
            sql = "UPDATE facerecognize.person_train set `name` = '%s',sex = %d, age = '%d' " \
                "WHERE id = '%s'" \
                % (realname, sex, age, personId )
        else:
            file_metas = self.request.files['file_frontface']  # 上传的正面照
            # 上传至文件服务器
            rec = self.upload(file_metas[0]['body'], 'jpg')
            if rec['Status'] == 'Upload successed.':
                frontfaceUrl = rec['Remote file_id']

            '''path = upload_file(realname, file_metas, 'edit', oldName)
            frontfaceUrl = path['file_path'][path['file_path'].find('personPhotos'):].replace(join_str, '/')
            folder_path = path['folder_path'][path['folder_path'].find('personPhotos'):].replace(join_str, '/')
            sql = "UPDATE facerecognize.person_train set `name` = '%s',sex = %d, age = '%d', pic_url='%s'," \
                  "photos_folder = '%s' WHERE id = %d" \
                  % (realname, sex, age, frontfaceUrl, folder_path, personId)'''
            # print '上传正面照且修改名称'
            sql = "UPDATE facerecognize.person_train set `name` = '%s',sex = %d, age = '%d', pic_url='%s' " \
                  " WHERE id = '%s'" \
                  % (realname, sex, age, frontfaceUrl, personId)
        self.cur.execute(sql)
        self.mysql_conn.commit()
        self.cur.close()
        self.mysql_conn.close()
        self.finish({
            'msg': 'ok',
            # 'data': {'personId': self.cur.lastrowid},
        })

# 物理删除人物
class deleteItem(BaseHandler):
    def post(self):
        # 用JQuery实现表单提交,获取参数
        personId = self.get_argument('personId')
        # 游标设置为字典类型
        self.cur = self.mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
        sql = "DELETE FROM facerecognize.person_train " \
              " WHERE id = '%s'" \
              % (personId)
        self.cur.execute(sql)
        self.mysql_conn.commit()
        self.cur.close()
        self.mysql_conn.close()
        self.finish({
            'msg': 'ok',
        })

# 照片上传
class uploadPhotos(BaseHandler):
    def post(self):
        # 该文件返回一个元素为字典的列表
        # meta有三个键值对可以通过img.keys()查看
        # 分别是 'filename', 'body', 'content_type' 对应着文件名,内容(二进制)和文件类型
        userName = self.get_argument('inputName')
        self.isFolder = self.get_argument('isFolder')
        old_name = self.get_argument('oldName')
        if self.isFolder == 'Y':
            file_metas = self.request.files['multiplePhotos']
        else:
            file_metas = self.request.files['file_frontface']

        # 上传至文件服务器
        for meta in file_metas:
            rec = self.upload(meta["body"], 'jpg')
            if rec['Status'] == 'Upload successed.':
                file_path = rec['Remote file_id']
                # 在文件表添加记录
                person_id = self.get_argument('hid_personId')
                self.cur = self.mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
                newId = uuid.uuid1()
                sql = "insert into facerecognize.person_files VALUES  \
                              ('%s', '%s', '%s')" % \
                      (newId, person_id, file_path)
                self.cur.execute(sql)
                self.mysql_conn.commit()
                # 获取文件系统的地址
                file_url = paramApi.get_sys_param(self, 'fileServer')
                self.cur.close()
                self.mysql_conn.close()

        '''path = upload_file(userName,file_metas,'',old_name)
        self.finish({
            'data': {'latestPhotos': path['file_path'].replace(join_str, '/')}
        })'''
        latest_photos_url = file_url + file_path
        self.finish({
            'data': {'latestPhotos': latest_photos_url}
        })

# 获取编辑页面的数据
class getItem(BaseHandler):
    def get(self):
        # 获取参数
        personId = self.get_argument('personId')
        # 游标设置为字典类型
        self.cur = self.mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
        # 获取文件系统的地址
        file_url = paramApi.get_sys_param(self, 'fileServer')
        '''sql = 'SELECT CONCAT(p.id) as personId, CONCAT(p.age) as age, p.`name`, CONCAT("%s",p.pic_url) AS pic_url, p.recognition,p.sex, ' \
              ' group_concat(CONCAT("%s",f.file_path)) AS allPhotos ' \
              ' FROM facerecognize.person_train p ' \
            ' LEFT JOIN facerecognize.person_files f ON f.person_id = p.id' \
            ' WHERE p.id = "%s" GROUP BY p.id ' % (file_url,file_url,personId)'''
        sql = 'SELECT p.id, CONCAT(p.age) As age,p.`name`, CONCAT("%s",IFNULL(p.pic_url,"")) AS pic_url,IFNULL(p.recognition,"") AS recognition,' \
              ' p.sex,k.allPhotos   ' \
              'from facerecognize.person_train p ' \
              ' left join (select p.person_id, group_concat(CONCAT("%s",p.file_path)) AS allPhotos  ' \
              ' FROM facerecognize.person_files p GROUP BY p.person_id) as k on p.id= k.person_id ' \
              ' WHERE p.id = "%s" ' % (file_url,file_url,personId)
        self.cur.execute(sql)
        rs = self.cur.fetchone()
        self.cur.close()
        self.mysql_conn.close()
        if not rs: raise tornado.web.HTTPError(404)
        # 返回所有照片
        '''allPhotos = []
        photosFolder = rs['photos_folder'][rs['photos_folder'].find('personPhotos'):].replace('/', join_str)
        path = os.path.join(server_abspath, 'static' + join_str + photosFolder)  # 文件的暂存路径
        # path = os.path.join(server_abspath, photosFolder)  # 文件的暂存路径
        pathDir = os.listdir(path)
        for allDir in pathDir:
            child = os.path.join('%s/%s' % (path, allDir))
            child = child[child.find('personPhotos'):].replace(join_str, '/')
            allPhotos.append(child)
            # print child.decode('gbk')  # .decode('gbk')是解决中文显示乱码问题
            '''
        if rs['allPhotos'] == None:
            rs['allPhotos'] =  rs['pic_url']
        else:
            rs['allPhotos'] = rs['pic_url'] + ',' + rs['allPhotos']
        self.finish({
            'msg': 'ok',
            'data': {'elderItem': rs }
        })

# 删除照片文件
class deletePhotos(tornado.web.RequestHandler):
    def post(self):
        photos_file_name = self.get_body_arguments("phptosIds", None) # 获取request的数组参数
        photos_folder = self.get_argument('photosFolder').replace('/', join_str)
        path = os.path.join(server_abspath, 'static' + join_str + photos_folder)  # 文件的暂存路径
        # path = os.path.join(server_abspath, photos_folder)  # 文件的暂存路径
        pathDir = os.listdir(path)
        for allDir in pathDir:
            child = os.path.join(path + join_str + allDir)
            split1 = os.path.split(child)
            for item in photos_file_name:
                if item == split1[1]:
                    print "Delete File [%s],Path[%s]" % (item, child)
                    os.remove(child)
        self.finish({
            'msg': 'ok',
            'data': {}
        })

# 获取个人所有照片,用以浏览
class getPersonalPhotos(BaseHandler):
    def post(self):
        # 获取参数
        personId = self.get_argument('personId')
        # 游标设置为字典类型
        self.cur = self.mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
        # 获取文件系统的地址
        file_url = paramApi.get_sys_param(self, 'fileServer')
        sql = 'SELECT group_concat(CONCAT("%s",f.file_path)) AS allPhotos ' \
              ' FROM facerecognize.person_files f WHERE f.person_id = "%s"' % (file_url,personId)
        self.cur.execute(sql)
        rs = self.cur.fetchone()
        self.cur.close()
        self.mysql_conn.close()
        self.finish({
            'msg': 'ok',
            'data': {'personalPhotos': rs}
        })

# 分页--获取人员列表
class getPersonListOfPage(BaseHandler):
    def post(self):
        pageIndex = self.get_argument('pageIndex')
        flag = self.get_argument('flag')  # 转码
        if flag == 'modal':
            pageCount = int(paramApi.get_sys_param(self, 'modalPageCount'))
        elif flag == 'normal':
            pageCount = int(paramApi.get_sys_param(self, 'pageCount'))
        start = int(int(pageIndex) * int(pageCount))

        name = self.get_argument('name').encode('utf8')  # 转码

        self.cur = self.mysql_conn.cursor(cursor=pymysql.cursors.DictCursor)
        '''sql = 'SELECT p.id, CONCAT(p.age) as age, p.`name`, p.pic_url,p.recognition,' \
              'p.photos_folder,case p.sex when 1 THEN "男" when 0 then "女" END as sex, ' \
              'CONCAT(COUNT(DISTINCT f.id)+1) AS photos_sum ' \
              ' FROM facerecognize.person_train p ' \
              ' LEFT JOIN facerecognize.person_files f ON f.person_id = p.id' \
              ' WHERE 1=1 '''
        sql = 'SELECT p.id, IFNULL(k.count,"") AS photos_sum,CONCAT(p.age) As age,p.`name`, p.pic_url,IFNULL(p.recognition,"") AS recognition,' \
              'p.photos_folder,case p.sex when 1 THEN "男" when 0 then "女" END as sex ' \
              'from facerecognize.person_train p ' \
              ' left join (select  p.person_id, IFNULL(CONCAT(COUNT(DISTINCT p.id)+1),"0") as count ' \
              ' FROM facerecognize.person_files p GROUP BY p.person_id) as k on p.id= k.person_id '\
              ' WHERE 1=1 '

        sqlCount = 'SELECT COUNT(p.id) FROM facerecognize.person_train p WHERE 1=1 '   # 记录个数
        # 查询条件
        if name != "":
            sql += ' and p.`name` like "%%%s%%" ' % name
            sqlCount += ' and p.`name` like "%%%s%%" ' % name
        # sql += ' GROUP BY p.id LIMIT %d,%d' % (start, pageCount)
        sql += ' LIMIT %d,%d' % (start, pageCount)
        self.cur.execute(sql)  # 所有记录
        rs = self.cur.fetchall()
        self.cur.execute(sqlCount)  # 记录个数
        records_count = self.cur.fetchone()
        # 获取文件系统的地址
        file_url = paramApi.get_sys_param(self, 'fileServer')
        self.cur.close()
        self.mysql_conn.close()
        for item in rs:
            item['pic_url'] = file_url + str(item['pic_url'])
        self.finish({
            'msg': 'ok',
            'data': {
                'personalList': rs,
                'recordsCount': records_count['COUNT(p.id)'],
                'pageCount': pageCount
            }
        })

# 文件操作
def upload_file(user_name, file_metas, flag, old_name):
    # 汉字转拼音,保存到对应文件夹下
    test = pinyin.PinYin()
    test.load_word("common/hanzi_to_pinyin/word.data")
    pinyinStr = test.hanzi2pinyin_split(user_name)
    # 每个人有一个文件夹
    new_path = os.path.join(server_abspath,'static' + join_str + 'personPhotos' + join_str + pinyinStr)
    if flag == 'add':
        # new_path = os.path.join(server_abspath, 'personPhotos' + join_str + pinyinStr)
        # 判断路径是否存在
        if not os.path.isdir(new_path):
            # 如果不存在则创建目录
            print new_path + ' 创建成功'
            # 创建目录操作函数
            os.makedirs(new_path)
    elif flag == 'edit':
        if old_name != '' and old_name != user_name:
            old_pinyin = test.hanzi2pinyin_split(old_name)
            old_path = os.path.join(server_abspath, 'static'+join_str+'personPhotos' + join_str + old_pinyin)
            # old_path = os.path.join(server_abspath, 'personPhotos' + join_str + old_pinyin)
            # 分离路径和文件夹
            split1 = os.path.split(old_path)
            # 判断是否为指定的文件夹
            if split1[1] == old_pinyin:
                # 将文件夹名称改为新的文件夹名称
                os.rename(old_path, split1[0] + join_str + pinyinStr)
                # print "文件夹 [%s] 已改名为 [%s]" % (old_path, pinyinStr)
                new_path = os.path.join(server_abspath, 'static'+join_str+'personPhotos' + join_str + pinyinStr)
                # new_path = os.path.join(server_abspath, 'personPhotos' + join_str + pinyinStr)
                pathDir = os.listdir(new_path)
                for allDir in pathDir:
                    child = os.path.join(new_path, allDir)
                    if os.path.isfile(child) and child[-3:] == 'png':  # 将读取文件名字的后三个字符与'png'匹对
                        split2 = os.path.split(child)
                        # print "分离路径和文件夹: [%s]--[%s]" % (split2[0], split2[1])
                        two_name = split2[1].replace(old_pinyin, pinyinStr)
                        new_file_name = split2[0] + join_str + two_name
                        os.rename(child, new_file_name)
                        # print "图片[%s]改名为: [%s]" % (child,new_file_name)
            if file_metas == '': # 若没有文件上传,则返回新文件夹
                path = {}
                path['old_name'] = old_pinyin
                path['new_name'] = pinyinStr
                path['folder_path'] = new_path
                return path

    upload_path = new_path  # 文件的暂存路径
    file_path = ''
    for meta in file_metas:
        # 要上传的文件名
        filename = meta['filename']
        print "fileType: " + meta['content_type']
        # 若文件类型为图片
        if meta['content_type'] == 'image/jpg' or meta['content_type'] == 'image/png' \
                or meta['content_type'] == 'image/jpeg':
            # 对文件进行重命名
            mirS = str(datetime.datetime.now().microsecond)
            filename = str(time.strftime('%Y%m%d%H%M%S', time.localtime()) + '_' + mirS + '_' + pinyinStr + '.png')
            file_path = os.path.join(upload_path, filename)
            with open(file_path, 'wb') as f:
                # image有多种打开方式,一种是 Image.open('xx.png')
                # 另一种就是 Image.open(StringIO(buffer))
                im = Image.open(StringIO(meta['body']))
                # 修改图片大小resize接受两个参数, 第一个是宽高的元组数据,第二个是对图片细节的处理,本文表示抗锯齿
                im = im.resize((290, 290), Image.ANTIALIAS)
                # 打开io 就像文件一样
                im_file = StringIO()
                im.save(im_file, format='png')
                # 这是获取io中的内容
                im_data = im_file.getvalue()
                f.write(im_data)
        else:
            file_path = os.path.join(upload_path, filename)
            with open(file_path, 'wb') as up:  # 有些文件需要已二进制的形式存储,实际中可以更改
                up.write(meta['body'])
    path = {}
    path['folder_path'] = upload_path
    path['file_path'] = file_path
    return path