text:
#include <model/Bonus.h>
#include <guslib/trace/trace.h>
#include <guslib/system/random.h>
using namespace GUtils;

namespace Serpents
{
#if 0
	BonusReward::BonusReward(BonusRewardType brt, std::string sId, double aValue)
		: type( brt )
		, id( sId )
		, value( aValue )
	{
	}

	BonusReward::~BonusReward()
	{
	}

	//
	//	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BonusRoot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//

	BonusRoot::BonusRoot()
	{
	}

	BonusRoot::~BonusRoot()
	{
		rewards.clear();
	}

	void BonusRoot::addReward( BonusReward &reward )
	{
		rewards.push_back(reward);
	}

	BonusRewardList BonusRoot::getRewardsCopy() const
	{
		return rewards;
	}

	void BonusRoot::setRewards(BonusRewardList r)
	{
		rewards.clear();
		rewards = r;
	}

	//
	//	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BonusPrototypeBase ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//

	BonusPrototypeBase::BonusPrototypeBase(std::string nameToUse)
		: BonusRoot()
		, internalName( nameToUse )
		, generationOddWeight( 1 )
	{
	}

	BonusPrototypeBase::~BonusPrototypeBase()
	{
	}

	//
	//	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BonusBase ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//

	BonusBase::BonusBase( const BonusPrototypeBase * prototype, long initialTimeToLive )
		: timeToLive( initialTimeToLive )
		, picked( false )
	{
		BonusPrototypeBase * tempBonus = (BonusPrototypeBase*) prototype;
		linkToPrototype = tempBonus;
		setShape(MapObject::ObjectShapeCircular);
		if( tempBonus )
		{
			//	copy the values of the prototype
			setRewards( tempBonus->getRewardsCopy() );
		}
	}

	BonusBase::~BonusBase(void)
	{
	}

	//
	//	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BonusManagerBase ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//

	BonusManagerBase::BonusManagerBase()
		: maximumAllowedBonuses( 15 )
		, defaultTimeToLive( 30000 )
		, maxValueForRandom( 0 ) // the randomizer
		, minimumBonusesToKeepOnScreen( 2 )
		, maxValueForSpawnRandom( 100 )
		, genValueForSpawnRandom( 1 )
	{
		defaultSize.x = defaultSize.y = 15;
	}

	BonusManagerBase::~BonusManagerBase()
	{
		GTRACE(5, "BonusManagerBase destructor entered");
		for( PrototypeBaseList::iterator it = prototypes.begin(); it!=prototypes.end(); ++it )
		{
			delete (*it);
		}
		prototypes.clear();
		GTRACE(5, "cleared proros, clearing bonuses");
		for( BonusBaseList::iterator it = bonuses.begin(); it!=bonuses.end(); ++it )
		{
			delete (*it);
		}
		bonuses.clear();
		GTRACE(5, "BonusManagerBase destructor exiting");
	}

	bool BonusManagerBase::addBonusPrototype( BonusPrototypeBase * prototype )
	{
		if( !prototype )
			return false;
		bool nameAlreadyInUse = false;
		for( PrototypeBaseList::iterator it = prototypes.begin(); it!=prototypes.end(); ++it)
		{
			if( (*it)->getInternalName() == prototype->getInternalName() )
			{
				nameAlreadyInUse = true;
			}
		}
		if( nameAlreadyInUse )
		{
			GTRACE(1, "SEVERE: addBonusPrototype with non-unique name (in use): " << prototype->getInternalName() );
			return false;
		}
		GTRACE(4, "Prototype added with name : " <<prototype->getInternalName());
		prototypes.push_back( prototype );
		maxValueForRandom += prototype->getGenerationOddsWeight();
		return true;
	}

	BonusBase * BonusManagerBase::createBonusFromPrototype( const std::string & prototypeName )
	{
		return createBonusFromPrototype( getPrototypeForName( prototypeName ) );
	}

	BonusBase* BonusManagerBase::getItemAt( int index )
	{
		if( (int)bonuses.size() <= index )
			return NULL;
		return bonuses[ index ];
	}

	int BonusManagerBase::getNumberOfItems() const
	{
		return (int)bonuses.size();
	}

	BonusPrototypeBase * BonusManagerBase::getRandomBonusType()
	{
		GTRACE(5, "BonusManagerBase::getRandomBonusType()");
		int i=0;
		maxValueForRandom = 0;
		for( PrototypeBaseList::iterator it = prototypes.begin(); it!=prototypes.end(); ++it )
		{
			maxValueForRandom += (*it)->getGenerationOddsWeight();
		}
		int x = guslib::Random::getPtr()->getValueUpTo(maxValueForRandom);

		for( i=0; i<(int)prototypes.size() && x>=0; i++ )
		{
			x -= prototypes[i]->getGenerationOddsWeight();
		}
		GTRACE(4, "Randomed to bonus type " << (i-1));
		return prototypes[i-1];
	}

	BonusPrototypeBase * BonusManagerBase::getPrototypeForName( const std::string & name )
	{
		for( PrototypeBaseList::iterator it = prototypes.begin(); it!= prototypes.end(); ++it )
		{
			if( (*it)->getInternalName() == name )
			{
				return (*it);
			}
		}
		return NULL;
	}

	void BonusManagerBase::onTimeGoesBy( double timeUnits )
	{
		GUS_LOCK_MUTEX ( listAccessMutex );
		if( bonuses.empty() )
			return;
		GTRACE(5, "BonusManagerBase::onTimeGoesBy:"<<timeUnits<<", numbonuses="<< bonuses.size() );
		for( BonusBaseList::iterator it = bonuses.begin(); it!=bonuses.end(); ++it )
		{
			if( ! *it )
				continue;
			(*it)->setTimeToLive( (*it)->getTimeToLive() - (long) timeUnits );
			if( (*it)->getTimeToLive() < 0 )
			{
				if( (*it)->getLinkToPrototype() )
				{
					GTRACE(3, "A bonus is being removed :"<< (*it)->getLinkToPrototype()->getInternalName());
				}
				delete (*it);
				bonuses.erase(it);
				if( bonuses.size() == 0 )
				{
					GTRACE(4, "eraseop caused empty vect. exiting func.");
					return;
				}
			}
		}
	}

	void BonusManagerBase::pickBonusAt( int indexInBonusList )
	{
		GTRACE(3, "Picking bonus at index " <<indexInBonusList);
		getItemAt(indexInBonusList)->setPicked();
		getItemAt(indexInBonusList)->setTimeToLive( -1 );
	}

	void BonusManagerBase::pickBonus( BonusBaseList::iterator &it )
	{
		delete (*it);
		bonuses.erase(it);
	}

	bool BonusManagerBase::removeAllBonusPrototypes()
	{
		GUS_LOCK_MUTEX( listAccessMutex );
		bool ret = true;
		for( PrototypeBaseList::iterator it = prototypes.begin(); it!=prototypes.end(); ++it )
		{
			bool canRemove = true;

			//	prototypes in use cannot be removed.
			for( BonusBaseList::iterator it2 = bonuses.begin(); it2!=bonuses.end(); ++it2 )
			{
				if( (*it2)->getLinkToPrototype() == (*it) )
				{
					GTRACE(1, "ERROR! Unable to remove prototype ["<<(*it)->getInternalName()<<"] because it is used by a bonus");
					canRemove = false;
				}
			}
			if( canRemove )
			{
				maxValueForRandom -= (*it)->getGenerationOddsWeight();
				GTRACE(5, "Removing prototype " <<(*it)->getInternalName());
				prototypes.erase( it );
				GTRACE(5, "Removed prototype.");
			}
			else
			{
				ret = false;
			}
		}
		return ret;
	}

	bool BonusManagerBase::removeBonusPrototype( BonusPrototypeBase * prototype )
	{
		if( prototype == NULL )
			return false;

		//	if the current prototype is used by any bonuses, removal is not allowed!
		for( BonusBaseList::iterator it = bonuses.begin(); it!=bonuses.end(); ++it )
		{
			if( (*it)->getLinkToPrototype() == prototype )
			{
				GTRACE(1, "ERROR! Unable to remove prototype [" << prototype->getInternalName() << "] because it is used by a bonus");
				return false;
			}
		}
		maxValueForRandom -= prototype->getGenerationOddsWeight();
		for( PrototypeBaseList::iterator pit = prototypes.begin(); pit!=prototypes.end(); ++pit )
		{
			if( (*pit) == prototype )
			{
				delete (*pit);
				prototypes.erase(pit);
			}
		}
		GTRACE(5, "removing bonus prototype...")
		return true;
	}

	bool BonusManagerBase::spawnNewBonus( DPOINT point, const BonusPrototypeBase * prototype )
	{
		if( prototype == NULL )
		{
			GTRACE(1, "ERROR: NULL prototype specified on new bonus spawn");
			return false;
		}

		GTRACE(3, "Spawning new bonus, type=[" << prototype->getInternalName() << "]");
		BonusBase * myBonus = createBonusFromPrototype(prototype);
		if( myBonus == NULL )
			return false;

		myBonus->setTimeToLive( defaultTimeToLive );
		myBonus->setPivot( MapObject::CenterPivot );
		myBonus->setSize( defaultSize );
		myBonus->setLocation( point );
		myBonus->setRewards( prototype->getRewardsCopy() );
		bonuses.push_back( myBonus );

		return true;
	}

#endif
} // namespace Serpents


text:
/*
 * http://sequelizejs.com/docs/latest/models
 */

var Sequelize = require('sequelize')
  ,	assert = require('assert')
  ,	_ = require('underscore')
  ,	json = require('format-json')
  ,	colors = require('colors');

module.exports = function(sequelize){

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-find
	 */
	it('#101: Data retrieval / Finders.\
		find - Search for one specific element in the database.', function(cb){
		var Project = sequelize
							.define('Project101', {
								title: Sequelize.STRING,
								name: Sequelize.STRING
							});
		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([
					{ title: 'Project 1 title', name: 'Project 1' },
					{ title: 'Project 2 title', name: 'Project 2' },
					{ title: 'Project 3 title', name: 'Project 3' }]);
			})
			.then(function(){
				// search for known ids
				return Project.find(2);
			})
			.then(function(project){
				// project will be an instance of Project and stores the content of the table entry
				// with id 2. if such an entry is not defined you will get null
				assert.equal(project.id, 2);
				// search for attributes
				return Project.find({ where: {title: 'Project 2 title'} });
			})
			.then(function(project){
				// project will be the first entry of the Projects table with the title 'aProject' || null
				assert.equal(project.id, 2);
				// since v1.3.0: only select some attributes and rename one
				return Project
							.find({
								where: { title: 'Project 2 title' },
								attributes: ['id', ['name', 'title']]
							});
			})
			.then(function(project){
				// project will be the first entry of the Projects table with the title 'aProject' || null
				// project.title will contain the name of the project
				assert.equal(project.id, 2);
				assert.equal(project.title, 'Project 2');
				cb();
			})
			.catch(function(err){
				console.log('#101:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-findorcreate
	 */
	it('#102: Data retrieval / Finders.\
		findOrCreate - Search for a specific element or create it if not available', function(cb){
		var User = sequelize
						.define('User102', {
							username: Sequelize.STRING,
							job: Sequelize.STRING
						});

		User.sync({ force: true })
			.then(function(){
				return User.findOrCreate({ where: {username: 'sdepold', job: 'Technical Lead JavaScript'} });
			})
			.spread(function(user, created){
				assert.equal(user.username, 'sdepold');
				assert(created);
				return User.findOrCreate({ where: {username: 'sdepold', job: 'Technical Lead JavaScript'} });
			})
			.spread(function(user, created){
				// So when we already have an instance
				assert.equal(user.username, 'sdepold');
				assert(!created);
				cb();
			})
			.catch(function(err){
				console.log('#102:'.bold, err.message.bold);
				assert(false);
				cb();
			});

	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-findandcountall
	 */
	it('#103: Data retrieval / Finders.\
		findAndCountAll - Search for multiple elements in the database, returns both data and total count', function(cb){
		var Project = sequelize
							.define('Project103', {
								title: Sequelize.STRING
							});

		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([
					{ title: 'foo1' },
					{ title: 'foo2' },
					{ title: 'foo3' }]);
			})
			.then(function(){
				return Project
							.findAndCountAll({
								where: ["title LIKE 'foo%'"],
								//~ where: { title: 'foo2' },
								offset: 1,
								limit: 2
							});
			})
			.then(function(result){
				// an integer, total number of records (matching the where clause)
				assert.equal(result.count, 3);
				// an array of objects, the records (matching the where clause) within the limit/offset range
				assert.equal(result.rows.length, 2);
				assert.equal(result.rows[0].title, 'foo2');
				assert.equal(result.rows[1].title, 'foo3');
				cb();
			})
			.catch(function(err){
				console.log('#103:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-findall
	 */
	it('#104: Data retrieval / Finders.\
		findAll - Search for multiple elements in the database', function(cb){
		var Project = sequelize
							.define('Project104', {
								name: Sequelize.STRING
							});

		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([
					{ name: 'Project 1' },
					{ name: 'Project 2' },
					{ name: 'Project 3' }]);
			})
			.then(function(){
				// find multiple entries
				return Project.findAll();
			})
			.then(function(projects){
				// projects will be an array of all Project instances
				assert.equal(projects.length, 3);
				// also possible:
				return Project.all();
			})
			.then(function(projects){
				// projects will be an array of all Project instances
				assert.equal(projects.length, 3);
				// search for specific attributes - hash usage
				return Project.findAll({ where: {name: 'Project 2'} });
			})
			.then(function(projects){
				// projects will be an array of Project instances with the specified name
				assert.equal(projects.length, 1);
				assert.equal(projects[0].name, 'Project 2');
				// search with string replacements
				return Project.findAll({ where: ["id > ?", 2] });
			})
			.then(function(projects){
				// projects will be an array of Projects having a greater id than 2
				assert.equal(projects.length, 1);
				assert.equal(projects[0].id, 3);
				// search within a specific range
				return Project.findAll({ where: { id: [1,3] } });
			})
			.then(function(projects){
				// projects will be an array of Projects having the id 1, 3
				// this is actually doing an IN query
				assert.equal(projects.length, 2);
				assert(_.findWhere(projects, { id: 1 }));
				assert(_.findWhere(projects, { id: 3 }));
				// or
				return Project.findAll({ where: "name = 'Project 2'" });
			})
			.then(function(projects){
				// the difference between this and the usage of hashes (objects) is, that string usage
				// is not sql injection safe. so make sure you know what you are doing!
				assert.equal(projects.length, 1);
				assert.equal(projects[0].name, 'Project 2');
				// since v1.7.0 we can now improve our where searches
				return Project.findAll({ where: {id: {gt: 2}} }); // id > 2
			})
			.then(function(projects){
				// projects will be an array of Projects having a greater id than 2
				assert.equal(projects.length, 1);
				assert.equal(projects[0].id, 3);
				cb();
			})
			.catch(function(err){
				console.log('#104:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-complex-where-queries
	 */
	it('#105: Data retrieval / Finders.\
		Complex filtering / OR queries', function(cb){
		var Project = sequelize
							.define('Project105', {
								name: Sequelize.STRING
							});

		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([
					{ name: 'Project 1' },
					{ name: 'Project 1' },
					{ name: 'Project 3' },
					{ name: 'Project 4' },
					{ name: 'Project 5' }]);
			})
			.then(function(){
				// Since v1.7.0-rc3, it is possible to do complex where queries with multiple levels of nested AND and OR conditions.
				// Notice, that instead of Sequelize.and you can also use a plain array which will be treated as Sequelize.and
				// if it contains objects or hashes or other complex data types.
				return Project
							.find({
								where: Sequelize.and(
									{ name: 'Project 1' },
									Sequelize.or(
										{ id: 5 },
										{ id: { lt: 3 }}
									)
								)
							});
			})
			.then(function(project){
				assert.equal(project.id, 1);
				cb();
			})
			.catch(function(err){
				console.log('#105:'.bold, err.message.bold);
				assert(false);
				cb();
			});

	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-limit---offset---order---group
	 */
	it('#106: Data retrieval / Finders.\
		Manipulating the dataset with limit, offset, order and group', function(cb){
		var Project = sequelize
							.define('Project106', {
								name: Sequelize.STRING,
								age: Sequelize.INTEGER
							});

		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([
					{ name: 'Project 1', age: 10 },
					{ name: 'Project 1', age: 20 },
					{ name: 'Project 3', age: 30 },
					{ name: 'Project 4', age: 40 },
					{ name: 'Project 5', age: 50 }]);
			})
			.then(function(){
				// limit the results of the query
				return Project.findAll({ limit: 3 });
			})
			.then(function(projects){
				assert.equal(projects.length, 3);
				// step over the first 2 elements
				return Project.findAll({ offset: 2 });
			})
			.then(function(projects){
				assert.equal(projects.length, 3);
				// step over the first 2 elements, and take 2
				return Project.findAll({ offset: 2, limit: 2 });
			})
			.then(function(projects){
				assert.equal(projects.length, 2);
				assert(_.findWhere(projects, { id: 3 }));
				assert(_.findWhere(projects, { id: 4 }));
				// yields ORDER BY id DESC
				return Project.findAll({ order: 'id DESC' });
			})
			.then(function(projects){
				assert.equal(projects[0].id, 5);
				assert.equal(projects[1].id, 4);
				assert.equal(projects[2].id, 3);
				assert.equal(projects[3].id, 2);
				assert.equal(projects[4].id, 1);
				// yields GROUP BY name
				// TODO: example for array notation of `group` and `order`
				return Project.findAll({ group: 'name' });
			})
			.then(function(projects){
				assert(_.filter(projects, function(elem){ return elem.id == 1 }).length, 1);
				cb();
			})
			.catch(function(err){
				console.log('#106:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-count
	 */
	it('#107: Data retrieval / Finders.\
		count - Count the occurences of elements in the database', function(cb){
		var Project = sequelize
							.define('Project107', {});

		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([{}, {}, {}, {}, {}]);
			})
			.then(function(){
				// There is also a method for counting database objects
				return Project.count({ where: ['id > ?', 3] });
			})
			.then(function(c){
				assert.equal(c, 2);
				cb();
			})
			.catch(function(err){
				console.log('#107:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finders-max
	 */
	it('#108: Data retrieval / Finders.\
		max - Get the greatest value of a specific attribute within a specific table', function(cb){
		var Project = sequelize
							.define('Project108', { age: Sequelize.INTEGER });

		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([{ age: 10 }, { age: 20 }, { age: 30 }, { age: 40 }, { age: 50 }]);
			})
			.then(function(){
				// There is also a method for counting database objects
				return Project.max('age', { where: { age: { lt: 20 }}});
			})
			.then(function(max){
				assert.equal(max, 10);
				cb();
			})
			.catch(function(err){
				console.log('#108:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#finder-sum
	 */
	it('#109: Data retrieval / Finders.\
		sum - Sum the value of specific attributes', function(cb){
		var Project = sequelize
							.define('Project109', { age: Sequelize.INTEGER });

		Project
			.sync({ force: true })
			.then(function(){
				return Project.bulkCreate([{ age: 10 }, { age: 20 }, { age: 30 }, { age: 40 }, { age: 50 }]);
			})
			.then(function(){
				// There is also a method for counting database objects
				return Project.sum('age', { where: { age: { lt: 30 }}});
			})
			.then(function(sum){
				assert.equal(sum, 30);
				cb();
			})
			.catch(function(err){
				console.log('#109:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#eager-loading
	 */
	it('#110: Data retrieval / Finders.\
		Eager loading', function(cb){
		var User = sequelize.define('User110', { name: Sequelize.STRING })
		var Task = sequelize.define('Task110', { name: Sequelize.STRING })
		var Tool = sequelize.define('Tool110', { name: Sequelize.STRING });

		Task.belongsTo(User);
		User.hasMany(Task);
		User.hasMany(Tool, { as: 'Instruments' });

		User.sync()
			.then(function(){
				return [Tool.sync(), Task.sync()];
			})
			.spread(function(){
				return [User.destroy(), Task.destroy(), Tool.destroy()];
			})
			.spread(function(){
				return [
					Task.create({ name: 'Task1' })
				  ,	Task.create({ name: 'Task2' })
				  ,	Task.create({ name: 'Task3' })
				  ,	Task.create({ name: 'Task4' })
				  ,	User.create({ name: 'User1' })
				  ,	User.create({ name: 'User2' })
				  ,	User.create({ name: 'User3' })
				  ,	Tool.create({ name: 'Tool1' })
				  ,	Tool.create({ name: 'Tool2' })
				  ,	Tool.create({ name: 'Tool3' })
				];
			})
			.spread(function(	task1, task2, task3, task4,
								user1, user2, user3,
								tool1, tool2, tool3){
				return 	[
							user1.setTask110s([task1, task4])
						  ,	user2.setTask110s([task2])
						  ,	user3.setTask110s([task3])
						  ,	user1.setInstruments([tool1])
						  ,	user2.setInstruments([tool2])
						  ,	user3.setInstruments([tool3])
						];
			})
			.spread(function(){
				// OK. So, first of all, let's load all tasks with their associated user
				return Task.findAll({ include: [ User ] });
			})
			.then(function(tasks){
				assert(_.findWhere(tasks, function(elem){
					return elem.name == 'Task1' && elem.User110.name == 'User1';
				}));
				assert(_.findWhere(tasks, function(elem){
					return elem.name == 'Task2' && elem.User110.name == 'User2';
				}));
				assert(_.findWhere(tasks, function(elem){
					return elem.name == 'Task3' && elem.User110.name == 'User3';
				}));
				// Next thing: Loading of data with many-to-something associations!
				return User.findAll({ include: [ Task ] });
			})
			.then(function(users){
				assert(_.findWhere(users, function(elem){
					return 	elem.name == 'User1' &&
							_.every(elem.Task110s, function(_elem){
								return 	_elem.name == 'Task1' ||
										_elem.name == 'Task4';
							});
				}));
				assert(_.findWhere(users, function(elem){
					return elem.name == 'User2' && elem.Task110s.name == 'Task2';
				}));
				assert(_.findWhere(users, function(elem){
					return elem.name == 'User3' && elem.Task110s.name == 'Task3';
				}));
				// If an association is aliased (using theasoption), you must specify this alias when including the model
				return User.findAll({ include: [{ model: Tool, as: 'Instruments' }] });
			})
			.then(function(users){
				assert(_.findWhere(users, function(elem){
					return elem.name == 'Tool1' && elem.User110.name == 'User1';
				}));
				assert(_.findWhere(users, function(elem){
					return elem.name == 'Tool2' && elem.User110.name == 'User2';
				}));
				assert(_.findWhere(users, function(elem){
					return elem.name == 'Tool3' && elem.User110.name == 'User3';
				}));
				cb();
			})
			.catch(function(err){
				console.log('#110:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});

	/*
	 * http://sequelizejs.com/docs/latest/models#ordered-eager-loading
	 */
	it('#111: Data retrieval / Finders.\
		Ordering Eager Loaded Associations,\
		nested eager loading', function(cb){

		// TODO: example for the case of many-to-many joins

		// The case of a one-to-many relationship

		var Company = sequelize.define('Company111', { name: Sequelize.STRING });
		var Division = sequelize.define('Division111', { name: Sequelize.STRING });
		var Department = sequelize.define('Department111', { name: Sequelize.STRING });

		Company.hasMany(Division);
		Division.hasMany(Department);
		Division.belongsTo(Company);
		Department.belongsTo(Division);

		sequelize.sync()
			//~ .then(function(){
				//~ return [Division.sync(), Department.sync()];
			//~ })
			.spread(function(){
				return [Company.destroy(), Department.destroy(), Division.destroy()];
			})
			.spread(function(){
				return [
					Company.create({ name: 'Company1' })
				  ,	Company.create({ name: 'Company2' })
				  ,	Division.create({ name: 'Division1' })
				  ,	Division.create({ name: 'Division2' })
				  ,	Division.create({ name: 'Division3' })
				  ,	Division.create({ name: 'Division4' })
				  ,	Department.create({ name: 'Department1' })
				  ,	Department.create({ name: 'Department2' })
				  ,	Department.create({ name: 'Department3' })
				  ,	Department.create({ name: 'Department4' })
				  ,	Department.create({ name: 'Department5' })
				  ,	Department.create({ name: 'Department6' })
				  ,	Department.create({ name: 'Department7' })
				  ,	Department.create({ name: 'Department8' })
				];
			})
			.spread(function(	company1, company2,
								division1, division2, division3, division4,
								department1, department2, department3, department4,
								department5, department6, department7, department8){
				return [
					company1.setDivision111s([division1, division2])
				  ,	company2.setDivision111s([division3, division4])
				  ,	division1.setDepartment111s([department1, department2])
				  ,	division2.setDepartment111s([department3, department4])
				  ,	division3.setDepartment111s([department5, department6])
				  ,	division4.setDepartment111s([department7, department8])
				];
			})
			.spread(function(){
				return Company.findAll({
					include: [ Division ],
					order: [
						[ 'name' ]
					  , [ Division, 'name', 'DESC' ]
					]
				});
			})
			.then(function(companies){
				// companiesMap will contain all fields except auxiliary ones
				var companiesMap = _.map(companies, function(elem){
					return {
						name: elem.name,
						Division111s: _.map(elem.Division111s, function(_elem){
							return { name: _elem.name };
						})
					};
				});
				// Company names are ordered by ASC, but Division names by DESC
				assert.deepEqual(companiesMap, [
					{ name: 'Company1', Division111s: [{ name: 'Division2' }, { name: 'Division1' }]},
					{ name: 'Company2', Division111s: [{ name: 'Division4' }, { name: 'Division3' }]}
				]);
				// Nested eager loading
				return Company.findAll({
					attributes: [ 'name' ],
					// Use `order` for nested associations in this form.
					// See https://github.com/sequelize/sequelize/pull/1299
					order: [ 'name', [ Division, Department, 'name' ] ],
					include: [
						{
							model: Division,
							attributes: [ 'name' ],
							// Do not use it. See https://github.com/sequelize/sequelize/pull/1299
							//order: [[ 'name' ]],
							include: [
								{
									model: Department,
									// Do not use it. See https://github.com/sequelize/sequelize/pull/1299
									//order: [[ 'name' ]],
									attributes: [ 'name' ]
								}
							]
						}
					]
				});
			})
			.then(function(companies){
				// companiesMap will contain all fields except auxiliary ones
				var companiesMap = _.map(companies, function(elem){
					return {
						name: elem.name,
						Division111s: _.map(elem.Division111s, function(_elem){
							return {
								name: _elem.name,
								Department111s: _.map(_elem.Department111s, function(__elem){
									return { name: __elem.name };
								})
							};
						})
					};
				});
				assert.deepEqual(companiesMap, [
					{
						name: 'Company1',
						Division111s: [
							{
								name: 'Division1',
								Department111s: [
									{ name: 'Department1' }
								  ,	{ name: 'Department2' }
								]
							}
						  ,	{
								name: 'Division2',
								Department111s: [
									{ name: 'Department3' }
								  ,	{ name: 'Department4' }
								]
							}
						]
					},
					{
						name: 'Company2',
						Division111s: [
							{
								name: 'Division3',
								Department111s: [
									{ name: 'Department5' }
								  ,	{ name: 'Department6' }
								]
							}
						  ,	{
								name: 'Division4',
								Department111s: [
									{ name: 'Department7' }
								  ,	{ name: 'Department8' }
								]
							}
						]
					}
				], json.plain(companiesMap));
				cb();
			})
			.catch(function(err){
				console.log('#111:'.bold, err.message.bold);
				assert(false);
				cb();
			});
	});
}

redpajama_set_name: RedPajamaGithub


text:
layout: single
title: "De nuevo en Estambul"
redirect_from: /node/133
categories:
tags: []
comments:
---
Bueno, ya sabeis mas o menos lo que ha pasado estos dias. Para que sepais cuales son los planes actuales y futuros:

- Seguimos durmiendo en la casa de Ali (el panadero) Esta noche tenemos visita al Hamman y cena de despedida. Manyana queremos dormir en hostal para poder salir de fiestecilla sin compromiso y despedirnos como dios manda de Estambul. Tambien para dormir juntos, no hay que enganyar a nadie.

- Como esto es un poco caro, hemos cambiado la fecha de los billetes hacia Tailandia. El viernes por la noche salimos hacia Bangkok. Llegaremos a la manyana siguiente. Cuando hayamos superado el Jet Lag, ya os contare como es aquello.

![](/images/posts/2005-07-27-de-nuevo-en-estambul/PIC_0079.jpg)
![](/images/posts/2005-07-27-de-nuevo-en-estambul/PIC_0085.jpg)
![](/images/posts/2005-07-27-de-nuevo-en-estambul/PIC_0006.jpg)


text:
<?php

namespace kalibao\backend\modules\tree\models\branchType\crud;

use Yii;
use yii\data\ActiveDataProvider;
use kalibao\common\components\crud\ModelFilterInterface;
use kalibao\common\models\branchType\BranchType;

/**
 * This is the model filter class for controller "BranchType".
 *
 * @property integer $id
 * @property string $url
 * @property string $branch_type_i18n_label
 * @property string $created_at_start
 * @property string $created_at_end
 * @property string $updated_at_start
 * @property string $updated_at_end
 *
 * @package kalibao\backend\modules\tree\models\branchType\crud
 * @version 1.0
 */
class ModelFilter extends BranchType implements ModelFilterInterface
{
    public $branch_type_i18n_label;
    public $created_at_start;
    public $created_at_end;
    public $updated_at_start;
    public $updated_at_end;

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_DEFAULT => [
                'id', 'url', 'branch_type_i18n_label', 'created_at_start', 'created_at_end', 'updated_at_start', 'updated_at_end'
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['created_at_start', 'created_at_end', 'updated_at_start', 'updated_at_end'], 'date', 'format' => 'yyyy-MM-dd'],
            [['url'], 'string', 'max' => 200],
            [['branch_type_i18n_label'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'branch_type_i18n_label' => Yii::t('kalibao.backend','branch_type_i18n_label'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function search($requestParams, $language = null, $pageSize = 10)
    {
        $query = self::find();
        $query->joinWith([
            'branchTypeI18ns' => function ($query) use ($language) {
                $query->select(['branch_type_id', 'label'])->onCondition(['branch_type_i18n.i18n_id' => $language]);
            },
        ]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'attributes' => [
                    'id',
                    'url',
                    'branch_type_i18n_label' => [
                        'asc' => ['branch_type_i18n.label' => SORT_ASC],
                        'desc' => ['branch_type_i18n.label' => SORT_DESC],
                        'default' => SORT_DESC,
                        'label' => $this->getAttributeLabel('branch_type_i18n_label')
                    ],
                    'created_at',
                    'updated_at',
                ],
                'defaultOrder' => [
                    'id' => SORT_DESC
                ]
            ],
            'pagination' => [
                'defaultPageSize' => $pageSize,
                'pageSize' => $pageSize,
            ]
        ]);

        $this->load($requestParams);

        if (! $this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere(['>=', 'branch_type.created_at', $this->created_at_start]);
        if ($this->created_at_end != '') {
            $query->andWhere([
                '<=',
                'branch_type.created_at',
                (new \DateTime($this->created_at_end))->modify('+1 day')->format('Y-m-d')
            ]);
        }
        $query->andFilterWhere(['>=', 'branch_type.updated_at', $this->updated_at_start]);
        if ($this->updated_at_end != '') {
            $query->andWhere([
                '<=',
                'branch_type.updated_at',
                (new \DateTime($this->updated_at_end))->modify('+1 day')->format('Y-m-d')
            ]);
        }

        $query
            ->andFilterWhere(['branch_type.id' => $this->id])
            ->andFilterWhere(['like', 'branch_type.url', $this->url])
            ->andFilterWhere(['like', 'branch_type_i18n.label', $this->branch_type_i18n_label]);

        return $dataProvider;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

 <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/bootstrap/3.3.0/css/bootstrap.min.css">

<meta charset="UTF8">
<meta http-equiv="refresh" content="15">

    <title>Twitter Map</title>

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Ebola Tweet Mapping

Home

About

People saying (for the most part) really dumb stuff about Ebola

Recent geolocated tweets referencing "Ebola" from around the world.

{% block body %}{% endblock %}


text:
<?php
/**
 * Bundled Item Short Description template
 *
 * Override this template by copying it to 'yourtheme/woocommerce/single-product/bundled-item-description.php'.
 *
 * On occasion, this template file may need to be updated and you (the theme developer) will need to copy the new files to your theme to maintain compatibility.
 * We try to do this as little as possible, but it does happen.
 * When this occurs the version of the template file will be bumped and the readme will list any important changes.
 *
 * @version 4.2.0
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( $description === '' ){
	return;
}

?>
<?php
		echo $description;
?>


text:
const values = {};

export const setValue = (key, value) => {
  values[key] = value;
};

export const getValue = (key) => {
  if (process.env.NODE_ENV !== 'production') {
    if (!(key in values)) {
      throw new ReferenceError(`[Injector] Injectable "${key}" has never been configured`);
    }
  }

  return values[key];
};


text:
require([
    'jquery', 'underscore', 'orotranslation/js/translator', 'oroui/js/modal', 'oroui/js/mediator', 'routing'
], function($, _, __, Modal, mediator, routing) {
    'use strict';

    $(function() {
        $(document).on('click', '.entity-extend-apply', function(e) {
            var el = $(this);
            var title = __('Schema update confirmation');
            var content = '
' + __('Your config changes will be applied to schema.') + '
' +
                    '
' + __('It may take few minutes...') + '
';
            /** @type oro.Modal */
            var confirmUpdate = new Modal({
                allowCancel: true,
                className: 'modal modal-primary',
                cancelText: __('Cancel'),
                okText: __('Yes, Proceed'),
                title: title,
                content: content
            });

            function execute() {
                var url = $(el).data('url');
                var progress = $('#progressbar').clone();
                progress.removeAttr('id').find('h3').remove();

                var modal = new Modal({
                    allowCancel: false,
                    className: 'modal modal-primary',
                    title: title,
                    content: content
                });
                modal.open();
                modal.$el.find('.modal-footer').html(progress);
                progress.show();

                $.post(url, function() {
                    modal.close();
                    mediator.execute(
                        'showFlashMessage',
                        'success',
                        __('oro.entity_extend.schema_updated'),
                        {afterReload: true}
                    );
                    mediator.execute('showMessage', 'info', __('Please wait until page will be reloaded...'));
                    mediator.execute('showLoading');
                    // force reload of the application to make sure 'js/routes' is reloaded
                    window.location.href = routing.generate('oro_entityconfig_index');
                }).fail(function() {
                    modal.close();
                    mediator.execute('showFlashMessage', 'error', __('oro.entity_extend.schema_update_failed'));
                });
            }

            confirmUpdate.on('ok', execute);
            confirmUpdate.open();

            return false;
        });
    });
});