<commit_before>/**
 * @fileOverview WebRTC Framework to facilitate the development of Applications that seamless interoperate between each other
 * @author Paulo Chainho <paulo-g-chainho@ptinovacao.pt>
 * @author Steffen Druesedow <Steffen.Druesedow@telekom.de>
 * @author Miguel Seijo Simo <Miguel.Seijo@telekom.de>
 * @author Vasco Amaral <vasco-m-amaral@ptinovacao.pt>
 * @author Kay Haensge <Kay.Haensge@telekom.de>
 * @author Luis Oliveira <luis-f-oliveira@ptinovacao.pt>
 */

/*
 * TODO: State-machine for transitions of IdentityStatus should be described
 * TODO: Questions about MessagingStub-Listeners
 * Why do the addListener and removeListener methods have a Message as second param?
 * What is the purpose? Which message type would it be?
 */

/**
 * @class
 * The Identity represents a user and contains all information needed to support
 * Conversation services including the service endpoint to retrieve the protocol stack
 * (Messaging Stub) that will be used to establish a signalling channel
 * with the Identity domain messaging server.
 *
NOTE: Identities are only created by using the corresponding create-methods of the Idp.
 * This constructor will throw an exception if it is used directly.
 */
function Identity(rtcIdentity, idpRtcIdentity) {
	console.log("idpRtcIdentity", idpRtcIdentity)
	if (rtcIdentity)
		throw "Illegal attempt to create an Identity --> Please use Idp.getInstance().createIdentity(...) instead."

	// We use a string, RTCIdentityAssertion is not available.
	this.rtcIdentity = idpRtcIdentity;
	this.id = new Date().getTime();
	console.log("####################");
	console.log("created new Identiy for: " + this.rtcIdentity + " with id = " + this.id);
	console.trace();
	console.log("####################");
	this.idp = "";
	this.presence = {
		status: IdentityStatus.IDLE
				//app: this.prototype.resolveMyApp()
	};

	// TODO: initialise presence status
	//this.presence.status = IdentityStatus.IDLE; // not initialized yet TODO: do state changes in a central place
	//this.presence.app = this.prototype.resolveMyApp(); // not initialized yet TODO: do state changes in a central place

	//this.status = IdentityStatus.IDLE; // TODO: to be replaced with Identity.presence
	this.context;

	this.sessionId = "";

	this.messagingStubLibUrl = "";
	this.messagingStub;
	this.notificationAddress;
	this.messagingAddress;
	this.credentials;
	this.tone;
	this.avatar;
};

/**
 * resolveMyApp
 *
 * @returns AppType ... private function to resolve the type of Application used by the user
 *
 */
Identity.prototype.resolveMyApp = function () {
	// TODO: to check what kind of App is used:
	//     - Case is Web App running in a mobile browser it should return AppType.MOBILE_WEB_APP
	//     - Case is Mobile Web App running in a pc browser it should return AppType.WEB_APP

};

/**
 * This method downloads a messaging stub and keeps a reference to it in a local
 * attribute, if not already done before. That means the download will only be performed once.
 * After download it invokes the given callback with a reference to the downloaded MessagingStub.
 *
 * @param callback {callback(MessagingStub)} callback that is invoked with messagingStub as param; if download failed then the stub param is empty
 */
Identity.prototype.resolve = function (callback) {
	var that = this;
	console.log("resolving identity: " + this.rtcIdentity);
	if (!this.messagingStub.impl) {
		// not resolved yet --> let's ask Idp for a stub with the same downloadUri
		var knownStub = Idp.getInstance().getResolvedStub(this.messagingStubLibUrl);
		if (knownStub) {
			this.messagingStub = knownStub;
			callback(this.messagingStub);
			return;
		}

		console.log("downloading Messaging stub from: " + this.messagingStubLibUrl);
		require.config({
			'baseUrl': this.messagingStubDownloadUrl
		});
		require(['stub'], function (stub) {
			// assign the new messagingStub object to the "impl" field of the container stub
			stub.setImpl(stub);
			stub.message = "stub downloaded from: " + that.messagingStubLibUrl;
			// return container-stub in callback
			callback(stub);
		});

//		// parse the downloadURL to get the name of the Stub
//		var pathArr = this.messagingStubLibUrl.split("/");
//		var stubName = pathArr[pathArr.length-1];
//		stubName = stubName.substring(0, stubName.lastIndexOf("."));
//		console.log("stub-name is: " + stubName );
//
//		var check = function(stub, callback, count) {
//			if ( typeof(window[stub]) == "function" ) {
//				// instantiate stub
//				var messagingStub = new window[stub]();
//				//  should be an object now
//				if ( typeof(messagingStub) == "object" ) {
//					// assign the new messagingStub object to the "impl" field of the container stub
//					that.messagingStub.setImpl(messagingStub);
//					that.messagingStub.message = "stub downloaded from: " + that.messagingStubLibUrl;
//					// return container-stub in callback
//					callback(that.messagingStub);
//				}
//			}
//			else {
//				count++;
//				if ( count < 20 )
//					setTimeout( check, 500,  stub, callback, count );
//				else {
//					callback();
//				}
//			}
//		};
//		this.loadJSfile( this.messagingStubLibUrl );
//		setTimeout( check, 100, stubName, callback, 0 );
	}
	else {
		console.log(this.rtcIdentity + ": no need to download stub from: " + this.messagingStubLibUrl);
		callback(this.messagingStub);
	}
};

/**
 *
 * This method subscribes to add a listener to receive status information (CONTEXT message type) from the user associated to this Identity.
 * The Signalling on the fly concept is also used to ensure cross domain Presence management interoperability
 * by calling the Identiy.resolve() function
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.subscribe = function (subscriber) {
	// TODO: get messagingStub by invoking Identity.resolve() function, add Identity as messagingStub listener (including the subscription contextId)  and send SUBSCRIBE message through the MessagingStub
	this.context = guid(); //check this
	that = this;
	var from = subscriber.rtcIdentity;
	var to = this.rtcIdentity;
	console.log("Identity to subscribe", to);
	console.log("Identity subscriber", subscriber);

	console.log("Identity subscribe");
	this.resolve(function (stub) {

		//message.contextId = guid();
		stub.addListener(that.onMessage(that), "presence." + to, that.context);
		stub.sendMessage(MessageFactory.createSubscribeMessage(from, to, ""));
	});
};

/**
 *
 * This method removes a listener previously added with "subscribe()"  function to receive status information
 * (CONTEXT message type) from the user associated to this Identity
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.unsubscribe = function (subscriber, type) {
	// TODO: get messagingStub by invoking Identity.resolve() function and send BYE message through the MessagingStub
	this.messagingStub.sendMessage(MessageFactory.createUnsubscribeMessage(message));
};

/**
 * To set Identity status and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param status :
 *            String ... The status to set
 *
 */

Identity.prototype.setStatus = function (status, login) {
	//var message = new Object();
	//message.contextId = this.context;

	//from = identity.rtcIdentity;
	//to = this.rtcIdentity;
	var that = this;
	console.log("Identity SetStatus: ", status);

	this.presence.status = status;// TODO: change to that.presence.status = status;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage(that.rtcIdentity, "", status, login, that.sessionId));
	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**getPresence
 * To set Identity presence and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param presence :
 *            String ... The presence to set
 *
 */

Identity.prototype.setPresence = function (presence) {

	var that = this;
	that.presence.status = presence;

	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**
 * To set Identity context and to publish it by sending a CONTEXT message to address "rtcIdentity.context"
 *
 * @param context :
 *            String ... The context to set
 *
 */

Identity.prototype.setContext = function (context) {

	this.context = context;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage());
	// TODO: Send a CONTEXT message to address "rtcIdentity.context"
};

/**
 * getStatus
 *
 * @returns IdentityStatus ... gets the presence status attribute for this Identity
 *
 */
Identity.prototype.getStatus = function () {
// TODO: change to return this.presence.status;
	return this.presence.status;
};

/**
 * getPresence
 *
 * @returns Presence ... gets the presence  attribute for this Identity
 *
 */
Identity.prototype.getPresence = function () {
	return this.presence;
};

/**
 * sendMessage
 *
 * @sendmessage ...sendMessage
 *
 */

Identity.prototype.sendMessage = function (message) {
	this.messagingStub.sendMessage(message);
};

/**
 * getContext
 *
 * @returns ContextData ... gets the context attribute for this Identity
 *
 */
Identity.prototype.getContext = function () {
	return this.context;
};

/**
 * getMessagingStubDownloadUrl
 *
 * @returns URL ... gets the URL to download the MessagingStub for this Identity
 *
 */
Identity.prototype.getMessagingStubDownloadUrl = function () {
	//will be needed to the Idp
	return this.messagingStubDownloadUrl;
};

/**
 *
 * OnLastMessagingListerner is invoked by the MessagingStub as soon as the last listener has un-subscribed.
 * We use this callback to disconnect and unload the MessagingStub.
 *
 */
Identity.prototype.onLastMessagingListener = function () {
	if (this.messagingStub)
		this.messagingStub.disconnect();
	// "undefine" messagingStub
	delete this.messagingStub;
};

/**@ignore
 * Simple function to load an external Javascript file at runtime.
 * TODO: This might be a security risk, because the file is executed immediately.
 * @param url ... url of the file to be loaded
 */
Identity.prototype.loadJSfile = function (url) {
	var fileref = document.createElement('script');
	fileref.setAttribute("type", "text/javascript");
	fileref.setAttribute("src", url);
	if (typeof fileref != "undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
};

Identity.prototype.onMessage = function (message) {
	console.log("MESSAGES-->", message)
	switch (message.type) {
		case MessageType.CONTEXT:
			this.setStatus(message.identityPresence.status);
			break;
		case MessageType.ACCEPTED:
			break;
		case MessageType.NOT_ACCEPTED:
			break;
		case MessageType.CANCEL:
			break;
		default:
			break;
	}

}<commit_msg>apply require.js path without js-extension<commit_after>/**
 * @fileOverview WebRTC Framework to facilitate the development of Applications that seamless interoperate between each other
 * @author Paulo Chainho <paulo-g-chainho@ptinovacao.pt>
 * @author Steffen Druesedow <Steffen.Druesedow@telekom.de>
 * @author Miguel Seijo Simo <Miguel.Seijo@telekom.de>
 * @author Vasco Amaral <vasco-m-amaral@ptinovacao.pt>
 * @author Kay Haensge <Kay.Haensge@telekom.de>
 * @author Luis Oliveira <luis-f-oliveira@ptinovacao.pt>
 */

/*
 * TODO: State-machine for transitions of IdentityStatus should be described
 * TODO: Questions about MessagingStub-Listeners
 * Why do the addListener and removeListener methods have a Message as second param?
 * What is the purpose? Which message type would it be?
 */

/**
 * @class
 * The Identity represents a user and contains all information needed to support
 * Conversation services including the service endpoint to retrieve the protocol stack
 * (Messaging Stub) that will be used to establish a signalling channel
 * with the Identity domain messaging server.
 *
NOTE: Identities are only created by using the corresponding create-methods of the Idp.
 * This constructor will throw an exception if it is used directly.
 */
function Identity(rtcIdentity, idpRtcIdentity) {
	console.log("idpRtcIdentity", idpRtcIdentity)
	if (rtcIdentity)
		throw "Illegal attempt to create an Identity --> Please use Idp.getInstance().createIdentity(...) instead."

	// We use a string, RTCIdentityAssertion is not available.
	this.rtcIdentity = idpRtcIdentity;
	this.id = new Date().getTime();
	console.log("####################");
	console.log("created new Identiy for: " + this.rtcIdentity + " with id = " + this.id);
	console.trace();
	console.log("####################");
	this.idp = "";
	this.presence = {
		status: IdentityStatus.IDLE
				//app: this.prototype.resolveMyApp()
	};

	// TODO: initialise presence status
	//this.presence.status = IdentityStatus.IDLE; // not initialized yet TODO: do state changes in a central place
	//this.presence.app = this.prototype.resolveMyApp(); // not initialized yet TODO: do state changes in a central place

	//this.status = IdentityStatus.IDLE; // TODO: to be replaced with Identity.presence
	this.context;

	this.sessionId = "";

	this.messagingStubLibUrl = "";
	this.messagingStub;
	this.notificationAddress;
	this.messagingAddress;
	this.credentials;
	this.tone;
	this.avatar;
};

/**
 * resolveMyApp
 *
 * @returns AppType ... private function to resolve the type of Application used by the user
 *
 */
Identity.prototype.resolveMyApp = function () {
	// TODO: to check what kind of App is used:
	//     - Case is Web App running in a mobile browser it should return AppType.MOBILE_WEB_APP
	//     - Case is Mobile Web App running in a pc browser it should return AppType.WEB_APP

};

/**
 * This method downloads a messaging stub and keeps a reference to it in a local
 * attribute, if not already done before. That means the download will only be performed once.
 * After download it invokes the given callback with a reference to the downloaded MessagingStub.
 *
 * @param callback {callback(MessagingStub)} callback that is invoked with messagingStub as param; if download failed then the stub param is empty
 */
Identity.prototype.resolve = function (callback) {
	var that = this;
	console.log("resolving identity: " + this.rtcIdentity);
	if (!this.messagingStub.impl) {
		// not resolved yet --> let's ask Idp for a stub with the same downloadUri
		var knownStub = Idp.getInstance().getResolvedStub(this.messagingStubLibUrl);
		if (knownStub) {
			this.messagingStub = knownStub;
			callback(this.messagingStub);
			return;
		}

		console.log("downloading Messaging stub from: " + this.messagingStubLibUrl);
		// apply require.js config; remove ".js" extension from path
		require.config({
			'baseUrl': this.messagingStubDownloadUrl.substring(0, this.messagingStubDownloadUrl.length - 3)
		});
		require(['stub'], function (stub) {
			// assign the new messagingStub object to the "impl" field of the container stub
			stub.setImpl(stub);
			stub.message = "stub downloaded from: " + that.messagingStubLibUrl;
			// return container-stub in callback
			callback(stub);
		});

//		// parse the downloadURL to get the name of the Stub
//		var pathArr = this.messagingStubLibUrl.split("/");
//		var stubName = pathArr[pathArr.length-1];
//		stubName = stubName.substring(0, stubName.lastIndexOf("."));
//		console.log("stub-name is: " + stubName );
//
//		var check = function(stub, callback, count) {
//			if ( typeof(window[stub]) == "function" ) {
//				// instantiate stub
//				var messagingStub = new window[stub]();
//				//  should be an object now
//				if ( typeof(messagingStub) == "object" ) {
//					// assign the new messagingStub object to the "impl" field of the container stub
//					that.messagingStub.setImpl(messagingStub);
//					that.messagingStub.message = "stub downloaded from: " + that.messagingStubLibUrl;
//					// return container-stub in callback
//					callback(that.messagingStub);
//				}
//			}
//			else {
//				count++;
//				if ( count < 20 )
//					setTimeout( check, 500,  stub, callback, count );
//				else {
//					callback();
//				}
//			}
//		};
//		this.loadJSfile( this.messagingStubLibUrl );
//		setTimeout( check, 100, stubName, callback, 0 );
	}
	else {
		console.log(this.rtcIdentity + ": no need to download stub from: " + this.messagingStubLibUrl);
		callback(this.messagingStub);
	}
};

/**
 *
 * This method subscribes to add a listener to receive status information (CONTEXT message type) from the user associated to this Identity.
 * The Signalling on the fly concept is also used to ensure cross domain Presence management interoperability
 * by calling the Identiy.resolve() function
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.subscribe = function (subscriber) {
	// TODO: get messagingStub by invoking Identity.resolve() function, add Identity as messagingStub listener (including the subscription contextId)  and send SUBSCRIBE message through the MessagingStub
	this.context = guid(); //check this
	that = this;
	var from = subscriber.rtcIdentity;
	var to = this.rtcIdentity;
	console.log("Identity to subscribe", to);
	console.log("Identity subscriber", subscriber);

	console.log("Identity subscribe");
	this.resolve(function (stub) {

		//message.contextId = guid();
		stub.addListener(that.onMessage(that), "presence." + to, that.context);
		stub.sendMessage(MessageFactory.createSubscribeMessage(from, to, ""));
	});
};

/**
 *
 * This method removes a listener previously added with "subscribe()"  function to receive status information
 * (CONTEXT message type) from the user associated to this Identity
 * @param subscriber :
 *            Identity ... The identity of the subscriber
 * @param type :
 *            SubscriptionType ... The subscription type
 *
 */
Identity.prototype.unsubscribe = function (subscriber, type) {
	// TODO: get messagingStub by invoking Identity.resolve() function and send BYE message through the MessagingStub
	this.messagingStub.sendMessage(MessageFactory.createUnsubscribeMessage(message));
};

/**
 * To set Identity status and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param status :
 *            String ... The status to set
 *
 */

Identity.prototype.setStatus = function (status, login) {
	//var message = new Object();
	//message.contextId = this.context;

	//from = identity.rtcIdentity;
	//to = this.rtcIdentity;
	var that = this;
	console.log("Identity SetStatus: ", status);

	this.presence.status = status;// TODO: change to that.presence.status = status;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage(that.rtcIdentity, "", status, login, that.sessionId));
	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**getPresence
 * To set Identity presence and to publish it by sending a CONTEXT message to address "rtcIdentity.presence"
 *
 * @param presence :
 *            String ... The presence to set
 *
 */

Identity.prototype.setPresence = function (presence) {

	var that = this;
	that.presence.status = presence;

	// TODO: check status transitions according to IdentityStatus state machine
	// TODO: Send a CONTEXT message to address "rtcIdentity.presence"
};

/**
 * To set Identity context and to publish it by sending a CONTEXT message to address "rtcIdentity.context"
 *
 * @param context :
 *            String ... The context to set
 *
 */

Identity.prototype.setContext = function (context) {

	this.context = context;
	this.messagingStub.sendMessage(MessageFactory.createContextMessage());
	// TODO: Send a CONTEXT message to address "rtcIdentity.context"
};

/**
 * getStatus
 *
 * @returns IdentityStatus ... gets the presence status attribute for this Identity
 *
 */
Identity.prototype.getStatus = function () {
// TODO: change to return this.presence.status;
	return this.presence.status;
};

/**
 * getPresence
 *
 * @returns Presence ... gets the presence  attribute for this Identity
 *
 */
Identity.prototype.getPresence = function () {
	return this.presence;
};

/**
 * sendMessage
 *
 * @sendmessage ...sendMessage
 *
 */

Identity.prototype.sendMessage = function (message) {
	this.messagingStub.sendMessage(message);
};

/**
 * getContext
 *
 * @returns ContextData ... gets the context attribute for this Identity
 *
 */
Identity.prototype.getContext = function () {
	return this.context;
};

/**
 * getMessagingStubDownloadUrl
 *
 * @returns URL ... gets the URL to download the MessagingStub for this Identity
 *
 */
Identity.prototype.getMessagingStubDownloadUrl = function () {
	//will be needed to the Idp
	return this.messagingStubDownloadUrl;
};

/**
 *
 * OnLastMessagingListerner is invoked by the MessagingStub as soon as the last listener has un-subscribed.
 * We use this callback to disconnect and unload the MessagingStub.
 *
 */
Identity.prototype.onLastMessagingListener = function () {
	if (this.messagingStub)
		this.messagingStub.disconnect();
	// "undefine" messagingStub
	delete this.messagingStub;
};

/**@ignore
 * Simple function to load an external Javascript file at runtime.
 * TODO: This might be a security risk, because the file is executed immediately.
 * @param url ... url of the file to be loaded
 */
Identity.prototype.loadJSfile = function (url) {
	var fileref = document.createElement('script');
	fileref.setAttribute("type", "text/javascript");
	fileref.setAttribute("src", url);
	if (typeof fileref != "undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
};

Identity.prototype.onMessage = function (message) {
	console.log("MESSAGES-->", message)
	switch (message.type) {
		case MessageType.CONTEXT:
			this.setStatus(message.identityPresence.status);
			break;
		case MessageType.ACCEPTED:
			break;
		case MessageType.NOT_ACCEPTED:
			break;
		case MessageType.CANCEL:
			break;
		default:
			break;
	}

}<|endoftext|>


<commit_before>import style from './style.js'
import {format} from '@mapbox/mapbox-gl-style-spec'
import ReconnectingWebSocket from 'reconnecting-websocket'

export class ApiStyleStore {

  constructor(opts) {
    this.onLocalStyleChange = opts.onLocalStyleChange || (() => {})
    const port = opts.port || '8000'
    const host = opts.host || 'localhost'
    this.localUrl = `http://${host}:${port}`
    this.websocketUrl = `ws://${host}:${port}/ws`
    this.init = this.init.bind(this)
  }

  init(cb) {
    fetch(this.localUrl + '/styles', {
      mode: 'cors',
    })
    .then((response) =>  {
      return response.json();
    })
    .then((body) => {
      const styleIds = body;
      this.latestStyleId = styleIds[0]
      this.notifyLocalChanges()
      cb(null)
    })
    .catch(function(e) {
      cb(new Error('Can not connect to style API'))
    })
  }

  notifyLocalChanges() {
    const connection = new ReconnectingWebSocket(this.websocketUrl)
    connection.onmessage = e => {
      if(!e.data) return
      console.log('Received style update from API')
      let parsedStyle = style.emptyStyle
      try {
        parsedStyle = JSON.parse(e.data)
      } catch(err) {
        console.error(err)
      }
      const updatedStyle = style.ensureStyleValidity(parsedStyle)
      this.onLocalStyleChange(updatedStyle)
    }
  }

  latestStyle(cb) {
    if(this.latestStyleId) {
      fetch(this.localUrl + '/styles/' + this.latestStyleId, {
        mode: 'cors',
      })
      .then(function(response) {
        return response.json();
      })
      .then(function(body) {
        cb(style.ensureStyleValidity(body))
      })
    } else {
      throw new Error('No latest style available. You need to init the api backend first.')
    }
  }

  // Save current style replacing previous version
  save(mapStyle) {
    const styleJSON = format(
      style.stripAccessTokens(
        style.replaceAccessTokens(newStyle)
      )
    );

    const id = mapStyle.id
    fetch(this.localUrl + '/styles/' + id, {
      method: "PUT",
      mode: 'cors',
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      body: styleJSON
    })
    .catch(function(error) {
      if(error) console.error(error)
    })
    return mapStyle
  }
}
<commit_msg>Fix for desktop build<commit_after>import style from './style.js'
import {format} from '@mapbox/mapbox-gl-style-spec'
import ReconnectingWebSocket from 'reconnecting-websocket'

export class ApiStyleStore {

  constructor(opts) {
    this.onLocalStyleChange = opts.onLocalStyleChange || (() => {})
    const port = opts.port || '8000'
    const host = opts.host || 'localhost'
    this.localUrl = `http://${host}:${port}`
    this.websocketUrl = `ws://${host}:${port}/ws`
    this.init = this.init.bind(this)
  }

  init(cb) {
    fetch(this.localUrl + '/styles', {
      mode: 'cors',
    })
    .then((response) =>  {
      return response.json();
    })
    .then((body) => {
      const styleIds = body;
      this.latestStyleId = styleIds[0]
      this.notifyLocalChanges()
      cb(null)
    })
    .catch(function(e) {
      cb(new Error('Can not connect to style API'))
    })
  }

  notifyLocalChanges() {
    const connection = new ReconnectingWebSocket(this.websocketUrl)
    connection.onmessage = e => {
      if(!e.data) return
      console.log('Received style update from API')
      let parsedStyle = style.emptyStyle
      try {
        parsedStyle = JSON.parse(e.data)
      } catch(err) {
        console.error(err)
      }
      const updatedStyle = style.ensureStyleValidity(parsedStyle)
      this.onLocalStyleChange(updatedStyle)
    }
  }

  latestStyle(cb) {
    if(this.latestStyleId) {
      fetch(this.localUrl + '/styles/' + this.latestStyleId, {
        mode: 'cors',
      })
      .then(function(response) {
        return response.json();
      })
      .then(function(body) {
        cb(style.ensureStyleValidity(body))
      })
    } else {
      throw new Error('No latest style available. You need to init the api backend first.')
    }
  }

  // Save current style replacing previous version
  save(mapStyle) {
    const styleJSON = format(
      style.stripAccessTokens(
        style.replaceAccessTokens(mapStyle)
      )
    );

    const id = mapStyle.id
    fetch(this.localUrl + '/styles/' + id, {
      method: "PUT",
      mode: 'cors',
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      body: styleJSON
    })
    .catch(function(error) {
      if(error) console.error(error)
    })
    return mapStyle
  }
}
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/component/CrossFade", "Tone/component/Merge", "Tone/component/Split"],
function(Tone){

	"use strict";

	/**
	 *  Panner.
	 *
	 *  @class  Equal Power Gain L/R Panner. Not 3D.
	 *          0 = 100% Left
	 *          1 = 100% Right
	 *
	 *  @constructor
	 *  @extends {Tone}
	 *  @param {number} [initialPan=0.5] the initail panner value (defaults to 0.5 = center)
	 *  @example
	 *  var panner = new Tone.Panner(1);
	 *  // ^ pan the input signal hard right.
	 */
	Tone.Panner = function(initialPan){

		Tone.call(this, 1, 0);

		/**
		 *  the dry/wet knob
		 *  @type {Tone.CrossFade}
		 *  @private
		 */
		this._crossFade = new Tone.CrossFade();

		/**
		 *  @type {Tone.Merge}
		 *  @private
		 */
		this._merger = this.output = new Tone.Merge();

		/**
		 *  @type {Tone.Split}
		 *  @private
		 */
		this._splitter = new Tone.Split();

		/**
		 *  the pan control
		 *  @type {Tone.Signal}
		 */
		this.pan = this._crossFade.fade;

		//CONNECTIONS:
		this.input.connect(this._splitter);
		//left channel is dry, right channel is wet
		this._splitter.connect(this._crossFade, 0, 0);
		this._splitter.connect(this._crossFade, 1, 1);
		//merge it back together
		this._crossFade.a.connect(this._merger.left);
		this._crossFade.b.connect(this._merger.right);

		//initial value
		this.pan.value = this.defaultArg(initialPan, 0.5);
	};

	Tone.extend(Tone.Panner);

	/**
	 *  clean up
	 *  @returns {Tone.Panner} `this`
	 */
	Tone.Panner.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this._crossFade.dispose();
		this._crossFade = null;
		this._splitter.dispose();
		this._splitter = null;
		this._merger.dispose();
		this._merger = null;
		this.pan = null;
		return this;
	};

	return Tone.Panner;
});<commit_msg>uses StereoPannerNode when available<commit_after>define(["Tone/core/Tone", "Tone/component/CrossFade", "Tone/component/Merge",
	"Tone/component/Split", "Tone/signal/Signal", "Tone/signal/WaveShaper"],
function(Tone){

	"use strict";

	/**
	 *  Panner.
	 *
	 *  @class  Equal Power Gain L/R Panner. Not 3D.
	 *          0 = 100% Left
	 *          1 = 100% Right
	 *
	 *  @constructor
	 *  @extends {Tone}
	 *  @param {number} [initialPan=0.5] the initail panner value (defaults to 0.5 = center)
	 *  @example
	 *  var panner = new Tone.Panner(1);
	 *  // ^ pan the input signal hard right.
	 */
	Tone.Panner = function(initialPan){

		Tone.call(this);

		/**
		 *  indicates if the panner is using the new StereoPannerNode internally
		 *  @type  {boolean}
		 *  @private
		 */
		this._hasStereoPanner = this.isFunction(this.context.createStereoPanner);

		if (this._hasStereoPanner){

			/**
			 *  the panner node
			 *  @type {StereoPannerNode}
			 *  @private
			 */
			this._panner = this.input = this.output = this.context.createStereoPanner();

			/**
			 *  the pan control
			 *  @type {Tone.Signal}
			 */
			this.pan = new Tone.Signal(0, Tone.Signal.Units.Normal);

			/**
			 *  scale the pan signal to between -1 and 1
			 *  @type {Tone.WaveShaper}
			 *  @private
			 */
			this._scalePan = new Tone.WaveShaper([-1, -1, 1]);

			//connections
			this.pan.chain(this._scalePan, this._panner.pan);

		} else {

			/**
			 *  the dry/wet knob
			 *  @type {Tone.CrossFade}
			 *  @private
			 */
			this._crossFade = new Tone.CrossFade();

			/**
			 *  @type {Tone.Merge}
			 *  @private
			 */
			this._merger = this.output = new Tone.Merge();

			/**
			 *  @type {Tone.Split}
			 *  @private
			 */
			this._splitter = this.input = new Tone.Split();

			/**
			 *  the pan control
			 *  @type {Tone.Signal}
			 */
			this.pan = this._crossFade.fade;

			//CONNECTIONS:
			//left channel is a, right channel is b
			this._splitter.connect(this._crossFade, 0, 0);
			this._splitter.connect(this._crossFade, 1, 1);
			//merge it back together
			this._crossFade.a.connect(this._merger, 0, 0);
			this._crossFade.b.connect(this._merger, 0, 1);
		}

		//initial value
		this.pan.value = this.defaultArg(initialPan, 0.5);
	};

	Tone.extend(Tone.Panner);

	/**
	 *  clean up
	 *  @returns {Tone.Panner} `this`
	 */
	Tone.Panner.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		if (this._hasStereoPanner){
			this._panner.disconnect();
			this._panner = null;
			this.pan.dispose();
			this.pan = null;
			this._scalePan.dispose();
			this._scalePan = null;
		} else {
			this._crossFade.dispose();
			this._crossFade = null;
			this._splitter.dispose();
			this._splitter = null;
			this._merger.dispose();
			this._merger = null;
			this.pan = null;
		}
		return this;
	};

	return Tone.Panner;
});<|endoftext|>


<commit_before>var Promise = require('bluebird');
var fsep = require('fs-extra-promise');
var pg = require('postgres-bluebird');
var copyFrom = require('pg-copy-streams').from;
var config = require('./config');
var throat = require('throat')
var path = require('path');
var fs = require('fs');
var logger = require('./logger');
var Utils = require('./utils');
var Promise = require('bluebird');

module.exports.importFilesCmd = function(parentDir, body, year, quarter, fund_number, tableName, concurrency){
	return fsep.readdirAsync(parentDir)
	.then(function(files) {

		files = Utils.filterFiles(files, body, year, quarter, fund_number);
		return module.exports.importFiles(parentDir, files, tableName, concurrency);
	})
	.then(function(res){
		fsep.writeFile("errors.log", res['errors']);
	})
	.catch(function(err){
		logger.error("error:" + err)
	})
}

module.exports.importFileCmd = function(filePath, tableName){

	var filename =  filePath.replace(/^.*(\\|\/|\:)/, '');
	var parentDir = filePath.substr(0, filePath.length - filename.length);

	//process.stdout.cursorTo (0);
	process.stdout.write("Importing: "+filename + "\n");

    return module.exports.importFile(parentDir, filename, tableName)
	.then(function(res){
		if (!res){
			logger.info("Not imported")
		}
		else{
			logger.info("Done importing.")
		}
	})
	.catch(function(err){
		logger.error("error:" +err);
	})
}

/**
 * Import files to db, concurrently --> resolves to
 *
 *
 * result['done'] = [filenames...]
 * result['errors'] = [filenames...]
 */
module.exports.importFiles = function(parentDir, files, tableName, concurrency){

	if ( concurrency == undefined) concurrency = 4;
	var total = files.length;
	var counter = 0;

	return Promise.all(files.map(throat(concurrency, function(filename){

		//process.stdout.cursorTo (0);
		process.stdout.write(++counter+'/'+total + ":"+ filename + "\n");

		if ( filename.substr(-4) !== '.csv' ){
			return;
		}

		return module.exports.importFile(parentDir, filename, tableName);

	})))
	.then(function(resArr){

		//resArr - array of booleans,
		//represents success/fail of corresponding file index

		var result = {}
		result['errors'] = [];
		result['done'] = [];

		for (i in resArr){
			if(resArr[i] === true){
				result['done'].push(files[i]);
			}
			else if (resArr[i] === false){
				result['errors'].push(files[i]);
			}
		}

		return result;
	});
}

//import file to db --> resolves to boolean
module.exports.importFile = function(parentDir, filename, tableName){
	return  pg.connectAsync(config.connection_string)
				.spread(function(client, release) {

		            var filePath = path.join(parentDir, filename);

		            if (!fs.existsSync(filePath)){
			            var absolutePath = path.resolve(filePath);
			            console.log("File not found " + absolutePath);
		            }

					//Check if file already loaded to DB
					var year = filename.split('_')[1];
					var quarter = filename.split('_')[2];
					var fund = filename.split('_')[3].split('.')[0];
					var managing_body = filename.split('_')[0];

					var countFundSql = "SELECT count(*) FROM "+ tableName +" WHERE managing_body='" +managing_body +"'"
										+ " AND report_year='"+year+"' AND report_qurater='"+quarter+"'"
										+ " AND fund='"+fund+"' ";

					return client.queryAsync(countFundSql)
						.then(function(qresult){
							release();
							return new Promise(function(resolve,reject){

								var count = qresult.rows[0].count;

								if (count > 0){ //file in DB, skip file
									logger.info([managing_body, year, quarter, fund].join("_") + " file already loaded to DB	")
									resolve();
									return;
								}

								//File not in DB, copy to table
								var pgstream = client.query(copyFrom('COPY '+ tableName +' FROM STDIN HEADER CSV NULL \'\'' ));
								var sqlStream = fsep.createReadStream(filePath);

							  	sqlStream.on('error',
								  	function(err){
								  		logger.error(" " +err)
										resolve(false);
							  	});
							  	sqlStream.pipe(pgstream)
									.on('end',
									  	function(){
											resolve(true);
								  		})
								  	.on('error',
								  		function(err){
									  		logger.error(" " +err)
											resolve(false);
									  	});

							});

					})
			})
}<commit_msg>new logger + sql template<commit_after>var fsep = require('fs-extra-promise');
var pg = require('postgres-bluebird');
var copyFrom = require('pg-copy-streams').from;
var config = require('./config');
var throat = require('throat')
var path = require('path');
var fs = require('fs');
var logger = require('./logger')(module);
var Utils = require('./utils');
var Promise = require('bluebird');
var countFundRowsTemplate = handlebars.compile(fs.readFileSync(__dirname + '/sql/countFundRows.hbs').toString());

module.exports.importFilesCmd = function(parentDir, body, year, quarter, fund_number, tableName, concurrency){
	return fsep.readdirAsync(parentDir)
	.then(function(files) {

		files = Utils.filterFiles(files, body, year, quarter, fund_number);
		return module.exports.importFiles(parentDir, files, tableName, concurrency);
	})
	.then(function(res){
		fsep.writeFile("errors.log", res['errors']);
	})
	.catch(function(err){
		logger.error("error:" + err)
	})
}

module.exports.importFileCmd = function(filePath, tableName){

	var filename =  filePath.replace(/^.*(\\|\/|\:)/, '');
	var parentDir = filePath.substr(0, filePath.length - filename.length);

	//process.stdout.cursorTo (0);
	process.stdout.write("Importing: "+filename + "\n");

    return module.exports.importFile(parentDir, filename, tableName)
	.then(function(res){
		if (!res){
			logger.warn("Not imported",res);
		}
		else{
			logger.info("Done importing.");
		}
	})
	.catch(function(err){
		logger.error("error:" +err);
	})
}

/**
 * Import files to db, concurrently --> resolves to
 *
 *
 * result['done'] = [filenames...]
 * result['errors'] = [filenames...]
 */
module.exports.importFiles = function(parentDir, files, tableName, concurrency){

	if ( concurrency == undefined) concurrency = 4;
	var total = files.length;
	var counter = 0;

	return Promise.all(files.map(throat(concurrency, function(filename){

		//process.stdout.cursorTo (0);
		process.stdout.write(++counter+'/'+total + ":"+ filename + "\n");

		if ( filename.substr(-4) !== '.csv' ){
			return;
		}

		return module.exports.importFile(parentDir, filename, tableName);

	})))
	.then(function(resArr){

		//resArr - array of booleans,
		//represents success/fail of corresponding file index

		var result = {}
		result['errors'] = [];
		result['done'] = [];

		for (i in resArr){
			if(resArr[i] === true){
				result['done'].push(files[i]);
			}
			else if (resArr[i] === false){
				result['errors'].push(files[i]);
			}
		}

		return result;
	});
}

//import file to db --> resolves to boolean
module.exports.importFile = function(parentDir, filename, tableName){
	return  pg.connectAsync(config.connection_string)
				.spread(function(client, release) {

		            var filePath = path.join(parentDir, filename);

		            if (!fs.existsSync(filePath)){
			            var absolutePath = path.resolve(filePath);
			            console.log("File not found " + absolutePath);
		            }

					//Check if file already loaded to DB
					var year = filename.split('_')[1];
					var quarter = filename.split('_')[2];
					var fund = filename.split('_')[3].split('.')[0];
					var managing_body = filename.split('_')[0];

					var data = {
						tableName : tableName,
						report_year : year,
						report_quarter : quarter,
						fund : fund,
						managing_body : managing_body
					};

					var countFundSql = countFundRowsTemplate(data);

					return client.queryAsync(countFundSql)
						.then(function(qresult){
							release();
							return new Promise(function(resolve,reject){

								var count = qresult.rows[0].count;

								if (count > 0){ //file in DB, skip file
									logger.info([managing_body, year, quarter, fund].join("_") + " file already loaded to DB	")
									resolve();
									return;
								}

								//File not in DB, copy to table
								var pgstream = client.query(copyFrom('COPY '+ tableName +' FROM STDIN HEADER CSV NULL \'\'' ));
								var sqlStream = fsep.createReadStream(filePath);

							  	sqlStream.on('error',
								  	function(err){
								  		logger.error(" " +err)
										resolve(false);
							  	});
							  	sqlStream.pipe(pgstream)
									.on('end',
									  	function(){
											resolve(true);
								  		})
								  	.on('error',
								  		function(err){
									  		logger.error(" " +err)
											resolve(false);
									  	});

							});

					})
			})
}<|endoftext|>


<commit_before><commit_msg>tsc compiled correctly, module added.<commit_after><|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, select } from '@storybook/addon-knobs/react';
import {
  COLORS,
  TINTS,
  Box,
  Heading1,
  Heading2,
  Heading3,
  Heading4,
  Heading5,
  Monospaced,
  TextBody,
  TextDisplay,
  TextSmall,
} from '../src';

storiesOf('Typography', module)
  .addParameters({
    info: {
      propTablesExclude: [Box],
    },
  })
  .add('Headings', () => (

      <Heading1
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
      >
        Heading 1 / font-size: 24px / line-height: 30px / weight: bold (700) / tracking: 0
      </Heading1>
      <Heading2
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 2 / font-size: 18px / line-height: 24px / weight: medium (500) / tracking: 0
      </Heading2>
      <Heading3
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 3 / font-size: 16px / line-height: 21px / weight: medium (500) / tracking: 0
      </Heading3>
      <Heading4
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 4 / font-size: 12px / line-height: 18px / weight: bold (700) / tracking: 0.6px
      </Heading4>
      <Heading5
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 5 / font-size: 14px / line-height: 18px / weight: semi bold (600) / tracking: 0
      </Heading5>

  ))
  .add('Text', () => (
    <Box overflow="hidden">
      <TextDisplay
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
      >
        Text display / font-size: 16px / line-height: 24px / weight: regular (400) / tracking: 0
      </TextDisplay>
      <TextBody
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        Text body / font-size: 14px / line-height: 21px / weight: regular (400) / tracking: 0
      </TextBody>
      <TextSmall
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        Text small / font-size: 12px / line-height: 18px / weight: regular (400) / tracking: 0
      </TextSmall>
    </Box>
  ))
  .add('Monospaced', () => (
    <Box padding={5}>
      <Heading1
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading1>
      <Heading2
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading2>
      <Heading3
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading3>
      <Heading4
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading4>
      <Heading5
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading5>
      <TextDisplay
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={6}
      >
        <Monospaced>1234567890</Monospaced>
      </TextDisplay>
      <TextBody
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </TextBody>
      <TextSmall
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </TextSmall>
    </Box>
  ));
<commit_msg>Update stories<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, select } from '@storybook/addon-knobs/react';
import {
  COLORS,
  TINTS,
  Box,
  Heading1,
  Heading2,
  Heading3,
  Heading4,
  Heading5,
  Monospaced,
  TextBody,
  TextBodyCompact,
  TextDisplay,
  TextSmall,
} from '../src';

storiesOf('Typography', module)
  .addParameters({
    info: {
      propTablesExclude: [Box],
    },
  })
  .add('Headings', () => (

      <Heading1
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
      >
        Heading 1 / font-size: 24px / line-height: 30px / weight: bold (700) / tracking: 0
      </Heading1>
      <Heading2
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 2 / font-size: 18px / line-height: 24px / weight: medium (500) / tracking: 0
      </Heading2>
      <Heading3
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 3 / font-size: 16px / line-height: 21px / weight: medium (500) / tracking: 0
      </Heading3>
      <Heading4
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 4 / font-size: 12px / line-height: 18px / weight: bold (700) / tracking: 0.6px
      </Heading4>
      <Heading5
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Heading 5 / font-size: 14px / line-height: 18px / weight: semi bold (600) / tracking: 0
      </Heading5>

  ))
  .add('Text', () => (
    <Box overflow="hidden">
      <TextDisplay
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
      >
        Text display / font-size: 16px / line-height: 24px / weight: regular (400) / tracking: 0
      </TextDisplay>
      <TextBody
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Text body / font-size: 14px / line-height: 21px / weight: regular (400) / tracking: 0
      </TextBody>
      <TextBodyCompact
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Text body compact / font-size: 14px / line-height: 18px / weight: regular (400) / tracking: 0
      </TextBodyCompact>
      <TextSmall
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={4}
      >
        Text small / font-size: 12px / line-height: 18px / weight: regular (400) / tracking: 0
      </TextSmall>
    </Box>
  ))
  .add('Monospaced', () => (
    <Box padding={5}>
      <Heading1
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading1>
      <Heading2
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading2>
      <Heading3
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading3>
      <Heading4
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading4>
      <Heading5
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </Heading5>
      <TextDisplay
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={6}
      >
        <Monospaced>1234567890</Monospaced>
      </TextDisplay>
      <TextBody
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </TextBody>
      <TextSmall
        color={select('Color', COLORS, 'teal')}
        ellipsis={boolean('Overflow ellipsis', false)}
        tint={select('Tint', TINTS, 'darkest')}
        marginTop={2}
      >
        <Monospaced>1234567890</Monospaced>
      </TextSmall>
    </Box>
  ));
<|endoftext|>


<commit_before>'use strict';

var toUint = require('../../number/to-uint')
  , value  = require('../../object/valid-value')

  , min = Math.min;

module.exports = function (searchString/*, endPosition*/) {
	var self, start, endPos;
	self = String(value(this));
	searchString = String(searchString);
	endPos = arguments[1];
	start = ((endPos == null) ? self.length :
			min(toUint(endPos), self.length)) - searchString.length;
	return (start < 0) ? false : (self.indexOf(searchString, start) === start);
};
<commit_msg>Adjust String#endsWith to specification<commit_after>'use strict';

var toInt = require('../../number/to-int')
  , value = require('../../object/valid-value')

  , min = Math.min, max = Math.max;

module.exports = function (searchString/*, endPosition*/) {
	var self, start, endPos;
	self = String(value(this));
	searchString = String(searchString);
	endPos = arguments[1];
	start = ((endPos == null) ? self.length :
			min(max(toInt(endPos), 0), self.length)) - searchString.length;
	return (start < 0) ? false : (self.indexOf(searchString, start) === start);
};
<|endoftext|>


<commit_before>"use strict";

var generated = Object.create(null)

  , random = Math.random;

module.exports = function () {
	var str;
	do {
 str = random().toString(36).slice(2);
} while (generated[str]);
	return str;
};
<commit_msg>style: lint<commit_after>"use strict";

var generated = Object.create(null), random = Math.random;

module.exports = function () {
	var str;
	do {
		str = random()
			.toString(36)
			.slice(2);
	} while (generated[str]);
	return str;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

//command line arguments
//first argument is the directory you want to
//turn into a soundfont.
const sfPath = process.argv[2];

//only these files will be parsed
var acceptExt = [
	".wav", ".ogg", ".mp3", ".aiff", ".aif"
];

var noteExp = /(?:\\-|\b)[a-g]#?[0-7]/ig;
var velExp = /(vel[^-]+)[\d]/ig;

function getFileNamesInFolder(folderPath) {
	folderPath = path.resolve(folderPath); //make it absolute.

	if (fs.lstatSync(folderPath).isDirectory()) {
		var filenames = fs.readdirSync(folderPath);

		return filenames;
	} else {throw Error(`${folderPath} is not a directory!`);}
}

function setNote(noteLetter) {
	switch (noteLetter) {
		case "a": return "10";
		case "a#": return "11";
		case "b": return "12";
		case "c": return "01";
		case "c#": return "02";
		case "d": return "03";
		case "d#": return "04";
		case "e": return "05";
		case "f": return "06";
		case "f#": return "07";
		case "g": return "08";
		case "g#": return "09";
	}
}

function parseSFZ() {
	var sfz = "";
	var notes = [];
	var venabled = false;

	//get conversion information
	for (var f in names) {
		var note = {
			letter : "n",
			octave : {},
			note : {},
			velocity : null,
			sample : {}
		};

		if (acceptExt.includes(path.extname(names[f]))) {
			notes.push(note); //push instance
			note.sample = names[f]; //store the filename

			var noteNames = names[f].toLowerCase().match(noteExp);
			var velNums = names[f].match(velExp);

			if (velNums != null) { //store velocity
				note.velocity = velNums[0].replace(/\D/g,''); //isolate the velocity integers
				venabled = true;
			} else if (venabled) {
				console.log("Check", names[f], "for missing velocity markings.");
				process.exit(1);
			}

			if (noteNames == null) { //debug if dashes aren't used properly
				console.log("Check", names[f], "for improper formatting.");
				process.exit(1);
			} else {
				if (noteNames.length > 1) { //too many instances resembling note names
					console.log("Check", names[f], "for instances resembling note names.");

					for (var i in noteNames) {
						console.log("Detected Sequence " + (parseInt(i) + 1) + " is " + noteNames[i]);
					} process.exit(1);
				} else { //store note name
					if (noteNames[0].length > 2) {
						note.letter = noteNames[0][0] + noteNames[0][1];
						note.octave = noteNames[0][2];
						note.note = setNote(noteNames[0][0] + noteNames[0][1]);
					} else {
						note.letter = noteNames[0][0];
						note.octave = noteNames[0][1];
						note.note = setNote(noteNames[0][0]);
					}
				}
			}
		}
	}

	notes = notes.sort(function(a,b) {
		if (a.octave == b.octave) {
			if (a.note == b.note) { return parseInt(a.velocity) - parseInt(b.velocity); } //by velocity
			else { return parseInt(a.note) - parseInt(b.note); } //by note
		} else { return parseInt(a.octave) - parseInt(b.octave); } //by octave
	});

	//console.log(notes);

	//build text file
	for (var i in notes) {
		var down = null;
		var up = null;
		var low = "";
		var high = "";
		var vel = "";

		sfz = sfz + "<region>\n";
		sfz = sfz + "sample=" + notes[i].sample + "\n";

		down = findNextNote(notes[i], notes, "down");
		up = findNextNote(notes[i], notes, "up");

		if (down != null) {low = middleKey( notes[i], down, "down"); }
		if (up != null) {high = middleKey( notes[i], up, "up"); }
		if (low != "") {sfz = sfz + "lokey=" + low + "\n";}
		if (high != "") {sfz = sfz + "hikey=" + high + "\n";}

		if (notes[i].velocity != null) {
			if (i > 0) {
				if (notes[i-1].letter == notes[i].letter && notes[i-1].octave == notes[i].octave) {
					vel = setVelocity(notes[i-1].velocity, "high");
					sfz = sfz + "lovel=" + vel + "\n";
				}
			}

			sfz = sfz + "hivel=" + notes[i].velocity + "\n";
		}

		/*
		if (i == 0) { //first in the array
			//high = middleKey(notes[i], notes[parseInt(i) + 1], "up");
			next = findNextNote(notes[i], notes, "up");
			high = middleKey(notes[i], next, "up");
			sfz = sfz + "hikey=" + high + "\n";

			console.log(next);

			if (notes[i].velocity != null) {
				sfz = sfz + "hivel=" + notes[i].velocity + "\n";
			} else {console.log("this is it");}
		} else if (i == notes.length - 1) { //last in the array
			//low = middleKey(notes[i], notes[parseInt(i) - 1], "down");
			next = findNextNote(notes[i], notes, "down");
			low = middleKey(notes[i], next, "down");
			sfz = sfz + "lokey=" + low + "\n";

			//low velocity
			if (notes[i].velocity != null) { //if velocity was specified at all in filename
				if (notes[i-1].letter == notes[i].letter && notes[i-1].octave == notes[i].octave) {
					vel = setVelocity(notes[i-1].velocity, "high");
					sfz = sfz + "lovel=" + vel + "\n";
				} sfz = sfz + "hivel=" + notes[i].velocity + "\n"; //high velocity
			}
		} else { //middle of the array
			next = findNextNote(notes[i], notes, "down");
			low = middleKey(notes[i], next, "down");
			//low = middleKey(notes[i], notes[parseInt(i) - 1], "down");
			next = findNextNote(notes[i], notes, "up");
			//high = middleKey(notes[i], notes[parseInt(i) + 1], "up");
			high = middleKey(notes[i], next, "up");
			sfz = sfz + "lokey=" + low + "\n";
			sfz = sfz + "hikey=" + high + "\n";

			if (notes[i].velocity != null) {
				if (notes[i-1].letter == notes[i].letter && notes[i-1].octave == notes[i].octave) {
					vel = setVelocity(notes[i-1].velocity, "high");
					sfz = sfz + "lovel=" + vel + "\n";
				} sfz = sfz + "hivel=" + notes[i].velocity + "\n";
			}
		}
		*/
		sfz = sfz + "pitch_keycenter=" + notes[i].letter + notes[i].octave + "\n";
		sfz += "\n";
	}

	return sfz;
}

function setVelocity(vel) {
	vel = parseInt(vel);
	vel = vel + 1;
	return vel.toString();
}

function findNextNote(self, friends, dir) {
	var okay = false;

	if (dir == "up") {
		for (var f = 0; f < friends.length; f++) {
			if (okay) {
				if (self.letter != friends[f].letter) {return friends[f];}
				else if (self.octave != friends[f].octave) {return friends[f];}
			} else if (friends[f] == self) {okay = true;}
		}
	} else {
		for (var g = friends.length - 1; g > -1; g--) {
			if (okay) {
				if (self.letter != friends[g].letter) {return friends[g];}
				else if (self.octave != friends[g].octave) {return friends[g];}
			} else if (friends[g] == self) {okay = true;}
		}
	}
}

//find note between samples
function middleKey(self, friend, dir) {
	var newKey = "";
	var noteCount = [];

	var myNote = parseInt(self.note);
	var myOctave = parseInt(self.octave)
	var frNote = parseInt(friend.note);
	var frOctave = parseInt(friend.octave)

	var distance = distCount(myNote, frNote, myOctave, frOctave, dir);

	var distLow = Math.floor(distance/2);
	var distHigh = distance - distLow - 1;

	if (dir == "down") {noteCount = keyCount(myNote, distLow, myOctave, "down");}
	else {noteCount = keyCount(myNote, distHigh, myOctave, "up");}

	newKey = nameNote(self, friend, noteCount[0], noteCount[1]);

	return newKey;
}

//name note...obvs
function nameNote(me, them, num, oct) {
	var numString = ""

	switch (num) {
		case 1: numString = "c"; break;
		case 2: numString = "c#"; break;
		case 3: numString = "d"; break;
		case 4: numString = "d#"; break;
		case 5: numString = "e"; break;
		case 6: numString = "f"; break;
		case 7: numString = "f#"; break;
		case 8: numString = "g"; break;
		case 9: numString = "g#"; break;
		case 10: numString = "a"; break;
		case 11: numString = "a#"; break;
		case 12: numString = "b"; break;
	}

	if (numString == them.letter && oct == them.octave) {
		numString = me.letter + me.octave;
	} else {numString = numString + oct.toString();}

	return numString;
}

//find note
function keyCount(countFrom, countAmount, octave, dir) {
	var count = 0;
	var newOctave = octave;
	var newKey = countFrom;
	var both = [];

	while(count < countAmount) {
		if (dir == "up") {newKey++;}
		if (dir == "down") {newKey--;}

		if (newKey > 12) {newOctave++; newKey = 1;}
		if (newKey < 1) {newOctave--; newKey = 12;}
		count++;
	}

	both.push(newKey);
	both.push(newOctave);

	return both;
}

//find distance
function distCount(countFrom, countTo, sOct, fOct, dir) {
	var distance = 0;
	var count = countFrom;
	var nOct = sOct;

	while (count != countTo || nOct != fOct) {
		if (dir == "up") {
			distance++;
			count++;
		}

		if (dir == "down") {
			distance++;
			count--;
		}

		if (count > 12) {nOct++; count = 1;}
		if (count < 1) {nOct--; count = 12;}
	}

	return distance;
}

function writeFile(filePath, contents) {
	filePath = path.resolve(filePath);
	fs.writeFileSync(filePath, contents);
}

var names = getFileNamesInFolder(sfPath);
var folderName = path.basename(sfPath);

//write sfz to text file
writeFile(path.join(sfPath, folderName + ".sfz"), parseSFZ(names));<commit_msg>velocity support and code clean up<commit_after>#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

//command line arguments
//first argument is the directory you want to
//turn into a soundfont.
const sfPath = process.argv[2];

//only these files will be parsed
var acceptExt = [
	".wav", ".ogg", ".mp3", ".aiff", ".aif"
];

var noteExp = /(?:\\-|\b)[a-g]#?[0-7]/ig;
var velExp = /(vel[^-]+)[\d]/ig;

function getFileNamesInFolder(folderPath) {
	folderPath = path.resolve(folderPath); //make it absolute.

	if (fs.lstatSync(folderPath).isDirectory()) {
		var filenames = fs.readdirSync(folderPath);

		return filenames;
	} else {throw Error(`${folderPath} is not a directory!`);}
}

function setNote(noteLetter) {
	switch (noteLetter) {
		case "a": return "10";
		case "a#": return "11";
		case "b": return "12";
		case "c": return "01";
		case "c#": return "02";
		case "d": return "03";
		case "d#": return "04";
		case "e": return "05";
		case "f": return "06";
		case "f#": return "07";
		case "g": return "08";
		case "g#": return "09";
	}
}

function parseSFZ() {
	var sfz = "";
	var notes = [];
	var venabled = false;

	//get conversion information
	for (var f in names) {
		var note = {
			letter : "n",
			octave : {},
			note : {},
			velocity : null,
			sample : {}
		};

		if (acceptExt.includes(path.extname(names[f]))) {
			notes.push(note); //push instance
			note.sample = names[f]; //store the filename

			var noteNames = names[f].toLowerCase().match(noteExp);
			var velNums = names[f].match(velExp);

			if (velNums != null) { //store velocity
				note.velocity = velNums[0].replace(/\D/g,''); //isolate the velocity integers
				venabled = true;
			} else if (venabled) {
				console.log("Check", names[f], "for missing velocity markings.");
				process.exit(1);
			}

			if (noteNames == null) { //debug if dashes aren't used properly
				console.log("Check", names[f], "for improper formatting.");
				process.exit(1);
			} else {
				if (noteNames.length > 1) { //too many instances resembling note names
					console.log("Check", names[f], "for instances resembling note names.");

					for (var i in noteNames) {
						console.log("Detected Sequence " + (parseInt(i) + 1) + " is " + noteNames[i]);
					} process.exit(1);
				} else { //store note name
					if (noteNames[0].length > 2) {
						note.letter = noteNames[0][0] + noteNames[0][1];
						note.octave = noteNames[0][2];
						note.note = setNote(noteNames[0][0] + noteNames[0][1]);
					} else {
						note.letter = noteNames[0][0];
						note.octave = noteNames[0][1];
						note.note = setNote(noteNames[0][0]);
					}
				}
			}
		}
	}

	notes = notes.sort(function(a,b) {
		if (a.octave == b.octave) {
			if (a.note == b.note) { return parseInt(a.velocity) - parseInt(b.velocity); } //by velocity
			else { return parseInt(a.note) - parseInt(b.note); } //by note
		} else { return parseInt(a.octave) - parseInt(b.octave); } //by octave
	});

	//console.log(notes);

	//build text file
	for (var i in notes) {
		var down = null;
		var up = null;
		var low = "";
		var high = "";
		var vel = "";

		sfz = sfz + "<region>\n";
		sfz = sfz + "sample=" + notes[i].sample + "\n";

		down = findNextNote(notes[i], notes, "down");
		up = findNextNote(notes[i], notes, "up");

		if (down != null) {low = middleKey( notes[i], down, "down"); }
		if (up != null) {high = middleKey( notes[i], up, "up"); }
		if (low != "") {sfz = sfz + "lokey=" + low + "\n";}
		if (high != "") {sfz = sfz + "hikey=" + high + "\n";}

		if (notes[i].velocity != null) {
			if (i > 0) {
				if (notes[i-1].letter == notes[i].letter && notes[i-1].octave == notes[i].octave) {
					vel = setVelocity(notes[i-1].velocity, "high");
					sfz = sfz + "lovel=" + vel + "\n";
				}
			}

			sfz = sfz + "hivel=" + notes[i].velocity + "\n";
		}

		sfz = sfz + "pitch_keycenter=" + notes[i].letter + notes[i].octave + "\n";
		sfz += "\n";
	}

	return sfz;
}

function setVelocity(vel) {
	vel = parseInt(vel);
	vel = vel + 1;
	return vel.toString();
}

function findNextNote(self, friends, dir) {
	var foundSelf = false;

	if (dir == "up") {
		for (var f = 0; f < friends.length; f++) {
			if (foundSelf) {
				if (self.letter != friends[f].letter) {return friends[f];}
				else if (self.octave != friends[f].octave) {return friends[f];}
			} else if (friends[f] == self) {foundSelf = true;}
		}
	} else {
		for (var g = friends.length - 1; g > -1; g--) {
			if (foundSelf) {
				if (self.letter != friends[g].letter) {return friends[g];}
				else if (self.octave != friends[g].octave) {return friends[g];}
			} else if (friends[g] == self) {foundSelf = true;}
		}
	}
}

//find note between samples
function middleKey(self, friend, dir) {
	var newKey = "";
	var noteCount = [];

	var myNote = parseInt(self.note);
	var myOctave = parseInt(self.octave)
	var frNote = parseInt(friend.note);
	var frOctave = parseInt(friend.octave)

	var distance = distCount(myNote, frNote, myOctave, frOctave, dir);

	var distLow = Math.floor(distance/2);
	var distHigh = distance - distLow - 1;

	if (dir == "down") {noteCount = keyCount(myNote, distLow, myOctave, "down");}
	else {noteCount = keyCount(myNote, distHigh, myOctave, "up");}

	newKey = nameNote(self, friend, noteCount[0], noteCount[1]);

	return newKey;
}

//name note...obvs
function nameNote(me, them, num, oct) {
	var numString = ""

	switch (num) {
		case 1: numString = "c"; break;
		case 2: numString = "c#"; break;
		case 3: numString = "d"; break;
		case 4: numString = "d#"; break;
		case 5: numString = "e"; break;
		case 6: numString = "f"; break;
		case 7: numString = "f#"; break;
		case 8: numString = "g"; break;
		case 9: numString = "g#"; break;
		case 10: numString = "a"; break;
		case 11: numString = "a#"; break;
		case 12: numString = "b"; break;
	}

	if (numString == them.letter && oct == them.octave) {
		numString = me.letter + me.octave;
	} else {numString = numString + oct.toString();}

	return numString;
}

//find note
function keyCount(countFrom, countAmount, octave, dir) {
	var count = 0;
	var newOctave = octave;
	var newKey = countFrom;
	var both = [];

	while(count < countAmount) {
		if (dir == "up") {newKey++;}
		if (dir == "down") {newKey--;}

		if (newKey > 12) {newOctave++; newKey = 1;}
		if (newKey < 1) {newOctave--; newKey = 12;}
		count++;
	}

	both.push(newKey);
	both.push(newOctave);

	return both;
}

//find distance
function distCount(countFrom, countTo, sOct, fOct, dir) {
	var distance = 0;
	var count = countFrom;
	var nOct = sOct;

	while (count != countTo || nOct != fOct) {
		if (dir == "up") {
			distance++;
			count++;
		}

		if (dir == "down") {
			distance++;
			count--;
		}

		if (count > 12) {nOct++; count = 1;}
		if (count < 1) {nOct--; count = 12;}
	}

	return distance;
}

function writeFile(filePath, contents) {
	filePath = path.resolve(filePath);
	fs.writeFileSync(filePath, contents);
}

var names = getFileNamesInFolder(sfPath);
var folderName = path.basename(sfPath);

//write sfz to text file
writeFile(path.join(sfPath, folderName + ".sfz"), parseSFZ(names));<|endoftext|>


<commit_before>// dependencies
const express = require("express");
const path = require("path");

// express middleware
const cookieParser = require("cookie-parser");
const morgan = require("morgan");
// templating engine
const htmlEngine = require("gaikan");

var app = express();

/**
 * express configuration
 */
app.use(cookieParser());

app.set("views", path.join(__dirname, "views"));
app.set("view engine", ".html");
app.engine("html", htmlEngine);

app.use("/static", express.static(path.join(__dirname, "static")));

var config = loadConfig();

var ShieldProxy = require("./lib/shield-proxy");
var ShieldAccess = require("./lib/shield-access");
var AuthService = require("./lib/auth-service");
var authService = AuthService(app);
var shieldAuth = [require("./lib/check-auth")(authService), require("./lib/auth/basic-auth")(authService)];

// setup html engine helpers
// TODO: make single param function
htmlEngine.set["hasRole"] = function (auth, role) {
    return role == undefined || auth && auth.hasRole(root, role);
};

// setup access
app.locals.secretKey = config.secretKey;
app.locals.users = config.users;

function loadConfig(){
    var fileName = path.join(__dirname, "root", "config.json");
    return require(fileName);
}

function createShield(app){
    var shieldMapping = express.Router();
    // shield authentication
    shieldMapping.route("*").all(shieldAuth);
    // shield access controll
    if(app.hasOwnProperty("access")){
        shieldMapping.route("*").all(ShieldAccess(app.access));
    }
    if(app.hasOwnProperty("url")) {
        // shield proxy
        shieldMapping.route("*").all(ShieldProxy(app.url));
    }
    // link
    this.use(app.path, shieldMapping);
    // add associated app module
    if(app.hasOwnProperty("module")) {
        var moduleName = (app.development ? "./apps/" : "") + app.module;
        // we need to link it this way to get mount event
        this.use(app.path, require(moduleName));
    }
}

function bootstrap(logger, env) {

    var server = require("./lib/shield-start").create({
        rootDir: path.join(__dirname, "root"),
        tls: config.tls
    }, app);
    app.server = server;

    if (env == "development") {
        app.use(morgan(logger.format, logger.options));
    }
    app.route("/").all(shieldAuth[0]);
    app.route("/").get(function(req, res){
        res.status(200).render("index", { title: "Mapping", apps: config.apps });
    });

    config.apps.forEach(createShield, app);

    /**
     * Not found handler
     */
    app.use(function(req, res){
        res.status(404).render("404", { title: "404" });
    });

    /**
     * Error handler
     */
    if (env == "development") {
        app.use(function errorHandler(err, req, res, next) { //eslint-disable-line
            var stack = (err.stack || "").split("\n").slice(1);
            var message = err.message;
            app.locals.logger.error(err.stack);
            res.status(500).render("500", { title: "500", err: {
                message: message,
                stack: stack
            }});
        });
    }

    return server;
}

/**
 * run server
 */
function startServer() {

    var env = app.get("env");
    var logger = app.locals.logger = require("./lib/shield-logger");

    bootstrap(logger, env).on("error", function(err){
        app.locals.logger.error(err);
    })
    .listen(config.port || 8080, config.hostname, function() {
        app.locals.logger.log("[%s] listening on port %d (%s)", env, this.address().port, this.type);
    });
}

if(require.main === module){
    // generate password hash
    if(process.argv[2] == "hash"){
        console.log(AuthService.generateKey({pass: process.argv[3]}, app.locals.secretKey)); //eslint-disable-line
        return;
    }
    startServer();
}else {
    module.exports = startServer;
}<commit_msg>security enhancements<commit_after>// dependencies
const express = require("express");
const path = require("path");

// express middleware
const cookieParser = require("cookie-parser");
const morgan = require("morgan");
// templating engine
const htmlEngine = require("gaikan");

var app = express();

/**
 * express configuration
 */
app.use(cookieParser());

app.set("views", path.join(__dirname, "views"));
app.set("view engine", ".html");
app.engine("html", htmlEngine);

app.use("/static", express.static(path.join(__dirname, "static")));

var config = loadConfig();

var ShieldProxy = require("./lib/shield-proxy");
var ShieldAccess = require("./lib/shield-access");
var AuthService = require("./lib/auth-service");
var authService = AuthService(app);
var shieldAuth = [require("./lib/check-auth")(authService), require("./lib/auth/basic-auth")(authService)];

// setup html engine helpers
// TODO: make single param function
htmlEngine.set["hasRole"] = function (auth, role) {
    return role == undefined || auth && auth.hasRole(root, role);
};

// setup access
app.locals.secretKey = config.secretKey;
app.locals.users = config.users;

function loadConfig(){
    var fileName = path.join(__dirname, "root", "config.json");
    return require(fileName);
}

function createShield(app){
    var shieldMapping = express.Router();
    // shield authentication
    shieldMapping.route("*").all(shieldAuth);
    // shield access controll
    if(app.hasOwnProperty("access")){
        shieldMapping.route("*").all(ShieldAccess(app.access));
    }
    if(app.hasOwnProperty("url")) {
        // shield proxy
        shieldMapping.route("*").all(ShieldProxy(app.url));
    }
    // link
    this.use(app.path, shieldMapping);
    // add associated app module
    if(app.hasOwnProperty("module")) {
        var moduleName = (app.development ? "./apps/" : "") + app.module;
        // we need to link it this way to get mount event
        var handler = require(moduleName);
        if(typeof handler.disable == "function") {
            handler.disable("x-powered-by");
        }
        this.use(app.path, handler);
    }
}

function bootstrap(logger, env) {

    var server = require("./lib/shield-start").create({
        rootDir: path.join(__dirname, "root"),
        tls: config.tls
    }, app);
    app.server = server;

    app.use(morgan(logger.format, logger.options));

    app.route("/").all(shieldAuth[0]);
    app.route("/").get(function(req, res){
        res.status(200).render("index", { title: "Mapping", apps: config.apps });
    });

    config.apps.forEach(createShield, app);

    /**
     * Not found handler
     */
    app.use(function(req, res){
        res.status(404).render("404", { title: "404" });
    });

    /**
     * Error handler
     */
    if (env == "development") {
        app.use(function errorHandler(err, req, res, next) { //eslint-disable-line
            var stack = (err.stack || "").split("\n").slice(1);
            var message = err.message || err;
            logger.error(err.stack || err);
            res.status(500).render("500", { title: "500", err: {
                message: message,
                stack: stack
            }});
        });
    } else {
        app.use(function errorHandler(err, req, res, next) { //eslint-disable-line
            logger.error(err.stack || err);
            res.status(500).render("500", { title: "500", err: {
                message: "Check server logs.",
            }});
        });
        app.disable("x-powered-by");
    }

    return server;
}

/**
 * run server
 */
function startServer() {

    var env = app.get("env");
    var logger = app.locals.logger = require("./lib/shield-logger");

    bootstrap(logger, env).on("error", function(err){
        logger.error(err);
    })
    .listen(config.port || 8080, config.hostname, function() {
        logger.log("[%s] listening on port %d (%s)", env, this.address().port, this.type);
    });
}

if(require.main === module){
    // generate password hash
    if(process.argv[2] == "hash"){
        console.log(AuthService.generateKey({pass: process.argv[3]}, app.locals.secretKey)); //eslint-disable-line
        return;
    }
    startServer();
}else {
    module.exports = startServer;
}<|endoftext|>


<commit_before>var irc = require("irc");
var repl = require("repl");
var fs = require("fs");

var bot = new irc.Client("irc.awfulnet.org", "simbot", {
	userName: "simbot",
	realName: "sim642",
	autoRejoin: false,
	channels: [],
});
bot.conn.setTimeout(180 * 1000);
bot.conn.on("timeout", function() {
	bot.conn.destroy();
	//bot.connect();
});

bot.on("error", function(message) {
	console.log(message);
});

bot.on("registered", function(message) {
	bot.send("UMODE2", "+B");
});

bot.plugins = require("./plugins");

fs.readFile("autoload.json", function(err, data) {
	var autoload = JSON.parse(data).autoload;
	for (var i = 0; i < autoload.length; i++) {
		console.log(autoload[i]);
		bot.plugins.load(autoload[i]);
	}
});

process.on("SIGINT", function() {
	for (var name in bot.plugins) {
		if (bot.plugins[name].name) {
			bot.plugins.unload(name);
		}
	}
	process.exit(0);
});

repl.start({
	useGlobal: true
}).context.bot = bot;

<commit_msg>Lowered message split<commit_after>var irc = require("irc");
var repl = require("repl");
var fs = require("fs");

var bot = new irc.Client("irc.awfulnet.org", "simbot", {
	userName: "simbot",
	realName: "sim642",
	autoRejoin: false,
	channels: [],
	messageSplit: 300,
});
bot.conn.setTimeout(180 * 1000);
bot.conn.on("timeout", function() {
	bot.conn.destroy();
	//bot.connect();
});

bot.on("error", function(message) {
	console.log(message);
});

bot.on("registered", function(message) {
	bot.send("UMODE2", "+B");
});

bot.plugins = require("./plugins");

fs.readFile("autoload.json", function(err, data) {
	var autoload = JSON.parse(data).autoload;
	for (var i = 0; i < autoload.length; i++) {
		console.log(autoload[i]);
		bot.plugins.load(autoload[i]);
	}
});

process.on("SIGINT", function() {
	for (var name in bot.plugins) {
		if (bot.plugins[name].name) {
			bot.plugins.unload(name);
		}
	}
	process.exit(0);
});

repl.start({
	useGlobal: true
}).context.bot = bot;

<|endoftext|>


<commit_before>'use strict';

function $(selector){
    return document.querySelector(selector);
}

function $All(selector){
    return document.querySelectorAll(selector);
}

function assignGlobalObjects(list){
    for(let item of Object.keys(list))
	window[item] = $(list[item]);
}

function create(type, properties){
    var element = document.createElement(type);

    /* no property is set, return the new element without processing */
    if(!properties)
	return element;

    /* shortcut for textContent */
    if(typeof properties == 'string'){
	element.textContent = properties;
	return element;
    }

    /* shortcut for children */
    if(Array.isArray(properties)){
	let children = properties;
	properties = {};
	properties.children = children;
    }

    /* assign array-like data structures */
    if(properties.children){
	for(let child of properties.children){
	    if(!child)
		continue;
	    element.appendChild(child);
	}
	delete properties.children;
    }
    if(properties.classList){
	for(let className of properties.classList){
	    if(!className)
		continue;
	    element.classList.add(className);
	}
	delete properties.classList;
    }
    /* assign objects */
    ['style', 'dataset'].forEach(function(item){
	if(properties[item]){
	    for(let I of Object.keys(properties[item])){
		if(!properties[item][I])
		    continue;
		element[item][I] = properties[item][I];
	    }
	    delete properties[item];
	}
    });

    /* assign other properties */
    for(let I of Object.keys(properties)){
	if(!properties[I])
	    continue;
	element[I] = properties[I];
    }

    return element;
}

function duplicate(node){
    return document.importNode(node, true);
}

function hide(element){
    if(element.style.display == 'none')
	return false;
    if(element.style.display)
	element.dataset.style_display = element.style.display;
    element.style.display = 'none';
    return true;
}

function show(element){
    if(element.style.display != 'none')
	return false;
    if(element.dataset.style_display){
	element.style.display = element.dataset.style_display;
	delete element.dataset.style_display;
    }else{
	element.style.display = '';
    }
    return true;
}

function printf(args){
    var string = arguments[0];
    /* note that %n in the string must be in ascending order */
    /* like 'Foo %1 Bar %2 %3' */
    var i;
    for(i=arguments.length-1; i>0; i--)
	string = string.replace('%'+i, arguments[i]);
    return string;
}
<commit_msg>Add assignMethods() (moved from subway-ui)<commit_after>'use strict';

function $(selector){
    return document.querySelector(selector);
}

function $All(selector){
    return document.querySelectorAll(selector);
}

function assignGlobalObjects(list){
    for(let item of Object.keys(list))
	window[item] = $(list[item]);
}

function assignMethods(constructor, methods){
    for(let I of Object.keys(methods))
	constructor.prototype[I] = methods[I];
}

function create(type, properties){
    var element = document.createElement(type);

    /* no property is set, return the new element without processing */
    if(!properties)
	return element;

    /* shortcut for textContent */
    if(typeof properties == 'string'){
	element.textContent = properties;
	return element;
    }

    /* shortcut for children */
    if(Array.isArray(properties)){
	let children = properties;
	properties = {};
	properties.children = children;
    }

    /* assign array-like data structures */
    if(properties.children){
	for(let child of properties.children){
	    if(!child)
		continue;
	    element.appendChild(child);
	}
	delete properties.children;
    }
    if(properties.classList){
	for(let className of properties.classList){
	    if(!className)
		continue;
	    element.classList.add(className);
	}
	delete properties.classList;
    }
    /* assign objects */
    ['style', 'dataset'].forEach(function(item){
	if(properties[item]){
	    for(let I of Object.keys(properties[item])){
		if(!properties[item][I])
		    continue;
		element[item][I] = properties[item][I];
	    }
	    delete properties[item];
	}
    });

    /* assign other properties */
    for(let I of Object.keys(properties)){
	if(!properties[I])
	    continue;
	element[I] = properties[I];
    }

    return element;
}

function duplicate(node){
    return document.importNode(node, true);
}

function hide(element){
    if(element.style.display == 'none')
	return false;
    if(element.style.display)
	element.dataset.style_display = element.style.display;
    element.style.display = 'none';
    return true;
}

function show(element){
    if(element.style.display != 'none')
	return false;
    if(element.dataset.style_display){
	element.style.display = element.dataset.style_display;
	delete element.dataset.style_display;
    }else{
	element.style.display = '';
    }
    return true;
}

function printf(args){
    var string = arguments[0];
    /* note that %n in the string must be in ascending order */
    /* like 'Foo %1 Bar %2 %3' */
    var i;
    for(i=arguments.length-1; i>0; i--)
	string = string.replace('%'+i, arguments[i]);
    return string;
}
<|endoftext|>


<commit_before>//If this extention is loaded in the master process.
if (server.isMaster) {

	console.info("Master extention loading!!!") ;

	//Set the global variable "set_in_master" to the value "Hello :)".
	server.setGlobal("set_in_master","Hello :)").then(_=>{

		//When it is set, get the variable and log it.
		server.getGlobal("set_in_master").then(d=>console.info(d)) ;

	}) ;

}

//Not master, so worker.
else {

	console.info("Worker extention loading!!!") ;

	//Get the global var "set_in_master" that we set in the master and log it.
	server.getGlobal("set_in_master").then(d=>console.info("Getting the global set in master resolved:",d)) ;

	//Request handle is called as soon as  a request is recieved & before anything important happens.
	server.handle("request",(req,resp)=>{

		console.info("Got it") ;

		if (req.url === "/Hello_World") {

			resp.writeHead(200) ;
			resp.end("YAY") ;
			//When true is returned, the server will stop handling this request, it is to say that you have handled it.
			return true ;

		}

		//Get the global variable "hello_world"
		server.getGlobal("hello_world").then(d=>{

			//Log the variable, it will be undefined the first time the page loads because it has not been set yet.
			console.info(d) ;
			//Now we set the variable to "test"
			server.setGlobal("hello_world","test") ;

		}) ;

		//We return false & thus the server carries on handling the request as it would.
		return false ;

	}) ;

	//This is called when a request has been processed, redirects, host alieses etc applied.
	server.handle("fullrequest",(req,resp)=>{

		console.info("Got it - full") ;

		//The orig_url property is the origional, unchanged URL.
		console.info(req.orig_url) ;

		//The URL now has the hostname at the start of it & is lower cased.
		console.info(req.url) ;

		if (req.url === "/hello_world_yay") {

			resp.writeHead(200) ;
			resp.end("YAY 2.0") ;
			//Return true so ther server no longer handles it.
			return true ;

		}

		//The server can carry on because we return false.
		return false ;

	}) ;

	server.handle("request",(req,resp)=>{

		//Multiple handles can be set, they will all get fired, even if 1 returns true, so remember that.
		console.info("This also gets triggered!") ;

		//A promise can also be returned, the resolve value is the equivilent of the return value.
		return new Promise(resolve=>resolve(false)) ;

	}) ;

}<commit_msg>Added locked extention demo<commit_after>//If this extention is loaded in the master process.
if (server.isMaster) {

	console.info("Master extention loading!!!") ;

	//Set the global variable "set_in_master" to the value "Hello :)".
	server.setGlobal("set_in_master","Hello :)").then(_=>{

		//When it is set, get the variable and log it.
		server.getGlobal("set_in_master").then(d=>console.info(d)) ;

	}) ;

}

//Not master, so worker.
else {

	console.info("Worker extention loading!!!") ;

	//Get the global var "set_in_master" that we set in the master and log it.
	server.getGlobal("set_in_master").then(d=>console.info("Getting the global set in master resolved:",d)) ;

	//Request handle is called as soon as  a request is recieved & before anything important happens.
	server.handle("request",(req,resp)=>{

		console.info("Got it") ;

		if (req.url === "/Hello_World") {

			resp.writeHead(200) ;
			resp.end("YAY") ;
			//When true is returned, the server will stop handling this request, it is to say that you have handled it.
			return true ;

		}

		//Get the global variable "hello_world"
		server.getGlobal("hello_world").then(d=>{

			//Log the variable, it will be undefined the first time the page loads because it has not been set yet.
			console.info(d) ;
			//Now we set the variable to "test"
			server.setGlobal("hello_world","test") ;

		}) ;

		//We return false & thus the server carries on handling the request as it would.
		return false ;

	}) ;

	//This is called when a request has been processed, redirects, host alieses etc applied.
	server.handle("fullrequest",(req,resp)=>{

		console.info("Got it - full") ;

		//The orig_url property is the origional, unchanged URL.
		console.info(req.orig_url) ;

		//The URL now has the hostname at the start of it & is lower cased.
		console.info(req.url) ;

		if (req.url === "/hello_world_yay") {

			resp.writeHead(200) ;
			resp.end("YAY 2.0") ;
			//Return true so ther server no longer handles it.
			return true ;

		}

		//The server can carry on because we return false.
		return false ;

	}) ;

	server.handle("request",(req,resp)=>{

		//Multiple handles can be set, they will all get fired, even if 1 returns true, so remember that.
		console.info("This also gets triggered!") ;

		//A promise can also be returned, the resolve value is the equivilent of the return value.
		return new Promise(resolve=>resolve(false)) ;

	}) ;

}

//Create a new lock, this will give the extention we will load it's own variable pool (that we can access).
let demoLock = new server.lock("demo-lock") ;

//Load an extention with our lock.
server.loadExt("./locked-demo.js",demoLock) ;<|endoftext|>


<commit_before>function setup() {
  createCanvas(600,400);
}

function draw(){
  background(255);

  for(var x=0;x<=600;x=x+10){
    stroke(110,210,75);
    line(x,0,x,400);

    var y=random(390);
    stroke(110,210,75);
    line(x,y,x+5,y+5);
    line(x+5,y+5,x,y+10);

    stroke(255);
    line(x,y+1,x,y+9);
    noLoop();
  }

}
<commit_msg>Delete sketch.js<commit_after><|endoftext|>


<commit_before>(function(){
	angular
		.module('app', ['angular-datepicker']);
})();

(function(){
	angular
		.module('app')
		.controller('PickDate', PickDate);

	function PickDate(){

	}
})();<commit_msg>onChangeDate demo<commit_after>(function(){
	angular
		.module('app', ['angular-datepicker']);
})();

(function(){
	angular
		.module('app')
		.controller('PickDate', PickDate);

	function PickDate($scope){
		$scope.date = '2009-06-25T00:00:00-03:00';
        $scope.onChangeDateFn = function(){
            console.log(arguments);
        }
	}
})();<|endoftext|>


<commit_before>var fs = require('fs'),
	sys = require('sys'),
    child_process = require('child_process');

var start = exports.start = function (project, createCallback, exitCallback) {
	var tempFile = __dirname + '/tmp/' + Math.random() + '.js';
	fs.writeFile(tempFile, project.lastHandler.code, function(err) {
		if (err)
		    throw err;
		var aggrOut = '';
		var aggrErr = '';
		var node = child_process.spawn('node', [tempFile]);
		createCallback(node.pid);
		node.stdout.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrOut += data;
		});
		node.stderr.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrErr += data;
		});
		node.on('exit', function (code) {
		    clearTimeout(timeoutId);
		    aggrOut += '\nExit code: ' + code;
		    fs.unlink(tempFile, function (err) {
		        if (err)
					console.log("Unable to delete " + tempFile + ".");
				exitCallback(aggrOut, aggrErr);
		    });
		});
		var timeoutCallback = function (child) {
		    if (child) {
		        console.log("Killing process " + child.pid);
		        child.kill('SIGKILL');
		    }
		};
		var timeoutId = setTimeout(timeoutCallback, 300000, node)
		return node.pid;
	});
}

var stop = exports.stop = function (pid) {
	if (pid) {
        console.log("Killing process " + pid);
        try {
		    process.kill(pid, 'SIGKILL');
		}
		catch(err) {
		    console.log(err);
		}
	}
}

var debug = exports.debug = function (project, createCallback, exitCallback) {
	var tempFile = __dirname + '/tmp/' + Math.random() + '.js';
	fs.writeFile(tempFile, project.lastHandler.code, function(err) {
		if (err)
		    throw err;
		var aggrOut = '';
		var aggrErr = '';
		var node = child_process.spawn('node', [__dirname + '/node-inspector/bin/inspector.js', '--start=' + tempFile]);
		createCallback(node.pid);
		node.stdout.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrOut += data;
		});
		node.stderr.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrErr += data;
		});
		node.on('exit', function (code) {
		    clearTimeout(timeoutId);
		    aggrOut += '\nExit code: ' + code;
		    fs.unlink(tempFile, function (err) {
		        if (err)
					console.log("Unable to delete " + tempFile + ".");
				exitCallback(aggrOut, aggrErr);
		    });
		});
		var timeoutCallback = function (child) {
		    if (child) {
		        console.log("Killing process " + child.pid);
		        child.kill('SIGKILL');
		    }
		};
		var timeoutId = setTimeout(timeoutCallback, 300000, node)
		return node.pid;
	});
}

<commit_msg>Expect the node-inspector package to be installed.<commit_after>var fs = require('fs'),
	sys = require('sys'),
    child_process = require('child_process');

var start = exports.start = function (project, createCallback, exitCallback) {
	var tempFile = __dirname + '/tmp/' + Math.random() + '.js';
	fs.writeFile(tempFile, project.lastHandler.code, function(err) {
		if (err)
		    throw err;
		var aggrOut = '';
		var aggrErr = '';
		var node = child_process.spawn('node', [tempFile]);
		createCallback(node.pid);
		node.stdout.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrOut += data;
		});
		node.stderr.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrErr += data;
		});
		node.on('exit', function (code) {
		    clearTimeout(timeoutId);
		    aggrOut += '\nExit code: ' + code;
		    fs.unlink(tempFile, function (err) {
		        if (err)
					console.log("Unable to delete " + tempFile + ".");
				exitCallback(aggrOut, aggrErr);
		    });
		});
		var timeoutCallback = function (child) {
		    if (child) {
		        console.log("Killing process " + child.pid);
		        child.kill('SIGKILL');
		    }
		};
		var timeoutId = setTimeout(timeoutCallback, 300000, node)
		return node.pid;
	});
}

var stop = exports.stop = function (pid) {
	if (pid) {
        console.log("Killing process " + pid);
        try {
		    process.kill(pid, 'SIGKILL');
		}
		catch(err) {
		    console.log(err);
		}
	}
}

var debug = exports.debug = function (project, createCallback, exitCallback) {
	var tempFile = __dirname + '/tmp/' + Math.random() + '.js';
	fs.writeFile(tempFile, project.lastHandler.code, function(err) {
		if (err)
		    throw err;
		var aggrOut = '';
		var aggrErr = '';
		var node = child_process.spawn('node-inspector', ['--start=' + tempFile]);
		createCallback(node.pid);
		node.stdout.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrOut += data;
		});
		node.stderr.on('data', function (data) {
		    console.log('Stdout data: ' + data);
		    aggrErr += data;
		});
		node.on('exit', function (code) {
		    clearTimeout(timeoutId);
		    aggrOut += '\nExit code: ' + code;
		    fs.unlink(tempFile, function (err) {
		        if (err)
					console.log("Unable to delete " + tempFile + ".");
				exitCallback(aggrOut, aggrErr);
		    });
		});
		var timeoutCallback = function (child) {
		    if (child) {
		        console.log("Killing process " + child.pid);
		        child.kill('SIGKILL');
		    }
		};
		var timeoutId = setTimeout(timeoutCallback, 300000, node)
		return node.pid;
	});
}

<|endoftext|>