text:
'use strict';
var gulp = require('gulp'),
    concat = require('gulp-concat'),
    imagemin = require('gulp-imagemin'),
    notify = require('gulp-notify'),
    jshint = require('gulp-jshint'),
    clean = require('gulp-clean'),
    filesize  = require('gulp-filesize'),
    nodemon = require('gulp-nodemon'),
    karma = require('gulp-karma'),
    mocha = require('gulp-mocha'),
    paths = {
      scripts: ['app/modules/**/*.js', 'app/core/**/*.js'],
      ext_scripts: ['static/js/vendor/**/*.js', 'static/js/frontend/**/*.js'],
      styles: ['static/css/**/*.css', 'app/modules/**/static/css/**/*.css'],
      images: 'static/images/**/*',
      tests: ['specs/**/*.js'],
      mochaTests: ['app/modules/**/specs/**/*.js']
    };

gulp.task('nodemon', function() {
  nodemon({ script: 'app.js', ext: 'html js css' })
    .on('change', ['styles', 'scripts'])
    .on('restart', function () {
      console.log('restarted!');
    });
});

gulp.task('test', ['clean-complexity', 'jshint', 'mocha'], function () {
  return gulp.src(paths.tests, {read: false})
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }));
});

gulp.task('mocha',  function () {
  return gulp.src(paths.mochaTests)
    .pipe(mocha());
});

gulp.task('clean-complexity', function () {
  return gulp.src('complexity', {read: false})
    .pipe(clean({force: true}));
});

gulp.task('clean-styles', function () {
  return gulp.src('build/css', {read: false})
    .pipe(clean({force: true}))
    .pipe(gulp.dest('./css'));
});

gulp.task('clean-scripts', function () {
  return gulp.src(['./build/js', './static/js/scripts.min.js'], {read: false})
    .pipe(clean({force: true}))
    .pipe(gulp.dest('./js'));
});

gulp.task('clean-images', function () {
  return gulp.src('build/images', {read: false})
    .pipe(clean({force: true}))
    .pipe(gulp.dest('./images'));
});

gulp.task('styles', ['clean-styles'], function() {
   // Minify and copy all JavaScript (except vendor styles)
  return gulp.src(paths.styles)
     .pipe(concat('styles.min.css'))
     .pipe(gulp.dest('build/css'))
     .pipe(filesize());
});

gulp.task('scripts', ['clean-scripts'], function() {
  return gulp.src(paths.ext_scripts)
    .pipe(concat('scripts.min.js'))
    // .pipe(stripDebug())
    // .pipe(uglify())
    .pipe(gulp.dest('./static/js/'));
});

gulp.task('jshint', function() {
  return gulp.src(paths.scripts)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('checkstyle'));
});

gulp.task('lintHTML', function() {
  return gulp.src('./src/*.html')
    // if flag is not defined default value is 'auto'
    .pipe(jshint.extract('auto|always|never'))
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

// Copy all static images
gulp.task('images', ['clean-images'], function() {
  return gulp.src(paths.images)
    // Pass in options to the task
    .pipe(imagemin({optimizationLevel: 5}))
    .pipe(gulp.dest('build/images'))
    .pipe(filesize())
    .pipe(notify({
       message: "Images are minified!"
     }));
});

// Rerun the task when a file changes
gulp.task('watch', function() {
  gulp.watch(paths.scripts, ['jshint']);
  gulp.watch(paths.styles, ['styles']);
  gulp.watch(paths.images, ['images']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', [
  'styles', 'scripts', 'images', 'nodemon'
]);

gulp.task('ci', ['test']);


text:
var express = require('express');
var Cliente = require('../dbconnection/clienteconection.js');

var clienteroute = express.Router();

clienteroute.route('/clientes')
  .get(function(req, res) {
    Cliente.find(function(err, cliente) {
      if (err) {
        return res.send(err);
      }
      res.json(cliente);
    });
  })

  .post(function(req, res) {
    var cliente = new Cliente(req.body);

    cliente.save(function(err) {
      if (err) {
        return res.send(err);
      }
      res.send({ message: 'Cliente Added' });
    });
  });

clienteroute.route('/clientes/:id')
  .put(function(req,res){
     Cliente.findOne({ _id: req.params.id }, function(err, cliente) {
        if (err) {
          return res.send(err);
        }

        for (prop in req.body) {
          cliente[prop] = req.body[prop];
        }

        cliente.save(function(err) {
          if (err) {
            return res.send(err);
          }
        res.json({ message: 'cliente updated!' });
    });
  });
});

clienteroute.route('/clientes/:id')
    .get(function(req, res) {
      Cliente.findOne({ _id: req.params.id}, function(err, cliente) {
        if (err) {
          return res.send(err);
        }
        res.json(cliente);
  });
});

clienteroute.route('/clientes/:id')
    .delete(function(req, res) {
      Cliente.remove({
        _id: req.params.id
      }, function(err, cliente) {
       if (err) {
         return res.send(err);
      }
    res.json({ message: 'Satisfactoriamente deleted' });
  });
});

module.exports = clienteroute;

redpajama_set_name: RedPajamaGithub


text:
// Copyright (C) 2002-2011 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h

#ifndef __IRR_QUATERNION_H_INCLUDED__
#define __IRR_QUATERNION_H_INCLUDED__

#include "irrTypes.h"
#include "irrMath.h"
#include "matrix4.h"
#include "vector3d.h"

namespace irr
{
namespace core
{

//! Quaternion class for representing rotations.
/** It provides cheap combinations and avoids gimbal locks.
Also useful for interpolations. */
class quaternion
{
	public:

		//! Default Constructor
		quaternion() : X(0.0f), Y(0.0f), Z(0.0f), W(1.0f) {}

		//! Constructor
		quaternion(f32 x, f32 y, f32 z, f32 w) : X(x), Y(y), Z(z), W(w) { }

		//! Constructor which converts euler angles (radians) to a quaternion
		quaternion(f32 x, f32 y, f32 z);

		//! Constructor which converts euler angles (radians) to a quaternion
		quaternion(const vector3df& vec);

		//! Constructor which converts a matrix to a quaternion
		quaternion(const matrix4& mat);

		//! Equalilty operator
		bool operator==(const quaternion& other) const;

		//! inequality operator
		bool operator!=(const quaternion& other) const;

		//! Assignment operator
		inline quaternion& operator=(const quaternion& other);

		//! Matrix assignment operator
		inline quaternion& operator=(const matrix4& other);

		//! Add operator
		quaternion operator+(const quaternion& other) const;

		//! Multiplication operator
		quaternion operator*(const quaternion& other) const;

		//! Multiplication operator with scalar
		quaternion operator*(f32 s) const;

		//! Multiplication operator with scalar
		quaternion& operator*=(f32 s);

		//! Multiplication operator
		vector3df operator*(const vector3df& v) const;

		//! Multiplication operator
		quaternion& operator*=(const quaternion& other);

		//! Calculates the dot product
		inline f32 dotProduct(const quaternion& other) const;

		//! Sets new quaternion
		inline quaternion& set(f32 x, f32 y, f32 z, f32 w);

		//! Sets new quaternion based on euler angles (radians)
		inline quaternion& set(f32 x, f32 y, f32 z);

		//! Sets new quaternion based on euler angles (radians)
		inline quaternion& set(const core::vector3df& vec);

		//! Sets new quaternion from other quaternion
		inline quaternion& set(const core::quaternion& quat);

		//! returns if this quaternion equals the other one, taking floating point rounding errors into account
		inline bool equals(const quaternion& other,
				const f32 tolerance = ROUNDING_ERROR_f32 ) const;

		//! Normalizes the quaternion
		inline quaternion& normalize();

		//! Creates a matrix from this quaternion
		matrix4 getMatrix() const;

		//! Creates a matrix from this quaternion
		void getMatrix( matrix4 &dest, const core::vector3df &translation ) const;

		/*!
			Creates a matrix from this quaternion
			Rotate about a center point
			shortcut for
			core::quaternion q;
			q.rotationFromTo ( vin[i].Normal, forward );
			q.getMatrixCenter ( lookat, center, newPos );

			core::matrix4 m2;
			m2.setInverseTranslation ( center );
			lookat *= m2;

			core::matrix4 m3;
			m2.setTranslation ( newPos );
			lookat *= m3;

		*/
		void getMatrixCenter( matrix4 &dest, const core::vector3df &center, const core::vector3df &translation ) const;

		//! Creates a matrix from this quaternion
		inline void getMatrix_transposed( matrix4 &dest ) const;

		//! Inverts this quaternion
		quaternion& makeInverse();

		//! Set this quaternion to the linear interpolation between two quaternions
		/** \param q1 First quaternion to be interpolated.
		\param q2 Second quaternion to be interpolated.
		\param time Progress of interpolation. For time=0 the result is
		q1, for time=1 the result is q2. Otherwise interpolation
		between q1 and q2.
		*/
		quaternion& lerp(quaternion q1, quaternion q2, f32 time);

		//! Set this quaternion to the result of the spherical interpolation between two quaternions
		/** \param q1 First quaternion to be interpolated.
		\param q2 Second quaternion to be interpolated.
		\param time Progress of interpolation. For time=0 the result is
		q1, for time=1 the result is q2. Otherwise interpolation
		between q1 and q2.
		\param threshold To avoid inaccuracies at the end (time=1) the
		interpolation switches to linear interpolation at some point.
		This value defines how much of the remaining interpolation will
		be calculated with lerp. Everything from 1-threshold up will be
		linear interpolation.
		*/
		quaternion& slerp(quaternion q1, quaternion q2,
				f32 time, f32 threshold=.05f);

		//! Create quaternion from rotation angle and rotation axis.
		/** Axis must be unit length.
		The quaternion representing the rotation is
		q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k).
		\param angle Rotation Angle in radians.
		\param axis Rotation axis. */
		quaternion& fromAngleAxis (f32 angle, const vector3df& axis);

		//! Fills an angle (radians) around an axis (unit vector)
		void toAngleAxis (f32 &angle, core::vector3df& axis) const;

		//! Output this quaternion to an euler angle (radians)
		void toEuler(vector3df& euler) const;

		//! Set quaternion to identity
		quaternion& makeIdentity();

		//! Set quaternion to represent a rotation from one vector to another.
		quaternion& rotationFromTo(const vector3df& from, const vector3df& to);

		//! Quaternion elements.
		f32 X; // vectorial (imaginary) part
		f32 Y;
		f32 Z;
		f32 W; // real part
};

// Constructor which converts euler angles to a quaternion
inline quaternion::quaternion(f32 x, f32 y, f32 z)
{
	set(x,y,z);
}

// Constructor which converts euler angles to a quaternion
inline quaternion::quaternion(const vector3df& vec)
{
	set(vec.X,vec.Y,vec.Z);
}

// Constructor which converts a matrix to a quaternion
inline quaternion::quaternion(const matrix4& mat)
{
	(*this) = mat;
}

// equal operator
inline bool quaternion::operator==(const quaternion& other) const
{
	return ((X == other.X) &&
		(Y == other.Y) &&
		(Z == other.Z) &&
		(W == other.W));
}

// inequality operator
inline bool quaternion::operator!=(const quaternion& other) const
{
	return !(*this == other);
}

// assignment operator
inline quaternion& quaternion::operator=(const quaternion& other)
{
	X = other.X;
	Y = other.Y;
	Z = other.Z;
	W = other.W;
	return *this;
}

// matrix assignment operator
inline quaternion& quaternion::operator=(const matrix4& m)
{
	const f32 diag = m(0,0) + m(1,1) + m(2,2) + 1;

	if( diag > 0.0f )
	{
		const f32 scale = sqrtf(diag) * 2.0f; // get scale from diagonal

		// TODO: speed this up
		X = ( m(2,1) - m(1,2)) / scale;
		Y = ( m(0,2) - m(2,0)) / scale;
		Z = ( m(1,0) - m(0,1)) / scale;
		W = 0.25f * scale;
	}
	else
	{
		if ( m(0,0) > m(1,1) && m(0,0) > m(2,2))
		{
			// 1st element of diag is greatest value
			// find scale according to 1st element, and double it
			const f32 scale = sqrtf( 1.0f + m(0,0) - m(1,1) - m(2,2)) * 2.0f;

			// TODO: speed this up
			X = 0.25f * scale;
			Y = (m(0,1) + m(1,0)) / scale;
			Z = (m(2,0) + m(0,2)) / scale;
			W = (m(2,1) - m(1,2)) / scale;
		}
		else if ( m(1,1) > m(2,2))
		{
			// 2nd element of diag is greatest value
			// find scale according to 2nd element, and double it
			const f32 scale = sqrtf( 1.0f + m(1,1) - m(0,0) - m(2,2)) * 2.0f;

			// TODO: speed this up
			X = (m(0,1) + m(1,0) ) / scale;
			Y = 0.25f * scale;
			Z = (m(1,2) + m(2,1) ) / scale;
			W = (m(0,2) - m(2,0) ) / scale;
		}
		else
		{
			// 3rd element of diag is greatest value
			// find scale according to 3rd element, and double it
			const f32 scale = sqrtf( 1.0f + m(2,2) - m(0,0) - m(1,1)) * 2.0f;

			// TODO: speed this up
			X = (m(0,2) + m(2,0)) / scale;
			Y = (m(1,2) + m(2,1)) / scale;
			Z = 0.25f * scale;
			W = (m(1,0) - m(0,1)) / scale;
		}
	}

	return normalize();
}

// multiplication operator
inline quaternion quaternion::operator*(const quaternion& other) const
{
	quaternion tmp;

	tmp.W = (other.W * W) - (other.X * X) - (other.Y * Y) - (other.Z * Z);
	tmp.X = (other.W * X) + (other.X * W) + (other.Y * Z) - (other.Z * Y);
	tmp.Y = (other.W * Y) + (other.Y * W) + (other.Z * X) - (other.X * Z);
	tmp.Z = (other.W * Z) + (other.Z * W) + (other.X * Y) - (other.Y * X);

	return tmp;
}

// multiplication operator
inline quaternion quaternion::operator*(f32 s) const
{
	return quaternion(s*X, s*Y, s*Z, s*W);
}

// multiplication operator
inline quaternion& quaternion::operator*=(f32 s)
{
	X*=s;
	Y*=s;
	Z*=s;
	W*=s;
	return *this;
}

// multiplication operator
inline quaternion& quaternion::operator*=(const quaternion& other)
{
	return (*this = other * (*this));
}

// add operator
inline quaternion quaternion::operator+(const quaternion& b) const
{
	return quaternion(X+b.X, Y+b.Y, Z+b.Z, W+b.W);
}

// Creates a matrix from this quaternion
inline matrix4 quaternion::getMatrix() const
{
	core::matrix4 m;
	getMatrix_transposed(m);
	return m;
}

/*!
	Creates a matrix from this quaternion
*/
inline void quaternion::getMatrix( matrix4 &dest, const core::vector3df &center ) const
{
	f32 * m = dest.pointer();

	m[0] = 1.0f - 2.0f*Y*Y - 2.0f*Z*Z;
	m[1] = 2.0f*X*Y + 2.0f*Z*W;
	m[2] = 2.0f*X*Z - 2.0f*Y*W;
	m[3] = 0.0f;

	m[4] = 2.0f*X*Y - 2.0f*Z*W;
	m[5] = 1.0f - 2.0f*X*X - 2.0f*Z*Z;
	m[6] = 2.0f*Z*Y + 2.0f*X*W;
	m[7] = 0.0f;

	m[8] = 2.0f*X*Z + 2.0f*Y*W;
	m[9] = 2.0f*Z*Y - 2.0f*X*W;
	m[10] = 1.0f - 2.0f*X*X - 2.0f*Y*Y;
	m[11] = 0.0f;

	m[12] = center.X;
	m[13] = center.Y;
	m[14] = center.Z;
	m[15] = 1.f;

	//dest.setDefinitelyIdentityMatrix ( matrix4::BIT_IS_NOT_IDENTITY );
	dest.setDefinitelyIdentityMatrix ( false );
}

/*!
	Creates a matrix from this quaternion
	Rotate about a center point
	shortcut for
	core::quaternion q;
	q.rotationFromTo ( vin[i].Normal, forward );
	q.getMatrix ( lookat, center );

	core::matrix4 m2;
	m2.setInverseTranslation ( center );
	lookat *= m2;
*/
inline void quaternion::getMatrixCenter(matrix4 &dest,
					const core::vector3df &center,
					const core::vector3df &translation) const
{
	f32 * m = dest.pointer();

	m[0] = 1.0f - 2.0f*Y*Y - 2.0f*Z*Z;
	m[1] = 2.0f*X*Y + 2.0f*Z*W;
	m[2] = 2.0f*X*Z - 2.0f*Y*W;
	m[3] = 0.0f;

	m[4] = 2.0f*X*Y - 2.0f*Z*W;
	m[5] = 1.0f - 2.0f*X*X - 2.0f*Z*Z;
	m[6] = 2.0f*Z*Y + 2.0f*X*W;
	m[7] = 0.0f;

	m[8] = 2.0f*X*Z + 2.0f*Y*W;
	m[9] = 2.0f*Z*Y - 2.0f*X*W;
	m[10] = 1.0f - 2.0f*X*X - 2.0f*Y*Y;
	m[11] = 0.0f;

	dest.setRotationCenter ( center, translation );
}

// Creates a matrix from this quaternion
inline void quaternion::getMatrix_transposed( matrix4 &dest ) const
{
	dest[0] = 1.0f - 2.0f*Y*Y - 2.0f*Z*Z;
	dest[4] = 2.0f*X*Y + 2.0f*Z*W;
	dest[8] = 2.0f*X*Z - 2.0f*Y*W;
	dest[12] = 0.0f;

	dest[1] = 2.0f*X*Y - 2.0f*Z*W;
	dest[5] = 1.0f - 2.0f*X*X - 2.0f*Z*Z;
	dest[9] = 2.0f*Z*Y + 2.0f*X*W;
	dest[13] = 0.0f;

	dest[2] = 2.0f*X*Z + 2.0f*Y*W;
	dest[6] = 2.0f*Z*Y - 2.0f*X*W;
	dest[10] = 1.0f - 2.0f*X*X - 2.0f*Y*Y;
	dest[14] = 0.0f;

	dest[3] = 0.f;
	dest[7] = 0.f;
	dest[11] = 0.f;
	dest[15] = 1.f;
	//dest.setDefinitelyIdentityMatrix ( matrix4::BIT_IS_NOT_IDENTITY );
	dest.setDefinitelyIdentityMatrix ( false );
}

// Inverts this quaternion
inline quaternion& quaternion::makeInverse()
{
	X = -X; Y = -Y; Z = -Z;
	return *this;
}

// sets new quaternion
inline quaternion& quaternion::set(f32 x, f32 y, f32 z, f32 w)
{
	X = x;
	Y = y;
	Z = z;
	W = w;
	return *this;
}

// sets new quaternion based on euler angles
inline quaternion& quaternion::set(f32 x, f32 y, f32 z)
{
	f64 angle;

	angle = x * 0.5;
	const f64 sr = sin(angle);
	const f64 cr = cos(angle);

	angle = y * 0.5;
	const f64 sp = sin(angle);
	const f64 cp = cos(angle);

	angle = z * 0.5;
	const f64 sy = sin(angle);
	const f64 cy = cos(angle);

	const f64 cpcy = cp * cy;
	const f64 spcy = sp * cy;
	const f64 cpsy = cp * sy;
	const f64 spsy = sp * sy;

	X = (f32)(sr * cpcy - cr * spsy);
	Y = (f32)(cr * spcy + sr * cpsy);
	Z = (f32)(cr * cpsy - sr * spcy);
	W = (f32)(cr * cpcy + sr * spsy);

	return normalize();
}

// sets new quaternion based on euler angles
inline quaternion& quaternion::set(const core::vector3df& vec)
{
	return set(vec.X, vec.Y, vec.Z);
}

// sets new quaternion based on other quaternion
inline quaternion& quaternion::set(const core::quaternion& quat)
{
	return (*this=quat);
}

//! returns if this quaternion equals the other one, taking floating point rounding errors into account
inline bool quaternion::equals(const quaternion& other, const f32 tolerance) const
{
	return core::equals(X, other.X, tolerance) &&
		core::equals(Y, other.Y, tolerance) &&
		core::equals(Z, other.Z, tolerance) &&
		core::equals(W, other.W, tolerance);
}

// normalizes the quaternion
inline quaternion& quaternion::normalize()
{
	const f32 n = X*X + Y*Y + Z*Z + W*W;

	if (n == 1)
		return *this;

	//n = 1.0f / sqrtf(n);
	return (*this *= reciprocal_squareroot ( n ));
}

// set this quaternion to the result of the linear interpolation between two quaternions
inline quaternion& quaternion::lerp(quaternion q1, quaternion q2, f32 time)
{
	const f32 scale = 1.0f - time;
	return (*this = (q1*scale) + (q2*time));
}

// set this quaternion to the result of the interpolation between two quaternions
inline quaternion& quaternion::slerp(quaternion q1, quaternion q2, f32 time, f32 threshold)
{
	f32 angle = q1.dotProduct(q2);

	// make sure we use the short rotation
	if (angle < 0.0f)
	{
		q1 *= -1.0f;
		angle *= -1.0f;
	}

	if (angle <= (1-threshold)) // spherical interpolation
	{
		const f32 theta = acosf(angle);
		const f32 invsintheta = reciprocal(sinf(theta));
		const f32 scale = sinf(theta * (1.0f-time)) * invsintheta;
		const f32 invscale = sinf(theta * time) * invsintheta;
		return (*this = (q1*scale) + (q2*invscale));
	}
	else // linear interploation
		return lerp(q1,q2,time);
}

// calculates the dot product
inline f32 quaternion::dotProduct(const quaternion& q2) const
{
	return (X * q2.X) + (Y * q2.Y) + (Z * q2.Z) + (W * q2.W);
}

//! axis must be unit length, angle in radians
inline quaternion& quaternion::fromAngleAxis(f32 angle, const vector3df& axis)
{
	const f32 fHalfAngle = 0.5f*angle;
	const f32 fSin = sinf(fHalfAngle);
	W = cosf(fHalfAngle);
	X = fSin*axis.X;
	Y = fSin*axis.Y;
	Z = fSin*axis.Z;
	return *this;
}

inline void quaternion::toAngleAxis(f32 &angle, core::vector3df &axis) const
{
	const f32 scale = sqrtf(X*X + Y*Y + Z*Z);

	if (core::iszero(scale) || W > 1.0f || W < -1.0f)
	{
		angle = 0.0f;
		axis.X = 0.0f;
		axis.Y = 1.0f;
		axis.Z = 0.0f;
	}
	else
	{
		const f32 invscale = reciprocal(scale);
		angle = 2.0f * acosf(W);
		axis.X = X * invscale;
		axis.Y = Y * invscale;
		axis.Z = Z * invscale;
	}
}

inline void quaternion::toEuler(vector3df& euler) const
{
	const f64 sqw = W*W;
	const f64 sqx = X*X;
	const f64 sqy = Y*Y;
	const f64 sqz = Z*Z;
	const f64 test = 2.0 * (Y*W - X*Z);

	if (core::equals(test, 1.0, 0.000001))
	{
		// heading = rotation about z-axis
		euler.Z = (f32) (-2.0*atan2(X, W));
		// bank = rotation about x-axis
		euler.X = 0;
		// attitude = rotation about y-axis
		euler.Y = (f32) (core::PI64/2.0);
	}
	else if (core::equals(test, -1.0, 0.000001))
	{
		// heading = rotation about z-axis
		euler.Z = (f32) (2.0*atan2(X, W));
		// bank = rotation about x-axis
		euler.X = 0;
		// attitude = rotation about y-axis
		euler.Y = (f32) (core::PI64/-2.0);
	}
	else
	{
		// heading = rotation about z-axis
		euler.Z = (f32) atan2(2.0 * (X*Y +Z*W),(sqx - sqy - sqz + sqw));
		// bank = rotation about x-axis
		euler.X = (f32) atan2(2.0 * (Y*Z +X*W),(-sqx - sqy + sqz + sqw));
		// attitude = rotation about y-axis
		euler.Y = (f32) asin( clamp(test, -1.0, 1.0) );
	}
}

inline vector3df quaternion::operator* (const vector3df& v) const
{
	// nVidia SDK implementation

	vector3df uv, uuv;
	vector3df qvec(X, Y, Z);
	uv = qvec.crossProduct(v);
	uuv = qvec.crossProduct(uv);
	uv *= (2.0f * W);
	uuv *= 2.0f;

	return v + uv + uuv;
}

// set quaternion to identity
inline core::quaternion& quaternion::makeIdentity()
{
	W = 1.f;
	X = 0.f;
	Y = 0.f;
	Z = 0.f;
	return *this;
}

inline core::quaternion& quaternion::rotationFromTo(const vector3df& from, const vector3df& to)
{
	// Based on Stan Melax's article in Game Programming Gems
	// Copy, since cannot modify local
	vector3df v0 = from;
	vector3df v1 = to;
	v0.normalize();
	v1.normalize();

	const f32 d = v0.dotProduct(v1);
	if (d >= 1.0f) // If dot == 1, vectors are the same
	{
		return makeIdentity();
	}
	else if (d <= -1.0f) // exactly opposite
	{
		core::vector3df axis(1.0f, 0.f, 0.f);
		axis = axis.crossProduct(v0);
		if (axis.getLength()==0)
		{
			axis.set(0.f,1.f,0.f);
			axis.crossProduct(v0);
		}
		// same as fromAngleAxis(core::PI, axis).normalize();
		return set(axis.X, axis.Y, axis.Z, 0).normalize();
	}

	const f32 s = sqrtf( (1+d)*2 ); // optimize inv_sqrt
	const f32 invs = 1.f / s;
	const vector3df c = v0.crossProduct(v1)*invs;
	return set(c.X, c.Y, c.Z, s * 0.5f).normalize();
}

} // end namespace core
} // end namespace irr

#endif


text:
import pickle

from django.contrib.auth.models import User
from django.test import TestCase
from django.utils.functional import SimpleLazyObject

class TestUtilsSimpleLazyObjectDjangoTestCase(TestCase):

    def test_pickle(self):
        user = User.objects.create_user('johndoe', 'john@example.com', 'pass')
        x = SimpleLazyObject(lambda: user)
        pickle.dumps(x)
        # Try the variant protocol levels.
        pickle.dumps(x, 0)
        pickle.dumps(x, 1)
        pickle.dumps(x, 2)


text:
/*jshint quotmark: false*/

'use strict';

var Promise          = require('../../lib/ext/promise');
var assertFile       = require('../helpers/assert-file');
var assertFileEquals = require('../helpers/assert-file-equals');
var conf             = require('../helpers/conf');
var ember            = require('../helpers/ember');
var fs               = require('fs-extra');
var outputFile       = Promise.denodeify(fs.outputFile);
var path             = require('path');
var remove           = Promise.denodeify(fs.remove);
var root             = process.cwd();
var tmp              = require('tmp-sync');
var tmproot          = path.join(root, 'tmp');
var EOL              = require('os').EOL;
var BlueprintNpmTask = require('../helpers/disable-npm-on-blueprint');
var expect           = require('chai').expect;

describe('Acceptance: ember generate', function() {
  var tmpdir;

  before(function() {
    BlueprintNpmTask.disableNPM();
    conf.setup();
  });

  after(function() {
    BlueprintNpmTask.restoreNPM();
    conf.restore();
  });

  beforeEach(function() {
    tmpdir = tmp.in(tmproot);
    process.chdir(tmpdir);
  });

  afterEach(function() {
    this.timeout(10000);

    process.chdir(root);
    return remove(tmproot);
  });

  function initApp() {
    return ember([
      'init',
      '--name=my-app',
      '--skip-npm',
      '--skip-bower'
    ]);
  }

  function initAddon() {
    return ember([
      'addon',
      'my-addon',
      '--skip-npm',
      '--skip-bower'
    ]);
  }

  function generate(args) {
    var generateArgs = ['generate'].concat(args);

    return initApp().then(function() {
      return ember(generateArgs);
    });
  }

  function generateInAddon(args) {
    var generateArgs = ['generate'].concat(args);

    return initAddon().then(function() {
      return ember(generateArgs);
    });
  }

  it('controller foo', function() {
    return generate(['controller', 'foo']).then(function() {
      assertFile('app/controllers/foo.js', {
        contains: [
          "import Ember from 'ember';",
          "export default Ember.Controller.extend({" + EOL + "});"
        ]
      });
      assertFile('tests/unit/controllers/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('controller:foo'"
        ]
      });
    });
  });

  it('controller foo/bar', function() {
    return generate(['controller', 'foo/bar']).then(function() {
      assertFile('app/controllers/foo/bar.js', {
        contains: [
          "import Ember from 'ember';",
          "export default Ember.Controller.extend({" + EOL + "});"
        ]
      });
      assertFile('tests/unit/controllers/foo/bar-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('controller:foo/bar'"
        ]
      });
    });
  });

  it('component x-foo', function() {
    return generate(['component', 'x-foo']).then(function() {
      assertFile('app/components/x-foo.js', {
        contains: [
          "import Ember from 'ember';",
          "export default Ember.Component.extend({",
          "});"
        ]
      });
      assertFile('app/templates/components/x-foo.hbs', {
        contains: "{{yield}}"
      });
      assertFile('tests/unit/components/x-foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleForComponent," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleForComponent('x-foo'"
        ]
      });
    });
  });

  it('helper foo-bar', function() {
    return generate(['helper', 'foo-bar']).then(function() {
      assertFile('app/helpers/foo-bar.js', {
        contains: "import Ember from 'ember';" + EOL + EOL +
                  "export function fooBar(params/*, hash*/) {" + EOL +
                  "  return params;" + EOL +
                  "}" +  EOL + EOL +
                  "export default Ember.HTMLBars.makeBoundHelper(fooBar);"
      });
      assertFile('tests/unit/helpers/foo-bar-test.js', {
        contains: "import {" + EOL +
          "  fooBar" + EOL +
          "} from '../../../helpers/foo-bar';"
      });
    });
  });

  it('helper foo/bar-baz', function() {
    return generate(['helper', 'foo/bar-baz']).then(function() {
      assertFile('app/helpers/foo/bar-baz.js', {
        contains: "import Ember from 'ember';" + EOL + EOL +
                  "export function fooBarBaz(params/*, hash*/) {" + EOL +
                  "  return params;" + EOL +
                  "}" + EOL + EOL +
                  "export default Ember.HTMLBars.makeBoundHelper(fooBarBaz);"
      });
      assertFile('tests/unit/helpers/foo/bar-baz-test.js', {
        contains: "import {" + EOL +
          "  fooBarBaz" + EOL +
          "} from '../../../helpers/foo/bar-baz';"
      });
    });
  });

  it('model foo', function() {
    return generate(['model', 'foo']).then(function() {
      assertFile('app/models/foo.js', {
        contains: [
          "import DS from 'ember-data';",
          "export default DS.Model.extend"
        ]
      });
      assertFile('tests/unit/models/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleForModel," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleForModel('foo'"
        ]
      });
    });
  });

  it('model foo with attributes', function() {
    return generate([
      'model',
      'foo',
      'noType',
      'firstName:string',
      'created_at:date',
      'is-published:boolean',
      'rating:number',
      'bars:has-many',
      'baz:belongs-to',
      'echo:hasMany',
      'bravo:belongs_to',
      'foo-names:has-many',
      'barName:has-many',
      'bazName:belongs-to',
      'test-name:belongs-to',
      'echoName:hasMany',
      'bravoName:belongs_to'
    ]).then(function() {
      assertFile('app/models/foo.js', {
        contains: [
          "noType: DS.attr()",
          "firstName: DS.attr('string')",
          "createdAt: DS.attr('date')",
          "isPublished: DS.attr('boolean')",
          "rating: DS.attr('number')",
          "bars: DS.hasMany('bar')",
          "baz: DS.belongsTo('baz')",
          "echos: DS.hasMany('echo')",
          "bravo: DS.belongsTo('bravo')",
          "fooNames: DS.hasMany('foo-name')",
          "barNames: DS.hasMany('bar-name')",
          "bazName: DS.belongsTo('baz-name')",
          "testName: DS.belongsTo('test-name')",
          "echoNames: DS.hasMany('echo-name')",
          "bravoName: DS.belongsTo('bravo-name')"
        ]
      });
      assertFile('tests/unit/models/foo-test.js', {
        contains: [
          "needs: [",
          "'model:bar',",
          "'model:baz',",
          "'model:echo',",
          "'model:bravo',",
          "'model:foo-name',",
          "'model:bar-name',",
          "'model:baz-name',",
          "'model:echo-name',",
          "'model:test-name',",
          "'model:bravo-name'",
          "]"
        ]
      });
    });
  });

  it('model foo/bar', function() {
    return generate(['model', 'foo/bar']).then(function() {
      assertFile('app/models/foo/bar.js', {
        contains: [
          "import DS from 'ember-data';",
          "export default DS.Model.extend"
        ]
      });
      assertFile('tests/unit/models/foo/bar-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleForModel," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleForModel('foo/bar'"
        ]
      });
    });
  });

  it('model-test foo', function() {
    return generate(['model-test', 'foo']).then(function() {
      assertFile('tests/unit/models/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleForModel," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleForModel('foo'"
        ],
        doesNotContain: 'needs'
      });
    });
  });

  it('route foo', function() {
    return generate(['route', 'foo']).then(function() {
      assertFile('app/router.js', {
        contains: 'this.route(\'foo\')'
      });
      assertFile('app/routes/foo.js', {
        contains: [
          "import Ember from 'ember';",
          "export default Ember.Route.extend({" + EOL + "});"
        ]
      });
      assertFile('app/templates/foo.hbs', {
        contains: '{{outlet}}'
      });
      assertFile('tests/unit/routes/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('route:foo'"
        ]
      });
    });
  });

  it('route foo with --path', function() {
    return generate(['route', 'foo', '--path=:foo_id/show']).then(function() {
      assertFile('app/router.js', {
        contains: [
          'this.route(\'foo\', {',
          'path: \':foo_id/show\'',
          '});'
        ]
      });
    });
  });

  it('route foos --type=resource', function() {
    return generate(['route', 'foos', '--type=resource']).then(function() {
      assertFile('app/router.js', {
        contains: 'this.resource(\'foos\', function() {});'
      });
    });
  });

  it('route index', function() {
    return generate(['route', 'index']).then(function() {
      assertFile('app/router.js', {
        doesNotContain: "this.route('index');"
      });
    });
  });

  it('route application', function() {
    // need to run `initApp` manually here instead of using `generate` helper
    // because we need to remove the templates/application.hbs file to prevent
    // a prompt (due to a conflict)
    return initApp().then(function() {
      return remove(path.join('app', 'templates', 'application.hbs'));
    })
    .then(function() {
      return ember(['generate', 'route', 'application']);
    })
    .then(function() {
      assertFile('app/router.js', {
        doesNotContain: "this.route('application');"
      });
    });
  });

  it('route basic isn\'t added to router', function() {
    return generate(['route', 'basic']).then(function() {
      assertFile('app/router.js', {
        doesNotContain: "this.route('basic');"
      });
      assertFile('app/routes/basic.js');
    });
  });

  it('template foo', function() {
    return generate(['template', 'foo']).then(function() {
      assertFile('app/templates/foo.hbs');
    });
  });

  it('template foo/bar', function() {
    return generate(['template', 'foo/bar']).then(function() {
      assertFile('app/templates/foo/bar.hbs');
    });
  });

  it('view foo', function() {
    return generate(['view', 'foo']).then(function() {
      assertFile('app/views/foo.js', {
        contains: [
          "import Ember from 'ember';",
          "export default Ember.View.extend({" + EOL + "})"
        ]
      });
      assertFile('tests/unit/views/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('view:foo'"
        ]
      });
    });
  });

  it('view foo/bar', function() {
    return generate(['view', 'foo/bar']).then(function() {
      assertFile('app/views/foo/bar.js', {
        contains: [
          "import Ember from 'ember';",
          "export default Ember.View.extend({" + EOL + "})"
        ]
      });
      assertFile('tests/unit/views/foo/bar-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('view:foo/bar'"
        ]
      });
    });
  });

  it('resource foos', function() {
    return generate(['resource', 'foos']).then(function() {
      assertFile('app/router.js', {
        contains: 'this.resource(\'foos\', function() {});'
      });
      assertFile('app/models/foo.js', {
        contains: 'export default DS.Model.extend'
      });
      assertFile('app/routes/foos.js', {
        contains: 'export default Ember.Route.extend({' + EOL + '});'
      });
      assertFile('app/templates/foos.hbs', {
        contains: '{{outlet}}'
      });
      assertFile('tests/unit/models/foo-test.js', {
        contains: "moduleForModel('foo'"
      });
      assertFile('tests/unit/routes/foos-test.js', {
        contains: "moduleFor('route:foos'"
      });
    });
  });

  it('resource foos with --path', function() {
    return generate(['resource', 'foos', '--path=app/foos']).then(function() {
      assertFile('app/router.js', {
        contains: [
          'this.resource(\'foos\', {',
          'path: \'app/foos\'',
          '}, function() {});'
        ]
      });
    });
  });

  it('initializer foo', function() {
    return generate(['initializer', 'foo']).then(function() {
      assertFile('app/initializers/foo.js', {
        contains: "export function initialize(/* container, application */) {" + EOL +
                  "  // application.inject('route', 'foo', 'service:foo');" + EOL +
                  "}" + EOL +
                  "" + EOL+
                  "export default {" + EOL +
                  "  name: 'foo'," + EOL +
                  "  initialize: initialize" + EOL +
                  "};"
      });

      assertFile('tests/unit/initializers/foo-test.js');
    });
  });

  it('initializer foo/bar', function() {
    return generate(['initializer', 'foo/bar']).then(function() {
      assertFile('app/initializers/foo/bar.js', {
        contains: "export function initialize(/* container, application */) {" + EOL +
                  "  // application.inject('route', 'foo', 'service:foo');" + EOL +
                  "}" + EOL +
                  "" + EOL+
                  "export default {" + EOL +
                  "  name: 'foo/bar'," + EOL +
                  "  initialize: initialize" + EOL +
                  "};"
      });

      assertFile('tests/unit/initializers/foo/bar-test.js');
    });
  });

  it('mixin foo', function() {
    return generate(['mixin', 'foo']).then(function() {
      assertFile('app/mixins/foo.js', {
        contains: [
          "import Ember from 'ember';",
          'export default Ember.Mixin.create({' + EOL + '});'
        ]
      });
      assertFile('tests/unit/mixins/foo-test.js', {
        contains: [
          "import FooMixin from '../../../mixins/foo';"
        ]
      });
    });
  });

  it('mixin foo/bar', function() {
    return generate(['mixin', 'foo/bar']).then(function() {
      assertFile('app/mixins/foo/bar.js', {
        contains: [
          "import Ember from 'ember';",
          'export default Ember.Mixin.create({' + EOL + '});'
        ]
      });
      assertFile('tests/unit/mixins/foo/bar-test.js', {
        contains: [
          "import FooBarMixin from '../../../mixins/foo/bar';"
        ]
      });
    });
  });

  it('mixin foo/bar/baz', function() {
    return generate(['mixin', 'foo/bar/baz']).then(function() {
      assertFile('tests/unit/mixins/foo/bar/baz-test.js', {
        contains: [
          "import FooBarBazMixin from '../../../mixins/foo/bar/baz';"
        ]
      });
    });
  });

  it('adapter application', function() {
    return generate(['adapter', 'application']).then(function() {
      assertFile('app/adapters/application.js', {
        contains: [
          "import DS from \'ember-data\';",
          "export default DS.RESTAdapter.extend({" + EOL + "});"
        ]
      });
      assertFile('tests/unit/adapters/application-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('adapter:application'"
        ]
      });
    });
  });

  it('adapter foo', function() {
    return generate(['adapter', 'foo']).then(function() {
      assertFile('app/adapters/foo.js', {
        contains: [
          "import ApplicationAdapter from \'./application\';",
          "export default ApplicationAdapter.extend({" + EOL + "});"
        ]
      });
      assertFile('tests/unit/adapters/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('adapter:foo'"
        ]
      });
    });
  });

  it('adapter foo/bar', function() {
    return generate(['adapter', 'foo/bar']).then(function() {
      assertFile('app/adapters/foo/bar.js', {
        contains: [
          "import ApplicationAdapter from \'./application\';",
          "export default ApplicationAdapter.extend({" + EOL + "});"
        ]
      });
    });
  });

  it('adapter application cannot extend from --base-class=application', function() {
    return generate(['adapter', 'application', '--base-class=application']).then(function() {
      expect(false);
    }, function(err) {
      expect(err.message).to.match(/Adapters cannot extend from themself/);
    });
  });

  it('adapter foo cannot extend from --base-class=foo', function() {
    return generate(['adapter', 'foo', '--base-class=foo']).then(function() {
      expect(false);
    }, function(err) {
      expect(err.message).to.match(/Adapters cannot extend from themself/);
    });
  });

  it('adapter extends from --base-class=bar', function() {
    return generate(['adapter', 'foo', '--base-class=bar']).then(function() {
      assertFile('app/adapters/foo.js', {
        contains: [
          "import BarAdapter from './bar';",
          "export default BarAdapter.extend({" + EOL + "});"
        ]
      });
    });
  });

  it('adapter extends from --base-class=foo/bar', function() {
    return generate(['adapter', 'foo/baz', '--base-class=foo/bar']).then(function() {
      assertFile('app/adapters/foo/baz.js', {
        contains: [
          "import FooBarAdapter from './foo/bar';",
          "export default FooBarAdapter.extend({" + EOL + "});"
        ]
      });
    });
  });

  it('adapter extends from application adapter if present', function() {
    return generate(['adapter', 'application']).then(function() {
      return generate(['adapter', 'foo']).then(function() {
        assertFile('app/adapters/foo.js', {
          contains: [
            "import ApplicationAdapter from './application';",
            "export default ApplicationAdapter.extend({" + EOL + "});"
          ]
        });
      });
    });
  });

  it('adapter favors  --base-class over  application', function() {
    return generate(['adapter', 'application']).then(function() {
      return generate(['adapter', 'foo', '--base-class=bar']).then(function() {
        assertFile('app/adapters/foo.js', {
          contains: [
            "import BarAdapter from './bar';",
            "export default BarAdapter.extend({" + EOL + "});"
          ]
        });
      });
    });
  });

  it('serializer foo', function() {
    return generate(['serializer', 'foo']).then(function() {
      assertFile('app/serializers/foo.js', {
        contains: [
          "import DS from 'ember-data';",
          'export default DS.RESTSerializer.extend({' + EOL + '});'
        ]
      });
      assertFile('tests/unit/serializers/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
        ]
      });
    });
  });

  it('serializer foo/bar', function() {
    return generate(['serializer', 'foo/bar']).then(function() {
      assertFile('app/serializers/foo/bar.js', {
        contains: [
          "import DS from 'ember-data';",
          'export default DS.RESTSerializer.extend({' + EOL + '});'
        ]
      });
      assertFile('tests/unit/serializers/foo/bar-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('serializer:foo/bar'"
        ]
      });
    });
  });

  it('transform foo', function() {
    return generate(['transform', 'foo']).then(function() {
      assertFile('app/transforms/foo.js', {
        contains: [
          "import DS from 'ember-data';",
          'export default DS.Transform.extend({' + EOL +
          '  deserialize: function(serialized) {' + EOL +
          '    return serialized;' + EOL +
          '  },' + EOL +
          EOL +
          '  serialize: function(deserialized) {' + EOL +
          '    return deserialized;' + EOL +
          '  }' + EOL +
          '});'
        ]
      });
      assertFile('tests/unit/transforms/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('transform:foo'"
        ]
      });
    });
  });

  it('transform foo/bar', function() {
    return generate(['transform', 'foo/bar']).then(function() {
      assertFile('app/transforms/foo/bar.js', {
        contains: [
          "import DS from 'ember-data';",
          'export default DS.Transform.extend({' + EOL +
          '  deserialize: function(serialized) {' + EOL +
          '    return serialized;' + EOL +
          '  },' + EOL +
          '' + EOL +
          '  serialize: function(deserialized) {' + EOL +
          '    return deserialized;' + EOL +
          '  }' + EOL +
          '});'
        ]
      });
      assertFile('tests/unit/transforms/foo/bar-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('transform:foo/bar'"
        ]
      });
    });
  });

  it('util foo-bar', function() {
    return generate(['util', 'foo-bar']).then(function() {
      assertFile('app/utils/foo-bar.js', {
        contains: 'export default function fooBar() {' + EOL +
                  '  return true;' + EOL +
                  '}'
      });
      assertFile('tests/unit/utils/foo-bar-test.js', {
        contains: [
          "import fooBar from '../../../utils/foo-bar';"
        ]
      });
    });
  });

  it('util foo-bar/baz', function() {
    return generate(['util', 'foo/bar-baz']).then(function() {
      assertFile('app/utils/foo/bar-baz.js', {
        contains: 'export default function fooBarBaz() {' + EOL +
                  '  return true;' + EOL +
                  '}'
      });
      assertFile('tests/unit/utils/foo/bar-baz-test.js', {
        contains: [
          "import fooBarBaz from '../../../utils/foo/bar-baz';"
        ]
      });
    });
  });

  it('service foo', function() {
    return generate(['service', 'foo']).then(function() {
      assertFile('app/services/foo.js', {
        contains: [
          "import Ember from 'ember';",
          'export default Ember.Service.extend({' + EOL + '});'
        ]
      });
      assertFile('tests/unit/services/foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('service:foo'"
        ]
      });
    });
  });

  it('service foo/bar', function() {
    return generate(['service', 'foo/bar']).then(function() {
      assertFile('app/services/foo/bar.js', {
        contains: [
          "import Ember from 'ember';",
          'export default Ember.Service.extend({' + EOL + '});'
        ]
      });
      assertFile('tests/unit/services/foo/bar-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleFor," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleFor('service:foo/bar'"
        ]
      });
    });
  });

  it('blueprint foo', function() {
    return generate(['blueprint', 'foo']).then(function() {
      assertFile('blueprints/foo/index.js', {
        contains: "module.exports = {" + EOL +
                  "  description: ''"+ EOL +
                  EOL +
                  "  // locals: function(options) {" + EOL +
                  "  //   // Return custom template variables here." + EOL +
                  "  //   return {" + EOL +
                  "  //     foo: options.entity.options.foo" + EOL +
                  "  //   };" + EOL +
                  "  // }" + EOL +
                  EOL +
                  "  // afterInstall: function(options) {" + EOL +
                  "  //   // Perform extra work here." + EOL +
                  "  // }" + EOL +
                  "};"
      });
    });
  });

  it('blueprint foo/bar', function() {
    return generate(['blueprint', 'foo/bar']).then(function() {
      assertFile('blueprints/foo/bar/index.js', {
        contains: "module.exports = {" + EOL +
                  "  description: ''"+ EOL +
                  EOL +
                  "  // locals: function(options) {" + EOL +
                  "  //   // Return custom template variables here." + EOL +
                  "  //   return {" + EOL +
                  "  //     foo: options.entity.options.foo" + EOL +
                  "  //   };" + EOL +
                  "  // }" + EOL +
                  EOL +
                  "  // afterInstall: function(options) {" + EOL +
                  "  //   // Perform extra work here." + EOL +
                  "  // }" + EOL +
                  "};"
      });
    });
  });

  it('http-mock foo', function() {
    this.timeout(10000);
    return generate(['http-mock', 'foo']).then(function() {
      assertFile('server/index.js', {
        contains:"mocks.forEach(function(route) { route(app); });"
      });
      assertFile('server/mocks/foo.js', {
        contains: "module.exports = function(app) {" + EOL +
                  "  var express = require('express');" + EOL +
                  "  var fooRouter = express.Router();" + EOL +
                  EOL +
                  "  fooRouter.get('/', function(req, res) {" + EOL +
                  "    res.send({" + EOL +
                  "      'foo': []" + EOL +
                  "    });" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooRouter.post('/', function(req, res) {" + EOL +
                  "    res.status(201).end();" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooRouter.get('/:id', function(req, res) {" + EOL +
                  "    res.send({" + EOL +
                  "      'foo': {" + EOL +
                  "        id: req.params.id" + EOL +
                  "      }" + EOL +
                  "    });" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooRouter.put('/:id', function(req, res) {" + EOL +
                  "    res.send({" + EOL +
                  "      'foo': {" + EOL +
                  "        id: req.params.id" + EOL +
                  "      }" + EOL +
                  "    });" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooRouter.delete('/:id', function(req, res) {" + EOL +
                  "    res.status(204).end();" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  app.use('/api/foo', fooRouter);" + EOL +
                  "};"
      });
      assertFile('server/.jshintrc', {
        contains: '{' + EOL + '  "node": true' + EOL + '}'
      });
    });
  });

  it('http-mock foo-bar', function() {
    return generate(['http-mock', 'foo-bar']).then(function() {
      assertFile('server/index.js', {
        contains: "mocks.forEach(function(route) { route(app); });"
      });
      assertFile('server/mocks/foo-bar.js', {
        contains: "module.exports = function(app) {" + EOL +
                  "  var express = require('express');" + EOL +
                  "  var fooBarRouter = express.Router();" + EOL +
                  EOL +
                  "  fooBarRouter.get('/', function(req, res) {" + EOL +
                  "    res.send({" + EOL +
                  "      'foo-bar': []" + EOL +
                  "    });" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooBarRouter.post('/', function(req, res) {" + EOL +
                  "    res.status(201).end();" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooBarRouter.get('/:id', function(req, res) {" + EOL +
                  "    res.send({" + EOL +
                  "      'foo-bar': {" + EOL +
                  "        id: req.params.id" + EOL +
                  "      }" + EOL +
                  "    });" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooBarRouter.put('/:id', function(req, res) {" + EOL +
                  "    res.send({" + EOL +
                  "      'foo-bar': {" + EOL +
                  "        id: req.params.id" + EOL +
                  "      }" + EOL +
                  "    });" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  fooBarRouter.delete('/:id', function(req, res) {" + EOL +
                  "    res.status(204).end();" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  app.use('/api/foo-bar', fooBarRouter);" + EOL +
                  "};"
      });
      assertFile('server/.jshintrc', {
        contains: '{' + EOL + '  "node": true' + EOL + '}'
      });
    });
  });

  it('http-proxy foo', function() {
    return generate(['http-proxy', 'foo', 'http://localhost:5000']).then(function() {
      assertFile('server/index.js', {
        contains: "proxies.forEach(function(route) { route(app); });"
      });
      assertFile('server/proxies/foo.js', {
        contains: "var proxyPath = '/foo';" + EOL +
                  EOL +
                  "module.exports = function(app) {" + EOL +
                  "  // For options, see:" + EOL +
                  "  // https://github.com/nodejitsu/node-http-proxy" + EOL +
                  "  var proxy = require('http-proxy').createProxyServer({});" + EOL +
                  EOL +
                  "  proxy.on('error', function(err, req) {" + EOL +
                  "    console.error(err, req.url);" + EOL +
                  "  });" + EOL +
                  EOL +
                  "  app.use(proxyPath, function(req, res, next){" + EOL +
                  "    // include root path in proxied request" + EOL +
                  "    req.url = proxyPath + '/' + req.url;" + EOL +
                  "    proxy.web(req, res, { target: 'http://localhost:5000' });" + EOL +
                  "  });" + EOL +
                  "};"
      });
      assertFile('server/.jshintrc', {
        contains: '{' + EOL + '  "node": true' + EOL + '}'
      });
    });
  });

  it('uses blueprints from the project directory', function() {
    return initApp()
      .then(function() {
        return outputFile(
          'blueprints/foo/files/app/foos/__name__.js',
          "import Ember from 'ember';" + EOL +
          'export default Ember.Object.extend({ foo: true });' + EOL
        );
      })
      .then(function() {
        return ember(['generate', 'foo', 'bar']);
      })
      .then(function() {
        assertFile('app/foos/bar.js', {
          contains: 'foo: true'
        });
      });
  });

  it('allows custom blueprints to override built-ins', function() {
    return initApp()
      .then(function() {
        return outputFile(
          'blueprints/controller/files/app/controllers/__name__.js',
          "import Ember from 'ember';" + EOL + EOL +
          "export default Ember.Controller.extend({ custom: true });" + EOL
        );
      })
      .then(function() {
        return ember(['generate', 'controller', 'foo']);
      })
      .then(function() {
        assertFile('app/controllers/foo.js', {
          contains: 'custom: true'
        });
      });
  });

  it('uses custom model-test blueprint when generating resources', function() {
    return initApp()
      .then(function() {
        return outputFile(
          'blueprints/model-test/files/tests/unit/models/__test__.js',
          "// custom model-test" + EOL
        );
      })
      .then(function() {
        return ember(['generate', 'resource', 'foo']);
      })
      .then(function() {
        assertFile('tests/unit/models/foo-test.js', {
          contains: '// custom model-test'
        });
      });
  });

  it('uses custom route-test blueprint when generating resources', function() {
    return initApp()
      .then(function() {
        return outputFile(
          'blueprints/route-test/files/tests/unit/routes/__test__.js',
          "// custom route-test" + EOL
        );
      })
      .then(function() {
        return ember(['generate', 'resource', 'foo']);
      })
      .then(function() {
        assertFile('tests/unit/routes/foo-test.js', {
          contains: '// custom route-test'
        });
      });
  });

  it('passes custom cli arguments to blueprint options', function() {
    return initApp()
      .then(function() {
        outputFile(
          'blueprints/customblue/files/app/__name__.js',
          "Q: Can I has custom command? A: <%= hasCustomCommand %>"
        );
        return outputFile(
          'blueprints/customblue/index.js',
          "module.exports = {" + EOL +
          "  locals: function(options) {" + EOL +
          "    var loc = {};" + EOL +
          "    loc.hasCustomCommand = (options.customCommand) ? 'Yes!' : 'No. :C';" + EOL +
          "    return loc;" + EOL +
          "  }," + EOL +
          "};" + EOL
        );
      })
      .then(function() {
        return ember(['generate', 'customblue', 'foo', '--custom-command']);
      })
      .then(function() {
        assertFile('app/foo.js', {
          contains: 'A: Yes!'
        });
      });
  });

  it('acceptance-test foo', function() {
    return generate(['acceptance-test', 'foo']).then(function() {
      var expected = path.join(__dirname, '../fixtures/generate/acceptance-test-expected.js');

      assertFileEquals('tests/acceptance/foo-test.js', expected);
    });
  });

  it('test-helper foo', function() {
    return generate(['test-helper', 'foo']).then(function() {
      assertFile('tests/helpers/foo.js', {
        contains: "import Ember from 'ember';" + EOL +
                  EOL +
                  "export default Ember.Test.registerAsyncHelper('foo', function(app) {" + EOL +
                  EOL +
                  "});"
      });
    });
  });

  it('correctly identifies the root of the project', function() {
    return initApp()
      .then(function() {
        return outputFile(
          'blueprints/controller/files/app/controllers/__name__.js',
          "import Ember from 'ember';" + EOL + EOL +
          "export default Ember.Controller.extend({ custom: true });" + EOL
        );
      })
      .then(function() {
        process.chdir(path.join(tmpdir, 'app'));
      })
      .then(function() {
        return ember(['generate', 'controller', 'foo']);
      })
      .then(function() {
        process.chdir(tmpdir);
      })
      .then(function() {
        assertFile('app/controllers/foo.js', {
          contains: 'custom: true'
        });
      });
  });

  it('route foo --dry-run does not change router.js', function() {
    return generate(['route', 'foo', '--dry-run']).then(function() {
      assertFile('app/router.js', {
        doesNotContain: "route('foo')"
      });
    });
  });

  it('in-repo-addon foo-bar', function() {
    return generate(['in-repo-addon', 'foo-bar']).then(function() {
      assertFile('lib/foo-bar/index.js', {
        contains: [
          'module.exports = {',
          'name: \'foo-bar\'',
          '',
          'isDevelopingAddon: function() {',
          'return true;',
          '}',
          '}'
        ]
      });

      assertFile('lib/foo-bar/package.json', {
        contains: [
          '{',
          '  "name": "foo-bar"',
          '  "keywords": [',
          '    "ember-addon"',
          '  ]',
          '}'
        ]
      });

      assertFile('package.json', {
        contains: [
          '"' + path.normalize('lib/foo-bar').replace('\\', '\\\\') + '"'
        ]
      });

      assertFile('lib/.jshintrc');
    });
  });

  it('server', function() {
    return generate(['server']).then(function() {
      assertFile('server/index.js');
      assertFile('server/.jshintrc');
    });
  });

  it('in-addon component x-foo', function() {
    return generateInAddon(['component', 'x-foo']).then(function() {
      assertFile('addon/components/x-foo.js', {
        contains: [
          "import Ember from 'ember';",
          "import layout from '../templates/components/x-foo';",
          "export default Ember.Component.extend({",
          "layout: layout",
          "});"
        ]
      });
      assertFile('addon/templates/components/x-foo.hbs', {
        contains: "{{yield}}"
      });
      assertFile('app/components/x-foo.js', {
        contains: [
          "import xFoo from 'my-addon/components/x-foo';",
          "export default xFoo;"
        ]
      });
      assertFile('tests/unit/components/x-foo-test.js', {
        contains: [
          "import {" + EOL +
          "  moduleForComponent," + EOL +
          "  test" + EOL +
          "} from 'ember-qunit';",
          "moduleForComponent('x-foo'"
        ]
      });
    });
  });

  it('availableOptions work with aliases.', function() {
    return generate(['route', 'foo', '-resource']).then(function() {
      assertFile('app/router.js', {
        contain: ["resource('foo')"]
      });
    });
  });

  it('lib', function() {
    return generate(['lib']).then(function() {
      assertFile('lib/.jshintrc');
    });
  });
});


text:
from .framework import (Framework, main)
from Box2D import (b2CircleShape, b2EdgeShape, b2Filter, b2FixtureDef,
                   b2PolygonShape, b2Vec2)

class CollisionFiltering (Framework):
    name = "Collision Filtering"
    description = "See which shapes collide with each other."
    # This is a test of collision filtering.
    # There is a triangle, a box, and a circle.
    # There are 6 shapes. 3 large and 3 small.
    # The 3 small ones always collide.
    # The 3 large ones never collide.
    # The boxes don't collide with triangles (except if both are small).
    # The box connected to the large triangle has no filter settings,
    # so it collides with everything.

    def __init__(self):
        super(CollisionFiltering, self).__init__()
        # Ground body
        world = self.world
        ground = world.CreateBody(
            shapes=b2EdgeShape(vertices=[(-40, 0), (40, 0)])
        )

        # Define the groups that fixtures can fall into
        # Note that negative groups never collide with other negative ones.
        smallGroup = 1
        largeGroup = -1

        # And the categories
        # Note that these are bit-locations, and as such are written in
        # hexadecimal.
        # defaultCategory = 0x0001
        triangleCategory = 0x0002
        boxCategory = 0x0004
        circleCategory = 0x0008

        # And the masks that define which can hit one another
        # A mask of 0xFFFF means that it will collide with everything else in
        # its group. The box mask below uses an exclusive OR (XOR) which in
        # effect toggles the triangleCategory bit, making boxMask = 0xFFFD.
        # Such a mask means that boxes never collide with triangles.  (if
        # you're still confused, see the implementation details below)

        triangleMask = 0xFFFF
        boxMask = 0xFFFF ^ triangleCategory
        circleMask = 0xFFFF

        # The actual implementation determining whether or not two objects
        # collide is defined in the C++ source code, but it can be overridden
        # in Python (with b2ContactFilter).
        # The default behavior goes like this:
        #   if (filterA.groupIndex == filterB.groupIndex and filterA.groupIndex != 0):
        #       collide if filterA.groupIndex is greater than zero (negative groups never collide)
        #   else:
        #       collide if (filterA.maskBits & filterB.categoryBits) != 0 and (filterA.categoryBits & filterB.maskBits) != 0
        #
        # So, if they have the same group index (and that index isn't the
        # default 0), then they collide if the group index is > 0 (since
        # negative groups never collide)
        # (Note that a body with the default filter settings will always
        # collide with everything else.)
        # If their group indices differ, then only if their bitwise-ANDed
        # category and mask bits match up do they collide.
        #
        # For more help, some basics of bit masks might help:
        # -> http://en.wikipedia.org/wiki/Mask_%28computing%29

        # Small triangle
        triangle = b2FixtureDef(
            shape=b2PolygonShape(vertices=[(-1, 0), (1, 0), (0, 2)]),
            density=1,
            filter=b2Filter(
                groupIndex=smallGroup,
                categoryBits=triangleCategory,
                maskBits=triangleMask,
            )
        )

        world.CreateDynamicBody(
            position=(-5, 2),
            fixtures=triangle,
        )

        # Large triangle (recycle definitions)
        triangle.shape.vertices = [
            2.0 * b2Vec2(v) for v in triangle.shape.vertices]
        triangle.filter.groupIndex = largeGroup

        trianglebody = world.CreateDynamicBody(
            position=(-5, 6),
            fixtures=triangle,
            fixedRotation=True,  # <--
        )
        # note that the large triangle will not rotate

        # Small box
        box = b2FixtureDef(
            shape=b2PolygonShape(box=(1, 0.5)),
            density=1,
            restitution=0.1,
            filter = b2Filter(
                groupIndex=smallGroup,
                categoryBits=boxCategory,
                maskBits=boxMask,
            )
        )

        world.CreateDynamicBody(
            position=(0, 2),
            fixtures=box,
        )

        # Large box
        box.shape.box = (2, 1)
        box.filter.groupIndex = largeGroup
        world.CreateDynamicBody(
            position=(0, 6),
            fixtures=box,
        )

        # Small circle
        circle = b2FixtureDef(
            shape=b2CircleShape(radius=1),
            density=1,
            filter=b2Filter(
                groupIndex=smallGroup,
                categoryBits=circleCategory,
                maskBits=circleMask,
            )
        )

        world.CreateDynamicBody(
            position=(5, 2),
            fixtures=circle,
        )

        # Large circle
        circle.shape.radius *= 2
        circle.filter.groupIndex = largeGroup
        world.CreateDynamicBody(
            position=(5, 6),
            fixtures=circle,
        )

        # Create a joint for fun on the big triangle
        # Note that it does not inherit or have anything to do with the
        # filter settings of the attached triangle.
        box = b2FixtureDef(shape=b2PolygonShape(box=(0.5, 1)), density=1)

        testbody = world.CreateDynamicBody(
            position=(-5, 10),
            fixtures=box,
        )
        world.CreatePrismaticJoint(
            bodyA=trianglebody,
            bodyB=testbody,
            enableLimit=True,
            localAnchorA=(0, 4),
            localAnchorB=(0, 0),
            localAxisA=(0, 1),
            lowerTranslation=-1,
            upperTranslation=1,
        )

if __name__ == "__main__":
    main(CollisionFiltering)


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;

namespace NMF.Models.Tests.Railway
{

    public class SwitchPositionsCollection : ObservableOppositeList<ISwitch, ISwitchPosition>
    {

        public SwitchPositionsCollection(ISwitch parent) :
                base(parent)
        {
        }

        private void OnItemDeleted(object sender, System.EventArgs e)
        {
            this.Remove(((ISwitchPosition)(sender)));
        }

        protected override void SetOpposite(ISwitchPosition item, ISwitch parent)
        {
            if ((parent != null))
            {
                item.Deleted += this.OnItemDeleted;
                item.Switch = parent;
            }
            else
            {
                item.Deleted -= this.OnItemDeleted;
                if ((item.Switch == this.Parent))
                {
                    item.Switch = parent;
                }
            }
        }
    }
}


text:
title: I.T lesson 27-06-16
layout: post
author: horatio.holloway
permalink: /i.t-lesson-27-06-16/
source-id: 14G8em1SJ9hy8POO4y9FtwwycUqK1697vJApSZtW9iEA
published: true
---
In the lesson today we had to move into a different room. We then looked at what we were scared of on social media. It allowed me to learn about some dangers on social media that i didn't know about before like catfishing. It was also a good way to see all of the potential uses of social media. It felt quite scary that there were so many dangers on social media and how many people, for example, can hack into your account.

For homework, we had to look up news stories on sexting and revenge pornography.

Thanks, raish-04


text:
<?php
namespace Project {
    \defined( '_JEXEC' ) or die( 'Restricted access' );

    //******************************************************************************
    // SECTION - GENERAL
    \defined('DS') or \define('DS', \DIRECTORY_SEPARATOR);

    $this->inDebugMode                  = \TRUE;
    $this->inProductionMode             = !$this->inDebugMode;
    $this->systemAdminName              = "Zeakis George";
    $this->systemAdminEmailAddress      = "zeageorge@gmail.com";
    $this->siteRootUrl                  = "http://localhost/Project01_8PD/";
    $this->siteTitle                    = "Steak House";
    $this->publicUrl                    = 'public/';
    $this->cssUrl                       = $this->publicUrl.'css/';
    $this->jsUrl                        = $this->publicUrl.'js/';
    $this->imagesUrl                    = $this->publicUrl.'images/';
    $this->photoGalleryUrl              = $this->imagesUrl.'photo_gallery/';

    //******************************************************************************
    // SECTION - Framework GENERAL

        // Physical Paths
    $this->protectedFolderPath          = $this->entryPoint.         "protected".       \DS;
    $this->publicFolderPath             = $this->entryPoint.         "public".          \DS;
    $this->libsFolderPath               = $this->protectedFolderPath."libs".            \DS;
    $this->controllersFolderPath        = $this->protectedFolderPath."controllers".     \DS;
    $this->modelsFolderPath             = $this->protectedFolderPath."models".          \DS;
    $this->viewsFolderPath              = $this->protectedFolderPath."views".           \DS;
    $this->formsFolderPath              = $this->protectedFolderPath."forms".           \DS;
    $this->cssFolderPath                = $this->publicFolderPath   ."css".             \DS;
    $this->jsFolderPath                 = $this->publicFolderPath   ."js".              \DS;
    $this->imagesFolderPath             = $this->publicFolderPath   ."images".          \DS;
    $this->photoGalleryFolderPath       = $this->imagesFolderPath   ."photo_gallery".   \DS;
    $this->newsXMLFilePath              = $this->publicFolderPath   ."news.xml";

    $this->db_connectionData = array(
        'type'          =>'mysql',
        'host'          =>'localhost',
        'port'          =>'3306',
        'dbName'        =>'db_3964_01',
        'username'      =>'3964',
        'password'      =>'1234',
        'tablePrefix'   =>'tbl_',
    );

    $this->http_request_fieldName               = 'url'; // if you change this you must also change it in .htaccess
    $this->http_request_defaultControllerName   = 'index';
    $this->http_request_defaultActionName       = 'index'; // this is for all controllers

    //******************************************************************************
    // SECTION - COMPONENTS
    //

    //******************************************************************************
    // SECTION - PHP RUNTIME GENERAL
    //
    if ($this->inProductionMode){
        \ini_set('display_startup_errors',0);
        \ini_set('display_errors', 0);
    } else {
        \ini_set('display_startup_errors',1);
        \ini_set('display_errors', 1);
    }
    \error_reporting(-1);
    \date_default_timezone_set('Europe/Athens');
    \setlocale(\LC_ALL,'es_ES.UTF-8');
}
?>


text:
@implementation SPTransRequest
{
    NSMutableDictionary *respostaServer;
    NSString *previsaoDaChegada;
}

+(void)token: (NSString *)token{
    [[NSUserDefaults standardUserDefaults]setValue:token forKey:@"token"];
}

+(NSString *)token{
   return [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
}

+(void)requestServerSPTrans: (requestMethodGET)methodGET
                       line: (id)line
                   response: (void (^)(NSMutableDictionary *response))sucess
                       erro: (void (^)(NSError *error))fail{

    NSString *requestToken = [NSString stringWithFormat:@"http://api.olhovivo.sptrans.com.br/v0/Login/Autenticar?token=%@", [self token]];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:requestToken]];
    [httpClient setAuthorizationHeaderWithToken:[self token]];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:Nil parameters:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"User authorized: %@", [operation responseString]);
        if ([[operation responseString] isEqualToString:@"true"]) {
            AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:[self returnURL:methodGET line:line]]];
            NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:Nil parameters:nil];
            AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
            [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSError *fail;
                sucess([NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&fail]);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                fail(error);
            }];
            [operation start];

        }else{
            NSLog(@"ERROR: User no authorized: %@", [operation responseString]);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(error);
    }];
    [operation start];
}

+(NSString *)returnURL: (requestMethodGET)methodGET line:(id)line{
    NSString *SPTrans = @"http://api.olhovivo.sptrans.com.br/v0";
    switch (methodGET) {
        case requestMethodGETLinhas:                return [NSString stringWithFormat:@"%@/Linha/Buscar?termosBusca=%@", SPTrans, line]; break;
        case requestMethodGETDetalhes:              return [NSString stringWithFormat:@"%@/Linha/CarregarDetalhes?codigoLinha=%@", SPTrans, line] ;break;
        case requestMethodGETParadas:               return [NSString stringWithFormat:@"%@/Parada/Buscar?termosBusca=%@", SPTrans, line] ;break;
        case requestMethodGETParadasPorLinha:       return [NSString stringWithFormat:@"%@/Parada/BuscarParadasPorLinha?codigoLinha=%@", SPTrans, line] ;break;
        case requestMethodGETParadasPorCorredor:    return [NSString stringWithFormat:@"%@/Parada/BuscarParadasPorCorredor?codigoCorredor=%@", SPTrans, line] ;break;
        case requestMethodGETCorredores:            return [NSString stringWithFormat:@"%@/Corredor", SPTrans] ;break;
        case requestMethodGETPosicaoDoVeiculo:      return [NSString stringWithFormat:@"%@/Posicao?codigoLinha=%@", SPTrans, line] ;break;
        case requestMethodGETLinha:                 return [NSString stringWithFormat:@"%@/Previsao/Linha?codigoLinha=%@", SPTrans, line] ;break;
        case requestMethodGETParada:                return [NSString stringWithFormat:@"%@/Previsao/Parada?codigoParada=%@", SPTrans, line] ;break;
    }
    return nil;
}

@end


text:
package org.sfm.jdbc;

import org.junit.Test;
import org.sfm.beans.Db1DeepObject;
import org.sfm.beans.Db2DeepObject;
import org.sfm.beans.DbFinal1DeepObject;
import org.sfm.map.column.FieldMapperColumnDefinition;
import org.sfm.reflect.Getter;
import org.sfm.test.jdbc.DbHelper;
import org.sfm.test.jdbc.TestRowHandler;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class JdbcMapperSubObjectTest {

	private static final String QUERY = "select 33 as id, "
			+ "'value' as value,  "
			+ "id as db_object_id, "
			+ "name as db_object_name, "
			+ "email as db_object_email, "
			+ "creation_time as db_object_creation_time, "
			+ "type_ordinal as db_object_type_ordinal, "
			+ "type_name as db_object_type_name "
			+ "from TEST_DB_OBJECT where id = 1 ";

	@Test
	public void testMapInnerObjectWithStaticMapper() throws Exception {
		JdbcMapperBuilder<Db1DeepObject> builder = JdbcMapperFactoryHelper.asm().newBuilder(Db1DeepObject.class);

		addColumns(builder);

		final JdbcMapper<Db1DeepObject> mapper = builder.mapper();

		DbHelper.testQuery(new TestRowHandler<PreparedStatement>() {
			@Override
			public void handle(PreparedStatement t) throws Exception {
				ResultSet rs = t.executeQuery();
				rs.next();

				Db1DeepObject object = mapper.map(rs);
				assertEquals(33, object.getId());
				assertEquals("value", object.getValue());
				DbHelper.assertDbObjectMapping(object.getDbObject());
			}
		}, QUERY);
	}

    @Test
    public void testMapInnerObjectWithColumnDefinition() throws Exception {
        JdbcMapperBuilder<Db1DeepObject> builder = JdbcMapperFactoryHelper.asm().newBuilder(Db1DeepObject.class);

        FieldMapperColumnDefinition<JdbcColumnKey> columnDefinition = FieldMapperColumnDefinition.customGetter(new Getter<ResultSet, String>() {
            @Override
            public String get(ResultSet target) throws Exception {
                return "ov1";
            }
        });
        builder.addMapping("db_object_name", columnDefinition);

        final JdbcMapper<Db1DeepObject> mapper = builder.mapper();

        ResultSet rs = mock(ResultSet.class);

        when(rs.getString(1)).thenReturn("name1");
        when(rs.next()).thenReturn(true, false);

        Db1DeepObject next = mapper.iterator(rs).next();

        assertEquals("ov1", next.getDbObject().getName());

    }

	@Test
	public void testMapInnerFinalObjectWithStaticMapper() throws Exception {
		JdbcMapperBuilder<DbFinal1DeepObject> builder = JdbcMapperFactoryHelper.asm().newBuilder(DbFinal1DeepObject.class);

		addColumns(builder);

		final JdbcMapper<DbFinal1DeepObject> mapper = builder.mapper();

		DbHelper.testQuery(new TestRowHandler<PreparedStatement>() {
			@Override
			public void handle(PreparedStatement t) throws Exception {
				ResultSet rs = t.executeQuery();
				rs.next();

				DbFinal1DeepObject object = mapper.map(rs);
				assertEquals(33, object.getId());
				assertEquals("value", object.getValue());
				DbHelper.assertDbObjectMapping(object.getDbObject());
			}
		}, QUERY);
	}

	@Test
	public void testMapInnerObject2LevelWithStaticMapper() throws Exception {
		final JdbcMapperBuilder<Db2DeepObject> builder = JdbcMapperFactoryHelper.asm().newBuilder(Db2DeepObject.class);

		DbHelper.testQuery(new TestRowHandler<PreparedStatement>() {
			@Override
			public void handle(PreparedStatement t) throws Exception {
				ResultSet rs = t.executeQuery();

				JdbcMapper<Db2DeepObject> mapper = builder.addMapping(rs.getMetaData()).mapper();

				rs.next();

				Db2DeepObject object = mapper.map(rs);
				assertEquals(33, object.getId());
				assertEquals(32, object.getDb1Object().getId());
				assertEquals("value12", object.getDb1Object().getValue());
				DbHelper.assertDbObjectMapping(object.getDb1Object().getDbObject());
			}
		}, "select 33 as id, "
				+ "32 as db1_object_id,  "
				+ "'value12' as db1_object_value,  "
				+ "id as db1_object_db_object_id, "
				+ "name as db1_object_db_object_name, "
				+ "email as db1_object_db_object_email, "
				+ "creation_time as db1_object_db_object_creation_time, "
				+ "type_ordinal as db1_object_db_object_type_ordinal, "
				+ "type_name as db1_object_db_object_type_name "
				+ "from TEST_DB_OBJECT where id = 1 ");
	}

	public void addColumns(JdbcMapperBuilder<?> builder) {
		builder.addMapping("id");
		builder.addMapping("value");
		builder.addMapping("db_object_id");
		builder.addMapping("db_object_name");
		builder.addMapping("db_object_email");
		builder.addMapping("db_object_creation_time");
		builder.addMapping("db_object_type_ordinal");
		builder.addMapping("db_object_type_name");
	}

}


text:
namespace Anycmd.MiniUI
{
    using Util;
    using ViewModel;

    /// <summary>
    ///
    /// </summary>
    public abstract class MiniNode : IViewModel
    {
        private string id = null;
        /// <summary>
        ///
        /// </summary>
        public virtual string Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value.SafeToLower();
            }
        }
        private string parentId = null;
        /// <summary>
        ///
        /// </summary>
        public virtual string ParentId
        {
            get
            {
                return parentId;
            }
            set
            {
                parentId = value.SafeToLower();
            }
        }
        /// <summary>
        ///
        /// </summary>
        public virtual string Name { get; set; }
        /// <summary>
        ///
        /// </summary>
        public virtual bool isLeaf { get; set; }
        /// <summary>
        ///
        /// </summary>
        public virtual bool expanded { get; set; }
    }
}


text:
{% if page.comments != false %}
  {% case site.comments_provider %}
    {% when 'disqus' %}
      {% if site.disqus_username %}
        {% assign load_disqus = true %}

        {% if site.disqus_username == 'gongenbo' %}
          {% assign load_disqus = false %}
          {% if site.url contains 'gongenbo' %}
            {% assign load_disqus = true %}
          {% endif %}
        {% endif %}
        {% if load_disqus %}

          Please enable JavaScript to view the comments powered by Disqus.
        {% endif %}
      {% endif %}
    {% when 'duoshuo' %}
      {% if site.duoshuo_username %}

      {% endif %}
    {% when 'changyan' %}

    {% when 'livere' %}

        为正常使用来必力评论功能请激活JavaScript

  {% endcase %}
{% endif %}


text:
import peventy
import timer
import filesystem

count = [0]
@timer.onTimer(1000)
def timerTest(event):
	print "Test", count[0]
	count[0] += 1

	if ((count[0] % 5) == 4):
		@filesystem.readFile("test.bin")
		def readFileTest(data):
			c = len(data.split('\n'))
			print "Read %d lines from test.bin" % c

	return True

peventy.run()


text:
<?php

/**
 * Processes the "remember me" cookie.
 *
 * @package    symfony
 * @subpackage plugin
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfGuardBasicSecurityFilter.class.php 23319 2009-10-25 12:22:23Z Kris.Wallsmith $
 *
 * @deprecated Use {@link sfGuardRememberMeFilter} instead
 */
class sfGuardBasicSecurityFilter extends sfBasicSecurityFilter
{
  /**
   * Executes the filter chain.
   *
   * @param sfFilterChain $filterChain
   */
  public function execute($filterChain)
  {
    $cookieName = sfConfig::get('app_sf_guard_plugin_remember_cookie_name', 'sfRemember');

    if ($this->isFirstCall())
    {
      // deprecated notice
      $this->context->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array(sprintf('The filter "%s" is deprecated. Use "sfGuardRememberMeFilter" instead.', __CLASS__), 'priority' => sfLogger::NOTICE)));

      if (
        $this->context->getUser()->isAnonymous()
        &&
        $cookie = $this->context->getRequest()->getCookie($cookieName)
      )
      {
        $q = Doctrine::getTable('sfGuardRememberKey')->createQuery('r')
              ->innerJoin('r.sfGuardUser u')
              ->where('r.remember_key = ?', $cookie);

        if ($q->count())
        {
          $this->context->getUser()->signIn($q->fetchOne()->sfGuardUser);
        }
      }
    }

    parent::execute($filterChain);
  }
}


text:
using RelhaxModpack.Database;
using RelhaxModpack.Utilities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RelhaxModpack.Automation.Tasks
{
    /// <summary>
    /// A MacroStringInputMacroTask allows for creation of a macro by using an already existing macro and a custom string retrieval implementation.
    /// </summary>
    /// <remarks>The name of the macro to use (that already exists in the list of macros) is specified rather then passing the macro as an input text value.</remarks>
    public abstract class MacroStringInputMacroTask : MacroStringTask, IXmlSerializable
    {
        /// <summary>
        /// The name of the macro in the list of macros to use as input text.
        /// </summary>
        public string InputMacroName { get; set; }

        /// <summary>
        /// The result of the retrieval of the given macro by name.
        /// </summary>
        /// <seealso cref="InputMacroName"/>
        protected string inputMacroText;

        #region Xml serialization
        /// <summary>
        /// Defines a list of properties in the class to be serialized into xml attributes.
        /// </summary>
        /// <returns>A list of string property names.</returns>
        /// <remarks>Xml attributes will always be written, xml elements are optional.</remarks>
        public override string[] PropertiesForSerializationAttributes()
        {
            return base.PropertiesForSerializationAttributes().Concat(new string[] { nameof(InputMacroName) }).ToArray();
        }
        #endregion

        #region Task execution
        /// <summary>
        /// Process any macros that exist in the task's arguments.
        /// </summary>
        public override void ProcessMacros()
        {
            base.ProcessMacros();
            InputMacroName = ProcessMacro(nameof(InputMacroName), InputMacroName);
        }

        /// <summary>
        /// Validates that all task arguments are correct and the task is initialized correctly to execute. Additionally assigns the result of finding the macro by InputMacroName to inputMacroText.
        /// </summary>
        public override void ValidateCommands()
        {
            base.ValidateCommands();
            if (ValidateCommandStringNullEmptyTrue(nameof(InputMacroName), InputMacroName))
                return;
            AutomationMacro result = Macros.Find(mac => mac.Name.Equals(InputMacroName));
            if (ValidateCommandTrue(result == null, string.Format("The macro \"{0}\" was not found in the macro list", InputMacroName)))
                return;
            inputMacroText = result.Value;
        }

        /// <summary>
        /// Runs the main feature of the task.
        /// </summary>
        public override async Task RunTask()
        {
            await base.RunTask();
            bool gotString = GetStringReturnValue();
            if (!gotString)
            {
                Logging.Error("String return value gave false exit result");
                return;
            }
            Logging.Info("Creating macro, Name: {0}, Value: {1}", MacroName, stringReturnValue);
            Macros.Add(new AutomationMacro() { MacroType = MacroType.Local, Name = MacroName, Value = stringReturnValue });
        }

        /// <summary>
        /// Do not call GetStringValue() for any task deriving from MacroStringInputMacroTask
        /// </summary>
        protected override Task GetStringValue()
        {
            Logging.Error("Do not call GetStringValue() for any task deriving from MacroStringInputMacroTask (did you mean to implement GetStringReturnValue?)");
            throw new NotImplementedException();
        }

        /// <summary>
        /// Runs a task implementation to parse inputMacroText to get a string result saved to stringReturnValue
        /// </summary>
        /// <returns>True if the implementation was successful, false otherwise.</returns>
        protected abstract bool GetStringReturnValue();

        /// <summary>
        /// Validate that the task executed without error and any expected output resources were processed correctly.
        /// </summary>
        public override void ProcessTaskResults()
        {
            base.ProcessTaskResults();
        }
        #endregion
    }
}


text:
/*
ExternalFiles.h
Written by Matthew Fisher

All #includes that are part of C++ core, STL, or other libraries
*/

//
// All libraries
// Media Foundation: Mfreadwrite.lib;Mfplat.lib
// DirectX: DXGI.lib;d3d9.lib;d3dx9.lib
// Windows: winmm.lib;opengl32.lib
// Math: libtaucs.lib;blas_win32.lib;lapack_win32.lib;libatlas.lib;libcblas.lib;libf77blas.lib;liblapack.lib;libmetis.lib;vcf2c.lib
// Images: libpng.lib;zdll.lib;SDL_image.lib;SDL.lib;SDLMain.lib
//

//
// Enables all standard C-runtime functions without warnings
//
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE
#endif
#define _SCL_SECURE_NO_WARNINGS

#define NOMINMAX

// Windows
#include <windows.h>
#include <winuser.h>

#ifdef USE_D3D9
// DirectX 9
#include <d3d9.h>
#include <D3dx9.h>
//#include <dxerr.h>
#endif

#ifdef USE_D3D10
// DirectX 10
#include <d3d10.h>
#include <d3dx10.h>
#endif

#ifdef USE_OPENGL
// OpenGL
#include <gl\gl.h>
#include <gl\glu.h>
#endif

// C/C++
#include <math.h>
#include <memory.h>
#include <time.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <fstream>
#include <limits>

// STL
#include <map>
#include <unordered_map>
#include <queue>
#include <set>
#include <unordered_set>
#include <functional>

// TAUCS (sparse matrix package)
#ifdef USE_TAUCS
extern "C" {
#include "Taucs.h"
};
#endif

#ifdef USE_ZLIB

// ZLib (compression)
#include "libpng\zlib.h"

// PNG saving and loading (requires zlib)
#ifdef USE_PNG
#include "libpng\png.h"
#endif

#endif

#ifdef USE_SDL
#include "SDL\SDL_image.h"
#endif

#ifdef USE_TNT
#include "TNT\jama_eig.h"
#endif

//using namespace std avoids typing std::
using namespace std;
using namespace stdext;


text:
package org.socialsignin.spring.data.dynamodb.domain.sample;

import org.socialsignin.spring.data.dynamodb.repository.DynamoDBPagingAndSortingRepository;
import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.socialsignin.spring.data.dynamodb.repository.EnableScanCount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

@EnableScan
@EnableScanCount
public interface FeedPagingRepository extends DynamoDBPagingAndSortingRepository<Feed, String> {
	Page<Feed> findAllByMessageOrderByRegDateDesc(String message, Pageable pageable);
}


text:
package hu.akarnokd.rxjava2;

import org.junit.Test;

import io.reactivex.Flowable;

public class MaxByTest {

    @Test
    public void test() {
        Flowable.fromArray("a", "bb", "ccc", "d", "eee", "ffff")
        .reduce((last, current) ->
            Integer.compare(last.length(), current.length()) >= 0
            ? last : current)
        .subscribe(System.out::println);
    }
}


text:
Mango is essentially a routing package designed to simplify the development of web service code in Golang. The Router object implements the standard library's http.Handler interface, so it can be used with the http.ListenAndServe method.

Mango uses a context per request approach which enables simplified handlers, as
much of the boiler plate work is done for you. The Context object takes care
of tasks such as serialization/deserialization, respecting the Content-Type
and Accept headers to ensure responses match the request. You can add your own custom content-type encoders if required.

A radix-tree based routing system enables better response times and greater flexibility in the way routes are structured and added to the system.

Hooks and other mechanisms exist to enable customization in accordance with your specific application, such as authentication, database repository injection.

Mango includes many features to speed up your webservice development, including simple CORS setup, a customizable validation system for your routes and models (with several validators built in), plus an easy to use *test browser* to enable  end-to-end simulation testing.

### A *Hello World* example:

```go
package main

import (
  "net/http"

  "github.com/spaceweasel/mango"
)

func main() {
  // get a new router instance
  r := mango.NewRouter()

  // register a GET handler function
  r.Get("/hello", hello)

  // assign the router as the main handler
  http.ListenAndServe(":8080", r)
}

// hello handler function
func hello(c *mango.Context) {
  c.RespondWith("Hello world!")
}
```
### Documentation

* [Home](https://github.com/spaceweasel/mango/wiki)
* [Getting Started](https://github.com/spaceweasel/mango/wiki/getting-started)
* [Routing](https://github.com/spaceweasel/mango/wiki/routing)
  * [Registration Methods](https://github.com/spaceweasel/mango/wiki/registration-methods)
  * [Routing Patterns](https://github.com/spaceweasel/mango/wiki/routing-patterns)
  * [Handler Functions](https://github.com/spaceweasel/mango/wiki/handler-functions)
  * [Organizing Handlers](https://github.com/spaceweasel/mango/wiki/organizing-handlers)
* [The Context Object](https://github.com/spaceweasel/mango/wiki/context-object)
  * [Response Helpers](https://github.com/spaceweasel/mango/wiki/response-helpers)
  * [Identity and Authenticated](https://github.com/spaceweasel/mango/wiki/identity-auth)
  * [Model Binding](https://github.com/spaceweasel/mango/wiki/model-binding)
  * [Model Validation](https://github.com/spaceweasel/mango/wiki/model-validation)
* [Logging](https://github.com/spaceweasel/mango/wiki/logging)
* [CORS](https://github.com/spaceweasel/mango/wiki/cors)
* [PreHooks and PostHooks](https://github.com/spaceweasel/mango/wiki/pre-post-hooks)
* [Handler Wrapping](https://github.com/spaceweasel/mango/wiki/handler-wrapping)
* [Encoders](https://github.com/spaceweasel/mango/wiki/encoders)
* [Validators](https://github.com/spaceweasel/mango/wiki/validators)
* [Testing (Mango Browser)](https://github.com/spaceweasel/mango/wiki/testing)


text:
namespace df
{

extern std::string const kPrettyMoveAnim;
extern std::string const kPrettyFollowAnim;
extern std::string const kParallelFollowAnim;
extern std::string const kParallelLinearAnim;

class SequenceAnimation;
class MapLinearAnimation;
class MapFollowAnimation;
class MapScaleAnimation;

drape_ptr<SequenceAnimation> GetPrettyMoveAnimation(ScreenBase const & startScreen, ScreenBase const & endScreen);
drape_ptr<SequenceAnimation> GetPrettyMoveAnimation(ScreenBase const & screen,
                                                    m2::AnyRectD const & startRect, m2::AnyRectD const & endRect);
drape_ptr<SequenceAnimation> GetPrettyMoveAnimation(ScreenBase const & screen, double startScale, double endScale,
                                                    m2::PointD const & startPt, m2::PointD const & endPt);

drape_ptr<SequenceAnimation> GetPrettyFollowAnimation(ScreenBase const & startScreen, m2::PointD const & userPos,
                                                      double targetScale, double targetAngle, m2::PointD const & endPixelPos);

drape_ptr<MapLinearAnimation> GetRectAnimation(ScreenBase const & startScreen, ScreenBase const & endScreen);
drape_ptr<MapLinearAnimation> GetSetRectAnimation(ScreenBase const & screen,
                                                  m2::AnyRectD const & startRect, m2::AnyRectD const & endRect);

drape_ptr<MapFollowAnimation> GetFollowAnimation(ScreenBase const & startScreen, m2::PointD const & userPos,
                                                 double targetScale, double targetAngle, m2::PointD const & endPixelPos, bool isAutoZoom);

drape_ptr<MapScaleAnimation> GetScaleAnimation(ScreenBase const & startScreen, m2::PointD pxScaleCenter,
                                               m2::PointD glbScaleCenter, double factor);

} // namespace df