<commit_before>/**
 * Created by JCloudYu on 11/11/15.
 * Dependency: jQuery, PromiseJS
 */
(function( Promise ) {
	"use strict";

	if ( !Promise )
		throw "This extension is dependent on PromiseJS! Please refer to https://www.promisejs.org.";

	// region [ constants ]
	var RUN_STATE = {
		BOOT: 0,
		RUN: 1,
		WAIT: 2
	};
	// endregion

	var
	instMap		= {},
	instances	= {},
	execState	= RUN_STATE.BOOT;

	/*
	dangling	= {
		pause: function( target ) {

				if ( !target )
				{
					oops.util.each( instances, function( inst ){
						if ( !inst.pause ) return;
						inst.pause();
					});

					execState = RUN_STATE.WAIT;
					$( oops.app ).trigger( "paused" );
				}
				else
				{
					var inst = instMap[ target ] || instances[ target ] || null;
					if ( !inst || !oops.typing.isCallable(inst.pause) ) return;

					inst.pause();
				}
			},
			resume: function( target ) {

				if ( !target )
				{
					oops.util.each( instances, function( inst ){
						if ( !inst.resume ) return;
						inst.resume();
					});

					execState = RUN_STATE.RUN;
					$( oops.app ).trigger( "resumed" );
				}
				else
				{
					var inst = instMap[ target ] || instances[ target ] || null;
					if ( !inst || !oops.typing.isCallable(inst.resume) ) return;

					inst.resume();
				}
			}
	};
	*/

	oops.app = oops.app || {};
	oops.core.expand( oops.app, {
		initiate: function(){
			return new Promise(function( fulfill ){
				oops.app.initiate = ___DO_NOTHING;
				oops.util.each( instances, function( inst ){
					if ( !inst.initiate ) return;
					oops.async(function(){inst.initiate()});
				});

				execState = RUN_STATE.RUN;
				oops.async( fulfill );
			});
		},
		instantiate: function( instanceId, generator ){
			if ( oops.typing.isCallable(instanceId) )
			{
				generator = instanceId;
				instanceId = undefined;
			}

			if ( !oops.typing.isCallable( generator ) ) return undefined;

			var kernelCtrl	= {}, inst;
			if ( !( inst = generator(kernelCtrl) ) )
				throw "Invalid instance object is returned!";

			var uniqueId = oops.util.randomStr( 32 );
			while( instances[uniqueId] ) uniqueId = oops.util.randomStr( 32 );
			instances[ uniqueId ] = inst;
			inst.id = uniqueId;

			oops.core.expand( kernelCtrl, ___KERNEL_OPERATOR( uniqueId ) );

			var instId = instanceId || null;
			if ( instId == "external" ) {
				console.log( "\"external\" is a reserved keyword! Ignoring..." );
				instId = null;
			}
			if ( instId ) instMap[ instId.toString() ] = inst;

			if ( execState > RUN_STATE.BOOT && inst.initiate )
				oops.async(function(){inst.initiate()});

			return ___INST_WRAPPER( inst );
		},
		tool: {}
	}, true );

	function ___INST_WRAPPER( inst ) {
		var _instance = inst;

		return {
			message: function( message ){
				oops.async(function(){
					if ( !_instance.message ) return;
					_instance.message( { system:false, content:message, target:null, source:"external" } );
				});
			},
			trigger: function( evtType, evtParam ){
				oops.async(function(){
					var
					evtParam = (oops.typing.isObject(evtParam)) ? evtParam : { param: evtParam },
					event = { type:evtType, system:false, target:null, source:"external" };

					oops.core.expand( event, evtParam, false );

					if ( !_instance.event ) return;
					_instance.event( event );
				});
			},
			pause: function(){
				if ( !_instance.pause ) return;
				_instance.pause();
			},
			resume: function(){
				if ( !_instance.resume ) return;
				_instance.resume();
			}
		};
	}
	function ___KERNEL_OPERATOR( refId ) {
		return {
			trigger: function( target, evtType, evtParam ) {
				if ( arguments.length == 0 ) return;
				if ( arguments.length == 1 )
				{
					evtType = target;
					evtParam = {};
					target = null;
				}
				else
				if ( arguments.length == 2 )
				{
					evtParam = evtType;
					evtType = target;
					target = null;
				}

				oops.async(function(){
					var event = { type:evtType, system:false, target:target, source:refId };
					evtParam = (oops.typing.isObject(evtParam)) ? evtParam : { param: evtParam };

					oops.core.expand( event, evtParam, false );

					if ( !target )
					{
						oops.util.each( instances, function( inst ){
							if ( !inst.event ) return;
							inst.event( event );
						});
					}
					else
					{
						var inst = instMap[ target ] || instances[ target ] || null;
						if ( !inst || !oops.typing.isCallable(inst.event) ) return;

						inst.event( event );
					}
				});
			},
			message: function( target, message ) {
				if ( arguments.length == 0 ) return;
				if ( arguments.length == 1 )
				{
					message = target;
					target = null;
				}

				oops.async(function(){
					var msg = { system:false, content:message, target:target, source:refId };

					if ( !target )
					{
						oops.util.each( instances, function( inst ){
							if ( !inst.message ) return;
							inst.message( msg );
						});
					}
					else
					{
						var inst = instMap[ target ] || instances[ target ] || null;
						if ( !inst || !oops.typing.isCallable(inst.message) ) return;

						inst.message( msg );
					}
				});
			}
		};
	}
	function ___DO_NOTHING(){}

})( window.Promise );
<commit_msg>Remove external dependency of promise library by building promise-7.0.4 into oops.app<commit_after>/**
 * Created by JCloudYu on 11/11/15.
 * Dependency: jQuery, PromiseJS
 */
(function( window ) {
	"use strict";

	if ( !window.Promise ) __PROMISE_7_0_4();

	var
	// INFO: Constants
	RUN_STATE = { BOOT: 0, RUN: 1, WAIT: 2 },

	// INFO: System-wide variables
	instMap		= {},
	instances	= {},
	execState	= RUN_STATE.BOOT;

	/*
	dangling	= {
		pause: function( target ) {

				if ( !target )
				{
					oops.util.each( instances, function( inst ){
						if ( !inst.pause ) return;
						inst.pause();
					});

					execState = RUN_STATE.WAIT;
					$( oops.app ).trigger( "paused" );
				}
				else
				{
					var inst = instMap[ target ] || instances[ target ] || null;
					if ( !inst || !oops.typing.isCallable(inst.pause) ) return;

					inst.pause();
				}
			},
			resume: function( target ) {

				if ( !target )
				{
					oops.util.each( instances, function( inst ){
						if ( !inst.resume ) return;
						inst.resume();
					});

					execState = RUN_STATE.RUN;
					$( oops.app ).trigger( "resumed" );
				}
				else
				{
					var inst = instMap[ target ] || instances[ target ] || null;
					if ( !inst || !oops.typing.isCallable(inst.resume) ) return;

					inst.resume();
				}
			}
	};
	*/

	oops.app = oops.app || {};
	oops.core.expand( oops.app, {
		initiate: function(){
			return new Promise(function( fulfill ){
				oops.app.initiate = ___DO_NOTHING;
				oops.util.each( instances, function( inst ){
					if ( !inst.initiate ) return;
					oops.async(function(){inst.initiate()});
				});

				execState = RUN_STATE.RUN;
				oops.async( fulfill );
			});
		},
		instantiate: function( instanceId, generator ){
			if ( oops.typing.isCallable(instanceId) )
			{
				generator = instanceId;
				instanceId = undefined;
			}

			if ( !oops.typing.isCallable( generator ) ) return undefined;

			var kernelCtrl	= {}, inst;
			if ( !( inst = generator(kernelCtrl) ) )
				throw "Invalid instance object is returned!";

			var uniqueId = oops.util.randomStr( 32 );
			while( instances[uniqueId] ) uniqueId = oops.util.randomStr( 32 );
			instances[ uniqueId ] = inst;
			inst.id = uniqueId;

			oops.core.expand( kernelCtrl, ___KERNEL_OPERATOR( uniqueId ) );

			var instId = instanceId || null;
			if ( instId == "external" ) {
				console.log( "\"external\" is a reserved keyword! Ignoring..." );
				instId = null;
			}
			if ( instId ) instMap[ instId.toString() ] = inst;

			if ( execState > RUN_STATE.BOOT && inst.initiate )
				oops.async(function(){inst.initiate()});

			return ___INST_WRAPPER( inst );
		},
		tool: {}
	}, true );

	function ___INST_WRAPPER( inst ) {
		var _instance = inst;

		return {
			message: function( message ){
				oops.async(function(){
					if ( !_instance.message ) return;
					_instance.message( { system:false, content:message, target:null, source:"external" } );
				});
			},
			trigger: function( evtType, evtParam ){
				oops.async(function(){
					var
					evtParam = (oops.typing.isObject(evtParam)) ? evtParam : { param: evtParam },
					event = { type:evtType, system:false, target:null, source:"external" };

					oops.core.expand( event, evtParam, false );

					if ( !_instance.event ) return;
					_instance.event( event );
				});
			},
			pause: function(){
				if ( !_instance.pause ) return;
				_instance.pause();
			},
			resume: function(){
				if ( !_instance.resume ) return;
				_instance.resume();
			}
		};
	}
	function ___KERNEL_OPERATOR( refId ) {
		return {
			trigger: function( target, evtType, evtParam ) {
				if ( arguments.length == 0 ) return;
				if ( arguments.length == 1 )
				{
					evtType = target;
					evtParam = {};
					target = null;
				}
				else
				if ( arguments.length == 2 )
				{
					evtParam = evtType;
					evtType = target;
					target = null;
				}

				oops.async(function(){
					var event = { type:evtType, system:false, target:target, source:refId };
					evtParam = (oops.typing.isObject(evtParam)) ? evtParam : { param: evtParam };

					oops.core.expand( event, evtParam, false );

					if ( !target )
					{
						oops.util.each( instances, function( inst ){
							if ( !inst.event ) return;
							inst.event( event );
						});
					}
					else
					{
						var inst = instMap[ target ] || instances[ target ] || null;
						if ( !inst || !oops.typing.isCallable(inst.event) ) return;

						inst.event( event );
					}
				});
			},
			message: function( target, message ) {
				if ( arguments.length == 0 ) return;
				if ( arguments.length == 1 )
				{
					message = target;
					target = null;
				}

				oops.async(function(){
					var msg = { system:false, content:message, target:target, source:refId };

					if ( !target )
					{
						oops.util.each( instances, function( inst ){
							if ( !inst.message ) return;
							inst.message( msg );
						});
					}
					else
					{
						var inst = instMap[ target ] || instances[ target ] || null;
						if ( !inst || !oops.typing.isCallable(inst.message) ) return;

						inst.message( msg );
					}
				});
			}
		};
	}
	function ___DO_NOTHING(){}

	function __PROMISE_7_0_4(){
		(function e( t, n, r ) {
			function s( o, u ) {
				if ( !n[ o ] ) {
					if ( !t[ o ] ) {
						var a = typeof require == "function" && require;
						if ( !u && a ) return a( o, !0 );
						if ( i ) return i( o, !0 );
						var f = new Error( "Cannot find module '" + o + "'" );
						throw f.code = "MODULE_NOT_FOUND", f;
					}
					var l = n[ o ] = {
						exports: {}
					};
					t[ o ][ 0 ].call( l.exports, function( e ) {
						var n = t[ o ][ 1 ][ e ];
						return s( n ? n : e );
					}, l, l.exports, e, t, n, r );
				}
				return n[ o ].exports;
			}

			var i = typeof require == "function" && require;
			for ( var o = 0; o < r.length; o++ ) s( r[ o ] );
			return s;
		})( {
			1: [ function( require, module, exports ) {
				"use strict";
				var asap = require( "asap/raw" );

				function noop() {}

				var LAST_ERROR = null;
				var IS_ERROR = {};

				function getThen( obj ) {
					try {
						return obj.then;
					} catch ( ex ) {
						LAST_ERROR = ex;
						return IS_ERROR;
					}
				}

				function tryCallOne( fn, a ) {
					try {
						return fn( a );
					} catch ( ex ) {
						LAST_ERROR = ex;
						return IS_ERROR;
					}
				}

				function tryCallTwo( fn, a, b ) {
					try {
						fn( a, b );
					} catch ( ex ) {
						LAST_ERROR = ex;
						return IS_ERROR;
					}
				}

				module.exports = Promise;
				function Promise( fn ) {
					if ( typeof this !== "object" ) {
						throw new TypeError( "Promises must be constructed via new" );
					}
					if ( typeof fn !== "function" ) {
						throw new TypeError( "not a function" );
					}
					this._37 = 0;
					this._12 = null;
					this._59 = [];
					if ( fn === noop ) return;
					doResolve( fn, this );
				}

				Promise._99 = noop;
				Promise.prototype.then = function( onFulfilled, onRejected ) {
					if ( this.constructor !== Promise ) {
						return safeThen( this, onFulfilled, onRejected );
					}
					var res = new Promise( noop );
					handle( this, new Handler( onFulfilled, onRejected, res ) );
					return res;
				};
				function safeThen( self, onFulfilled, onRejected ) {
					return new self.constructor( function( resolve, reject ) {
						var res = new Promise( noop );
						res.then( resolve, reject );
						handle( self, new Handler( onFulfilled, onRejected, res ) );
					} );
				}

				function handle( self, deferred ) {
					while ( self._37 === 3 ) {
						self = self._12;
					}
					if ( self._37 === 0 ) {
						self._59.push( deferred );
						return;
					}
					asap( function() {
						var cb = self._37 === 1 ? deferred.onFulfilled : deferred.onRejected;
						if ( cb === null ) {
							if ( self._37 === 1 ) {
								resolve( deferred.promise, self._12 );
							} else {
								reject( deferred.promise, self._12 );
							}
							return;
						}
						var ret = tryCallOne( cb, self._12 );
						if ( ret === IS_ERROR ) {
							reject( deferred.promise, LAST_ERROR );
						} else {
							resolve( deferred.promise, ret );
						}
					} );
				}

				function resolve( self, newValue ) {
					if ( newValue === self ) {
						return reject( self, new TypeError( "A promise cannot be resolved with itself." ) );
					}
					if ( newValue && (typeof newValue === "object" || typeof newValue === "function") ) {
						var then = getThen( newValue );
						if ( then === IS_ERROR ) {
							return reject( self, LAST_ERROR );
						}
						if ( then === self.then && newValue instanceof Promise ) {
							self._37 = 3;
							self._12 = newValue;
							finale( self );
							return;
						} else if ( typeof then === "function" ) {
							doResolve( then.bind( newValue ), self );
							return;
						}
					}
					self._37 = 1;
					self._12 = newValue;
					finale( self );
				}

				function reject( self, newValue ) {
					self._37 = 2;
					self._12 = newValue;
					finale( self );
				}

				function finale( self ) {
					for ( var i = 0; i < self._59.length; i++ ) {
						handle( self, self._59[ i ] );
					}
					self._59 = null;
				}

				function Handler( onFulfilled, onRejected, promise ) {
					this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null;
					this.onRejected = typeof onRejected === "function" ? onRejected : null;
					this.promise = promise;
				}

				function doResolve( fn, promise ) {
					var done = false;
					var res = tryCallTwo( fn, function( value ) {
						if ( done ) return;
						done = true;
						resolve( promise, value );
					}, function( reason ) {
						if ( done ) return;
						done = true;
						reject( promise, reason );
					} );
					if ( !done && res === IS_ERROR ) {
						done = true;
						reject( promise, LAST_ERROR );
					}
				}
			}, {
				"asap/raw": 4
			} ],
			2: [ function( require, module, exports ) {
				"use strict";
				var Promise = require( "./core.js" );
				module.exports = Promise;
				var TRUE = valuePromise( true );
				var FALSE = valuePromise( false );
				var NULL = valuePromise( null );
				var UNDEFINED = valuePromise( undefined );
				var ZERO = valuePromise( 0 );
				var EMPTYSTRING = valuePromise( "" );

				function valuePromise( value ) {
					var p = new Promise( Promise._99 );
					p._37 = 1;
					p._12 = value;
					return p;
				}

				Promise.resolve = function( value ) {
					if ( value instanceof Promise ) return value;
					if ( value === null ) return NULL;
					if ( value === undefined ) return UNDEFINED;
					if ( value === true ) return TRUE;
					if ( value === false ) return FALSE;
					if ( value === 0 ) return ZERO;
					if ( value === "" ) return EMPTYSTRING;
					if ( typeof value === "object" || typeof value === "function" ) {
						try {
							var then = value.then;
							if ( typeof then === "function" ) {
								return new Promise( then.bind( value ) );
							}
						} catch ( ex ) {
							return new Promise( function( resolve, reject ) {
								reject( ex );
							} );
						}
					}
					return valuePromise( value );
				};
				Promise.all = function( arr ) {
					var args = Array.prototype.slice.call( arr );
					return new Promise( function( resolve, reject ) {
						if ( args.length === 0 ) return resolve( [] );
						var remaining = args.length;

						function res( i, val ) {
							if ( val && (typeof val === "object" || typeof val === "function") ) {
								if ( val instanceof Promise && val.then === Promise.prototype.then ) {
									while ( val._37 === 3 ) {
										val = val._12;
									}
									if ( val._37 === 1 ) return res( i, val._12 );
									if ( val._37 === 2 ) reject( val._12 );
									val.then( function( val ) {
										res( i, val );
									}, reject );
									return;
								} else {
									var then = val.then;
									if ( typeof then === "function" ) {
										var p = new Promise( then.bind( val ) );
										p.then( function( val ) {
											res( i, val );
										}, reject );
										return;
									}
								}
							}
							args[ i ] = val;
							if ( --remaining === 0 ) {
								resolve( args );
							}
						}

						for ( var i = 0; i < args.length; i++ ) {
							res( i, args[ i ] );
						}
					} );
				};
				Promise.reject = function( value ) {
					return new Promise( function( resolve, reject ) {
						reject( value );
					} );
				};
				Promise.race = function( values ) {
					return new Promise( function( resolve, reject ) {
						values.forEach( function( value ) {
							Promise.resolve( value ).then( resolve, reject );
						} );
					} );
				};
				Promise.prototype[ "catch" ] = function( onRejected ) {
					return this.then( null, onRejected );
				};
			}, {
				"./core.js": 1
			} ],
			3: [ function( require, module, exports ) {
				"use strict";
				var rawAsap = require( "./raw" );
				var freeTasks = [];
				var pendingErrors = [];
				var requestErrorThrow = rawAsap.makeRequestCallFromTimer( throwFirstError );

				function throwFirstError() {
					if ( pendingErrors.length ) {
						throw pendingErrors.shift();
					}
				}

				module.exports = asap;
				function asap( task ) {
					var rawTask;
					if ( freeTasks.length ) {
						rawTask = freeTasks.pop();
					} else {
						rawTask = new RawTask();
					}
					rawTask.task = task;
					rawAsap( rawTask );
				}

				function RawTask() {
					this.task = null;
				}

				RawTask.prototype.call = function() {
					try {
						this.task.call();
					} catch ( error ) {
						if ( asap.onerror ) {
							asap.onerror( error );
						} else {
							pendingErrors.push( error );
							requestErrorThrow();
						}
					} finally {
						this.task = null;
						freeTasks[ freeTasks.length ] = this;
					}
				};
			}, {
				"./raw": 4
			} ],
			4: [ function( require, module, exports ) {
				(function( global ) {
					"use strict";
					module.exports = rawAsap;
					function rawAsap( task ) {
						if ( !queue.length ) {
							requestFlush();
							flushing = true;
						}
						queue[ queue.length ] = task;
					}

					var queue = [];
					var flushing = false;
					var requestFlush;
					var index = 0;
					var capacity = 1024;

					function flush() {
						while ( index < queue.length ) {
							var currentIndex = index;
							index = index + 1;
							queue[ currentIndex ].call();
							if ( index > capacity ) {
								for ( var scan = 0, newLength = queue.length - index; scan < newLength; scan++ ) {
									queue[ scan ] = queue[ scan + index ];
								}
								queue.length -= index;
								index = 0;
							}
						}
						queue.length = 0;
						index = 0;
						flushing = false;
					}

					var BrowserMutationObserver = global.MutationObserver || global.WebKitMutationObserver;
					if ( typeof BrowserMutationObserver === "function" ) {
						requestFlush = makeRequestCallFromMutationObserver( flush );
					} else {
						requestFlush = makeRequestCallFromTimer( flush );
					}
					rawAsap.requestFlush = requestFlush;
					function makeRequestCallFromMutationObserver( callback ) {
						var toggle = 1;
						var observer = new BrowserMutationObserver( callback );
						var node = document.createTextNode( "" );
						observer.observe( node, {
							characterData: true
						} );
						return function requestCall() {
							toggle = -toggle;
							node.data = toggle;
						};
					}

					function makeRequestCallFromTimer( callback ) {
						return function requestCall() {
							var timeoutHandle = setTimeout( handleTimer, 0 );
							var intervalHandle = setInterval( handleTimer, 50 );

							function handleTimer() {
								clearTimeout( timeoutHandle );
								clearInterval( intervalHandle );
								callback();
							}
						};
					}

					rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer;
				}).call( this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {} );
			}, {} ],
			5: [ function( require, module, exports ) {
				if ( typeof Promise.prototype.done !== "function" ) {
					Promise.prototype.done = function( onFulfilled, onRejected ) {
						var self = arguments.length ? this.then.apply( this, arguments ) : this;
						self.then( null, function( err ) {
							setTimeout( function() {
								throw err;
							}, 0 );
						} );
					};
				}
			}, {} ],
			6: [ function( require, module, exports ) {
				var asap = require( "asap" );
				if ( typeof Promise === "undefined" ) {
					Promise = require( "./lib/core.js" );
					require( "./lib/es6-extensions.js" );
				}
				require( "./polyfill-done.js" );
			}, {
				"./lib/core.js"          : 1,
				"./lib/es6-extensions.js": 2,
				"./polyfill-done.js"     : 5,
				asap                     : 3
			} ]
		}, {}, [ 6 ] );
		//# sourceMappingURL=/polyfills/promise-7.0.4.js.map
	}
})( window );
<|endoftext|>


<commit_before>const path = require('path'),
  fs = require('fs'),
  dependencySolver = require('dependency-solver'),
  _ = require('lodash'),
  crypto = require('crypto'),
  config = require('./config'),
  logger = require('./logger')

const isMigrationFile = /\.migsi\.js$/

const migrationBase = {
  dependencies: null,
  noImplicitDependencies: false,
  hasBeenRun: false,
  runDate: null,
}

function sortMigrations(unsorted) {
  const dependencyMap = _.fromPairs(unsorted.map(migration => [migration.migsiName, migration.dependencies.length ? migration.dependencies : ['*']]))
  const migrationMap = _.keyBy(unsorted, migration => migration.migsiName)
  if (process.env.MIGSI_PRINT_DEPENDENCY_MAP) logger.log(JSON.stringify(dependencyMap, null, 2))
  const solved = dependencySolver.solve(dependencyMap)
  const dependencySorterMigrations = _.compact(solved.filter(e => e !== '*').map(name => migrationMap[name]))
  return fixParallelDependencyOrder(dependencySorterMigrations)

}

function fixParallelDependencyOrder(migrations) {
  const migs = [].concat(migrations) // clone
  for (let i = 0; i < migs.length - 1; ++i) {
    const a = migs[i],
      b = migs[i + 1]
    if (a.toBeRun && !b.eligibleToRun) {
      if (!b.dependencies.includes(a.migsiName)) {
        migs.splice(i, 2, b, a)
      } else {
        if (config.allowRerunningAllMigrations) {
          returnAllDependants(a, migrations)
        } else {
          // cannot fix, abort
          return migs
        }
      }
    } else if (a.toBeRun && !b.toBeRun) { // b could be run, but doesn't need to be
      if (!b.dependencies.includes(a.migsiName)) { // reorder them to for ideal order
        migs.splice(i, 2, b, a)
        --i
      }
    } else if (a.inDevelopment && !b.inDevelopment) { // production scripts before development
      if (!b.dependencies.includes(a.migsiName)) { // reorder them to for ideal order
        migs.splice(i, 2, b, a)
        --i
      }
    }
  }
  return migs
}

function checkMigrationOrderValidity(migrations, dependenciesHaveBeenUpdated = false) {
  let anyToRun = false,
    potentialDependencyMigration,
    toBeRun = []
  for (let migration of migrations) {
    if (migration.toBeRun || (anyToRun && config.allowRerunningAllMigrations)) {
      anyToRun = true
      toBeRun.push(migration.migsiName)
    } else {
      if (!anyToRun) {
        potentialDependencyMigration = migration.migsiName
      } else if (!migration.inDevelopment) {
        if (dependenciesHaveBeenUpdated) {
          console.error(`${migration.migsiName} can not be run, as it should've been run before the migrations ${toBeRun.join(', ')}, which ha(s|ve) not been run.

        To solve this problem, you can either:
        - add an explicit dependency to run ${migration.migsiName} before the others; usually by having ${migration.migsiName} depend on a migration script that
        has already been run (the latest one being ${potentialDependencyMigration})
        - re-create the migration script as a new one (making it the last migration to be run)
        - set the environment variable MIGSI_ALLOW_RERUNNING_ALL_MIGRATIONS to value of 1 to force it and its descendants to be rerun
        `)
        }
        throw new Error('Invalid migration order')
      } else {
        console.warn(`Some of the dependencies of ${migration.migsiName} are to be run despite it having been run already. This is permitted as the script is still under development. If you need it run as well, please increment its version number.`)
      }
    }
  }
}

module.exports.findMigrations = async function findMigrations(dependenciesUpdated = false) {
  const pastMigrations = await config.storage.loadPastMigrations()
  const files = findAllMigrationFiles()
  const migrations = files.map(function (file) {
    const past = pastMigrations.find(migration => migration.migsiName === file.split('.migsi.js')[0])

    if (past && !past.inDevelopment && !config.allowRerunningAllMigrations) {
      return Object.assign({}, migrationBase, {hasBeenRun: true}, past, {toBeRun: false, eligibleToRun: false})
    }
    const migration = Object.assign({}, past || {}, migrationBase, loadMigration(file))
    if (past) {
      migration.versionChanged = migration.version !== past.version
      migration.hasBeenRun = past.hasBeenRun
    }
    migration.toBeRun = !past || migration.versionChanged
    migration.eligibleToRun = !past || !!past.inDevelopment || (config.allowRerunningAllMigrations && migration.toBeRun)
    return migration
  })
  try {
    const sortedMigrations = sortMigrations(migrations)
    checkMigrationOrderValidity(sortedMigrations, dependenciesUpdated)
    return sortedMigrations
  } catch(err) {
    if (!dependenciesUpdated) {
      const potentiallyOutdated = migrations.filter(mig => mig.hasBeenRun && !mig.inDevelopment)
      for (let migration of potentiallyOutdated) {
        await updateDependencies(migration)
      }
      return findMigrations(pastMigrations, true)
    } else {
      throw err
    }
  }
}

async function updateDependencies(migration) {
  const fullFilename = path.join(config.getDir('migrationDir'), migration.migsiName + '.migsi.js')
  const migrationFromDisk = exportFriendlyRequire(fullFilename)
  const d1 = migration.dependencies || [],
    d2 = migrationFromDisk.dependencies || []

  if (d2.length) {
    if (d1.length !== d2.length || _.difference(d2, d1).length > 0) {
      logger.log('Updating dependencies of', migration.migsiName)
      migration.dependencies = d2
      await config.storage.updateStatus(migration)
    }
  }
}

function loadMigration(filename) {
  const fullFilename = path.join(config.getDir('migrationDir'), filename)
  const migration = exportFriendlyRequire(fullFilename)
  migration.dependencies = _.compact(migration.dependencies || [])
  migration.migsiName = filename.split('.migsi.js')[0]
  if (migration.version === 'hash') {
    migration.version += ':' + getHash(fullFilename)
  }
  return migration
}

function findAllMigrationFiles() {
  return [...findMigrationFilesFrom('./')]
}

function* findMigrationFilesFrom(subdir) {
  const contents = fs.readdirSync(path.join(config.getDir('migrationDir'), subdir))
  for (let file of contents) {
    const fullPath = path.join(config.getDir('migrationDir'), subdir, file)
    if (isMigrationFile.test(file)) {
      yield path.join(subdir, file)
    } else if (fs.statSync(fullPath).isDirectory()) {
      yield* findMigrationFilesFrom(path.join(subdir, file))
    }
  }
}

function getHash(filename) {
  const hash = crypto.createHash('sha256')
  hash.update(fs.readFileSync(filename, 'UTF-8'))
  return hash.digest('hex')
}

function exportFriendlyRequire(filename) {
  const module = require(filename)
  return module.default || module
}

function returnAllDependants(parent, migrations) {
  const dependencies = {}

  for (let migration of migrations) {
    if (isDependant(migration, parent)) {
      migration.eligibleToRun = true
      migration.toBeRun = true
    }
  }

  function isDependant(migration, potentialParent) {
    return getAllDependencies(migration).includes(potentialParent.migsiName)
  }

  function getAllDependencies(migration) {
    if (dependencies[migration.migsiName]) return dependencies[migration.migsiName]

    let migDeps = migration.dependencies || []
    return dependencies[migration.migsiName] = _.flatten(migDeps.concat(migDeps.map(migrationName => getAllDependencies(getMigration(migrationName)))))
  }

  function getMigration(name) {
    return migrations.find(migration => migration.migsiName === name)
  }
}<commit_msg>Initialize dependencies for all migrations<commit_after>const path = require('path'),
  fs = require('fs'),
  dependencySolver = require('dependency-solver'),
  _ = require('lodash'),
  crypto = require('crypto'),
  config = require('./config'),
  logger = require('./logger')

const isMigrationFile = /\.migsi\.js$/

const migrationBase = {
  dependencies: null,
  noImplicitDependencies: false,
  hasBeenRun: false,
  runDate: null,
}

function sortMigrations(unsorted) {
  const dependencyMap = _.fromPairs(unsorted.map(migration => [migration.migsiName, migration.dependencies.length ? migration.dependencies : ['*']]))
  const migrationMap = _.keyBy(unsorted, migration => migration.migsiName)
  if (process.env.MIGSI_PRINT_DEPENDENCY_MAP) logger.log(JSON.stringify(dependencyMap, null, 2))
  const solved = dependencySolver.solve(dependencyMap)
  const dependencySorterMigrations = _.compact(solved.filter(e => e !== '*').map(name => migrationMap[name]))
  return fixParallelDependencyOrder(dependencySorterMigrations)

}

function fixParallelDependencyOrder(migrations) {
  const migs = [].concat(migrations) // clone
  for (let i = 0; i < migs.length - 1; ++i) {
    const a = migs[i],
      b = migs[i + 1]
    if (a.toBeRun && !b.eligibleToRun) {
      if (!b.dependencies.includes(a.migsiName)) {
        migs.splice(i, 2, b, a)
      } else {
        if (config.allowRerunningAllMigrations) {
          returnAllDependants(a, migrations)
        } else {
          // cannot fix, abort
          return migs
        }
      }
    } else if (a.toBeRun && !b.toBeRun) { // b could be run, but doesn't need to be
      if (!b.dependencies.includes(a.migsiName)) { // reorder them to for ideal order
        migs.splice(i, 2, b, a)
        --i
      }
    } else if (a.inDevelopment && !b.inDevelopment) { // production scripts before development
      if (!b.dependencies.includes(a.migsiName)) { // reorder them to for ideal order
        migs.splice(i, 2, b, a)
        --i
      }
    }
  }
  return migs
}

function checkMigrationOrderValidity(migrations, dependenciesHaveBeenUpdated = false) {
  let anyToRun = false,
    potentialDependencyMigration,
    toBeRun = []
  for (let migration of migrations) {
    if (migration.toBeRun || (anyToRun && config.allowRerunningAllMigrations)) {
      anyToRun = true
      toBeRun.push(migration.migsiName)
    } else {
      if (!anyToRun) {
        potentialDependencyMigration = migration.migsiName
      } else if (!migration.inDevelopment) {
        if (dependenciesHaveBeenUpdated) {
          console.error(`${migration.migsiName} can not be run, as it should've been run before the migrations ${toBeRun.join(', ')}, which ha(s|ve) not been run.

        To solve this problem, you can either:
        - add an explicit dependency to run ${migration.migsiName} before the others; usually by having ${migration.migsiName} depend on a migration script that
        has already been run (the latest one being ${potentialDependencyMigration})
        - re-create the migration script as a new one (making it the last migration to be run)
        - set the environment variable MIGSI_ALLOW_RERUNNING_ALL_MIGRATIONS to value of 1 to force it and its descendants to be rerun
        `)
        }
        throw new Error('Invalid migration order')
      } else {
        console.warn(`Some of the dependencies of ${migration.migsiName} are to be run despite it having been run already. This is permitted as the script is still under development. If you need it run as well, please increment its version number.`)
      }
    }
  }
}

module.exports.findMigrations = async function findMigrations(dependenciesUpdated = false) {
  const pastMigrations = await config.storage.loadPastMigrations()
  const files = findAllMigrationFiles()
  const migrations = files.map(function (file) {
    const past = pastMigrations.find(migration => migration.migsiName === file.split('.migsi.js')[0])

    if (past && !past.inDevelopment && !config.allowRerunningAllMigrations) {
      return Object.assign({}, migrationBase, {hasBeenRun: true}, past, {toBeRun: false, eligibleToRun: false})
    }
    const migration = Object.assign({}, past || {}, migrationBase, loadMigration(file))
    if (past) {
      migration.versionChanged = migration.version !== past.version
      migration.hasBeenRun = past.hasBeenRun
    }
    migration.toBeRun = !past || migration.versionChanged
    migration.eligibleToRun = !past || !!past.inDevelopment || (config.allowRerunningAllMigrations && migration.toBeRun)
    return migration
  })
  for (let migration of migrations) {
    if (!migration.dependencies) migration.dependencies = []
  }
  try {
    const sortedMigrations = sortMigrations(migrations)
    checkMigrationOrderValidity(sortedMigrations, dependenciesUpdated)
    return sortedMigrations
  } catch(err) {
    if (!dependenciesUpdated) {
      const potentiallyOutdated = migrations.filter(mig => mig.hasBeenRun && !mig.inDevelopment)
      for (let migration of potentiallyOutdated) {
        await updateDependencies(migration)
      }
      return findMigrations(pastMigrations, true)
    } else {
      throw err
    }
  }
}

async function updateDependencies(migration) {
  const fullFilename = path.join(config.getDir('migrationDir'), migration.migsiName + '.migsi.js')
  const migrationFromDisk = exportFriendlyRequire(fullFilename)
  const d1 = migration.dependencies || [],
    d2 = migrationFromDisk.dependencies || []

  if (d2.length) {
    if (d1.length !== d2.length || _.difference(d2, d1).length > 0) {
      logger.log('Updating dependencies of', migration.migsiName)
      migration.dependencies = d2
      await config.storage.updateStatus(migration)
    }
  }
}

function loadMigration(filename) {
  const fullFilename = path.join(config.getDir('migrationDir'), filename)
  const migration = exportFriendlyRequire(fullFilename)
  migration.dependencies = _.compact(migration.dependencies || [])
  migration.migsiName = filename.split('.migsi.js')[0]
  if (migration.version === 'hash') {
    migration.version += ':' + getHash(fullFilename)
  }
  return migration
}

function findAllMigrationFiles() {
  return [...findMigrationFilesFrom('./')]
}

function* findMigrationFilesFrom(subdir) {
  const contents = fs.readdirSync(path.join(config.getDir('migrationDir'), subdir))
  for (let file of contents) {
    const fullPath = path.join(config.getDir('migrationDir'), subdir, file)
    if (isMigrationFile.test(file)) {
      yield path.join(subdir, file)
    } else if (fs.statSync(fullPath).isDirectory()) {
      yield* findMigrationFilesFrom(path.join(subdir, file))
    }
  }
}

function getHash(filename) {
  const hash = crypto.createHash('sha256')
  hash.update(fs.readFileSync(filename, 'UTF-8'))
  return hash.digest('hex')
}

function exportFriendlyRequire(filename) {
  const module = require(filename)
  return module.default || module
}

function returnAllDependants(parent, migrations) {
  const dependencies = {}

  for (let migration of migrations) {
    if (isDependant(migration, parent)) {
      migration.eligibleToRun = true
      migration.toBeRun = true
    }
  }

  function isDependant(migration, potentialParent) {
    return getAllDependencies(migration).includes(potentialParent.migsiName)
  }

  function getAllDependencies(migration) {
    if (dependencies[migration.migsiName]) return dependencies[migration.migsiName]

    let migDeps = migration.dependencies || []
    return dependencies[migration.migsiName] = _.flatten(migDeps.concat(migDeps.map(migrationName => getAllDependencies(getMigration(migrationName)))))
  }

  function getMigration(name) {
    return migrations.find(migration => migration.migsiName === name)
  }
}<|endoftext|>


<commit_before>'use strict';

var _ = require('./underscore_ext');
var unicode = require('./unicode_utils');
var chromInfo = require('./chromInfo');
var centromere = require('./centromere');

var toInt = x => parseInt(x, 10);
var clip = (len, x) => x < 1 ? 1 : (x > len ? len : x);
var M = 1000 * 1000;

module.exports = function (text, assembly) {
	// strip spaces, cvt to lower, match chr1:2-chr3:4 format
	text = unicode.normalize(text).replace(/ /g, '').toLowerCase();
	var pos = text.match(/^(chr[0-9xyXY]+)([pq]?)(:([0-9,]+)(-([0-9,]+))?)?$/);
	if (pos) {
		let chrom = pos[1].replace(/x/, 'X').replace(/y/, 'Y'),
			cm = _.getIn(centromere, [assembly, chrom]),
			maxEnd = _.getIn(chromInfo, [assembly, chrom], 250 * M),
			baseStart, baseEnd;

		if (pos[3] !== undefined) {
			baseStart = clip(baseEnd, toInt(pos[4].replace(/,/g, '')));
			baseEnd = baseStart;
			if (pos[6] !== undefined) {
				baseEnd = clip(maxEnd, toInt(pos[6].replace(/,/g, '')));
			}
		} else if (cm && pos[2] === 'p') {
			baseStart = 1;
			baseEnd = cm - 1;
		} else if (cm && pos[2] === 'q') {
			baseStart = cm;
			baseEnd = maxEnd;
		} else {
			baseStart = 1;
			baseEnd = maxEnd;
		}
		return {chrom, baseStart, baseEnd};
	}
};
<commit_msg>reverse parsePos<commit_after>'use strict';

var _ = require('./underscore_ext');
var unicode = require('./unicode_utils');
var chromInfo = require('./chromInfo');
var centromere = require('./centromere');

var toInt = x => parseInt(x, 10);
var clip = (len, x) => x < 1 ? 1 : (x > len ? len : x);
var M = 1000 * 1000;

module.exports = function (text, assembly) {
	// strip spaces, cvt to lower, match chr1:2-chr3:4 format
	text = unicode.normalize(text).replace(/ /g, '').toLowerCase();
	var pos = text.match(/^(chr[0-9xyXY]+)([pq]?)(:([0-9,]+)-([0-9,]+))?$/);
	//var pos = text.match(/^(chr[0-9xyXY]+)([pq]?)(:([0-9,]+)(-([0-9,]+))?)?$/);
	if (pos) {
		let chrom = pos[1].replace(/x/, 'X').replace(/y/, 'Y'),
			cm = _.getIn(centromere, [assembly, chrom]),
			maxEnd = _.getIn(chromInfo, [assembly, chrom], 250 * M),
			baseStart, baseEnd;

		if (pos[3] !== undefined) {
			baseEnd = clip(maxEnd, toInt(pos[5].replace(/,/g, '')));
			baseStart = clip(baseEnd, toInt(pos[4].replace(/,/g, '')));
			/*baseEnd = baseStart;
			if (pos[6] !== undefined) {
				baseEnd = clip(maxEnd, toInt(pos[6].replace(/,/g, '')));
			}*/
		} else if (cm && pos[2] === 'p') {
			baseStart = 1;
			baseEnd = cm - 1;
		} else if (cm && pos[2] === 'q') {
			baseStart = cm;
			baseEnd = maxEnd;
		} else {
			baseStart = 1;
			baseEnd = maxEnd;
		}
		return {chrom, baseStart, baseEnd};
	}
};
<|endoftext|>


<commit_before>//song list add here
//music url, album image, song name, artist
var arr_pg1 = [];

arr_pg1.push("http://drive.funados-radio.fr/playlist/HITS%20DU%20MOMENT/Alan%20Walker%20-%20Faded.mp3");
arr_pg1.push("https://upload.wikimedia.org/wikipedia/en/d/da/Alan_Walker_-_Faded.png");
arr_pg1.push("Faded");
arr_pg1.push("Alan Walker");

arr_pg1.push("http://dl.20track.ir/mahdi/Album2/MARS2017/Charlie%20Puth%20-%20Attention%20-%20MP3%20128.mp3");
arr_pg1.push("http://youth.newagebd.net/wordpress/wp-content/uploads/2017/05/Song.gif");
arr_pg1.push("Attention");
arr_pg1.push("Charlie Puth");

arr_pg1.push("http://tegos.kz/new/mp3_full/Sia_-_Cheap_Thrills.mp3");
arr_pg1.push("https://i.pinimg.com/736x/3d/c0/c1/3dc0c120a6cfa21db550b28e08357431--maddie-ziegler-tim-beta.jpg");
arr_pg1.push("Cheap Thrills");
arr_pg1.push("Sia");

arr_pg1.push("http://dl2.djring.com/sd1.djring.com/128/474893/Closer+-+The+Chainsmokers%20(DJJOhAL.Com).mp");
arr_pg1.push("https://upload.wikimedia.org/wikipedia/en/a/a5/Closer_%28featuring_Halsey%29_%28Official_Single_Cover%29_by_The_Chainsmokers.png");
arr_pg1.push("Closer");
arr_pg1.push("The Chainsmokers");

arr_pg1.push("http://bossmp3.me/siteuploads/7/362/1198/Love%20Me%20Like%20You%20Do%20(Ellie%20Goulding)%20-%20320%20Kbps%20-%20(BossMp3.Me).mp3");
arr_pg1.push("http://1.bp.blogspot.com/-xVFj92sUzFI/VLFG3pN0KGI/AAAAAAAALq8/wA9ivYedHCQ/s1600/Ellie%2BGoulding%2B-%2BLove%2BMe%2BLike%2BYou%2BDo.jpg");
arr_pg1.push("Love Me Like You Do");
arr_pg1.push("Ellie Goulding");

arr_pg1.push("http://dl2.djring.com/lq.djring.com/48/482473/I%20m%20The%20One%20Ft%20Justin%20Bieber%20Quavo%20Chance%20The%20Rapper%20%20Lil%20Wayne%20-%20DJ%20Khaled%20(DJJOhAL.Com).mp3");
arr_pg1.push("https://www.lilwaynehq.com/images/blog/dj-khaled-im-the-one-lil-wayne-justin-bieber-chance-the-rapper-quavo-artwork.jpg");
arr_pg1.push("I'm The One");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://dl2.djring.com/sd2.djring.com/128/479068/Shape%20of%20You%20-%20Ed%20Sheeran%20(DJJOhAL.Com).mp3");
arr_pg1.push("https://upload.wikimedia.org/wikipedia/en/b/b4/Shape_Of_You_%28Official_Single_Cover%29_by_Ed_Sheeran.png");
arr_pg1.push("I'm The One");
arr_pg1.push("Ed Sheeran");

arr_pg1.push("http://dl2.djring.com/sd1.djring.com/128/474895/Cold+Water+-+Major+Lazer+Justin+Bieber%20(DJJOhAL.Com).mp3");
arr_pg1.push("http://coverlandia.net/sites/default/files/styles/music_artwork_page/public/artworks/music/38711471968021.png");
arr_pg1.push("Cold Water");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://srv2.teupload.com/Music/Album/Justin%20Bieber%20-%20Purpose%20(Deluxe)/Justin%20Bieber%20-%20Purpose%20(Deluxe)%20128/04%20Sorry.mp3");
arr_pg1.push("https://is1-ssl.mzstatic.com/image/thumb/Music6/v4/f6/40/c8/f640c8b9-b2f8-905a-9fff-2d38d8bfe35b/UMG_cvrart_00602547587428_01_RGB72_1500x1500_15UMGIM59808.jpg/1200x630bb.jpg");
arr_pg1.push("Sorry");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://tegos.kz/new/mp3_full/Clean_Bandit_-_Rockabye.mp3");
arr_pg1.push("https://img.discogs.com/wnJDCY_xI9BtICDCOq9oJx6e66c=/fit-in/600x520/filters:strip_icc():format(jpeg):mode_rgb():quality(90)/discogs-images/R-9444679-1480705235-2916.jpeg.jpg");
arr_pg1.push("Rockabye");
arr_pg1.push("Clean Bandit");

arr_pg1.push("http://dl2.djring.com/sd1.djring.com/128/479065/Let+Me+Love+You+-+DJ+Snake+Ft+Justin+Bieber%20(DJJOhAL.Com).mp3");
arr_pg1.push("http://media.socastsrm.com/wordpress/wp-content/blogs.dir/69/files/2016/07/bieber.jpg");
arr_pg1.push("Let Me Love You");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://tentechaudio.com/application/lagubarat/Charlie%20Puth%20(Feat.%20Selena%20Gomez)%20-%20We%20Don't%20Talk%20Anymore.mp3");
arr_pg1.push("https://images-na.ssl-images-amazon.com/images/M/MV5BOWQyYmJiOWUtNzkzYS00YWJlLWI5YjgtYTg4MjI0MmM1N2ZkXkEyXkFqcGdeQXVyNjE0ODc0MDc@._V1_SY300_SX300_AL_.jpg");
arr_pg1.push("We Don't Talk Anymore");
arr_pg1.push("Charlie Puth");

arr_pg1.push("http://skymaza.com/upload_file/1/3647/3663/3666/Linkin%20Park%20-%20Meteora%20-%2013%20-%20Numb-.mp3");
arr_pg1.push("https://is4-ssl.mzstatic.com/image/thumb/Features/v4/9a/c2/68/9ac26832-eeb4-3854-0c47-33f3e5c11cc8/dj.xkwgleci.jpg/1200x630bb.jpg");
arr_pg1.push("Numb");
arr_pg1.push("Linkin Park");
<commit_msg>Update playlist.js<commit_after>//song list add here
//music url, album image, song name, artist
var arr_pg1 = [];

arr_pg1.push("http://drive.funados-radio.fr/playlist/HITS%20DU%20MOMENT/Alan%20Walker%20-%20Faded.mp3");
arr_pg1.push("https://upload.wikimedia.org/wikipedia/en/d/da/Alan_Walker_-_Faded.png");
arr_pg1.push("Faded");
arr_pg1.push("Alan Walker");

arr_pg1.push("http://dl.20track.ir/mahdi/Album2/MARS2017/Charlie%20Puth%20-%20Attention%20-%20MP3%20128.mp3");
arr_pg1.push("http://youth.newagebd.net/wordpress/wp-content/uploads/2017/05/Song.gif");
arr_pg1.push("Attention");
arr_pg1.push("Charlie Puth");

arr_pg1.push("http://tegos.kz/new/mp3_full/Sia_-_Cheap_Thrills.mp3");
arr_pg1.push("https://i.pinimg.com/736x/3d/c0/c1/3dc0c120a6cfa21db550b28e08357431--maddie-ziegler-tim-beta.jpg");
arr_pg1.push("Cheap Thrills");
arr_pg1.push("Sia");

arr_pg1.push("http://dl2.djring.com/sd1.djring.com/128/474893/Closer+-+The+Chainsmokers%20(DJJOhAL.Com).mp");
arr_pg1.push("https://upload.wikimedia.org/wikipedia/en/a/a5/Closer_%28featuring_Halsey%29_%28Official_Single_Cover%29_by_The_Chainsmokers.png");
arr_pg1.push("Closer");
arr_pg1.push("The Chainsmokers");

arr_pg1.push("http://bossmp3.me/siteuploads/7/362/1198/Love%20Me%20Like%20You%20Do%20(Ellie%20Goulding)%20-%20320%20Kbps%20-%20(BossMp3.Me).mp3");
arr_pg1.push("http://1.bp.blogspot.com/-xVFj92sUzFI/VLFG3pN0KGI/AAAAAAAALq8/wA9ivYedHCQ/s1600/Ellie%2BGoulding%2B-%2BLove%2BMe%2BLike%2BYou%2BDo.jpg");
arr_pg1.push("Love Me Like You Do");
arr_pg1.push("Ellie Goulding");

arr_pg1.push("http://dl2.djring.com/lq.djring.com/48/482473/I%20m%20The%20One%20Ft%20Justin%20Bieber%20Quavo%20Chance%20The%20Rapper%20%20Lil%20Wayne%20-%20DJ%20Khaled%20(DJJOhAL.Com).mp3");
arr_pg1.push("https://www.lilwaynehq.com/images/blog/dj-khaled-im-the-one-lil-wayne-justin-bieber-chance-the-rapper-quavo-artwork.jpg");
arr_pg1.push("I'm The One");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://dl2.djring.com/sd2.djring.com/128/479068/Shape%20of%20You%20-%20Ed%20Sheeran%20(DJJOhAL.Com).mp3");
arr_pg1.push("https://upload.wikimedia.org/wikipedia/en/b/b4/Shape_Of_You_%28Official_Single_Cover%29_by_Ed_Sheeran.png");
arr_pg1.push("Shape Of You");
arr_pg1.push("Ed Sheeran");

arr_pg1.push("http://dl2.djring.com/sd1.djring.com/128/474895/Cold+Water+-+Major+Lazer+Justin+Bieber%20(DJJOhAL.Com).mp3");
arr_pg1.push("http://coverlandia.net/sites/default/files/styles/music_artwork_page/public/artworks/music/38711471968021.png");
arr_pg1.push("Cold Water");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://srv2.teupload.com/Music/Album/Justin%20Bieber%20-%20Purpose%20(Deluxe)/Justin%20Bieber%20-%20Purpose%20(Deluxe)%20128/04%20Sorry.mp3");
arr_pg1.push("https://is1-ssl.mzstatic.com/image/thumb/Music6/v4/f6/40/c8/f640c8b9-b2f8-905a-9fff-2d38d8bfe35b/UMG_cvrart_00602547587428_01_RGB72_1500x1500_15UMGIM59808.jpg/1200x630bb.jpg");
arr_pg1.push("Sorry");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://tegos.kz/new/mp3_full/Clean_Bandit_-_Rockabye.mp3");
arr_pg1.push("https://img.discogs.com/wnJDCY_xI9BtICDCOq9oJx6e66c=/fit-in/600x520/filters:strip_icc():format(jpeg):mode_rgb():quality(90)/discogs-images/R-9444679-1480705235-2916.jpeg.jpg");
arr_pg1.push("Rockabye");
arr_pg1.push("Clean Bandit");

arr_pg1.push("http://dl2.djring.com/sd1.djring.com/128/479065/Let+Me+Love+You+-+DJ+Snake+Ft+Justin+Bieber%20(DJJOhAL.Com).mp3");
arr_pg1.push("http://media.socastsrm.com/wordpress/wp-content/blogs.dir/69/files/2016/07/bieber.jpg");
arr_pg1.push("Let Me Love You");
arr_pg1.push("Justin Bieber");

arr_pg1.push("http://tentechaudio.com/application/lagubarat/Charlie%20Puth%20(Feat.%20Selena%20Gomez)%20-%20We%20Don't%20Talk%20Anymore.mp3");
arr_pg1.push("https://images-na.ssl-images-amazon.com/images/M/MV5BOWQyYmJiOWUtNzkzYS00YWJlLWI5YjgtYTg4MjI0MmM1N2ZkXkEyXkFqcGdeQXVyNjE0ODc0MDc@._V1_SY300_SX300_AL_.jpg");
arr_pg1.push("We Don't Talk Anymore");
arr_pg1.push("Charlie Puth");

arr_pg1.push("http://skymaza.com/upload_file/1/3647/3663/3666/Linkin%20Park%20-%20Meteora%20-%2013%20-%20Numb-.mp3");
arr_pg1.push("https://is4-ssl.mzstatic.com/image/thumb/Features/v4/9a/c2/68/9ac26832-eeb4-3854-0c47-33f3e5c11cc8/dj.xkwgleci.jpg/1200x630bb.jpg");
arr_pg1.push("Numb");
arr_pg1.push("Linkin Park");
<|endoftext|>


<commit_before>'use strict'
var DynamicBytes = require('./DynamicByteArray')

class StringType extends DynamicBytes {
  constructor (location) {
    super(location)
    this.typeName = 'string'
  }

  decodeFromStorage (location, storageContent) {
    var decoded = super.decodeFromStorage(location, storageContent)
    return format(decoded)
  }

  decodeFromStack (stackDepth, stack, memory) {
    return super.decodeFromStack(stackDepth, stack, memory)
  }

  decodeFromMemoryInternal (offset, memory) {
    var decoded = super.decodeFromMemoryInternal(offset, memory)
    return format(decoded)
  }
}

function format (decoded) {
  if (decoded.error) {
    return decoded
  }
  var value = decoded.value
  value = value.replace('0x', '').replace(/(..)/g, '%$1')
  var ret = {
    length: decoded.length,
    raw: decoded.value
  }
  try {
    ret.value = decodeURIComponent(value)
  } catch (e) {
    ret.error = 'Invalid UTF8 encoding'
    ret.raw = decoded.value
  }
  return ret
}

module.exports = StringType
<commit_msg>type name for string<commit_after>'use strict'
var DynamicBytes = require('./DynamicByteArray')

class StringType extends DynamicBytes {
  constructor (location) {
    super(location)
    this.typeName = 'string'
  }

  decodeFromStorage (location, storageContent) {
    var decoded = super.decodeFromStorage(location, storageContent)
    return format(decoded)
  }

  decodeFromStack (stackDepth, stack, memory) {
    return super.decodeFromStack(stackDepth, stack, memory)
  }

  decodeFromMemoryInternal (offset, memory) {
    var decoded = super.decodeFromMemoryInternal(offset, memory)
    return format(decoded)
  }
}

function format (decoded) {
  if (decoded.error) {
    return decoded
  }
  var value = decoded.value
  value = value.replace('0x', '').replace(/(..)/g, '%$1')
  var ret = {
    length: decoded.length,
    raw: decoded.value,
    type: 'string'
  }
  try {
    ret.value = decodeURIComponent(value)
  } catch (e) {
    ret.error = 'Invalid UTF8 encoding'
    ret.raw = decoded.value
  }
  return ret
}

module.exports = StringType
<|endoftext|>


<commit_before>/* global define, crypto, Uint8Array: false */
define(['./Stopwatch'], function(Stopwatch) {

    'use strict';

    function getRandomValues(count) {
        var rands, d;
        if (crypto && crypto.getRandomValues) {
            rands = new Uint8Array(count);
            crypto.getRandomValues(rands);
        } else {
            rands = new Array(count);
            d = new Date().getTime();
            while (count--) {
                rands[count] = (d + Math.random() * 16) & 15;
            }
        }
        return rands;
    }

    function generateUUID() {
        var values = getRandomValues(36);
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
            .replace(/[xy]/g, function(c, i) {
                var r = values[i] & 15;
                return (c === 'x' ? r : (r & 0x3|0x8)).toString(16);
            });
    }

    function firstDefined() {
        var args = [].slice.call(arguments),
            result = args.shift();
        while (args.length && result === undefined) {
            result = args.shift();
        }
        return result;
    }

    function getValue(params) {

        var args = [].slice.call(arguments),
            def = args.pop(),
            names = args.slice(1);

        return names.reduce(function (prev, name) {
            return firstDefined((params.data || {})[name], params[name], prev);
        }, def);

    }

    function clone(obj) {
        return Object.keys(obj).reduce(function copy(result, key) {
            return result[key] = obj[key], result;
        }, {});
    }

    /**
     * Encapsulates the tracking information provided by all
     * tracking sources into a single consistent schema for
     * consumption by collectors.
     * @class TrackingInfo
     * @param {Object} params An object whose properties will
     *  be examined to set properties on the TrackingInfo
     *  instance.
     * @example
     * var info = new TrackingInfo({
     *   type: 'event',
     *   action: 'click',
     *   label: 'custom label'
     * });
     */
    return function TrackingInfo(params) {

        if (!(this instanceof TrackingInfo)) {
            return new TrackingInfo(params);
        }

        /**
         * @member {Object} [data] Any optional data
         *  associated with the current instance.
         */
        this.data = clone(params.data || {});

        /**
         * @member {Array} [tags] Any optional strings
         *  to associate with the current instance.
         */
        this.tags = getValue(params, 'tags', []);

        /**
         * @member {Number} [count=1] Typically used to
         *  indicate the number of times an event,
         *  mark, or measure has been collected.
         */
        this.count = getValue(params, 'count', 1);

        /**
         * @member {String} [type="unknown"] The type
         *  of this instance. Built-in types include
         *  'event', 'timer', 'mark', 'measure',
         *  'network', 'context', 'metric', and
         *  'dimension'
         */
        this.type = getValue(params, 'type', 'unknown');

        /**
         * @member {String} [id] The unique id to associate
         *  with this instance. If not provided, a universally
         *  unique identifier will be generated automatically.
         */
        this.id = getValue(params, 'id', undefined) || generateUUID();

        /**
         * @member {Number} [start] The number of milliseconds since
         *  1/1/1970 before this instance was started. If not
         *  provided, defaults to the current date and time.
         */
        this.start = getValue(params, 'start', 'startTime', Stopwatch.now());

        /**
         * @member {Number} [stop] The number of milliseconds since
         *  1/1/1970 before this instance was stopped. If not
         *  provided, defaults to the start time.
         */
        this.stop = getValue(params, 'stop', 'stopTime', this.start);

        /**
         * @member {Number} [duration] The number of milliseconds
         *  between this instance's stop time and start time.
         */
        this.duration = this.stop - this.start;

        /**
         * @member {String} [label] The label to associate with
         *  this instance.
         */
        this.label = getValue(params, 'label', undefined);

        /**
         * @member {String} [action] The action to associate with
         *  this instance.
         */
        this.action = getValue(params, 'action', undefined);

        /**
         * @member {String} [category] The category to associate
         *  with this instance.
         */
        this.category = getValue(params, 'category', undefined);

        /**
         * @member {*} [variable] Some custom value to associate
         *  with this instance. Typically used in conjunction with
         *  data events to register some conditional state of the
         *  application (such as the number of options available
         *  to the user at a given decision point).
         */
        this.variable = getValue(params, 'variable', undefined);

        /**
         * @member {Array} [children] Contains any nested TrackingInfo
         *  instances. Timers and measures can both have children, but
         *  technically any custom data object with a `children` array
         *  will be attempted to be converted into TrackingInfo instances.
         */
        this.children = getValue(params, 'children', []).map(TrackingInfo);

        Object.keys(this).forEach(function(key) {
            delete this.data[key];
        }.bind(this));

        this.toString = function toString() {
            return 'TrackingInfo: ' + JSON.stringify(this, null, 2);
        };

        Object.freeze(this);

    };

});
<commit_msg>Fix for IE not resolving `crypto` against window.<commit_after>/* global window, define, Uint8Array: false */
define(['./Stopwatch'], function(Stopwatch) {

    'use strict';

    function getRandomValues(count) {
        var rands, d;
        if (window.crypto && window.crypto.getRandomValues) {
            rands = new Uint8Array(count);
            window.crypto.getRandomValues(rands);
        } else {
            rands = new Array(count);
            d = new Date().getTime();
            while (count--) {
                rands[count] = (d + Math.random() * 16) & 15;
            }
        }
        return rands;
    }

    function generateUUID() {
        var values = getRandomValues(36);
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
            .replace(/[xy]/g, function(c, i) {
                var r = values[i] & 15;
                return (c === 'x' ? r : (r & 0x3|0x8)).toString(16);
            });
    }

    function firstDefined() {
        var args = [].slice.call(arguments),
            result = args.shift();
        while (args.length && result === undefined) {
            result = args.shift();
        }
        return result;
    }

    function getValue(params) {

        var args = [].slice.call(arguments),
            def = args.pop(),
            names = args.slice(1);

        return names.reduce(function (prev, name) {
            return firstDefined((params.data || {})[name], params[name], prev);
        }, def);

    }

    function clone(obj) {
        return Object.keys(obj).reduce(function copy(result, key) {
            return result[key] = obj[key], result;
        }, {});
    }

    /**
     * Encapsulates the tracking information provided by all
     * tracking sources into a single consistent schema for
     * consumption by collectors.
     * @class TrackingInfo
     * @param {Object} params An object whose properties will
     *  be examined to set properties on the TrackingInfo
     *  instance.
     * @example
     * var info = new TrackingInfo({
     *   type: 'event',
     *   action: 'click',
     *   label: 'custom label'
     * });
     */
    return function TrackingInfo(params) {

        if (!(this instanceof TrackingInfo)) {
            return new TrackingInfo(params);
        }

        /**
         * @member {Object} [data] Any optional data
         *  associated with the current instance.
         */
        this.data = clone(params.data || {});

        /**
         * @member {Array} [tags] Any optional strings
         *  to associate with the current instance.
         */
        this.tags = getValue(params, 'tags', []);

        /**
         * @member {Number} [count=1] Typically used to
         *  indicate the number of times an event,
         *  mark, or measure has been collected.
         */
        this.count = getValue(params, 'count', 1);

        /**
         * @member {String} [type="unknown"] The type
         *  of this instance. Built-in types include
         *  'event', 'timer', 'mark', 'measure',
         *  'network', 'context', 'metric', and
         *  'dimension'
         */
        this.type = getValue(params, 'type', 'unknown');

        /**
         * @member {String} [id] The unique id to associate
         *  with this instance. If not provided, a universally
         *  unique identifier will be generated automatically.
         */
        this.id = getValue(params, 'id', undefined) || generateUUID();

        /**
         * @member {Number} [start] The number of milliseconds since
         *  1/1/1970 before this instance was started. If not
         *  provided, defaults to the current date and time.
         */
        this.start = getValue(params, 'start', 'startTime', Stopwatch.now());

        /**
         * @member {Number} [stop] The number of milliseconds since
         *  1/1/1970 before this instance was stopped. If not
         *  provided, defaults to the start time.
         */
        this.stop = getValue(params, 'stop', 'stopTime', this.start);

        /**
         * @member {Number} [duration] The number of milliseconds
         *  between this instance's stop time and start time.
         */
        this.duration = this.stop - this.start;

        /**
         * @member {String} [label] The label to associate with
         *  this instance.
         */
        this.label = getValue(params, 'label', undefined);

        /**
         * @member {String} [action] The action to associate with
         *  this instance.
         */
        this.action = getValue(params, 'action', undefined);

        /**
         * @member {String} [category] The category to associate
         *  with this instance.
         */
        this.category = getValue(params, 'category', undefined);

        /**
         * @member {*} [variable] Some custom value to associate
         *  with this instance. Typically used in conjunction with
         *  data events to register some conditional state of the
         *  application (such as the number of options available
         *  to the user at a given decision point).
         */
        this.variable = getValue(params, 'variable', undefined);

        /**
         * @member {Array} [children] Contains any nested TrackingInfo
         *  instances. Timers and measures can both have children, but
         *  technically any custom data object with a `children` array
         *  will be attempted to be converted into TrackingInfo instances.
         */
        this.children = getValue(params, 'children', []).map(TrackingInfo);

        Object.keys(this).forEach(function(key) {
            delete this.data[key];
        }.bind(this));

        this.toString = function toString() {
            return 'TrackingInfo: ' + JSON.stringify(this, null, 2);
        };

        Object.freeze(this);

    };

});
<|endoftext|>


<commit_before><commit_msg>initialize masonry in js file<commit_after>var container = document.querySelector('#project-gallery');
var msnry = new Masonry( container, {
	// options
	columnWidth: 200,
	itemSelector: ".project-box"
});<|endoftext|>


<commit_before>var Projects = {  }

Projects.start = function(projectID, button){
	Core.controlPulseDuration()
	Core.projects[projectID].engine = setTimeout(function(){
		Projects.pulse(projectID, button)
	}, Core.base.pulseDuration)
}

Projects.stop = function(projectID, isCancelled){
	clearInterval(Core.projects[projectID].timer)
	clearTimeout(Core.projects[projectID].engine)
	Core.projects[projectID].engine = null
	Core.projects[projectID].timer = null
	if(!isCancelled){
		Stats.money += Core.projects[projectID].profit
		Stats.companyValue += Core.projects[projectID].profit / 2
	}
	Core.updateHUD()
	// if(Core.hasImprovement('autoSaveOnProjectComplete')){
	// 	Core.save(true)
	// }else{
	// 	if(Stats.projects > 50 && !Core._('.startImprovement[data-type=autoSaveOnProjectComplete]')){
	// 		Core.showImprovementButton('autoSaveOnProjectComplete')
	// 	}
	// }
	if(Stats.projects > 4 && !Core.hasImprovement('addProject') && !Core._('.startImprovement[data-type=addProject]')){
		Core.showImprovementButton('addProject')
	}
	if(Stats.projects > 24 && !Shop.items.virtualPersonalAssistant.owned && !Shop.items.virtualPersonalAssistant.showing){
		Shop.showItemButton('virtualPersonalAssistant')
	}
}

Projects.pulse = function(projectID, button){
	var oscilatingPlus = 0
	if(Core.base.oscilatingValue > 0){
		oscilatingPlus = Core.base.moneyIncPerPulse * (Core.base.oscilatingValue / 10)
	}

	Core.projects[projectID].profit += Core.base.moneyIncPerPulse + Core.projects[projectID].moneyPlus
	Core.projects[projectID].profit += oscilatingPlus
	var profitText = button.getAttribute('data-profit')
	if(profitText){
		profitText = profitText.replace(/Profit: ([0-9]+\.*.*)¢/, 'Profit: ' + Core.numberFormat(Core.projects[projectID].profit))
		if(oscilatingPlus > 0){
			profitText += ' (+' + Core.numberFormat(Core.projects[projectID].moneyPlus + oscilatingPlus, '/pulse)')
		}
		button.setAttribute('data-profit', profitText)
	}
	Core.isRunning = false
	Core.controlPulseDuration()
	Core.updateHUD()
	Core.projects[projectID].engine = setTimeout(function(){
		Projects.pulse(projectID, button)
	}, Core.base.pulseDuration)
}

// Quick projects
Projects.quickProjectFinder = function(){
	clearInterval(window.quickProjectFinderTimeout)
	var time = Math.floor(Math.random() * Core.base.quickProjectsMaxTime) + Core.base.quickProjectsMinTime
	if(Core.base.quickProjectsFinderTimeMagnifier){
		time += time * (Stats.projects / 3)
	}
	time *= 1000
	window.quickProjectFinderTimeout = setTimeout(function(){
		Core._('#takeQuickProject').removeAttribute('disabled')
		document.title = 'Quick project available! | devLife'
		setTimeout(function(){
			Core._('#takeQuickProject').setAttribute('disabled', true)
			document.title = Stats.companyName + ' intranet | devLife'
			Projects.quickProjectFinder()
		}, 15000)
	}, time)
}

Projects.takeQuickProject = function(bthis){
	document.title = Stats.companyName + ' intranet | devLife'
	var button = document.createElement('BUTTON')
		button.className = 'startProject'
		button.innerText = button.textContent = 'Quick project '
		button.setAttribute('disabled', true)
	Core._('#projects-section').appendChild(button)
	Projects.startQuickProject(button)
	bthis.setAttribute('disabled', true)
}

Projects.startQuickProject = function(button){
	// Calcular tiempo (corto)
	var max = 10
	var min = 4
	var projectTime = Projects.calcQuickProjectTime(max, min)
	// Porcentage
	// Iniciar interval actualizando la barra de siempre
	button.style.position = 'relative'
	var bar = document.createElement('div')
		bar.className = 'projectProgress'
		button.appendChild(bar)
	var percent = 100
	var projectID = 'qproject-' + new Date().getTime()
	Core.projects[projectID] = {  }
	// Plus de ganancia por trabajador
	Core.projects[projectID].moneyPlus = Core.base.moneyIncPerPulse * (Core.calcEmployeesMoneyInc() || 1)
	Core.projects[projectID].moneyPlus += Core.projects[projectID].moneyPlus * ((30 - projectTime) / 100)
	Core.projects[projectID].profit = 0
	Core.projects[projectID].secondsLeft = projectTime
	button.setAttribute('data-profit', '(Time left: '+ Core.timeFormat(projectTime * 1000) +') (Profit: 0' + Core.base.moneyChar + ')')
	Core.projects[projectID].timer = setInterval(function(){
		Core.projects[projectID].profit += Core.projects[projectID].moneyPlus
		Core.projects[projectID].secondsLeft--
		bar.setAttribute('data-percent', percent)
		if(Core.projects[projectID].secondsLeft <= 0){
			clearInterval(Core.projects[projectID].timer)
			Projects.stop(projectID)
			button.parentNode.removeChild(button)
			Stats.projects++
			Core.updateHUD()
			Core.notification('Project finished', 'Profit: ' + Core.numberFormat(Core.projects[projectID].profit))
		}else{
			percent = (Core.projects[projectID].secondsLeft / projectTime) * 100
			bar.style.width = percent + '%'
		}
		var profitText = '(Time left: '+ Core.timeFormat(Core.projects[projectID].secondsLeft * 1000) +') (Profit: ' + Core.numberFormat(Core.projects[projectID].profit) + ')'
			button.setAttribute('data-profit', profitText)
	}, 1000)
}

Projects.calcQuickProjectTime = function(max, min){
	var projectTime = Math.floor(Math.random() * max) + min
		projectTime += projectTime * (Stats.projects / 100)
	return projectTime
}

// Projects
Projects.startProject = function(button){
	var max = 30
	var min = 10
	var projectTime = Projects.calcProjectTime(max, min)
	button.setAttribute('disabled', true)
	button.innerText = button.textContent = 'Project'
	// Botón con relleno de cuenta atrás
	button.style.position = 'relative'
	var bar = document.createElement('div')
		bar.className = 'projectProgress'
		button.appendChild(bar)
	var percent = 100
	var projectID = 'project-' + new Date().getTime()
	Core.projects[projectID] = {  }
	// Plus de ganancia
	Core.projects[projectID].moneyPlus = Core.base.moneyIncPerPulse * Core.calcEmployeesMoneyInc()
	if(Core.base.oscilatingValue > 0){
		Core.projects[projectID].moneyPlus += Core.base.moneyIncPerPulse * (Core.base.oscilatingValue / 10)
	}
	Core.projects[projectID].profit = 0
	Core.projects[projectID].secondsLeft = projectTime

	var profitText = '(Time left: '+ Core.timeFormat(projectTime * 1000) +') (Profit: 0' + Core.base.moneyChar + ')'
	if(Core.projects[projectID].moneyPlus > 0){
		profitText += ' (+' + Core.numberFormat(Core.projects[projectID].moneyPlus ) + ')'
	}
	button.setAttribute('data-profit', profitText)
	Projects.start(projectID, button)
	Core.projects[projectID].timer = setInterval(function(){
		if(Projects.isCancelled()){
			Projects.stop(projectID, true)
			button.removeAttribute('disabled')
			button.innerText = button.textContent = 'Start project'
			button.setAttribute('data-profit', '')
			Core.updateHUD()
			Core.notification('Your project has been cancelled', '')
			Core.showPopUp({
				'title': 'Your project has been cancelled',
				'description': 'Try again when the projects demand is possitive'
			})
		}
		Core.projects[projectID].secondsLeft--
		bar.setAttribute('data-percent', percent)
		var profitSecondsText = button.getAttribute('data-profit')
			profitSecondsText = profitSecondsText.replace(/Time left: \s*([0-9]+[h|m|s])*\s*([0-9]+[h|m|s])*\s*([0-9]+[h|m|s])*/g, 'Time left: ' + Core.timeFormat(Core.projects[projectID].secondsLeft * 1000))
			button.setAttribute('data-profit', profitSecondsText)
		if(Core.projects[projectID].secondsLeft <= 0){
			Projects.stop(projectID)
			button.removeAttribute('disabled')
			button.innerText = button.textContent = 'Start project'
			button.setAttribute('data-profit', '')
			Stats.projects++
			Core.updateHUD()
			Core.notification('Project finished', 'Profit: ' + Core.numberFormat(Core.projects[projectID].profit))
		}else{
			percent = (Core.projects[projectID].secondsLeft / projectTime) * 100
			bar.style.width = percent + '%'
		}
	}, 1000)
}

Projects.calcProjectTime = function(max, min){
	var projectTime = Math.floor(Math.random() * max) + min
		projectTime += projectTime * Math.round(Stats.projects / 10)
	console.info('% reducción de tiempo: ' + Core.base.projectTimeReductionPercent)
	console.info('Tiempo inicial del proyecto: ' + projectTime)
		projectTime -= projectTime * (Core.base.projectTimeReductionPercent / 100)
	console.info('Tiempo final del proyecto: ' + projectTime)
	return projectTime
}

Projects.isCancelled = function(){
	if(Core.base.oscilatingValue >= 0) return false
	var failPercent = Math.abs(Core.base.oscilatingValue) * 10
	var randomPercent = Math.floor(Math.random() * 100)
	// var experienceReduction = Stats.projects / 100
	// randomPercent -= randomPercent * experienceReduction
	return failPercent < randomPercent
}
<commit_msg>Balance changes<commit_after>var Projects = {  }

Projects.start = function(projectID, button){
	Core.controlPulseDuration()
	Core.projects[projectID].engine = setTimeout(function(){
		Projects.pulse(projectID, button)
	}, Core.base.pulseDuration)
}

Projects.stop = function(projectID, isCancelled){
	clearInterval(Core.projects[projectID].timer)
	clearTimeout(Core.projects[projectID].engine)
	Core.projects[projectID].engine = null
	Core.projects[projectID].timer = null
	if(!isCancelled){
		Stats.money += Core.projects[projectID].profit
		Stats.companyValue += Core.projects[projectID].profit / 2
	}else{
		Stats.money += Core.projects[projectID].profit / 2
	}
	Core.updateHUD()
	// if(Core.hasImprovement('autoSaveOnProjectComplete')){
	// 	Core.save(true)
	// }else{
	// 	if(Stats.projects > 50 && !Core._('.startImprovement[data-type=autoSaveOnProjectComplete]')){
	// 		Core.showImprovementButton('autoSaveOnProjectComplete')
	// 	}
	// }
	if(Stats.projects > 4 && !Core.hasImprovement('addProject') && !Core._('.startImprovement[data-type=addProject]')){
		Core.showImprovementButton('addProject')
	}
}

Projects.pulse = function(projectID, button){
	var oscilatingPlus = 0
	if(Core.base.oscilatingValue > 0){
		oscilatingPlus = Core.base.moneyIncPerPulse * (Core.base.oscilatingValue / 10)
	}

	Core.projects[projectID].profit += Core.base.moneyIncPerPulse + Core.projects[projectID].moneyPlus
	Core.projects[projectID].profit += oscilatingPlus
	var profitText = button.getAttribute('data-profit')
	if(profitText){
		profitText = profitText.replace(/Profit: ([0-9]+\.*.*)¢/, 'Profit: ' + Core.numberFormat(Core.projects[projectID].profit))
		if(oscilatingPlus > 0){
			profitText += ' (+' + Core.numberFormat(Core.projects[projectID].moneyPlus + oscilatingPlus, '/pulse)')
		}
		button.setAttribute('data-profit', profitText)
	}
	Core.isRunning = false
	Core.controlPulseDuration()
	Core.updateHUD()
	Core.projects[projectID].engine = setTimeout(function(){
		Projects.pulse(projectID, button)
	}, Core.base.pulseDuration)
}

// Quick projects
Projects.quickProjectFinder = function(){
	clearInterval(window.quickProjectFinderTimeout)
	var time = Math.floor(Math.random() * Core.base.quickProjectsMaxTime) + Core.base.quickProjectsMinTime
	if(Core.base.quickProjectsFinderTimeMagnifier){
		time += time * (Stats.projects / 3)
	}
	time *= 1000
	window.quickProjectFinderTimeout = setTimeout(function(){
		Core._('#takeQuickProject').removeAttribute('disabled')
		document.title = 'Quick project available! | devLife'
		setTimeout(function(){
			Core._('#takeQuickProject').setAttribute('disabled', true)
			document.title = Stats.companyName + ' intranet | devLife'
			Projects.quickProjectFinder()
		}, 15000)
	}, time)
}

Projects.takeQuickProject = function(bthis){
	document.title = Stats.companyName + ' intranet | devLife'
	var button = document.createElement('BUTTON')
		button.className = 'startProject'
		button.innerText = button.textContent = 'Quick project '
		button.setAttribute('disabled', true)
	Core._('#projects-section').appendChild(button)
	Projects.startQuickProject(button)
	bthis.setAttribute('disabled', true)
}

Projects.startQuickProject = function(button){
	// Calcular tiempo (corto)
	var max = 10
	var min = 4
	var projectTime = Projects.calcQuickProjectTime(max, min)
	// Porcentage
	// Iniciar interval actualizando la barra de siempre
	button.style.position = 'relative'
	var bar = document.createElement('div')
		bar.className = 'projectProgress'
		button.appendChild(bar)
	var percent = 100
	var projectID = 'qproject-' + new Date().getTime()
	Core.projects[projectID] = {  }
	// Plus de ganancia por trabajador
	Core.projects[projectID].moneyPlus = Core.base.moneyIncPerPulse * (Core.calcEmployeesMoneyInc() || 1)
	Core.projects[projectID].moneyPlus += Core.projects[projectID].moneyPlus * ((30 - projectTime) / 100)
	Core.projects[projectID].profit = 0
	Core.projects[projectID].secondsLeft = projectTime
	button.setAttribute('data-profit', '(Time left: '+ Core.timeFormat(projectTime * 1000) +') (Profit: 0' + Core.base.moneyChar + ')')
	Core.projects[projectID].timer = setInterval(function(){
		Core.projects[projectID].profit += Core.projects[projectID].moneyPlus
		Core.projects[projectID].secondsLeft--
		bar.setAttribute('data-percent', percent)
		if(Core.projects[projectID].secondsLeft <= 0){
			clearInterval(Core.projects[projectID].timer)
			Projects.stop(projectID)
			button.parentNode.removeChild(button)
			Stats.projects++
			Core.updateHUD()
			Core.notification('Project finished', 'Profit: ' + Core.numberFormat(Core.projects[projectID].profit))
		}else{
			percent = (Core.projects[projectID].secondsLeft / projectTime) * 100
			bar.style.width = percent + '%'
		}
		var profitText = '(Time left: '+ Core.timeFormat(Core.projects[projectID].secondsLeft * 1000) +') (Profit: ' + Core.numberFormat(Core.projects[projectID].profit) + ')'
			button.setAttribute('data-profit', profitText)
	}, 1000)
}

Projects.calcQuickProjectTime = function(max, min){
	var projectTime = Math.floor(Math.random() * max) + min
		projectTime += projectTime * (Stats.projects / 100)
	return projectTime
}

// Projects
Projects.startProject = function(button){
	var max = 30
	var min = 10
	var projectTime = Projects.calcProjectTime(max, min)
	button.setAttribute('disabled', true)
	button.innerText = button.textContent = 'Project'
	// Botón con relleno de cuenta atrás
	button.style.position = 'relative'
	var bar = document.createElement('div')
		bar.className = 'projectProgress'
		button.appendChild(bar)
	var percent = 100
	var projectID = 'project-' + new Date().getTime()
	Core.projects[projectID] = {  }
	// Plus de ganancia
	Core.projects[projectID].moneyPlus = Core.base.moneyIncPerPulse * Core.calcEmployeesMoneyInc()
	if(Core.base.oscilatingValue > 0){
		Core.projects[projectID].moneyPlus += Core.base.moneyIncPerPulse * (Core.base.oscilatingValue / 10)
	}
	Core.projects[projectID].profit = 0
	Core.projects[projectID].secondsLeft = projectTime

	var profitText = '(Time left: '+ Core.timeFormat(projectTime * 1000) +') (Profit: 0' + Core.base.moneyChar + ')'
	if(Core.projects[projectID].moneyPlus > 0){
		profitText += ' (+' + Core.numberFormat(Core.projects[projectID].moneyPlus ) + ')'
	}
	button.setAttribute('data-profit', profitText)
	Projects.start(projectID, button)
	Core.projects[projectID].timer = setInterval(function(){
		if(Projects.isCancelled()){
			Projects.stop(projectID, true)
			button.removeAttribute('disabled')
			button.innerText = button.textContent = 'Start project'
			button.setAttribute('data-profit', '')
			Core.updateHUD()
			Core.notification('Your project has been cancelled', '')
			Core.showPopUp({
				'title': 'Your project has been cancelled',
				'description': 'Try again when the projects demand is possitive'
			})
		}
		Core.projects[projectID].secondsLeft--
		bar.setAttribute('data-percent', percent)
		var profitSecondsText = button.getAttribute('data-profit')
			profitSecondsText = profitSecondsText.replace(/Time left: \s*([0-9]+[h|m|s])*\s*([0-9]+[h|m|s])*\s*([0-9]+[h|m|s])*/g, 'Time left: ' + Core.timeFormat(Core.projects[projectID].secondsLeft * 1000))
			button.setAttribute('data-profit', profitSecondsText)
		if(Core.projects[projectID].secondsLeft <= 0){
			Projects.stop(projectID)
			button.removeAttribute('disabled')
			button.innerText = button.textContent = 'Start project'
			button.setAttribute('data-profit', '')
			Stats.projects++
			Core.updateHUD()
			Core.notification('Project finished', 'Profit: ' + Core.numberFormat(Core.projects[projectID].profit))
		}else{
			percent = (Core.projects[projectID].secondsLeft / projectTime) * 100
			bar.style.width = percent + '%'
		}
	}, 1000)
}

Projects.calcProjectTime = function(max, min){
	var projectTime = Math.floor(Math.random() * max) + min
		projectTime += projectTime * Math.round(Stats.projects / 10)
		projectTime -= projectTime * (Core.base.projectTimeReductionPercent / 100)
	return projectTime
}

Projects.isCancelled = function(){
	if(Core.base.oscilatingValue >= 0) return false
	var fail = Math.abs(Core.base.oscilatingValue) / 100
	var shot = Math.random()
	return fail > shot
}
<|endoftext|>


<commit_before>  function readFile() {
      var files = document.getElementById('datafile').files;
      if (!files.length) {
          alert('Please select a file!');
          return;
      }

      var file = files[0];

      var reader = new FileReader();

      reader.onloadend = function(evt) {
          if (evt.target.readyState == FileReader.DONE) { // DONE == 2
              var contentArea = document.getElementById('file_content');
              var FileContens = evt.target.result;

              var resContent = parseFile(FileContens);
              contentArea.innerHTML = resContent.originalContent;
              contentArea.hidden = false;

              var parseArea = document.getElementById('parse_content');
              parseArea.textContent = resContent.parseContent;
              parseArea.hidden = false;

              // 顯示 存檔按鈕
              $("#button_save").show();

          }
      };

      reader.readAsText(file);
  }

  function saveFile()
  {
  	var textToWrite = document.getElementById("parse_content").textContent;
  	var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = "NewFile"
  	// var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

  	var downloadLink = document.createElement("a");
  	downloadLink.download = fileNameToSaveAs;
  	downloadLink.innerHTML = "Download File";
  	if (window.webkitURL != null)
  	{
  		// Chrome allows the link to be clicked
  		// without actually adding it to the DOM.
  		downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
  	}
  	else
  	{
  		// Firefox requires the link to be added to the DOM
  		// before it can be clicked.
  		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  		downloadLink.onclick = destroyClickedElement;
  		downloadLink.style.display = "none";
  		document.body.appendChild(downloadLink);
  	}

  	downloadLink.click();
  }
  function destroyClickedElement(event)
  {
  	document.body.removeChild(event.target);
  }

  function parseFile(FileContens) {

    var resultContent = {
      originalContent : "",
      parseContent : ""
    };

    // 將檔案內容以行為單位儲存
    var lines = FileContens.split('\n');

    // 處理每一行的內容
    for(var i = 0; i < lines.length; i++)
    {
      var line = lines[i];

      var originalResult, parseResult;
      var start = '';
      var end = '';

      if (isChapter(line)) {
        originalResult = start + line + end;
        parseResult = "<chapter> " + line;
      }
      else {
        originalResult = line;
        parseResult = line;
      }

      resultContent.originalContent = (resultContent.originalContent || "") + originalResult;
      resultContent.parseContent = (resultContent.parseContent || "") + parseResult + '\n';
    }

    return resultContent;
  }

  function isChapter(str) {
    var patt = /(第?([0-9]|[零一二三四五六七八九十百千零壹貳參肆伍陸柒捌玖拾佰仟初兩])+章)|楔子/i;

    if(str.search(patt) != -1)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
<commit_msg>新增 TextContent & ChapterObj 定義.<commit_after>// 定義 TextContent
function TextContent(content){
  this.content = content || "";
}
TextContent.prototype = {
  AddContent : function (content) {
    this.content += content;
  }
}
// 定義 ChapterObj
function ChapterObj(title, content){
  this.title = title || "";
  this.originContent = new TextContent(content || "");
  this.parsedContent = "";

  this.parse = function () {};
}
ChapterObj.prototype = {
  print : function () {
    return this.title + "\n" + this.originContent.content + "\n";
  },
  AddContent : function (content) {
    this.originContent.AddContent(content);
  },
  setParseFun : function (parseFunction) {
    this.parse = parseFunction;
  },
  runParse : function () {
    this.parse();
  }
}

  function readFile() {
      var files = document.getElementById('datafile').files;
      if (!files.length) {
          alert('Please select a file!');
          return;
      }

      var file = files[0];

      var reader = new FileReader();

      reader.onloadend = function(evt) {
          if (evt.target.readyState == FileReader.DONE) { // DONE == 2
              var contentArea = document.getElementById('file_content');
              var FileContens = evt.target.result;

              var resContent = parseFile(FileContens);
              contentArea.innerHTML = resContent.originalContent;
              contentArea.hidden = false;

              var parseArea = document.getElementById('parse_content');
              parseArea.textContent = resContent.parseContent;
              parseArea.hidden = false;

              // 顯示 存檔按鈕
              $("#button_save").show();

          }
      };

      reader.readAsText(file);
  }

  function saveFile()
  {
  	var textToWrite = document.getElementById("parse_content").textContent;
  	var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = "NewFile"
  	// var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

  	var downloadLink = document.createElement("a");
  	downloadLink.download = fileNameToSaveAs;
  	downloadLink.innerHTML = "Download File";
  	if (window.webkitURL != null)
  	{
  		// Chrome allows the link to be clicked
  		// without actually adding it to the DOM.
  		downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
  	}
  	else
  	{
  		// Firefox requires the link to be added to the DOM
  		// before it can be clicked.
  		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  		downloadLink.onclick = destroyClickedElement;
  		downloadLink.style.display = "none";
  		document.body.appendChild(downloadLink);
  	}

  	downloadLink.click();
  }
  function destroyClickedElement(event)
  {
  	document.body.removeChild(event.target);
  }

  function parseFile(FileContens) {

    var resultContent = {
      originalContent : "",
      parseContent : ""
    };

    // 將檔案內容以行為單位儲存
    var lines = FileContens.split('\n');

    // 處理每一行的內容
    for(var i = 0; i < lines.length; i++)
    {
      var line = lines[i];

      var originalResult, parseResult;
      var start = '';
      var end = '';

      if (isChapter(line)) {
        originalResult = start + line + end;
        parseResult = "<chapter> " + line;
      }
      else {
        originalResult = line;
        parseResult = line;
      }

      resultContent.originalContent = (resultContent.originalContent || "") + originalResult;
      resultContent.parseContent = (resultContent.parseContent || "") + parseResult + '\n';
    }

    return resultContent;
  }

  function isChapter(str) {
    var patt = /(第?([0-9]|[零一二三四五六七八九十百千零壹貳參肆伍陸柒捌玖拾佰仟初兩])+章)|楔子/i;

    if(str.search(patt) != -1)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
<|endoftext|>