<commit_before>"use strict";

class gswaSynth {
	constructor() {
		this._nodes = new Map();
		this._startedKeys = new Map();
		this.data = this._proxyCreate();
	}

	// Context, dis/connect
	// ........................................................................
	setContext( ctx ) {
		const oscs = this.data.oscillators;

		this.stopAllKeys();
		this.disconnect();
		this.ctx = ctx;
		Object.keys( oscs ).forEach( this._oscsDel, this );
		Object.entries( oscs ).forEach( ( [ id, osc ] ) => this._oscsAdd( id, osc ) );
	}
	setBPM( bpm ) {
		this._bps = bpm / 60;
	}
	connect( dest ) {
		this._nodes.forEach( obj => obj.gain.connect( dest ) );
		this.connectedTo = dest;
	}
	disconnect() {
		this._nodes.forEach( obj => obj.gain.disconnect() );
		this.connectedTo = null;
	}

	// Start/stop keys
	// ........................................................................
	stopAllKeys() {
		this._startedKeys.forEach( ( _key, id ) => this.stopKey( id ) );
	}
	stopKey( id ) {
		const key = this._startedKeys.get( id );

		if ( key ) {
			key.oscs.forEach( this._destroyOscNode, this );
			this._startedKeys.delete( id );
		} else {
			console.error( "gswaSynth: stopKey id invalid", id );
		}
	}
	startKey( blocks, when, off, dur ) {
		const id = ++gswaSynth._startedMaxId,
			oscs = new Map(),
			blcsLen = blocks.length,
			blc0 = blocks[ 0 ][ 1 ],
			blc0when = blc0.when,
			bps = this._bps,
			key = {
				oscs, when, off, dur,
				midi: blc0.key,
				gain: blc0.gain,
				pan: blc0.pan,
			};

		if ( blcsLen > 1 ) {
			key.variations = [];
			blocks.reduce( ( prev, [ , blc ] ) => {
				if ( prev ) {
					const prevWhen = prev.when - blc0when,
						when = ( prevWhen + prev.duration ) / bps;

					key.variations.push( {
						when,
						duration: ( blc.when - blc0when ) / bps - when,
						midi: [ prev.key, blc.key ],
						gain: [ prev.gain, blc.gain ],
						pan: [ prev.pan, blc.pan ],
					} );
				}
				return blc;
			}, null );
		}
		Object.keys( this.data.oscillators )
			.forEach( oscId => oscs.set( oscId, this._createOscNode( key, oscId ) ) );
		this._startedKeys.set( id, key );
		return id;
	}

	// default gain envelope
	_scheduleOscNodeGain( key, par ) {
		const va = key.variations,
			attDur = .002,
			relDur = .002,
			{ when, dur, gain } = key;

		par.cancelScheduledValues( 0 );
		if ( !va || va[ 0 ].when > key.off ) {
			if ( key.off < .0001 ) {
				par.setValueAtTime( 0, when );
				par.setValueCurveAtTime( new Float32Array( [ 0, gain ] ), when, attDur );
			} else {
				par.setValueAtTime( gain, when );
			}
		}
		if ( Number.isFinite( dur ) && dur - attDur >= relDur ) {
			const vaLast = va && va[ va.length - 1 ],
				relWhen = when + dur - relDur;

			if ( !vaLast || when - key.off + vaLast.when + vaLast.duration < relWhen ) {
				const gainEnd = vaLast ? vaLast.gain[ 1 ] : gain;

				par.setValueCurveAtTime( new Float32Array( [ gainEnd, 0 ] ), relWhen, relDur );
			}
		}
	}

	// keys linked, variations
	_scheduleVariations( key, freq, gain, pan ) {
		if ( key.variations ) {
			key.variations.forEach( va => {
				const when = key.when - key.off + va.when,
					dur = va.duration,
					freqArr = new Float32Array( [
						gswaSynth.midiKeyToHz[ va.midi[ 0 ] ],
						gswaSynth.midiKeyToHz[ va.midi[ 1 ] ]
					] );

				if ( when > this.ctx.currentTime && dur > 0 ) {
					freq.setValueCurveAtTime( freqArr, when, dur );
					gain.setValueCurveAtTime( new Float32Array( va.gain ), when, dur );
					pan.setValueCurveAtTime( new Float32Array( va.pan ), when, dur );
				}
			} );
		}
	}

	// createOscNode
	_createOscNode( key, oscId ) {
		const node = this.ctx.createOscillator(),
			gainNode = this.ctx.createGain(),
			panNode = this.ctx.createStereoPanner(),
			osc = this.data.oscillators[ oscId ],
			atTime = key.when - key.off;

		this._nodeOscSetType( node, osc.type );
		node._panNode = panNode;
		node._gainNode = gainNode;
		node.connect( panNode );
		panNode.connect( gainNode );
		gainNode.connect( this._nodes.get( oscId ).pan );
		node.frequency.setValueAtTime( gswaSynth.midiKeyToHz[ key.midi ], atTime );
		node.detune.setValueAtTime( osc.detune, atTime );
		panNode.pan.setValueAtTime( key.pan, atTime );
		this._scheduleOscNodeGain( key, gainNode.gain );
		this._scheduleVariations( key, node.frequency, gainNode.gain, panNode.pan );
		node.start( key.when );
		if ( Number.isFinite( key.dur ) ) {
			node.stop( key.when + key.dur );
		}
		return node;
	}
	_destroyOscNode( node ) {
		node.stop();
		node.disconnect();
		node._gainNode.disconnect();
	}
	_nodeOscSetType( node, type ) {
		if ( gswaSynth.nativeTypes.indexOf( type ) > -1 ) {
			node.type = type;
		} else {
			const w = gswaPeriodicWaves.get( type );

			node.setPeriodicWave( this.ctx.createPeriodicWave( w.real, w.imag ) );
		}
	}
	_oscsAdd( id, osc ) {
		const gain = this.ctx.createGain(),
			pan = this.ctx.createStereoPanner();

		this._nodes.set( id, { gain, pan } );
		pan.pan.value = osc.pan;
		gain.gain.value = osc.gain;
		pan.connect( gain );
		if ( this.connectedTo ) {
			gain.connect( this.connectedTo );
		}
		this._startedKeys.forEach( key => key.oscs.set( id, this._createOscNode( key, id ) ) );
	}
	_oscsDel( id ) {
		const obj = this._nodes.get( id );

		obj.pan.disconnect();
		obj.gain.disconnect();
		this._startedKeys.forEach( key => {
			this._destroyOscNode( key.oscs.get( id ) );
			key.oscs.delete( id );
		} );
		this._nodes.delete( id );
	}
	_oscsChangeProp( id, prop, val ) {
		switch ( prop ) {
			case "pan": this._nodes.get( id ).pan.pan.value = val; break;
			case "gain": this._nodes.get( id ).gain.gain.value = val; break;
			case "type":
			case "detune":
				this._startedKeys.forEach( prop === "detune"
					? key => key.oscs.get( id ).detune.value = val
					: key => this._nodeOscSetType( key.oscs.get( id ), val ) );
		}
	}

	// Data proxy
	// ........................................................................
	_proxyCreate() {
		return Object.freeze( {
			oscillators: new Proxy( {}, {
				set: this._proxyAddOsc.bind( this ),
				deleteProperty: this._proxyDelOsc.bind( this )
			} )
		} );
	}
	_proxyDelOsc( target, oscId ) {
		delete target[ oscId ];
		if ( this.ctx ) {
			this._oscsDel( oscId );
		}
		return true;
	}
	_proxyAddOsc( target, oscId, osc ) {
		if ( oscId in target && this.ctx ) {
			this._oscsDel( oscId );
		}
		osc = Object.assign( Object.seal( {
			order: 0,
			type: "sine",
			detune: 0,
			pan: 0,
			gain: 1,
		} ), osc );
		target[ oscId ] = new Proxy( osc, {
			set: this._proxySetOscProp.bind( this, oscId )
		} );
		if ( this.ctx ) {
			this._oscsAdd( oscId, osc );
		}
		return true;
	}
	_proxySetOscProp( oscId, target, prop, val ) {
		target[ prop ] = val;
		if ( this.ctx ) {
			this._oscsChangeProp( oscId, prop, val );
		}
		return true;
	}
}

gswaSynth._startedMaxId = 0;

gswaSynth.nativeTypes = [ "sine", "triangle", "sawtooth", "square" ];

gswaSynth.midiKeyToHz = ( new Array( 12 ) ).concat( [
	//
	  // 27.5,
	  // 29.1353,
	  // 30.8677,

	//
	  32.7032, // C1 24
	  34.6479,
	  36.7081,
	  38.8909,
	  41.2035,
	  43.6536,
	  46.2493,
	  48.9995,
	  51.9130,
	  55,
	  58.2705,
	  61.7354,

	//
	  65.4064,
	  69.2957,
	  73.4162,
	  77.7817,
	  82.4069,
	  87.3071,
	  92.4986,
	  97.9989,
	 103.826,
	 110,
	 116.541,
	 123.471,

	//
	 130.813,
	 138.591,
	 146.832,
	 155.563,
	 164.814,
	 174.614,
	 184.997,
	 195.998,
	 207.652,
	 220,
	 233.082,
	 246.942,

	//
	 261.626,
	 277.183,
	 293.665,
	 311.127,
	 329.628,
	 349.228,
	 369.994,
	 391.995,
	 415.305,
	 440,
	 466.164,
	 493.883,

	//
	 523.251,
	 554.365,
	 587.33,
	 622.254,
	 659.255,
	 698.456,
	 739.989,
	 783.991,
	 830.609,
	 880,
	 932.328,
	 987.767,

	//
	1046.5,
	1108.73,
	1174.66,
	1244.51,
	1318.51,
	1396.91,
	1479.98,
	1567.98,
	1661.22,
	1760,
	1864.66,
	1975.53,

	//
	2093,
	2217.46,
	2349.32,
	2489.02,
	2637.02,
	2793.83,
	2959.96,
	3135.96,
	3322.44,
	3520,
	3729.31,
	3951.07,

	//
	4186.01,
] );
<commit_msg>gswaSynth: coding style<commit_after>"use strict";

class gswaSynth {
	constructor() {
		this._nodes = new Map();
		this._startedKeys = new Map();
		this.data = this._proxyCreate();
	}

	// Context, dis/connect
	// ........................................................................
	setContext( ctx ) {
		const oscs = this.data.oscillators;

		this.stopAllKeys();
		this.disconnect();
		this.ctx = ctx;
		Object.keys( oscs ).forEach( this._oscsDel, this );
		Object.entries( oscs ).forEach( ( [ id, osc ] ) => this._oscsAdd( id, osc ) );
	}
	setBPM( bpm ) {
		this._bps = bpm / 60;
	}
	connect( dest ) {
		this._nodes.forEach( obj => obj.gain.connect( dest ) );
		this.connectedTo = dest;
	}
	disconnect() {
		this._nodes.forEach( obj => obj.gain.disconnect() );
		this.connectedTo = null;
	}

	// Start/stop keys
	// ........................................................................
	stopAllKeys() {
		this._startedKeys.forEach( ( _key, id ) => this.stopKey( id ) );
	}
	stopKey( id ) {
		const key = this._startedKeys.get( id );

		if ( key ) {
			key.oscs.forEach( this._destroyOscNode, this );
			this._startedKeys.delete( id );
		} else {
			console.error( "gswaSynth: stopKey id invalid", id );
		}
	}
	startKey( blocks, when, off, dur ) {
		const id = ++gswaSynth._startedMaxId,
			oscs = new Map(),
			blcsLen = blocks.length,
			blc0 = blocks[ 0 ][ 1 ],
			blc0when = blc0.when,
			bps = this._bps,
			key = {
				oscs, when, off, dur,
				midi: blc0.key,
				gain: blc0.gain,
				pan: blc0.pan,
			};

		if ( blcsLen > 1 ) {
			key.variations = [];
			blocks.reduce( ( prev, [ , blc ] ) => {
				if ( prev ) {
					const prevWhen = prev.when - blc0when,
						when = ( prevWhen + prev.duration ) / bps;

					key.variations.push( {
						when,
						duration: ( blc.when - blc0when ) / bps - when,
						midi: [ prev.key, blc.key ],
						gain: [ prev.gain, blc.gain ],
						pan: [ prev.pan, blc.pan ],
					} );
				}
				return blc;
			}, null );
		}
		Object.keys( this.data.oscillators )
			.forEach( oscId => oscs.set( oscId, this._createOscNode( key, oscId ) ) );
		this._startedKeys.set( id, key );
		return id;
	}

	// default gain envelope
	_scheduleOscNodeGain( key, par ) {
		const va = key.variations,
			attDur = .002,
			relDur = .002,
			{ when, dur, gain } = key;

		par.cancelScheduledValues( 0 );
		if ( !va || va[ 0 ].when > key.off ) {
			if ( key.off < .0001 ) {
				par.setValueAtTime( 0, when );
				par.setValueCurveAtTime( new Float32Array( [ 0, gain ] ), when, attDur );
			} else {
				par.setValueAtTime( gain, when );
			}
		}
		if ( Number.isFinite( dur ) && dur - attDur >= relDur ) {
			const vaLast = va && va[ va.length - 1 ],
				relWhen = when + dur - relDur;

			if ( !vaLast || when - key.off + vaLast.when + vaLast.duration < relWhen ) {
				const gainEnd = vaLast ? vaLast.gain[ 1 ] : gain;

				par.setValueCurveAtTime( new Float32Array( [ gainEnd, 0 ] ), relWhen, relDur );
			}
		}
	}

	// keys linked, variations
	_scheduleVariations( key, freq, gain, pan ) {
		if ( key.variations ) {
			key.variations.forEach( va => {
				const when = key.when - key.off + va.when,
					dur = va.duration,
					freqArr = new Float32Array( [
						gswaSynth.midiKeyToHz[ va.midi[ 0 ] ],
						gswaSynth.midiKeyToHz[ va.midi[ 1 ] ]
					] );

				if ( when > this.ctx.currentTime && dur > 0 ) {
					freq.setValueCurveAtTime( freqArr, when, dur );
					gain.setValueCurveAtTime( new Float32Array( va.gain ), when, dur );
					pan.setValueCurveAtTime( new Float32Array( va.pan ), when, dur );
				}
			} );
		}
	}

	// createOscNode
	_createOscNode( key, oscId ) {
		const node = this.ctx.createOscillator(),
			gainNode = this.ctx.createGain(),
			panNode = this.ctx.createStereoPanner(),
			osc = this.data.oscillators[ oscId ],
			atTime = key.when - key.off;

		this._nodeOscSetType( node, osc.type );
		node._panNode = panNode;
		node._gainNode = gainNode;
		node.connect( panNode );
		panNode.connect( gainNode );
		gainNode.connect( this._nodes.get( oscId ).pan );
		node.frequency.setValueAtTime( gswaSynth.midiKeyToHz[ key.midi ], atTime );
		node.detune.setValueAtTime( osc.detune, atTime );
		panNode.pan.setValueAtTime( key.pan, atTime );
		this._scheduleOscNodeGain( key, gainNode.gain );
		this._scheduleVariations( key, node.frequency, gainNode.gain, panNode.pan );
		node.start( key.when );
		if ( Number.isFinite( key.dur ) ) {
			node.stop( key.when + key.dur );
		}
		return node;
	}
	_destroyOscNode( node ) {
		node.stop();
		node.disconnect();
		node._gainNode.disconnect();
	}
	_nodeOscSetType( node, type ) {
		if ( gswaSynth.nativeTypes.indexOf( type ) > -1 ) {
			node.type = type;
		} else {
			const w = gswaPeriodicWaves.get( type );

			node.setPeriodicWave( this.ctx.createPeriodicWave( w.real, w.imag ) );
		}
	}
	_oscsAdd( id, osc ) {
		const gain = this.ctx.createGain(),
			pan = this.ctx.createStereoPanner();

		this._nodes.set( id, { gain, pan } );
		pan.pan.value = osc.pan;
		gain.gain.value = osc.gain;
		pan.connect( gain );
		if ( this.connectedTo ) {
			gain.connect( this.connectedTo );
		}
		this._startedKeys.forEach( key => key.oscs.set( id, this._createOscNode( key, id ) ) );
	}
	_oscsDel( id ) {
		const obj = this._nodes.get( id );

		obj.pan.disconnect();
		obj.gain.disconnect();
		this._startedKeys.forEach( key => {
			this._destroyOscNode( key.oscs.get( id ) );
			key.oscs.delete( id );
		} );
		this._nodes.delete( id );
	}
	_oscsChangeProp( id, prop, val ) {
		switch ( prop ) {
			case "pan": this._nodes.get( id ).pan.pan.value = val; break;
			case "gain": this._nodes.get( id ).gain.gain.value = val; break;
			case "type":
			case "detune":
				this._startedKeys.forEach( prop === "detune"
					? key => key.oscs.get( id ).detune.value = val
					: key => this._nodeOscSetType( key.oscs.get( id ), val ) );
		}
	}

	// Data proxy
	// ........................................................................
	_proxyCreate() {
		return Object.freeze( {
			oscillators: new Proxy( {}, {
				set: this._proxyAddOsc.bind( this ),
				deleteProperty: this._proxyDelOsc.bind( this )
			} )
		} );
	}
	_proxyDelOsc( tar, oscId ) {
		delete tar[ oscId ];
		if ( this.ctx ) {
			this._oscsDel( oscId );
		}
		return true;
	}
	_proxyAddOsc( tar, oscId, oscObj ) {
		const oscTar = Object.assign( Object.seal( {
				order: 0,
				type: "sine",
				detune: 0,
				pan: 0,
				gain: 1,
			} ), oscObj ),
			osc = new Proxy( oscTar, {
				set: this._proxySetOscProp.bind( this, oscId )
			} );

		if ( oscId in tar && this.ctx ) {
			this._oscsDel( oscId );
		}
		tar[ oscId ] = osc;
		if ( this.ctx ) {
			this._oscsAdd( oscId, osc );
		}
		return true;
	}
	_proxySetOscProp( oscId, tar, prop, val ) {
		tar[ prop ] = val;
		if ( this.ctx ) {
			this._oscsChangeProp( oscId, prop, val );
		}
		return true;
	}
}

gswaSynth._startedMaxId = 0;

gswaSynth.nativeTypes = [ "sine", "triangle", "sawtooth", "square" ];

gswaSynth.midiKeyToHz = ( new Array( 12 ) ).concat( [
	//
	  // 27.5,
	  // 29.1353,
	  // 30.8677,

	//
	  32.7032, // C1 24
	  34.6479,
	  36.7081,
	  38.8909,
	  41.2035,
	  43.6536,
	  46.2493,
	  48.9995,
	  51.9130,
	  55,
	  58.2705,
	  61.7354,

	//
	  65.4064,
	  69.2957,
	  73.4162,
	  77.7817,
	  82.4069,
	  87.3071,
	  92.4986,
	  97.9989,
	 103.826,
	 110,
	 116.541,
	 123.471,

	//
	 130.813,
	 138.591,
	 146.832,
	 155.563,
	 164.814,
	 174.614,
	 184.997,
	 195.998,
	 207.652,
	 220,
	 233.082,
	 246.942,

	//
	 261.626,
	 277.183,
	 293.665,
	 311.127,
	 329.628,
	 349.228,
	 369.994,
	 391.995,
	 415.305,
	 440,
	 466.164,
	 493.883,

	//
	 523.251,
	 554.365,
	 587.33,
	 622.254,
	 659.255,
	 698.456,
	 739.989,
	 783.991,
	 830.609,
	 880,
	 932.328,
	 987.767,

	//
	1046.5,
	1108.73,
	1174.66,
	1244.51,
	1318.51,
	1396.91,
	1479.98,
	1567.98,
	1661.22,
	1760,
	1864.66,
	1975.53,

	//
	2093,
	2217.46,
	2349.32,
	2489.02,
	2637.02,
	2793.83,
	2959.96,
	3135.96,
	3322.44,
	3520,
	3729.31,
	3951.07,

	//
	4186.01,
] );
<|endoftext|>


<commit_before>  var goog = /^https?:\/\/(.*?)google(.*?)/;
  // Author choice to narrow down to a specific url
  if (goog.test(location.href)) {
    document.addEventListener("DOMContentLoaded", function(){
      console.log(prefix + "Loading tour button onto Google web page");
      // Let's attach a Take Tour button to the page
      //

▶ Tour

      var googtophf = document.getElementById("tophf");
      var a = document.createElement('input');
      a.setAttribute('id', 'googtour');
      a.setAttribute('aria-label','Google Tour');
      a.setAttribute('name', 'googtour');
      a.setAttribute('type', 'submit');
      a.setAttribute('value', 'Web Tour');
      googtophf.append(a);
      console.log(prefix + "Tour Button injected on Google WebSite...");
      console.log(prefix + "Happy Touring from the IBM CP4MCM Team!");

      var t = document.createElement ('script');
      t.src = "https://raw.githack.com/joshisa/huemix-blopscotch/master/tour/google.js";
      document.body.appendChild(t);
    });
  }
<commit_msg>Update google demo<commit_after>  var prefix = "Huemix-Blopscotch:: ";
  var goog = /^https?:\/\/(.*?)google(.*?)/;
  // Author choice to narrow down to a specific url
  if (goog.test(location.href)) {
    document.addEventListener("DOMContentLoaded", function(){
      console.log(prefix + "Loading tour button onto Google web page");
      // Let's attach a Take Tour button to the page
      //

▶ Tour

      var googtophf = document.getElementById("tophf");
      var a = document.createElement('input');
      a.setAttribute('id', 'googtour');
      a.setAttribute('aria-label','Google Tour');
      a.setAttribute('name', 'googtour');
      a.setAttribute('type', 'submit');
      a.setAttribute('value', 'Web Tour');
      googtophf.append(a);
      console.log(prefix + "Tour Button injected on Google WebSite...");
      console.log(prefix + "Happy Touring from the IBM CP4MCM Team!");

      var t = document.createElement ('script');
      t.src = "https://raw.githack.com/joshisa/huemix-blopscotch/master/tour/google.js";
      document.body.appendChild(t);
    });
  }
<|endoftext|>


<commit_before>'use strict';

var EventEmitter = require('events').EventEmitter,
    util = require('util'),
    _ = require('lodash');

function ConnectionCollection() {
    this.connections = {};

    this.get = this.get.bind(this);
    this.getUsers = this.getUsers.bind(this);
    this.getUserIds = this.getUserIds.bind(this);

    this.add = this.add.bind(this);
    this.remove = this.remove.bind(this);
    this.removeAll = this.removeAll.bind(this);
}

ConnectionCollection.prototype.get = function(connectionId) {
    return this.connections[connectionId];
};

ConnectionCollection.prototype.getUsers = function(filter) {
    var connections = this.connections;

    if (filter) {
        connections = this.query(filter);
    }

    var users = _.map(connections, function(value, key) {
        return value.user;
    });

    return _.uniq(users, 'id');
};

ConnectionCollection.prototype.getUserIds = function(filter) {
    var connections = this.connections;

    if (filter) {
        connections = this.query(filter);
    }

    var userIds = _.map(connections, function(value, key) {
        return value.user.id;
    });

    return _.uniq(userIds);
};

ConnectionCollection.prototype.getUsernames = function(filter) {
    var connections = this.connections;

    if (filter) {
        connections = this.query(filter);
    }

    var usernames = _.map(connections, function(value, key) {
        return value.user.username;
    });

    return _.uniq(usernames);
};

ConnectionCollection.prototype.query = function(options) {
    if (options.userId) {
        options.userId = options.userId.toString();
    }

    return _.map(this.connections, function(value, key) {
        return value;
    }).filter(function(conn) {
        var result = true;

        if (options.user) {
            var u = options.user;
            if (conn.user.id !== u && conn.user.username !== u) {
                result = false;
            }
        }

        if (options.userId && conn.user.id !== options.userId) {
            result = false;
        }

        if (options.type && conn.type !== options.type) {
            result = false;
        }

        return result;

    });
};

ConnectionCollection.prototype.byType = function(type) {
    return _.map(this.connections, function(value, key) {
        return value;
    }).filter(function(conn) {
        return conn.type === type;
    });
};

ConnectionCollection.prototype.add = function(connection) {
    this.connections[connection.id] = connection;
};

ConnectionCollection.prototype.remove = function(connection) {
    if (!connection) {
        return;
    }

    var connId = typeof connection === 'string' ? connection : connection.id;
    if (this.connections[connId]) {
        delete this.connections[connId];
        return true;
    } else {
        return false;
    }
};

ConnectionCollection.prototype.removeAll = function() {
    var keys = Object.keys(this.connections);

    keys.forEach(function(key) {
        delete this.connections[key];
    }, this);

    return true;
};

module.exports = ConnectionCollection;
<commit_msg>Cleaned up methods on ConnectionCollection<commit_after>'use strict';

var EventEmitter = require('events').EventEmitter,
    util = require('util'),
    _ = require('lodash');

function ConnectionCollection() {
    this.connections = {};

    this.get = this.get.bind(this);
    this.getUsers = this.getUsers.bind(this);
    this.getUserIds = this.getUserIds.bind(this);
    this.getUsernames = this.getUsernames.bind(this);

    this.add = this.add.bind(this);
    this.remove = this.remove.bind(this);
    this.removeAll = this.removeAll.bind(this);
}

ConnectionCollection.prototype.get = function(connectionId) {
    return this.connections[connectionId];
};

ConnectionCollection.prototype.getUsers = function(filter) {
    var connections = this.connections;

    if (filter) {
        connections = this.query(filter);
    }

    var users = _.chain(connections)
                .filter(function(value, key) {
                    return !!value.user;
                })
                .map(function(value, key) {
                    return value.user;
                })
                .uniq('id')
                .value();

    return users;
};

ConnectionCollection.prototype.getUserIds = function(filter) {
    var users = this.getUsers(filter);

    return _.map(users, function(user) {
        return user.id;
    });
};

ConnectionCollection.prototype.getUsernames = function(filter) {
    var users = this.getUsers(filter);

    return _.map(users, function(user) {
        return user.username;
    });
};

ConnectionCollection.prototype.query = function(options) {
    if (options.userId) {
        options.userId = options.userId.toString();
    }

    return _.map(this.connections, function(value, key) {
        return value;
    }).filter(function(conn) {
        var result = true;

        if (options.user) {
            var u = options.user;
            if (conn.user.id !== u && conn.user.username !== u) {
                result = false;
            }
        }

        if (options.userId && conn.user.id !== options.userId) {
            result = false;
        }

        if (options.type && conn.type !== options.type) {
            result = false;
        }

        return result;

    });
};

ConnectionCollection.prototype.byType = function(type) {
    return _.map(this.connections, function(value, key) {
        return value;
    }).filter(function(conn) {
        return conn.type === type;
    });
};

ConnectionCollection.prototype.add = function(connection) {
    this.connections[connection.id] = connection;
};

ConnectionCollection.prototype.remove = function(connection) {
    if (!connection) {
        return;
    }

    var connId = typeof connection === 'string' ? connection : connection.id;
    if (this.connections[connId]) {
        delete this.connections[connId];
        return true;
    } else {
        return false;
    }
};

ConnectionCollection.prototype.removeAll = function() {
    var keys = Object.keys(this.connections);

    keys.forEach(function(key) {
        delete this.connections[key];
    }, this);

    return true;
};

module.exports = ConnectionCollection;
<|endoftext|>


<commit_before>import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?autoConnect=false'
import Router from '../lib/router'

const {
  __NEXT_DATA__: {
    assetPrefix
  }
} = window

export default () => {
  webpackHotMiddlewareClient.setOptionsAndConnect({
    overlay: false,
    reload: true,
    path: `${assetPrefix}/_next/webpack-hmr`
  })

  const handlers = {
    reload (route) {
      if (route === '/_error') {
        for (const r of Object.keys(Router.components)) {
          const { err } = Router.components[r]
          if (err) {
            // reload all error routes
            // which are expected to be errors of '/_error' routes
            Router.reload(r)
          }
        }
        return
      }

      if (route === '/_document') {
        window.location.reload()
        return
      }

      Router.reload(route)
    },

    change (route) {
      if (route === '/_document') {
        window.location.reload()
        return
      }

      const { err, Component } = Router.components[route] || {}

      if (err) {
        // reload to recover from runtime errors
        Router.reload(route)
      }

      if (Router.route !== route) {
        // If this is a not a change for a currently viewing page.
        // We don't need to worry about it.
        return
      }

      if (!Component) {
        // This only happens when we create a new page without a default export.
        // If you removed a default export from a exising viewing page, this has no effect.
        console.log(`Hard reloading due to no default component in page: ${route}`)
        window.location.reload()
      }
    }
  }

  webpackHotMiddlewareClient.subscribe((obj) => {
    const fn = handlers[obj.action]
    if (fn) {
      const data = obj.data || []
      fn(...data)
    } else {
      throw new Error('Unexpected action ' + obj.action)
    }
  })
}
<commit_msg>Fixes overlay showing randomly (#3885)<commit_after>import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?autoConnect=false'
import Router from '../lib/router'

const {
  __NEXT_DATA__: {
    assetPrefix
  }
} = window

export default () => {
  webpackHotMiddlewareClient.setOptionsAndConnect({
    overlay: 'false',
    reload: 'true',
    path: `${assetPrefix}/_next/webpack-hmr`
  })

  const handlers = {
    reload (route) {
      if (route === '/_error') {
        for (const r of Object.keys(Router.components)) {
          const { err } = Router.components[r]
          if (err) {
            // reload all error routes
            // which are expected to be errors of '/_error' routes
            Router.reload(r)
          }
        }
        return
      }

      if (route === '/_document') {
        window.location.reload()
        return
      }

      Router.reload(route)
    },

    change (route) {
      if (route === '/_document') {
        window.location.reload()
        return
      }

      const { err, Component } = Router.components[route] || {}

      if (err) {
        // reload to recover from runtime errors
        Router.reload(route)
      }

      if (Router.route !== route) {
        // If this is a not a change for a currently viewing page.
        // We don't need to worry about it.
        return
      }

      if (!Component) {
        // This only happens when we create a new page without a default export.
        // If you removed a default export from a exising viewing page, this has no effect.
        console.log(`Hard reloading due to no default component in page: ${route}`)
        window.location.reload()
      }
    }
  }

  webpackHotMiddlewareClient.subscribe((obj) => {
    const fn = handlers[obj.action]
    if (fn) {
      const data = obj.data || []
      fn(...data)
    } else {
      throw new Error('Unexpected action ' + obj.action)
    }
  })
}
<|endoftext|>


<commit_before>var Game = Game || {};

Game.Snake = function(width, height, options) {
  'use strict';
  this.width = width;
  this.height = height;
  this.blockWidth = options.blockWidth || 20;
  this.blockHeight = options.blockHeight || 20;
  var columns = Math.round(this.width / this.blockWidth);
  var rows = Math.round(this.height / this.blockHeight);
  var midCol = Math.floor(columns / 2);
  var midRow = Math.floor(rows / 2);
  this.snake = [[midCol, midRow], [midCol - 1, midRow], [midCol - 2, midRow]];
  this.direction = 'right';
  this.pause = false
};

Game.Snake.prototype.DIRECTIONS = {
  UP: 'up',
  RIGHT: 'right',
  DOWN: 'down',
  LEFT: 'left'
};

Game.Snake.prototype.blockPosition = function(col, row) {
  'use strict';
  return {
    x: col * this.blockWidth,
    y: row * this.blockHeight
  };
};

Game.Snake.prototype.moveSnake = function() {
  'use strict';
  var headX = this.snake[0][0];
  var headY = this.snake[0][1];

  if (this.direction === this.DIRECTIONS.UP) {
    headY -= 1;
  } else if (this.direction === this.DIRECTIONS.RIGHT) {
    headX += 1;
  } else if (this.direction === this.DIRECTIONS.DOWN) {
    headY += 1;
  } else if (this.direction === this.DIRECTIONS.LEFT) {
    headX -= 1;
  }

  var tail = this.snake.pop();
  tail = [headX, headY];
  this.snake.unshift(tail);
};

Game.Snake.prototype.update = function(inputHandler) {
  'use strict';
  if (inputHandler.pressed && inputHandler.isDown('ESC')) {
    this.pause = !this.pause;
  }

  if (!this.pause) {
    if (inputHandler.isDown('UP')) {
      this.direction = this.DIRECTIONS.UP;
    } else if (inputHandler.isDown('RIGHT')) {
      this.direction = this.DIRECTIONS.RIGHT;
    } else if (inputHandler.isDown('DOWN')) {
      this.direction = this.DIRECTIONS.DOWN;
    } else if (inputHandler.isDown('LEFT')) {
      this.direction = this.DIRECTIONS.LEFT;
    }
    this.moveSnake();
  }
};

Game.Snake.prototype.render = function(context) {
  'use strict';
  var coordinates, textMeasure;
  var self = this;

  context.beginPath();
  context.fillStyle = '#000000';
  context.fillRect(0, 0, this.width, this.height);
  context.closePath();

  context.beginPath();
  this.snake.forEach(function(s) {
    coordinates = self.blockPosition(s[0], s[1]);
    context.fillStyle = '#FFFFFF';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                 self.blockHeight);
    context.lineWidth = "1";
    context.strokeStyle = '#000000';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                      self.blockHeight);
  });
  context.closePath();
  context.fill();
  context.stroke();

  if (this.pause) {
    context.beginPath();
    context.font = 'bold 120px Helvetica, Verdana, san-serif';
    context.fillStyle = '#FFDD88';
    textMeasure = context.measureText('Paused').width;
    context.fillText('Paused', (this.width / 2) - (textMeasure / 2), this.height / 2);
    context.closePath();
  }
};
<commit_msg>Add game over condition<commit_after>var Game = Game || {};

Game.Snake = function(width, height, options) {
  'use strict';
  this.width = width;
  this.height = height;
  this.blockWidth = options.blockWidth || 20;
  this.blockHeight = options.blockHeight || 20;
  this.columns = Math.round(this.width / this.blockWidth);
  this.rows = Math.round(this.height / this.blockHeight);
  var midCol = Math.floor(this.columns / 2);
  var midRow = Math.floor(this.rows / 2);
  this.snake = [[midCol, midRow], [midCol - 1, midRow], [midCol - 2, midRow]];
  this.direction = 'right';
  this.pause = false;
  this.gameOver = false;
};

Game.Snake.prototype.DIRECTIONS = {
  UP: 'up',
  RIGHT: 'right',
  DOWN: 'down',
  LEFT: 'left'
};

Game.Snake.prototype.blockPosition = function(col, row) {
  'use strict';
  return {
    x: col * this.blockWidth,
    y: row * this.blockHeight
  };
};

Game.Snake.prototype.moveSnake = function() {
  'use strict';
  var headX = this.snake[0][0];
  var headY = this.snake[0][1];

  if (this.direction === this.DIRECTIONS.UP) {
    headY -= 1;
  } else if (this.direction === this.DIRECTIONS.RIGHT) {
    headX += 1;
  } else if (this.direction === this.DIRECTIONS.DOWN) {
    headY += 1;
  } else if (this.direction === this.DIRECTIONS.LEFT) {
    headX -= 1;
  }

  var tail = this.snake.pop();
  tail = [headX, headY];
  this.snake.unshift(tail);
};

Game.Snake.prototype.isIntersecting = function(element, arr) {
  'use strict';
  return arr.some(function(a) {
    return a[0] === element[0] && a[1] === element[1];
  });
};

Game.Snake.prototype.isGameOver = function() {
  'use strict';
  var head = this.snake[0];
  if (head[0] < 0 || head[0] >= this.columns ||
     head[1] < 0 || head[1] >= this.rows ||
     this.isIntersecting(head, this.snake.slice(1))) {
    return true;
  }
  return false;
};

Game.Snake.prototype.update = function(inputHandler) {
  'use strict';

  this.gameOver = this.isGameOver();
  if (!this.gameOver) {

    if (inputHandler.pressed && inputHandler.isDown('ESC')) {
      this.pause = !this.pause;
    }
    if (!this.pause) {
      if (inputHandler.isDown('UP')) {
        this.direction = this.DIRECTIONS.UP;
      } else if (inputHandler.isDown('RIGHT')) {
        this.direction = this.DIRECTIONS.RIGHT;
      } else if (inputHandler.isDown('DOWN')) {
        this.direction = this.DIRECTIONS.DOWN;
      } else if (inputHandler.isDown('LEFT')) {
        this.direction = this.DIRECTIONS.LEFT;
      }
      this.moveSnake();
    }
  }
};

Game.Snake.prototype.render = function(context) {
  'use strict';
  var coordinates, textMeasure;
  var self = this;

  context.beginPath();
  context.fillStyle = '#000000';
  context.fillRect(0, 0, this.width, this.height);
  context.closePath();

  context.beginPath();
  this.snake.forEach(function(s) {
    coordinates = self.blockPosition(s[0], s[1]);
    context.fillStyle = '#FFFFFF';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                 self.blockHeight);
    context.lineWidth = "1";
    context.strokeStyle = '#000000';
    context.rect(coordinates.x, coordinates.y, self.blockWidth,
                      self.blockHeight);
  });
  context.closePath();
  context.fill();
  context.stroke();

  if (this.pause) {
    context.beginPath();
    context.font = 'bold 120px Helvetica, Verdana, san-serif';
    context.fillStyle = '#FFDD88';
    textMeasure = context.measureText('Paused').width;
    context.fillText('Paused', (this.width / 2) - (textMeasure / 2), this.height / 2);
    context.closePath();
  }

  if (this.gameOver) {
    context.beginPath();
    context.font = 'bold 120px Helvetica, Verdana, san-serif';
    context.fillStyle = '#FFDD88';
    textMeasure = context.measureText('Game Over').width;
    context.fillText('Game Over', (this.width / 2) - (textMeasure / 2), this.height / 2);
    context.closePath();
  }
};
<|endoftext|>


<commit_before>module.exports = {
  rules: {}
};
<commit_msg>Add rule override for chai<commit_after>module.exports = {
  rules: {
    // disallow usage of expressions in statement position
    'no-unused-expressions': 0
  }
};
<|endoftext|>


<commit_before>import {log} from 'gulp-util';
import {exec} from 'child_process';
import promisify from 'es6-promisify';
import gulp from 'gulp';
import {infoForUpdatedPackages, publishPackages} from './helpers/publish-helper';
import runSequence from 'run-sequence';

const execPromise = promisify(exec);

gulp.task('set-styleguide-env-to-production', () => process.env.STYLEGUIDE_ENV = 'production');

gulp.task('release-push-git-verify', async () => {
  const currentSha = await execPromise('git rev-parse HEAD');
  const masterSha = await execPromise('git rev-parse master');
  if (currentSha !== masterSha) {
    log('Error: You must be on master.');
    process.exit(1);
  }

  try {
    await execPromise('git diff --quiet && git diff --cached --quiet');
  } catch (e) {
    log('Error: You have uncommitted changes.');
    process.exit(2);
  }

  return execPromise('git fetch origin');
});

gulp.task('release-push-production-styleguide-verify', () =>
  // Verifies that we're logged in - will prevent future steps if not
  execPromise('cf target -o pivotal -s pivotal-ui')
    .catch(() => {
      log('Error: could not set the org and space. Are you logged in to cf?');
      process.exit(3);
    })
);

gulp.task('release-push-npm-publish', ['css-build', 'react-build'], () => {
  return gulp.src('dist/{css,react}/*/package.json')
    .pipe(infoForUpdatedPackages())
    .pipe(publishPackages());
});

gulp.task('release-push-git', async () => {
  const {version} = require('../package.json');
  log(`Cutting tag v${version}`);
  await execPromise(`git tag v${version}`);
  log('Pushing to origin/master');
  await execPromise('git push origin master');
  log('Pushing new tag');
  return await execPromise(`git push origin v${version}`);
});

gulp.task('release-push-production-styleguide', (done) => {
  const deployProcess = exec('cf push');
  deployProcess.stdout.pipe(process.stdout);
  deployProcess.stderr.pipe(process.stderr);
  deployProcess.on('exit', (code) => {
    if (code) { process.exit(code); }
    done();
  });
});

gulp.task('release-push', (done) => runSequence(
  'set-styleguide-env-to-production',
  ['release-push-git-verify', 'release-push-production-styleguide-verify'],
  'release-push-npm-publish',
  'monolith',
  ['release-push-git', 'release-push-production-styleguide'],
  done
));
<commit_msg>fix release-push gulp task and add --dry option to publish to sinopia<commit_after>import {log} from 'gulp-util';
import {exec} from 'child_process';
import promisify from 'es6-promisify';
import gulp from 'gulp';
import {infoForUpdatedPackages, publishPackages, publishFakePackages} from './helpers/publish-helper';
import runSequence from 'run-sequence';
import glob from 'glob';
import fs from 'fs';
import {argv} from 'yargs';

const execPromise = promisify(exec);

gulp.task('set-styleguide-env-to-production', () => process.env.STYLEGUIDE_ENV = 'production');

gulp.task('release-push-git-verify', async () => {
  const currentSha = await execPromise('git rev-parse HEAD');
  const masterSha = await execPromise('git rev-parse master');
  if (currentSha !== masterSha) {
    log('Error: You must be on master.');
    process.exit(1);
  }

  try {
    await execPromise('git diff --quiet && git diff --cached --quiet');
  } catch (e) {
    log('Error: You have uncommitted changes.');
    process.exit(2);
  }

  return execPromise('git fetch origin');
});

gulp.task('release-push-production-styleguide-verify', () =>
  // Verifies that we're logged in - will prevent future steps if not
  execPromise('cf target -o pivotal -s pivotal-ui')
    .catch(() => {
      log('Error: could not set the org and space. Are you logged in to cf?');
      process.exit(3);
    })
);

gulp.task('release-push-npm-publish', ['css-build', 'react-build'], async() => {
  const files = glob.sync('dist/{css,react}/*/package.json', {realpath: true})
    .map((filepath) => {
      return {
        contents: fs.readFileSync(filepath),
        path: filepath
      };
    } );
  const packageInfos = await infoForUpdatedPackages(files);

  if(argv.dry) {
    await publishFakePackages()(packageInfos);
  } else {
    await publishPackages()(packageInfos);
  }
});

gulp.task('release-push-git', async () => {
  const {version} = require('../package.json');
  log(`Cutting tag v${version}`);
  await execPromise(`git tag v${version}`);
  log('Pushing to origin/master');
  await execPromise('git push origin master');
  log('Pushing new tag');
  return await execPromise(`git push origin v${version}`);
});

gulp.task('release-push-production-styleguide', (done) => {
  const deployProcess = exec('cf push');
  deployProcess.stdout.pipe(process.stdout);
  deployProcess.stderr.pipe(process.stderr);
  deployProcess.on('exit', (code) => {
    if (code) { process.exit(code); }
    done();
  });
});

gulp.task('release-push', (done) => runSequence(
  'set-styleguide-env-to-production',
  ['release-push-git-verify', 'release-push-production-styleguide-verify'],
  'release-push-npm-publish',
  'monolith',
  ['release-push-git', 'release-push-production-styleguide'],
  done
));
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    host: 'http://developer.echonest.com',
    namespace: 'api/v4',
    apiKey: null,
    dataType: 'jsonp',

    initApiKey: Ember.on('init', function () {
        const ENV = this.container.lookupFactory('config:environment');
        if (Ember.isPresent(ENV) && Ember.isPresent(ENV.ECHONEST_KEY)) {
            this.set('apiKey', ENV.ECHONEST_KEY);
        } else {
            Ember.Logger.warn('Echonest Key was not found in your environment config!');
        }
    }),

    buildURL(modelName, id, snapshot, requestType, query) {
        let url = this._super.apply(this, arguments);
        if (Ember.isPresent(query) && Ember.isPresent(query.method)) {
            const method = query.method;
            delete query.method;
            return `${url}/${method}`;
        }
        return url;
    },

    ajaxOptions(url, type, options) {
        const apiKey = this.get('apiKey');
        Ember.assert('An Echonest API Key must be provided', apiKey);
        const dataType = this.get('dataType');

        const hash = this._super.apply(this, arguments);
        hash.data = hash.data || {};
        hash.data.api_key = apiKey;
        hash.data.format = dataType;
        hash.dataType = dataType;
        hash.traditional = true;
        return hash;
    }
});
<commit_msg>Remove unused vars<commit_after>import Ember from 'ember';
import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    host: 'http://developer.echonest.com',
    namespace: 'api/v4',
    apiKey: null,
    dataType: 'jsonp',

    initApiKey: Ember.on('init', function () {
        const ENV = this.container.lookupFactory('config:environment');
        if (Ember.isPresent(ENV) && Ember.isPresent(ENV.ECHONEST_KEY)) {
            this.set('apiKey', ENV.ECHONEST_KEY);
        } else {
            Ember.Logger.warn('Echonest Key was not found in your environment config!');
        }
    }),

    buildURL(modelName, id, snapshot, requestType, query) {
        let url = this._super.apply(this, arguments);
        if (Ember.isPresent(query) && Ember.isPresent(query.method)) {
            const method = query.method;
            delete query.method;
            return `${url}/${method}`;
        }
        return url;
    },

    ajaxOptions() {
        const apiKey = this.get('apiKey');
        Ember.assert('An Echonest API Key must be provided', apiKey);
        const dataType = this.get('dataType');

        const hash = this._super.apply(this, arguments);
        hash.data = hash.data || {};
        hash.data.api_key = apiKey;
        hash.data.format = dataType;
        hash.dataType = dataType;
        hash.traditional = true;
        return hash;
    }
});
<|endoftext|>


<commit_before>/* Justin Tulloss
 * 05/31/08
 *
 * Takes care of javascript present on a profile page.
 */
var profile_handler;

(function() {
	function hide_all() {
		var pbody = Ext.get('profile-body');
		var containers = pbody.query('.profile-sp-commentcontainer')
		for (var i=0; i<containers.length; i++) {
			var container = Ext.get(containers[i]);
			container.child('.view-comment').setDisplayed(true);
			container.child('.hide-comment').setDisplayed(false);
			container.child('.comments-body').setDisplayed(false);
		}
	}
    //this function is called whenever the profile page is loaded
	profile_handler = function(rest) {
		hide_all();

		var components = rest.split('/');
		//find all the edit_spotlight links and assign onclick handlers to them
		var edit_links = Ext.query('.edit-spotlight');

		for (i = 0; i < edit_links.length; i++) {
		    var spot_id = parseInt(edit_links[i].id);
            //this handler looks hackish because it solves a closure property (shudder)
            Ext.get(edit_links[i].id).removeAllListeners();
		    Ext.get(edit_links[i].id).on('click', (function(spot_id) {return function() {
    		    Ext.Ajax.request({
                    url: '/spotlight/find_album/'+spot_id,
                    success: function(response, options) {
                        record = eval('(' + response.responseText + ')');
                        record = record.data[0];
                        record['id'] = spot_id;
                        record.get = (function(key) { return record[key];});
                        show_spotlight(record, "edit");
                    },
                    failure: function(response, options) {
                        alert("failed to lookup spotlight");
                    }
                });
		    };})(spot_id));
		}

		edit_links = Ext.query('.edit-playlist-spotlight');
		for (i = 0; i < edit_links.length; i++) {
		    var spot_id = parseInt(edit_links[i].id);
            //this handler looks hackish because it solves a closure property (shudder)
            Ext.get(edit_links[i].id).removeAllListeners();
		    Ext.get(edit_links[i].id).on('click', (function(spot_id) {return function() {
    		    Ext.Ajax.request({
                    url: '/spotlight/find_playlist/'+spot_id,
                    success: function(response, options) {
                        record = eval('(' + response.responseText + ')');
                        record = record.data[0];
                        record['id'] = spot_id;
                        record.get = (function(key) { return record[key];});
                        show_spotlight(record, "edit_playlist");
                    },
                    failure: function(response, options) {
                        alert("failed to lookup spotlight");
                    }
                });
		    };})(spot_id));
		}

		if (components.length != 3 || components[1] != 'spcomments') {
			return;
		}
        var spot_id = components[2];
		//if the user clicked the edit spotlight link, this code is executed:

		if (components[1] == 'spcomments') {		 //the user must've clicked the add comment link
		    var target = Ext.get('spot-comment-'+spot_id);
		    if (target) {
    			target.child('.view-comment').setDisplayed(false);
				target.child('.hide-comment').setDisplayed(true);
			    target.child('.comments-body').setDisplayed(true);

			    var button = target.child('.send-spot-comment');
			    if (!button.managed) {
    				button.managed = true;
				    button.on('click', function(e) {
    					e.preventDefault();
					    var textarea = target.child('.spot-comment-textarea');
					    Ext.Ajax.request({
    						url: '/people/add_spotcomment/'+spot_id,
						    params: {comment: textarea.dom.value},
						    success: function() {
    							show_status_msg('Comment added!');
							    urlm.invalidate_page();
						    }
					    });
				    });
			    }
		    }
	    }
    }

    var friend_music_menu_link = null;
    var friend_music_menu = null;

    function browse_friends_music(friend, target) {
        if (friend == null) return;

        friend_music_menu = new Ext.menu.Menu({
            width: target.offsetWidth,
            defaultAlign: 'tr-br',
            shadow: false
        });

        var urlbase = ['#/browse/friend=', friend, '/profile=', friend];
        friend_music_menu.add(new Ext.menu.Item({
            text: 'artists',
            href: urlbase.concat(['/artist']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.add(new Ext.menu.Item({
            text: 'albums',
            href: urlbase.concat(['/album']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.add(new Ext.menu.Item({
            text: 'songs',
            href: urlbase.concat(['/song']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.add(new Ext.menu.Item({
            text: 'playlists',
            href: urlbase.concat(['/playlist']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.show(target);
    }

    urlm.register_action('browse_friend', browse_friends_music);
})();

function profile_factory(url) {
    var newprofile = new Profile(url);
    return newprofile.panel;
}

function Profile(id)
{
    var my = this;
    my.panel.on('show', function(){my.panel.syncSize()});

    urlm.register_handlers([
        ['/profile_comments/', view_comments],
    ]);

    my.go = function(url) {
        alert(url);
    }
}
<commit_msg>Fixed the commenting twice bug. The profile code is still incredibly hacked.<commit_after>/* Justin Tulloss
 * 05/31/08
 *
 * Takes care of javascript present on a profile page.
 */
var profile_handler;

(function() {
	function hide_all() {
		var pbody = Ext.get('profile-body');
		var containers = pbody.query('.profile-sp-commentcontainer')
		for (var i=0; i<containers.length; i++) {
			var container = Ext.get(containers[i]);
			container.child('.view-comment').setDisplayed(true);
			container.child('.hide-comment').setDisplayed(false);
			container.child('.comments-body').setDisplayed(false);
		}
	}
    //this function is called whenever the profile page is loaded
	profile_handler = function(rest) {
		hide_all();

		var components = rest.split('/');
		//find all the edit_spotlight links and assign onclick handlers to them
		var edit_links = Ext.query('.edit-spotlight');

		for (i = 0; i < edit_links.length; i++) {
		    var spot_id = parseInt(edit_links[i].id);
            //this handler looks hackish because it solves a closure property (shudder)
            Ext.get(edit_links[i].id).removeAllListeners();
		    Ext.get(edit_links[i].id).on('click', (function(spot_id) {return function() {
    		    Ext.Ajax.request({
                    url: '/spotlight/find_album/'+spot_id,
                    success: function(response, options) {
                        record = eval('(' + response.responseText + ')');
                        record = record.data[0];
                        record['id'] = spot_id;
                        record.get = (function(key) { return record[key];});
                        show_spotlight(record, "edit");
                    },
                    failure: function(response, options) {
                        alert("failed to lookup spotlight");
                    }
                });
		    };})(spot_id));
		}

		edit_links = Ext.query('.edit-playlist-spotlight');
		for (i = 0; i < edit_links.length; i++) {
		    var spot_id = parseInt(edit_links[i].id);
            //this handler looks hackish because it solves a closure property (shudder)
            Ext.get(edit_links[i].id).removeAllListeners();
		    Ext.get(edit_links[i].id).on('click', (function(spot_id) {return function() {
    		    Ext.Ajax.request({
                    url: '/spotlight/find_playlist/'+spot_id,
                    success: function(response, options) {
                        record = eval('(' + response.responseText + ')');
                        record = record.data[0];
                        record['id'] = spot_id;
                        record.get = (function(key) { return record[key];});
                        show_spotlight(record, "edit_playlist");
                    },
                    failure: function(response, options) {
                        alert("failed to lookup spotlight");
                    }
                });
		    };})(spot_id));
		}

		if (components.length != 3 || components[1] != 'spcomments') {
			return;
		}
        var spot_id = components[2];
		//if the user clicked the edit spotlight link, this code is executed:

		if (components[1] == 'spcomments') {		 //the user must've clicked the add comment link
		    var target = Ext.get('spot-comment-'+spot_id);
		    if (target) {
    			target.child('.view-comment').setDisplayed(false);
				target.child('.hide-comment').setDisplayed(true);
			    target.child('.comments-body').setDisplayed(true);

			    var button = target.child('.send-spot-comment');
			    if (!button.managed) {
    				button.managed = true;
					var button_enabled = true;
				    button.on('click', function(e) {
    					e.preventDefault();
						if (button_enabled) {
							button_enabled = false;
							var textarea =
								target.child('.spot-comment-textarea');
							Ext.Ajax.request({
								url: '/people/add_spotcomment/'+spot_id,
								params: {comment: textarea.dom.value},
								success: function() {
									show_status_msg('Comment added!');
									urlm.invalidate_page();
								},
								failure: function() {
									show_status_msg('Error adding comment');
									button_enabled = true;
								}
							});
						}
				    });
			    }
		    }
	    }
    }

    var friend_music_menu_link = null;
    var friend_music_menu = null;

    function browse_friends_music(friend, target) {
        if (friend == null) return;

        friend_music_menu = new Ext.menu.Menu({
            width: target.offsetWidth,
            defaultAlign: 'tr-br',
            shadow: false
        });

        var urlbase = ['#/browse/friend=', friend, '/profile=', friend];
        friend_music_menu.add(new Ext.menu.Item({
            text: 'artists',
            href: urlbase.concat(['/artist']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.add(new Ext.menu.Item({
            text: 'albums',
            href: urlbase.concat(['/album']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.add(new Ext.menu.Item({
            text: 'songs',
            href: urlbase.concat(['/song']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.add(new Ext.menu.Item({
            text: 'playlists',
            href: urlbase.concat(['/playlist']).join(''),
            itemCls: 'music-menu-item',
            overCls: 'music-menu-item-over',
            activeClass: 'music-menu-item-active',
            iconCls: 'no_icon'
        }));
        friend_music_menu.show(target);
    }

    urlm.register_action('browse_friend', browse_friends_music);
})();

function profile_factory(url) {
    var newprofile = new Profile(url);
    return newprofile.panel;
}

function Profile(id)
{
    var my = this;
    my.panel.on('show', function(){my.panel.syncSize()});

    urlm.register_handlers([
        ['/profile_comments/', view_comments],
    ]);

    my.go = function(url) {
        alert(url);
    }
}
<|endoftext|>


<commit_before>$(function() {
    $.fn.lazyload = function(){
        $this = $(this);
        $this.find('img').waypoint(function(){
            $this = $(this);
            $this.hide().attr("src", $this.data('original')).fadeIn(1000);
        }, {
            triggerOnce: true,
            offset: function() {
                return $.waypoints('viewportHeight') + $(this).height();
            }
        });
    };
    var $container = $('#items');
    var gutter = 10;
    var min_width = 200;
    function fit(index, width){
        var cols = Math.floor(width / min_width);
        return cols * min_width + (cols - 1) * gutter;
    };
    $('.item').width(fit);
    function proxy() {
        this.src = $(this).data('proxy');
    };
    $('img').one('error', proxy);
    //$('[data-lightbox]').simpleLightbox();
    $container.masonry({
        itemSelector: '.item',
        gutter: gutter,
        isAnimated: true,
        columnWidth: min_width
    });
    $container.lazyload();
    bootstrap_alert = function() {}
    bootstrap_alert.warning = function(message) {
        $('#alert_box').html('
×'+message+'
');
    }
    $('#items').waypoint('infinite', {
        items: '.item',
        more: '.more',
        onAfterAppended: function($items) {
            // ensure that images load before adding to masonry layout
            $items.width(fit);
            $items.find('img').one('error', proxy);
            //$items.find('[data-lightbox]').simpleLightbox();
            $container.masonry('appended', $items, true);
            $items.lazyload();
        },
        onBeforePageLoad: function() {
            $('#progress > .bar').css('width', '0%');
            $('#progress').show();
        },
        onAfterPageLoad: function() {
            $('#progress').hide();
        },
        progress: function(e) {
            console.log('progress');
            if (e.lengthComputable) {
                var p = (e.loaded / e.total) * 100;
                console.log(p);
                $('#progress > .bar').css('width', p + '%');
            } else {
                console.warn('Content Length not reported!');
            }
        },
        error: function() {
            bootstrap_alert.warning('Load more failed.');
        }
    });
});
<commit_msg>retry load more<commit_after>$(function() {
    $.fn.lazyload = function(){
        $this = $(this);
        $this.find('img').waypoint(function(){
            $this = $(this);
            $this.hide().attr("src", $this.data('original')).fadeIn(1000);
        }, {
            triggerOnce: true,
            offset: function() {
                return $.waypoints('viewportHeight') + $(this).height();
            }
        });
    };
    var $container = $('#items');
    var gutter = 10;
    var min_width = 200;
    function fit(index, width){
        var cols = Math.floor(width / min_width);
        return cols * min_width + (cols - 1) * gutter;
    };
    $('.item').width(fit);
    function proxy() {
        this.src = $(this).data('proxy');
    };
    $('img').one('error', proxy);
    //$('[data-lightbox]').simpleLightbox();
    $container.masonry({
        itemSelector: '.item',
        gutter: gutter,
        isAnimated: true,
        columnWidth: min_width
    });
    $container.lazyload();
    bootstrap_alert = function() {}
    bootstrap_alert.warning = function(message) {
        $('#alert_box').html('
×'+message+'
');
    }
    $('#items').waypoint('infinite', {
        items: '.item',
        more: '.more',
        onAfterAppended: function($items) {
            // ensure that images load before adding to masonry layout
            $items.width(fit);
            $items.find('img').one('error', proxy);
            //$items.find('[data-lightbox]').simpleLightbox();
            $container.masonry('appended', $items, true);
            $items.lazyload();
        },
        onBeforePageLoad: function() {
            $('#progress > .bar').css('width', '0%');
            $('#progress').show();
        },
        onAfterPageLoad: function() {
            $('#progress').hide();
            $('#alert_box').html('');
        },
        progress: function(e) {
            console.log('progress');
            if (e.lengthComputable) {
                var p = (e.loaded / e.total) * 100;
                console.log(p);
                $('#progress > .bar').css('width', p + '%');
            } else {
                console.warn('Content Length not reported!');
            }
        },
        error: function() {
            $('#progress').hide();
            bootstrap_alert.warning('Load more failed. Retrying...');
            $.waypoints('refresh');
        }
    });
});
<|endoftext|>


<commit_before>// Cron for loading songs to db
var CronJob = require('cron').CronJob;
var upload = require('../song/song_upload.js');
var del = require('../song/song_delete.js');

// start cron job
// cronjob currently set to 1 min - need to decide on an actual time
var uploadjob = new CronJob('*/5 * * * *', function () {
  upload.uploadSongs();
});

var deletejob = new CronJob('*/20 * * * *', function () {
  del.deleteSongs();
});

module.exports = exports = function(req, res) {
  uploadjob.start();
  deletejob.start();
};
<commit_msg>Temporarily turning off delete cronjob.<commit_after>// Cron for loading songs to db
var CronJob = require('cron').CronJob;
var upload = require('../song/song_upload.js');
var del = require('../song/song_delete.js');

// start cron job
// cronjob currently set to 1 min - need to decide on an actual time
var uploadjob = new CronJob('*/5 * * * *', function () {
  upload.uploadSongs();
});

var deletejob = new CronJob('*/20 * * * *', function () {
  del.deleteSongs();
});

module.exports = exports = function(req, res) {
  uploadjob.start();
  // deletejob.start();
};
<|endoftext|>


<commit_before>/**
 * General service to wrap standard API JSON returns from RCM
 *  - Deals with failed codes (code 0 = success)
 *  - Creates standard return on error if no standard API JSON object received
 *  - Deals with loading state
 *    See: ApiParams.loading
 *  - Formats error messages (from rcm input filter) into single strings (optional)
 *    See: ApiParams.prepareErrors
 */
angular.module('rcmApi', [])
    .factory(
    'rcmApiService',
    [
        '$http', '$log',
        function ($http, $log) {

            var self = this;

            /**
             * cache
             * @type {{}}
             */
            self.cache = {};

            /**
             * ApiParams
             * @constructor
             */
            self.ApiParams = function () {
                /**
                 * URL of request (can contain parsable params in format {myParam})
                 * @type {string}
                 */
                this.url = '';
                /**
                 * URL Params that will replace parsable params in url
                 * @type {object}
                 */
                this.urlParams = null;
                /**
                 * POST PUT DELETE data
                 * @type {object}
                 */
                this.data = null;
                /**
                 * GET query params
                 * @type {object}
                 */
                this.params = null;
                /**
                 * Prepare errors from input filters if set to true
                 * @type {boolean}
                 */
                this.prepareErrors = false;
                /**
                 * Loading callback, used to track loading state
                 * @param {boolean} loading
                 */
                this.loading = function (loading) {
                };
                /**
                 * Success callback, called if http and API is successful (error code == 0)
                 * @param {object} data
                 */
                this.success = function (data) {
                };
                /**
                 * Error callback, called if http or API is fails (error code > 0)
                 * @param data
                 */
                this.error = function (data) {
                };
            };

            /**
             * ApiData - Format expected from server
             * @constructor
             */
            self.ApiData = function () {
                this.code = null;
                this.message = null;
                this.data = [];
                this.errors = [];
            };

            /**
             * GET
             * @param apiParams
             * @param {bool} cache - if you ask for cache it will try to get it from and set it to the cache
             * @returns {*}
             */
            self.get = function (apiParams, cache) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                if (cache) {

                    if (self.cache[apiParams.url]) {

                        self.apiSuccess(
                            self.cache[apiParams.url],
                            apiParams,
                            'CACHE',
                            null,
                            null
                        );
                        return;
                    }

                    apiParams.cacheId = apiParams.url;
                }

                apiParams.loading(true);

                $http(
                    {
                        method: 'GET',
                        url: apiParams.url,
                        params: apiParams.params // @todo Validate this works for GET query
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * POST
             * @param apiParams
             */
            self.post = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'POST',
                        url: apiParams.url,
                        data: apiParams.data
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * PATCH
             * @param apiParams
             */
            self.patch = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'PATCH',
                        url: apiParams.url,
                        data: apiParams.data // angular.toJson(data)
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * PUT
             * @param apiParams
             */
            self.put = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'PUT',
                        url: apiParams.url,
                        data: apiParams.data
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * DELETE
             * @param apiParams
             */
            self.del = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'DELETE',
                        url: apiParams.url,
                        data: apiParams.data
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * Parse URL string and replace {#} with param value by key
             * @param {string} str
             * @param {array} urlParams
             * @returns {string}
             */
            self.formatUrl = function (str, urlParams) {

                if (typeof urlParams !== 'object' || urlParams === null) {
                    return str;
                }

                for (var arg in urlParams) {
                    str = str.replace(
                        RegExp("\\{" + arg + "\\}", "gi"),
                        urlParams[arg]
                    );
                }

                return str;
            };

            /**
             *
             * @param data
             * @param apiParams
             */
            self.apiError = function (data, apiParams, status, headers, config) {
                $log.error(
                    'An API error occured, status: ' + status + ' returned: ',
                    data
                );

                self.prepareErrorData(
                    data,
                    apiParams,
                    function (data) {
                        apiParams.loading(false);
                        apiParams.error(data);
                    }
                );
            };

            /**
             * apiSuccess
             * @param data
             * @param apiParams
             * @param cacheId
             */
            self.apiSuccess = function (data, apiParams, status, headers, config) {
                // $log.info('An API success: ', data);

                if (data.code > 0 || typeof data !== 'object') {

                    self.prepareErrorData(
                        data,
                        apiParams,
                        function (data) {
                            apiParams.loading(false);
                            apiParams.error(data);
                        }
                    )
                } else {

                    self.prepareData(
                        data,
                        apiParams,
                        function (data) {
                            if (apiParams.cacheId) {
                                self.cache[apiParams.cacheId] = angular.copy(data);
                            }
                            apiParams.loading(false);
                            apiParams.success(data);
                        }
                    );
                }
            };

            /**
             * prepareErrorData
             * @param data
             * @returns {ApiData} data
             */
            self.prepareErrorData = function (data, apiParams, callback) {

                if (typeof data !== 'object' || data === null) {
                    data = new self.ApiData();
                }

                if (!data.code) {
                    data.code = 1;
                }

                if (!data.message) {
                    data.message = 'An unknown error occured while making request.';
                }

                return self.prepareData(data, apiParams, callback);
            };

            /**
             * prepareData
             * @param data
             * @param {boolean} prepareErrors
             * @returns {ApiData} data
             */
            self.prepareData = function (data, apiParams, callback) {

                if (data.errors && apiParams.prepareErrors) {
                    self.prepareErrors(data, callback);
                    return;
                }

                callback(data);
            };

            /**
             * prepareErrors
             * @param data
             * @returns {ApiData} data
             */
            self.prepareErrors = function (data, callback) {

                angular.forEach(
                    data.errors,
                    function (value, key) {
                        if (typeof value === 'object' && value !== null) {
                            angular.forEach(
                                value,
                                function (evalue, ekey) {
                                    data.errors[key] = evalue + ' ';
                                }
                            );
                        }
                    }
                );
                callback(data);
            };

            return self;
        }
    ]
);

/**
 * Exposes Angular service to global scope for use by other libraries
 * - This is to support jQuery and native JavaScript modules and code
 */
var rcmApi = {
    rcmApiService: null // defined in angular
};

/**
 * Angular injector to get rcmApi Module services
 */
angular.injector(['ng', 'rcmApi']).invoke(
    [
        'rcmApiService',
        function (rcmApiService) {
            rcmApi.rcmApiService = rcmApiService;
        }
    ]
);
<commit_msg>Add error detail to rcm-api<commit_after>/**
 * General service to wrap standard API JSON returns from RCM
 *  - Deals with failed codes (code 0 = success)
 *  - Creates standard return on error if no standard API JSON object received
 *  - Deals with loading state
 *    See: ApiParams.loading
 *  - Formats error messages (from rcm input filter) into single strings (optional)
 *    See: ApiParams.prepareErrors
 */
angular.module('rcmApi', [])
    .factory(
    'rcmApiService',
    [
        '$http', '$log',
        function ($http, $log) {

            var self = this;

            /**
             * cache
             * @type {{}}
             */
            self.cache = {};

            /**
             * ApiParams
             * @constructor
             */
            self.ApiParams = function () {
                /**
                 * URL of request (can contain parsable params in format {myParam})
                 * @type {string}
                 */
                this.url = '';
                /**
                 * URL Params that will replace parsable params in url
                 * @type {object}
                 */
                this.urlParams = null;
                /**
                 * POST PUT DELETE data
                 * @type {object}
                 */
                this.data = null;
                /**
                 * GET query params
                 * @type {object}
                 */
                this.params = null;
                /**
                 * Prepare errors from input filters if set to true
                 * @type {boolean}
                 */
                this.prepareErrors = false;
                /**
                 * Loading callback, used to track loading state
                 * @param {boolean} loading
                 */
                this.loading = function (loading) {
                };
                /**
                 * Success callback, called if http and API is successful (error code == 0)
                 * @param {object} data
                 */
                this.success = function (data) {
                };
                /**
                 * Error callback, called if http or API is fails (error code > 0)
                 * @param data
                 */
                this.error = function (data) {
                };
            };

            /**
             * ApiData - Format expected from server
             * @constructor
             */
            self.ApiData = function () {
                this.code = null;
                this.message = null;
                this.data = [];
                this.errors = [];
            };

            /**
             * GET
             * @param apiParams
             * @param {bool} cache - if you ask for cache it will try to get it from and set it to the cache
             * @returns {*}
             */
            self.get = function (apiParams, cache) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                if (cache) {

                    if (self.cache[apiParams.url]) {

                        self.apiSuccess(
                            self.cache[apiParams.url],
                            apiParams,
                            'CACHE',
                            null,
                            null
                        );
                        return;
                    }

                    apiParams.cacheId = apiParams.url;
                }

                apiParams.loading(true);

                $http(
                    {
                        method: 'GET',
                        url: apiParams.url,
                        params: apiParams.params // @todo Validate this works for GET query
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * POST
             * @param apiParams
             */
            self.post = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'POST',
                        url: apiParams.url,
                        data: apiParams.data
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * PATCH
             * @param apiParams
             */
            self.patch = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'PATCH',
                        url: apiParams.url,
                        data: apiParams.data // angular.toJson(data)
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * PUT
             * @param apiParams
             */
            self.put = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'PUT',
                        url: apiParams.url,
                        data: apiParams.data
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * DELETE
             * @param apiParams
             */
            self.del = function (apiParams) {

                apiParams = angular.extend(new self.ApiParams(), apiParams);

                apiParams.url = self.formatUrl(apiParams.url, apiParams.urlParams);

                apiParams.loading(true);

                $http(
                    {
                        method: 'DELETE',
                        url: apiParams.url,
                        data: apiParams.data
                    }
                )
                    .success(
                    function (data, status, headers, config) {
                        self.apiSuccess(data, apiParams, status, headers, config)
                    }
                )
                    .error(
                    function (data, status, headers, config) {
                        self.apiError(data, apiParams, status, headers, config)
                    }
                );
            };

            /**
             * Parse URL string and replace {#} with param value by key
             * @param {string} str
             * @param {array} urlParams
             * @returns {string}
             */
            self.formatUrl = function (str, urlParams) {

                if (typeof urlParams !== 'object' || urlParams === null) {
                    return str;
                }

                for (var arg in urlParams) {
                    str = str.replace(
                        RegExp("\\{" + arg + "\\}", "gi"),
                        urlParams[arg]
                    );
                }

                return str;
            };

            /**
             *
             * @param data
             * @param apiParams
             */
            self.apiError = function (data, apiParams, status, headers, config) {
                $log.error(
                    'An API error occured, status: ' + status + ' returned: ',
                    data
                );

                self.prepareErrorData(
                    data,
                    apiParams,
                    function (data) {
                        apiParams.loading(false);
                        apiParams.error(data);
                    },
                    status
                );
            };

            /**
             * apiSuccess
             * @param data
             * @param apiParams
             * @param cacheId
             */
            self.apiSuccess = function (data, apiParams, status, headers, config) {
                // $log.info('An API success: ', data);

                if (data.code > 0 || typeof data !== 'object') {

                    self.prepareErrorData(
                        data,
                        apiParams,
                        function (data) {
                            apiParams.loading(false);
                            apiParams.error(data);
                        },
                        status
                    )
                } else {

                    self.prepareData(
                        data,
                        apiParams,
                        function (data) {
                            if (apiParams.cacheId) {
                                self.cache[apiParams.cacheId] = angular.copy(data);
                            }
                            apiParams.loading(false);
                            apiParams.success(data);
                        }
                    );
                }
            };

            /**
             * prepareErrorData
             * @param data
             * @param apiParams
             * @param callback
             * @param status
             * @returns {ApiData|*}
             */
            self.prepareErrorData = function (data, apiParams, callback, status) {

                if (typeof data !== 'object' || data === null) {
                    data = new self.ApiData();
                }

                if (!data.code) {
                    data.code = status;
                }

                if (!data.message) {
                    data.message = 'An unknown error occured while making request.';
                }

                return self.prepareData(data, apiParams, callback);
            };

            /**
             * prepareData
             * @param data
             * @param apiParams
             * @param callback
             */
            self.prepareData = function (data, apiParams, callback) {

                if (data.errors && apiParams.prepareErrors) {
                    self.prepareErrors(data, callback);
                    return;
                }

                callback(data);
            };

            /**
             * prepareErrors
             * @param data
             * @param callback
             */
            self.prepareErrors = function (data, callback) {

                angular.forEach(
                    data.errors,
                    function (value, key) {
                        if (typeof value === 'object' && value !== null) {
                            angular.forEach(
                                value,
                                function (evalue, ekey) {
                                    data.errors[key] = evalue + ' ';
                                }
                            );
                        }
                    }
                );
                callback(data);
            };

            return self;
        }
    ]
);

/**
 * Exposes Angular service to global scope for use by other libraries
 * - This is to support jQuery and native JavaScript modules and code
 */
var rcmApi = {
    rcmApiService: null // defined in angular
};

/**
 * Angular injector to get rcmApi Module services
 */
angular.injector(['ng', 'rcmApi']).invoke(
    [
        'rcmApiService',
        function (rcmApiService) {
            rcmApi.rcmApiService = rcmApiService;
        }
    ]
);
<|endoftext|>


<commit_before>var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MyScene = /** @class */ (function (_super) {
    __extends(MyScene, _super);
    function MyScene() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MyScene.prototype.preload = function () {
        this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
    };
    MyScene.prototype.create = function () {
        var sprite = this.add.sprite(400, 300, 'cards', 'clubs3');
        sprite.setInteractive();
        this.input.on('pointerdown', function () {
            sprite.setFrame('hearts4');
        });
    };
    return MyScene;
}(Phaser.Scene));
var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 800,
    height: 600,
    scene: MyScene
};
var game = new Phaser.Game(config);
var scene = new Phaser.Scene("");
var blitter = new Phaser.GameObjects.Blitter(scene, 10, 10);
var conf = {
    type: Phaser.AUTO,
    width: 100,
    height: 100,
    zoom: 1,
    resolution: 1
};
var tex = null;
tex.source[0].setFilter(Phaser.Textures.FilterMode.LINEAR);
tex.setFilter(Phaser.Textures.FilterMode.LINEAR);
tex.setFilter(Phaser.Textures.NEAREST);
var sprite = new Phaser.GameObjects.Sprite(scene, 0, 0, "test");
var MyVec = /** @class */ (function (_super) {
    __extends(MyVec, _super);
    function MyVec() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MyVec.prototype.extra = function () {
    };
    return MyVec;
}(Phaser.Geom.Rectangle));
var p = new MyVec();
sprite.getBounds(p).extra();
var container = scene.add.container(0, 0);
container.getWorldTransformMatrix();
//# sourceMappingURL=game.js.map<commit_msg>Delete game.js<commit_after>var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MyScene = /** @class */ (function (_super) {
    __extends(MyScene, _super);
    function MyScene() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MyScene.prototype.preload = function () {
        this.load.atlas('cards', 'assets/atlas/cards.png', 'assets/atlas/cards.json');
    };
    MyScene.prototype.create = function () {
        var sprite = this.add.sprite(400, 300, 'cards', 'clubs3');
        sprite.setInteractive();
        this.input.on('pointerdown', function () {
            sprite.setFrame('hearts4');
        });
    };
    return MyScene;
}(Phaser.Scene));
var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 800,
    height: 600,
    scene: MyScene
};
var game = new Phaser.Game(config);
var scene = new Phaser.Scene("");
var blitter = new Phaser.GameObjects.Blitter(scene, 10, 10);
var conf = {
    type: Phaser.AUTO,
    width: 100,
    height: 100,
    zoom: 1,
    resolution: 1
};
var tex = null;
tex.source[0].setFilter(Phaser.Textures.FilterMode.LINEAR);
tex.setFilter(Phaser.Textures.FilterMode.LINEAR);
tex.setFilter(Phaser.Textures.NEAREST);
var sprite = new Phaser.GameObjects.Sprite(scene, 0, 0, "test");
var MyVec = /** @class */ (function (_super) {
    __extends(MyVec, _super);
    function MyVec() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MyVec.prototype.extra = function () {
    };
    return MyVec;
}(Phaser.Geom.Rectangle));
var p = new MyVec();
sprite.getBounds(p).extra();
var container = scene.add.container(0, 0);
container.getWorldTransformMatrix();
//# sourceMappingURL=game.js.map<|endoftext|>


<commit_before>/**
 * Created by tlzhang on 2015/6/4.
 */
(function(window,document){
    window.jMap = {
        version:'1.0.0',
        author:'tlzhang'
    };

    var util = {
        scriptName:'index.js',
        jsFile:[

        ],
        jsTags:'',
        host:function(){
            var r = new RegExp("(^|(.*?\\/))(" + util.scriptName + ")(\\?|$)"),
                s = document.getElementsByTagName('script'),
                src, m, l = "";
            for(var i=0, len=s.length; i<len; i++) {
                src = s[i].getAttribute('src');
                if(src) {
                    var m = src.match(r);
                    if(m) {
                        l = m[1];
                        break;
                    }
                }
            }
            return l;
        }
    };

    (function(){
        for(var i = 0, len = util.jsFile.length; i < len; i++) {
            util.jsTags += "<script src='"+ util.host() + util.jsFile[i] +"'></script>"
        }
        document.write(util.jsTags);
    })();

})(window,document);
<commit_msg>Update index.js<commit_after>/**
 * Created by tlzhang on 2015/6/4.
 */
(function(window,document){
    window.jMap = {
        version:'1.0.0',
        author:'tlzhang'
    };

    var util = {
        scriptName:'index.js',
        jsFile:[
            "lib/util/util.js",
            "lib/controls/scale.js",
            "lib/controls/drag.js",
            "lib/geometry/geometry.js",
            'lib/geometry/Rectangle.js',
            "lib/geometry/Point.js",
            "lib/geometry/Circle.js",
            "lib/canvas/canvas.js",
            "lib/layer/layer.js"
        ],
        jsTags:'',
        host:function(){
            var r = new RegExp("(^|(.*?\\/))(" + util.scriptName + ")(\\?|$)"),
                s = document.getElementsByTagName('script'),
                src, m, l = "";
            for(var i=0, len=s.length; i<len; i++) {
                src = s[i].getAttribute('src');
                if(src) {
                    var m = src.match(r);
                    if(m) {
                        l = m[1];
                        break;
                    }
                }
            }
            return l;
        }
    };

    (function(){
        for(var i = 0, len = util.jsFile.length; i < len; i++) {
            util.jsTags += "<script src='"+ util.host() + util.jsFile[i] +"'></script>"
        }
        document.write(util.jsTags);
    })();

})(window,document);
<|endoftext|>