<commit_before>var undum = require('undum-commonjs'),
    md = require('markdown-it'),
    $ = require('jquery');

/* ---------------------------------------------------------------------------
  Raconteur is a rethought API for Undum, featuring more usable interfaces
  which coalesce as a DSL for defining Undum stories.
----------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------
  Helper functions
----------------------------------------------------------------------------*/

/*
  Normalises the whitespace on a string.
*/

String.prototype.normaliseTabs = function () {
  var lines = this.split('\n');
  var indents = lines
    .filter((l) => l !== '') // Ignore empty lines
    .map((l) => l.match(/^\s+/))
    .map(function (m) {
      if (m === null) return '';
      return m[0];
    });
  var smallestIndent = indents.reduce(function(max, curr) {
    if (curr.length < max.length) return curr;
    return max;
  }); // Find the "bottom" indentation level
  return lines.map(function (l) {
    return l.replace(new RegExp('^' + smallestIndent), '');
  }).join('\n');
};

/* Agnostic Call */
/*
  Many properties in Raconteur can be either a String, or a function that
  takes some objects from the game state (character, system, and the current
  situation) and returns a String. Or in Haskell terms:
  String | (CharacterObject -> SystemObject -> SituationString -> String)

  fcall() is added to the prototypes of both String and Function to handle
  these situations. When called on a Function, it's an alias for
  Function#call(); when called on a String, it only returns the string itself,
  discarding any input.
*/

Function.prototype.fcall = Function.prototype.call;

String.prototype.fcall = function () {return this;};

/*
  Markdown renderer, defined with options.
*/

var markdown = new md({
  typographer: true, // Use smart quotes.
  html: true // Passthrough html.
});

/*
  Ensures a string is a HTML string, by wrapping it in span tags.
*/

String.prototype.spanWrap = function () {
  return `<span>${this}</span>`;
};

/*
  Adds the "fade" class to a htmlString.
*/

String.prototype.fade = function () {
  return $(this).addClass('fade');
};

/* Situations ----------------------------------------------------------------

  The prototype RaconteurSituation is the basic spec for situations
  created with Raconteur. It should be able to handle any use case for Undum.

  Properties:

    (In addition to properties inherited from undum.Situation)

    actions :: {key: (character, system, from) -> null}

    An object containing definitions for actions, which are called when an
    action without a special marker (writer, inserter, replacer) is called
    when the situation is current, usually by clicking an action link.

    after :: (character, system, from) -> null

    A function that is called right after printing the content of the
    situation. Useful for housekeeping tasks (Such as changing character
    stats) or implementing custom behaviour in general.

    before :: (character, system, from) -> null

    Similar to after, but called first

    choices :: [String]

    A list of situation names and/or tags that can be listed as choices for
    this situation. That list will be further filtered by CanView and
    CanChoose.

    content :: markdownString | (character, system, from) -> markdownString

    The main content of the situation, printed when the situation is entered.

    visited :: Number

    Defaults to 0. Incremented every time the situation is entered.

    writers :: {key: markdownString | (character, system, from) -> markdownString}

    An object containing definitions for special actions called by inserter,
    writer, and replacer links. Note that the content of writer links will be
    interpreted as a regular markdownString, while the content of replacer
    and inserter links, on the assumption that it's meant to be written into
    an existing paragraph, will be interpreted as a inline markdown.

*/

var RaconteurSituation = function (spec) {
  undum.Situation.call(this, spec);

  // Add all properties of the spec to the object, indiscriminately.
  Object.keys(spec).forEach( key => {
    if (this[key] === undefined) {
      this[key] = spec[key];
    }
  });

  this.visited = 0;

};

RaconteurSituation.inherits(undum.Situation);

/*
  Undum calls Situation.enter every time a situation is entered, and
  passes it three arguments; The character object, the system object,
  and a string referencing the previous situation, or null if there is
  none (ie, for the starting situation).

  Raconteur's version of enter is set up to fulfill most use cases.
*/

RaconteurSituation.prototype.enter = function (character, system, f) {

  this.visited++;

  if (this.before) this.before(character, system, f);

  if (this.content) {
    system.write(
      markdown.render(
        this.content.fcall(this, character, system, f).normaliseTabs()));
  }

  if (this.after) this.after(character, system, f);

  if (this.choices) {
    let choices = system.getSituationIdChoices(this.choices,
      this.minChoices, this.maxChoices);
    system.writeChoices(choices);
  }
};

/*
  Situation.prototype.act() is called by Undum whenever an action link
  (Ie, a link that doesn't point at another situation or an external URL) is
  clicked.

  Raconteur's version of act() is set up to implement commonly used
  functionality: "writer" links, "replacer" links, "inserter" links, and
  generic "action" links that call functions which access the underlying
  Undum API.
*/

RaconteurSituation.prototype.act = function (character, system, action) {
  var actionClass,
      self = this;

  var responses = {
    writer: function (ref) {
      var beforeOpts = undefined;
      if (self.writers[ref] === undefined) {
        console.log(self);
        throw new Error("Tried to call undefined writer:" + ref);
      }
      if ($('.options')) {
        system.writeBefore(
          markdown.render(
            self.writers[ref].fcall(self, character, system, action))
            .fade(), '.options');
      } else {
        system.write(
          markdown.render(
            self.writers[ref].fcall(self, character, system, action)
          ).fade());
      }
    },
    replacer: function (ref) {
      if (self.writers[ref] === undefined) {
        throw new Error("Tried to call undefined replacer:" + ref);
      }
      system.replaceWith(
        markdown.renderInline(
          self.writers[ref].fcall(self, character, system, action)
        ).spanWrap().fade(), `#${ref}`);
    },
    inserter: function (ref) {
      if (self.writers[ref] === undefined) {
        throw new Error("Tried to call undefined inserter:" + ref);
      }
      system.writeInto(
        markdown.renderInline(
          self.writers[ref].fcall(self, character, system, action)
          ).spanWrap().fade(), `#${ref}`);
    }
  };

  if (actionClass = action.match(/^_(\w+)_(.+)$/)) {
    responses[actionClass[1]](actionClass[2]);
  } else if (self.actions.hasOwnProperty(action)) {
    self.actions[action].call(self, character, system, action);
  } else {
    throw new Err(`Action "${action}" attempted with no corresponding` +
      'action in current situation.');
  }

};

module.exports = function (name, spec) {
  spec.name = name;
  return (undum.game.situations[name] = new RaconteurSituation(spec));
};<commit_msg>Added hacky function to globally export undum<commit_after>var undum = require('undum-commonjs'),
    md = require('markdown-it'),
    $ = require('jquery');

/* ---------------------------------------------------------------------------
  Raconteur is a rethought API for Undum, featuring more usable interfaces
  which coalesce as a DSL for defining Undum stories.
----------------------------------------------------------------------------*/

/* ---------------------------------------------------------------------------
  Helper functions
----------------------------------------------------------------------------*/

/*
  Normalises the whitespace on a string.
*/

String.prototype.normaliseTabs = function () {
  var lines = this.split('\n');
  var indents = lines
    .filter((l) => l !== '') // Ignore empty lines
    .map((l) => l.match(/^\s+/))
    .map(function (m) {
      if (m === null) return '';
      return m[0];
    });
  var smallestIndent = indents.reduce(function(max, curr) {
    if (curr.length < max.length) return curr;
    return max;
  }); // Find the "bottom" indentation level
  return lines.map(function (l) {
    return l.replace(new RegExp('^' + smallestIndent), '');
  }).join('\n');
};

/* Agnostic Call */
/*
  Many properties in Raconteur can be either a String, or a function that
  takes some objects from the game state (character, system, and the current
  situation) and returns a String. Or in Haskell terms:
  String | (CharacterObject -> SystemObject -> SituationString -> String)

  fcall() is added to the prototypes of both String and Function to handle
  these situations. When called on a Function, it's an alias for
  Function#call(); when called on a String, it only returns the string itself,
  discarding any input.
*/

Function.prototype.fcall = Function.prototype.call;

String.prototype.fcall = function () {return this;};

/*
  Markdown renderer, defined with options.
*/

var markdown = new md({
  typographer: true, // Use smart quotes.
  html: true // Passthrough html.
});

/*
  Ensures a string is a HTML string, by wrapping it in span tags.
*/

String.prototype.spanWrap = function () {
  return `<span>${this}</span>`;
};

/*
  Adds the "fade" class to a htmlString.
*/

String.prototype.fade = function () {
  return $(this).addClass('fade');
};

/* Situations ----------------------------------------------------------------

  The prototype RaconteurSituation is the basic spec for situations
  created with Raconteur. It should be able to handle any use case for Undum.

  Properties:

    (In addition to properties inherited from undum.Situation)

    actions :: {key: (character, system, from) -> null}

    An object containing definitions for actions, which are called when an
    action without a special marker (writer, inserter, replacer) is called
    when the situation is current, usually by clicking an action link.

    after :: (character, system, from) -> null

    A function that is called right after printing the content of the
    situation. Useful for housekeeping tasks (Such as changing character
    stats) or implementing custom behaviour in general.

    before :: (character, system, from) -> null

    Similar to after, but called first

    choices :: [String]

    A list of situation names and/or tags that can be listed as choices for
    this situation. That list will be further filtered by CanView and
    CanChoose.

    content :: markdownString | (character, system, from) -> markdownString

    The main content of the situation, printed when the situation is entered.

    visited :: Number

    Defaults to 0. Incremented every time the situation is entered.

    writers :: {key: markdownString | (character, system, from) -> markdownString}

    An object containing definitions for special actions called by inserter,
    writer, and replacer links. Note that the content of writer links will be
    interpreted as a regular markdownString, while the content of replacer
    and inserter links, on the assumption that it's meant to be written into
    an existing paragraph, will be interpreted as a inline markdown.

*/

var RaconteurSituation = function (spec) {
  undum.Situation.call(this, spec);

  // Add all properties of the spec to the object, indiscriminately.
  Object.keys(spec).forEach( key => {
    if (this[key] === undefined) {
      this[key] = spec[key];
    }
  });

  this.visited = 0;

};

RaconteurSituation.inherits(undum.Situation);

/*
  Undum calls Situation.enter every time a situation is entered, and
  passes it three arguments; The character object, the system object,
  and a string referencing the previous situation, or null if there is
  none (ie, for the starting situation).

  Raconteur's version of enter is set up to fulfill most use cases.
*/

RaconteurSituation.prototype.enter = function (character, system, f) {

  this.visited++;

  if (this.before) this.before(character, system, f);

  if (this.content) {
    system.write(
      markdown.render(
        this.content.fcall(this, character, system, f).normaliseTabs()));
  }

  if (this.after) this.after(character, system, f);

  if (this.choices) {
    let choices = system.getSituationIdChoices(this.choices,
      this.minChoices, this.maxChoices);
    system.writeChoices(choices);
  }
};

/*
  Situation.prototype.act() is called by Undum whenever an action link
  (Ie, a link that doesn't point at another situation or an external URL) is
  clicked.

  Raconteur's version of act() is set up to implement commonly used
  functionality: "writer" links, "replacer" links, "inserter" links, and
  generic "action" links that call functions which access the underlying
  Undum API.
*/

RaconteurSituation.prototype.act = function (character, system, action) {
  var actionClass,
      self = this;

  var responses = {
    writer: function (ref) {
      var beforeOpts = undefined;
      if (self.writers[ref] === undefined) {
        throw new Error("Tried to call undefined writer:" + ref);
      }
      if ($('.options')) {
        system.writeBefore(
          markdown.render(
            self.writers[ref].fcall(self, character, system, action))
            .fade(), '.options');
      } else {
        system.write(
          markdown.render(
            self.writers[ref].fcall(self, character, system, action)
          ).fade());
      }
    },
    replacer: function (ref) {
      if (self.writers[ref] === undefined) {
        throw new Error("Tried to call undefined replacer:" + ref);
      }
      system.replaceWith(
        markdown.renderInline(
          self.writers[ref].fcall(self, character, system, action)
        ).spanWrap().fade(), `#${ref}`);
    },
    inserter: function (ref) {
      if (self.writers[ref] === undefined) {
        throw new Error("Tried to call undefined inserter:" + ref);
      }
      system.writeInto(
        markdown.renderInline(
          self.writers[ref].fcall(self, character, system, action)
          ).spanWrap().fade(), `#${ref}`);
    }
  };

  if (actionClass = action.match(/^_(\w+)_(.+)$/)) {
    responses[actionClass[1]](actionClass[2]);
  } else if (self.actions.hasOwnProperty(action)) {
    self.actions[action].call(self, character, system, action);
  } else {
    throw new Err(`Action "${action}" attempted with no corresponding` +
      'action in current situation.');
  }

};

module.exports = function (name, spec) {
  spec.name = name;
  return (undum.game.situations[name] = new RaconteurSituation(spec));
};

module.exports.exportUndum = function () {
  global.undum = undum;
};<|endoftext|>


<commit_before>/** Parse sieve analysis input files.
 * Expected input files:
 * 	FASTA file with vaccine ID and AA sequence
 * 	FASTA file with breakthrough sequences and IDs
 * 	CSV with seqID:treatment (vaccine/placebo) treatment
 * 	CSV with sequence mismatches (relative to vaccine) for each seqID */

/** 2D-array (of chars) representing AAs at each position in the sequence
 * for the vaccine and each sequence ID */
var sequences_raw = [];
/** Object holding a 2D-array of sequences for both the vaccine and placebo groups */
var sequences = {"vaccine":{}, "placebo":{}};
/** Object (dictionary) of sequence IDs with AA sequence (char array),
 * vac/plac, and mismatch (boolean array) */
var seqID_lookup = {};
/** Object with vaccine ID and AA sequence */
var vaccine = {};
/** Array with conservation and hxb2 info for each position */
var display_idx_map;
/* Lookup table with index for each hxb2 position*/
var refmap = {};
/** Number of people in the vaccine group */
var numvac = 0;
/** Number of people in the placebo group */
var numplac = 0;
/** Array of p-values */
var pvalues =[];
/** Array of absolute value of t-stats */
var tvalues =[];
/** Array of Entropy Values */
var entropies = {full:[],vaccine:[],placebo:[]};
/**  Object with nests of distances for each distance method */
var dists;

d3.csv("data/VTN502.trt.csv", function(assigndata)
{
	d3.text("data/VTN502.gag.MRK.fasta", function(fastadata)
	{
		doseqparsing(fastadata);
		d3.csv("data/VTN502.gag.MRK.vxmatch_site.distance.csv", function(distdata)
		{
			dodistparsing(distdata);
			d3.csv("data/TVN502.gag.MRK.vxmatch_site.results.csv", function(resultdata)
			{

			});
		});
	});
});

function doseqparsing(seqdata) {
	var lines = seqdata.split('\n');
	for (var i = 0; i < lines.length; ) {
		if (!lines[i].startsWith(">") || lines[i].length === 0) { i++; }
		else {
			var seqID = lines[i].substr(1).trim(/(\r\n|\n|\r)/gm);
			var seq = lines[i+1].split("");
			while (seq[seq.length-1].charCodeAt(0) < 32) { seq.pop(); }
			seqID_lookup[seqID].sequence = seq;
			sequences_raw.push(seq);
			if (seqID.startsWith("reference"))
			{
				vaccine.sequence = seq;
			} else if (seqID_lookup[seqID].vaccine) {
				sequences.vaccine.push(seq);
				numvac++;
			} else {
				sequences.placebo.push(seq);
				numplac++;
			}
			i += 2;
		}
	}
}

function dodistparsing(distdata)
{
	dists = d3.nest()
		.key(function(d) {return d.distance_method;})
		.rollup(function(data)
			{
				return d3.nest()
					.key(function(d) { return d.ptid; })
					.rollup(function(d) { return d.map(function(a) {return a.distance;}); })
					.entries(data);
			})
		.entries(distdata);
	display_idx_map = distdata.filter(function (d)
		{
			return d.ptid == distdata[0].ptid && d.distance_method == distdata[0].distance_method;
		}).map(function(d) {return d.display_position;});
	display_idx_map.foreach(function(d, i) {refmap[d] = i;});
}

/** Transpose 2D array */
function transpose(array) {
  return array[0].map(function (_, c) { return array.map(function (r) { return r[c]; }); });
}<commit_msg>fix conflict<commit_after>/** Parse sieve analysis input files.
 * Expected input files:
 * 	FASTA file with vaccine ID and AA sequence
 * 	FASTA file with breakthrough sequences and IDs
 * 	CSV with seqID:treatment (vaccine/placebo) treatment
 * 	CSV with sequence mismatches (relative to vaccine) for each seqID */

/** 2D-array (of chars) representing AAs at each position in the sequence
 * for the vaccine and each sequence ID */
var sequences_raw = [];
/** Object holding a 2D-array of sequences for both the vaccine and placebo groups */
var sequences = {"vaccine":{}, "placebo":{}};
/** Object (dictionary) of sequence IDs with AA sequence (char array),
 * vac/plac, and mismatch (boolean array) */
var seqID_lookup = {};
/** Object with vaccine ID and AA sequence */
var vaccine = {};
/** Array with conservation and hxb2 info for each position */
var display_idx_map;
/* Lookup table with index for each hxb2 position*/
var refmap = {};
/** Number of people in the vaccine group */
var numvac = 0;
/** Number of people in the placebo group */
var numplac = 0;
/** Array of p-values */
var pvalues =[];
/** Array of absolute value of t-stats */
var tvalues =[];
/** Array of Entropy Values */
var entropies = {full:[],vaccine:[],placebo:[]};
/**  Object with nests of distances for each distance method */
var dists;

d3.csv("data/VTN502.trt.csv", function(assigndata)
{
	parseTreatmentFile(assigndata);
	d3.text("data/VTN502.gag.MRK.fasta", function(fastadata)
	{
		doseqparsing(fastadata);
		d3.csv("data/VTN502.gag.MRK.vxmatch_site.distance.csv", function(distdata)
		{
			dodistparsing(distdata);
			d3.csv("data/TVN502.gag.MRK.vxmatch_site.results.csv", function(resultdata)
			{

			});
		});
	});
});

function parseTreatmentFile(assigndata){
	seqID_lookup = d3.nest()
		.key(function(d) {return d.ptid;})
		.rollup(function(d) {
			if (d[0].treatment.toUpperCase().startsWith("P")){
				numplac++;
				return { "mismatch": [], "sequence": [], "vaccine": false };
			} else if (d[0].treatment.toUpperCase().startsWith("V")){
				numvac++;
				return { "mismatch": [], "sequence": [], "vaccine": true };
			}
		})
		.map(assigndata);
}

function doseqparsing(seqdata) {
	var lines = seqdata.split('\n');
	for (var i = 0; i < lines.length; ) {
		if (!lines[i].startsWith(">") || lines[i].length === 0) { i++; }
		else {
			var seqID = lines[i].substr(1).trim(/(\r\n|\n|\r)/gm);
			var seq = lines[i+1].split("");
			while (seq[seq.length-1].charCodeAt(0) < 32) { seq.pop(); }
			seqID_lookup[seqID].sequence = seq;
			sequences_raw.push(seq);
			if (seqID.startsWith("reference"))
			{
				vaccine.sequence = seq;
			} else if (seqID_lookup[seqID].vaccine) {
				sequences.vaccine.push(seq);
				numvac++;
			} else {
				sequences.placebo.push(seq);
				numplac++;
			}
			i += 2;
		}
	}
}

function dodistparsing(distdata)
{
	dists = d3.nest()
		.key(function(d) {return d.distance_method;})
		.rollup(function(data)
			{
				return d3.nest()
					.key(function(d) { return d.ptid; })
					.rollup(function(d) { return d.map(function(a) {return a.distance;}); })
					.entries(data);
			})
		.entries(distdata);
	display_idx_map = distdata.filter(function (d)
		{
			return d.ptid == distdata[0].ptid && d.distance_method == distdata[0].distance_method;
		}).map(function(d) {return d.display_position;});
	display_idx_map.foreach(function(d, i) {refmap[d] = i;});
}

/** Transpose 2D array */
function transpose(array) {
  return array[0].map(function (_, c) { return array.map(function (r) { return r[c]; }); });
}<|endoftext|>


<commit_before>'use strict';

exports.Point = Point;

/**
 * Point constructor
 * @param {Nubmer} r    radius
 * @param {Number} teta polar angle
 * @param {Number} phi  azimuth angle
 * @constructor
 */
function Point(r, teta, phi) {
  if (!(typeof r === 'number' &&
        typeof teta === 'number' &&
        typeof phi === 'number')) {
    throw new TypeError('Wrong arguments');
  }

  if (r < 0) {
    throw new TypeError('Radius should be non negative');
  }

  this.r = r;

  teta = Math.abs(teta);
  while (teta > Math.PI) {
    teta -= 2 * Math.PI;
  }

  this.teta = Math.abs(teta);

  while (phi >= 2 * Math.PI) {
    phi -= 2 * Math.PI;
  }

  while (phi < 0) {
    phi += 2 * Math.PI;
  }

  this.phi = phi;
}

Point.prototype.toCartesian = function() {
  return [
    this.r * Math.sin(this.teta) * Math.cos(this.phi),
    this.r * Math.sin(this.teta) * Math.sin(this.phi),
    this.r * Math.cos(this.teta)
  ];
};
<commit_msg>added missed jsdoc commit<commit_after>'use strict';

exports.Point = Point;

/**
 * Point constructor
 * @param {Nubmer} r    radius
 * @param {Number} teta polar angle
 * @param {Number} phi  azimuth angle
 * @constructor
 */
function Point(r, teta, phi) {
  if (!(typeof r === 'number' &&
        typeof teta === 'number' &&
        typeof phi === 'number')) {
    throw new TypeError('Wrong arguments');
  }

  if (r < 0) {
    throw new TypeError('Radius should be non negative');
  }

  this.r = r;

  teta = Math.abs(teta);
  while (teta > Math.PI) {
    teta -= 2 * Math.PI;
  }

  this.teta = Math.abs(teta);

  while (phi >= 2 * Math.PI) {
    phi -= 2 * Math.PI;
  }

  while (phi < 0) {
    phi += 2 * Math.PI;
  }

  this.phi = phi;
}

/**
 * Translater point to Cartesian coordinates
 * @return {Array} array of coords [x, y, z]
 */
Point.prototype.toCartesian = function() {
  return [
    this.r * Math.sin(this.teta) * Math.cos(this.phi),
    this.r * Math.sin(this.teta) * Math.sin(this.phi),
    this.r * Math.cos(this.teta)
  ];
};
<|endoftext|>


<commit_before>const Async = require('crocks/Async')
const { ifElse } = require('crocks/logic')
const { pipe } = require('crocks/helpers')
const { map } = require('crocks/pointfree')
const finalhandler = require('finalhandler')
const http = require('http')
const https = require('https')
const mime = require('mime')
const opn = require('opn')
const os = require('os')
const path = require('path')
const serveStatic = require('serve-static')
const ws = require('ws')
const { update, readFile, notExists, writeFile, isObj, hasProp } = require('./utils')
const { fileNotFound, serverStarted } = require('./messages')

/*
|-------------------------------------------------------------------------------
| Relaod
|-------------------------------------------------------------------------------
*/

/**
 * RELOAD_FILE :: String
 *
 * This just points to the client facing reload file.
 **/
const RELOAD_FILE = path.join(__dirname, './websocket.js')

/**
 * startWsServer :: Server -> { wss: WebsocketServer, sendMessage: String -> Never }
 *
 * This function takes in the server object and starts a WebSocket Server.
 **/
const startWsServer = server => {
  const wss = new ws.Server({ server })
  return {
    wss,
    sendMessage: message => {
      wss.clients.forEach(client => {
        if (client.readyState === ws.OPEN) {
          client.send(JSON.stringify(message))
        }
      })
    }
  }
}

/*
|-------------------------------------------------------------------------------
| Handler
|-------------------------------------------------------------------------------
*/

/**
 * These are a set of constants to use so we always know we are using/checking the same values.
 **/
const PROXY_TYPE = 'proxy'
const CONTENT_TYPE = 'content'
const RELOAD_TYPE = 'reload'
const STATIC_TYPE = 'static'

/**
 * getProxy :: { proxyPrefix: String, proxyHost: String } -> ProxyServer|Bool
 *
 * This function takes in the proxy values and makes sure they are valid before returning the Proxy Server. If the values are invalid it returns false.
 *
 * TODO: Turn this into a Result ADT.
 **/
const getProxy = ({ proxyPrefix, proxyHost }) => (typeof proxyPrefix === 'string' && typeof proxyHost === 'string')
  ? require('http-proxy').createProxyServer()
  : false

/**
 * isRoot :: { pathname: String, fileType: String, pushstate: Bool } -> Bool
 *
 * This function returns boolean if the variables passed indicate the root.
 **/
const isRoot = ({ pathname, fileType, pushstate }) =>
  ((pushstate && fileType === null) ||
    pathname === '/' ||
    pathname === '')

/**
 * getRequestType :: ({ pathname: String, fileType: String }, { proxyPrefix: String, pushstate: Bool }) -> String
 *
 * This function returns one of the request type constants defined above using some of the passed in variables from the request.
 **/
function getRequestType ({ pathname, fileType }, { proxyPrefix, pushstate }) {
  if (pathname.startsWith(proxyPrefix)) {
    return PROXY_TYPE
  } else if (
    isRoot({ pathname, pushstate, fileType }) ||
    fileType === 'text/html'
  ) {
    return CONTENT_TYPE
  } else if (pathname === '/reload/reload.js') {
    return RELOAD_TYPE
  } else {
    return STATIC_TYPE
  }
}

/**
 * parseUrl :: (String, Model) -> { fullPath: String, getPath: String, isRoot: Bool, isType: String -> Bool}
 *
 * This function takes in the path from the request and the model and returns the needed values to finish running the request.
 **/
function parseUrl (pathname, model) {
  const fileType = pipe(path.extname, mime.getType)(pathname)
  const requestType = getRequestType({ pathname, fileType }, model)
  const rootPath = `${model.dir}/${model.startPage}`
  const fullPath = `${model.dir}${pathname}`
  return {
    rootPath,
    getPath: isRoot({ pathname, pushstate: model.pushstate, fileType }) ? rootPath : fullPath,
    isRoot: isRoot({ pathname, pushstate: model.pushstate, fileType }),
    isType (reqType) { return reqType === requestType }
  }
}

/**
 * resolveWith :: Resolver -> String -> ()
 *
 * This function resolves the request with the passed in contents and includes the reload script.
 **/
const resolveWith = res => contents => {
  res.setHeader('Content-Type', 'text/html')
  res.end(`

<!-- Inserted by Reload -->
<script src="/reload/reload.js"></script>
<!-- End Reload -->

${contents}
`)
}

/**
 * resolveNotFound :: Resolver -> () -> ()
 *
 * This function resolves the request with a 404.
 **/
function resolveNotFound (res) {
  return function () {
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.end('File Not Found')
  }
}

/**
 * resolveReload :: Resolver -> String -> ()
 *
 * This function resolves the request with the passed in contents of the reload file.
 **/
function resolveReload (res) {
  return function (file) {
    res.setHeader('Content-Type', 'text/javascript')
    res.end(file)
  }
}

/**
 * handler :: Model -> (Request, Resolver) -> ()
 *
 * This function is the server handler function. It takes the model and the Request and Resolver and parses the Request and returns the correct files to the client
 **/
function handler (model) {
  const proxy = getProxy(model)
  const serve = serveStatic(model.dir, { index: ['index.html', 'index.htm'] })

  return function (req, res) {
    const url = parseUrl(req.url, model)

    if (proxy && url.isType(PROXY_TYPE)) {
      proxy.web(req, res, {
        target: model.proxyHost,
        changeOrigin: true,
        hostRewrite: true
      })
    } else if (url.isType(CONTENT_TYPE)) {
      readFile(url.getPath, 'utf8')
        .alt(readFile(url.rootpath, 'utf8'))
        .fork(resolveNotFound(res), resolveWith(res))
    } else if (url.isType(RELOAD_TYPE)) {
      readFile(RELOAD_FILE, 'utf8')
        .map(file => file.replace(`'{{verbose}}'`, `${model.verbose}`))
        .map(file => file.replace(`'{{reload}}'`, `${model.reload}`))
        .fork(file => model.log(fileNotFound(file)), resolveReload(res))
    } else {
      serve(req, res, finalhandler(req, res))
    }
  }
}

/*
|-------------------------------------------------------------------------------
| Listener
|-------------------------------------------------------------------------------
*/

/**
 * maybeOpen :: Model -> () -> Model
 *
 * This function opens the browser at the root url if the open flag is on.
 **/
function maybeOpen (model) {
  return function (server) {
    if (model.open) {
      const protocol = model.ssl ? 'https://' : 'http://'
      opn(protocol + model.host + ':' + model.port)
    }
    return server
  }
}

/**
 * listener :: Model -> ()
 *
 * This function listens to the server being started and when it connects it generates the relaod file if it doesn't exist, opens the browser, and logs the server message.
 **/
function listener (model) {
  const runFile = path.join(
    os.tmpdir(),
    'reload-' +
      Math.random()
        .toString()
        .slice(2)
  )

  notExists(runFile)
    .chain(writeFile)
    .fork(
      () => model.log(serverStarted(model)),
      () => model.log(serverStarted(model))
    )
}

/*
|-------------------------------------------------------------------------------
| Start Helpers
|-------------------------------------------------------------------------------
*/

/**
 * startServer :: Protocal -> Model -> Model
 *
 * This function starts the server using the passed in protocal and updates the model with the returned Server instance.
 **/
const startServer = protocol => model => update(model, { server: protocol.createServer(typeof model.server !== 'object' ? {} : model.server, handler(model)) })

/**
 * startWs :: Model -> Async Error { sendMessage: String -> () }
 *
 * This function starts the WebSocket server and returns an Async ADT where it rejects with an error or resolves once the connection has been made successfully with the function to send messages to the client.
 **/
const startWs = model => ({ server: startWsServer(model.server) })

/**
 * setupListener :: Model -> Model
 *
 * This function sets the listener on the server instance in the model.
 **/
const setupListener = model => {
  model.server.listen({ port: model.port, host: model.host }, listener(model))
  return model
}

/**
 * readSsl :: Model -> Async Error Model
 *
 * This function returns an Async ADT that tries to read the passed in creds needed for an SSL cert and either rejects with the error or resolves with an updated model with the needed keys.
 **/
const readSsl = model => Async
  .of(key => cert => ({ server: { key, cert } }))
  .ap(readFile(model.ssl.key))
  .ap(readFile(model.ssl.cert))
  .map(server => update(model, server))

/**
 * generateSsl :: Model -> Async Error Model
 *
 * This function returns an Async ADT that tries to generate the creds needed for an SSL cert and either rejects with the error or resolves with an updated model with the needed keys.
 **/
const generateSsl = model => Async((reject, resolve) => {
  const pem = require('pem')
  const internalIp = require('internal-ip')
  const baseNames = [ 'localhost', '127.0.0.1' ]
  const ip = internalIp.v4.sync()
  const altNames = (ip && baseNames.indexOf(ip) === -1)
    ? [ip, ...baseNames]
    : baseNames

  pem.createCertificate({
    days: 1,
    selfSigned: true,
    commonName: ip,
    altNames
  }, function (err, { serviceKey, certificate }) {
    if (err) reject(err)
    resolve(update(model, { server: { key: serviceKey, cert: certificate } }))
  })
})

/**
 * getSsl :: Model -> Async Error Model
 *
 * This function returns an Async ADT that either uses the passed in cred locations or tries to generate the creds needed for an SSL cert and either rejects with the error or resolves with an updated model with the needed keys.
 **/
const getSsl = model => isObj(model.ssl) ? readSsl(model) : generateSsl(model)

/**
 * sendCompilingMessage :: String -> Server -> Server
 *
 * This function takes a message and the server instance ( which at this point will be the function to send messages to the Websocket client ) and sends the compiling message to the client. This function is needed so it can be sent when the server is first being started and on all the re-builds moving forward.
 **/
function sendCompilingMessage (message) {
  return function send (model) {
    model.server.sendMessage({ action: 'compiling', message })
    return model
  }
}

/**
 * sendMessage :: Model -> Model
 *
 * This function takes the model and sends the build result message to the client.
 **/
function sendMessage (model) {
  model.server.sendMessage(model.build)
  return model
}

/**
 * start :: Model -> Async Error Server
 *
 * This function takes the model and pipes it through the Server pipeline and returns an Async ADT that resolves with the sendMessage function to be merged into the model and used to update the client or rejects with the error.
 **/
const start = model => model.useServer ? pipe(
  ifElse(hasProp('ssl'), getSsl, Async.of),
  map(startServer(model.ssl ? https : http)),
  map(setupListener),
  map(startWs),
  map(maybeOpen(model))
)(model) : Async.of(model)

/*
|-------------------------------------------------------------------------------
| Export
|-------------------------------------------------------------------------------
*/
module.exports = {
  start,
  sendMessage,
  sendCompilingMessage
}
<commit_msg>Fixing proxy requests to remove the prefix<commit_after>const Async = require('crocks/Async')
const { ifElse } = require('crocks/logic')
const { pipe } = require('crocks/helpers')
const { map } = require('crocks/pointfree')
const finalhandler = require('finalhandler')
const http = require('http')
const https = require('https')
const mime = require('mime')
const opn = require('opn')
const os = require('os')
const path = require('path')
const serveStatic = require('serve-static')
const ws = require('ws')
const { update, readFile, notExists, writeFile, isObj, hasProp } = require('./utils')
const { fileNotFound, serverStarted } = require('./messages')

/*
|-------------------------------------------------------------------------------
| Relaod
|-------------------------------------------------------------------------------
*/

/**
 * RELOAD_FILE :: String
 *
 * This just points to the client facing reload file.
 **/
const RELOAD_FILE = path.join(__dirname, './websocket.js')

/**
 * startWsServer :: Server -> { wss: WebsocketServer, sendMessage: String -> Never }
 *
 * This function takes in the server object and starts a WebSocket Server.
 **/
const startWsServer = server => {
  const wss = new ws.Server({ server })
  return {
    wss,
    sendMessage: message => {
      wss.clients.forEach(client => {
        if (client.readyState === ws.OPEN) {
          client.send(JSON.stringify(message))
        }
      })
    }
  }
}

/*
|-------------------------------------------------------------------------------
| Handler
|-------------------------------------------------------------------------------
*/

/**
 * These are a set of constants to use so we always know we are using/checking the same values.
 **/
const PROXY_TYPE = 'proxy'
const CONTENT_TYPE = 'content'
const RELOAD_TYPE = 'reload'
const STATIC_TYPE = 'static'

/**
 * getProxy :: { proxyPrefix: String, proxyHost: String } -> ProxyServer|Bool
 *
 * This function takes in the proxy values and makes sure they are valid before returning the Proxy Server. If the values are invalid it returns false.
 *
 * TODO: Turn this into a Result ADT.
 **/
const getProxy = ({ proxyPrefix, proxyHost }) => (typeof proxyPrefix === 'string' && typeof proxyHost === 'string')
  ? require('http-proxy').createProxyServer()
  : false

/**
 * isRoot :: { pathname: String, fileType: String, pushstate: Bool } -> Bool
 *
 * This function returns boolean if the variables passed indicate the root.
 **/
const isRoot = ({ pathname, fileType, pushstate }) =>
  ((pushstate && fileType === null) ||
    pathname === '/' ||
    pathname === '')

/**
 * getRequestType :: ({ pathname: String, fileType: String }, { proxyPrefix: String, pushstate: Bool }) -> String
 *
 * This function returns one of the request type constants defined above using some of the passed in variables from the request.
 **/
function getRequestType ({ pathname, fileType }, { proxyPrefix, pushstate }) {
  if (pathname.startsWith(proxyPrefix)) {
    return PROXY_TYPE
  } else if (
    isRoot({ pathname, pushstate, fileType }) ||
    fileType === 'text/html'
  ) {
    return CONTENT_TYPE
  } else if (pathname === '/reload/reload.js') {
    return RELOAD_TYPE
  } else {
    return STATIC_TYPE
  }
}

/**
 * parseUrl :: (String, Model) -> { fullPath: String, getPath: String, isRoot: Bool, isType: String -> Bool}
 *
 * This function takes in the path from the request and the model and returns the needed values to finish running the request.
 **/
function parseUrl (pathname, model) {
  const fileType = pipe(path.extname, mime.getType)(pathname)
  const requestType = getRequestType({ pathname, fileType }, model)
  const rootPath = `${model.dir}/${model.startPage}`
  const fullPath = `${model.dir}${pathname}`
  return {
    rootPath,
    getPath: isRoot({ pathname, pushstate: model.pushstate, fileType }) ? rootPath : fullPath,
    isRoot: isRoot({ pathname, pushstate: model.pushstate, fileType }),
    isType (reqType) { return reqType === requestType }
  }
}

/**
 * resolveWith :: Resolver -> String -> ()
 *
 * This function resolves the request with the passed in contents and includes the reload script.
 **/
const resolveWith = res => contents => {
  res.setHeader('Content-Type', 'text/html')
  res.end(`

<!-- Inserted by Reload -->
<script src="/reload/reload.js"></script>
<!-- End Reload -->

${contents}
`)
}

/**
 * resolveNotFound :: Resolver -> () -> ()
 *
 * This function resolves the request with a 404.
 **/
function resolveNotFound (res) {
  return function () {
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.end('File Not Found')
  }
}

/**
 * resolveReload :: Resolver -> String -> ()
 *
 * This function resolves the request with the passed in contents of the reload file.
 **/
function resolveReload (res) {
  return function (file) {
    res.setHeader('Content-Type', 'text/javascript')
    res.end(file)
  }
}

/**
 * handler :: Model -> (Request, Resolver) -> ()
 *
 * This function is the server handler function. It takes the model and the Request and Resolver and parses the Request and returns the correct files to the client
 **/
function handler (model) {
  const proxy = getProxy(model)
  const serve = serveStatic(model.dir, { index: ['index.html', 'index.htm'] })

  return function (req, res) {
    const url = parseUrl(req.url, model)

    if (proxy && url.isType(PROXY_TYPE)) {
      console.log(req.url.replace(model.proxyPrefix, ''))
      proxy.web(req, res, {
        target: model.proxyHost,
        changeOrigin: true,
        hostRewrite: true
      })
    } else if (url.isType(CONTENT_TYPE)) {
      readFile(url.getPath, 'utf8')
        .alt(readFile(url.rootpath, 'utf8'))
        .fork(resolveNotFound(res), resolveWith(res))
    } else if (url.isType(RELOAD_TYPE)) {
      readFile(RELOAD_FILE, 'utf8')
        .map(file => file.replace(`'{{verbose}}'`, `${model.verbose}`))
        .map(file => file.replace(`'{{reload}}'`, `${model.reload}`))
        .fork(file => model.log(fileNotFound(file)), resolveReload(res))
    } else {
      serve(req, res, finalhandler(req, res))
    }
  }
}

/*
|-------------------------------------------------------------------------------
| Listener
|-------------------------------------------------------------------------------
*/

/**
 * maybeOpen :: Model -> () -> Model
 *
 * This function opens the browser at the root url if the open flag is on.
 **/
function maybeOpen (model) {
  return function (server) {
    if (model.open) {
      const protocol = model.ssl ? 'https://' : 'http://'
      opn(protocol + model.host + ':' + model.port)
    }
    return server
  }
}

/**
 * listener :: Model -> ()
 *
 * This function listens to the server being started and when it connects it generates the relaod file if it doesn't exist, opens the browser, and logs the server message.
 **/
function listener (model) {
  const runFile = path.join(
    os.tmpdir(),
    'reload-' +
      Math.random()
        .toString()
        .slice(2)
  )

  notExists(runFile)
    .chain(writeFile)
    .fork(
      () => model.log(serverStarted(model)),
      () => model.log(serverStarted(model))
    )
}

/*
|-------------------------------------------------------------------------------
| Start Helpers
|-------------------------------------------------------------------------------
*/

/**
 * startServer :: Protocal -> Model -> Model
 *
 * This function starts the server using the passed in protocal and updates the model with the returned Server instance.
 **/
const startServer = protocol => model => update(model, { server: protocol.createServer(typeof model.server !== 'object' ? {} : model.server, handler(model)) })

/**
 * startWs :: Model -> Async Error { sendMessage: String -> () }
 *
 * This function starts the WebSocket server and returns an Async ADT where it rejects with an error or resolves once the connection has been made successfully with the function to send messages to the client.
 **/
const startWs = model => ({ server: startWsServer(model.server) })

/**
 * setupListener :: Model -> Model
 *
 * This function sets the listener on the server instance in the model.
 **/
const setupListener = model => {
  model.server.listen({ port: model.port, host: model.host }, listener(model))
  return model
}

/**
 * readSsl :: Model -> Async Error Model
 *
 * This function returns an Async ADT that tries to read the passed in creds needed for an SSL cert and either rejects with the error or resolves with an updated model with the needed keys.
 **/
const readSsl = model => Async
  .of(key => cert => ({ server: { key, cert } }))
  .ap(readFile(model.ssl.key))
  .ap(readFile(model.ssl.cert))
  .map(server => update(model, server))

/**
 * generateSsl :: Model -> Async Error Model
 *
 * This function returns an Async ADT that tries to generate the creds needed for an SSL cert and either rejects with the error or resolves with an updated model with the needed keys.
 **/
const generateSsl = model => Async((reject, resolve) => {
  const pem = require('pem')
  const internalIp = require('internal-ip')
  const baseNames = [ 'localhost', '127.0.0.1' ]
  const ip = internalIp.v4.sync()
  const altNames = (ip && baseNames.indexOf(ip) === -1)
    ? [ip, ...baseNames]
    : baseNames

  pem.createCertificate({
    days: 1,
    selfSigned: true,
    commonName: ip,
    altNames
  }, function (err, { serviceKey, certificate }) {
    if (err) reject(err)
    resolve(update(model, { server: { key: serviceKey, cert: certificate } }))
  })
})

/**
 * getSsl :: Model -> Async Error Model
 *
 * This function returns an Async ADT that either uses the passed in cred locations or tries to generate the creds needed for an SSL cert and either rejects with the error or resolves with an updated model with the needed keys.
 **/
const getSsl = model => isObj(model.ssl) ? readSsl(model) : generateSsl(model)

/**
 * sendCompilingMessage :: String -> Server -> Server
 *
 * This function takes a message and the server instance ( which at this point will be the function to send messages to the Websocket client ) and sends the compiling message to the client. This function is needed so it can be sent when the server is first being started and on all the re-builds moving forward.
 **/
function sendCompilingMessage (message) {
  return function send (model) {
    model.server.sendMessage({ action: 'compiling', message })
    return model
  }
}

/**
 * sendMessage :: Model -> Model
 *
 * This function takes the model and sends the build result message to the client.
 **/
function sendMessage (model) {
  model.server.sendMessage(model.build)
  return model
}

/**
 * start :: Model -> Async Error Server
 *
 * This function takes the model and pipes it through the Server pipeline and returns an Async ADT that resolves with the sendMessage function to be merged into the model and used to update the client or rejects with the error.
 **/
const start = model => model.useServer ? pipe(
  ifElse(hasProp('ssl'), getSsl, Async.of),
  map(startServer(model.ssl ? https : http)),
  map(setupListener),
  map(startWs),
  map(maybeOpen(model))
)(model) : Async.of(model)

/*
|-------------------------------------------------------------------------------
| Export
|-------------------------------------------------------------------------------
*/
module.exports = {
  start,
  sendMessage,
  sendCompilingMessage
}
<|endoftext|>


<commit_before>/////////////// Set Variables //////////////////
var rotateSpeed = 0.03;
var scaleDivisor = Number("1e15");
var systemSystemGeo = new THREE.Geometry();
var systemJumpGeo = new THREE.Geometry();
var systemSystem;

/////////////// Create Objects ///////////////////

// Scene
var scene = new THREE.Scene();

// Camera
var camera = new THREE.PerspectiveCamera( 75 , window.innerWidth / window.innerHeight, 0.1, 500000 );
camera.position.y = 1000;
camera.rotation.x = -90;

// renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

//controls
var control = new THREE.OrbitControls( camera, renderer.domElement );

// Stats
var stats = new Stats();
		stats.domElement.style.position = 'absolute';
		stats.domElement.style.top = '0px';
		document.body.appendChild( stats.domElement );

/////////////// Create Geometry ///////////////////
var planetTexture = THREE.ImageUtils.loadTexture( 'images/disc.png' );
var customUniforms =
{
	texture: {type: "t", value: planetTexture },
};

var customAttributes =
{
	customColor: { type: "c", value: [] },
};

//lines
var linematerial = new THREE.LineBasicMaterial( { color: 0xcccccc, opacity: 0.4, linewidth: 0.1 } );

for (var jump in jumps){
	var jumpgeo = new THREE.Geometry();
	var tox, toy, toz, fromx, fromy, fromz;

	fromx = system_list[jumps[jump][0]].x;
	fromy = system_list[jumps[jump][0]].y;
	fromz = system_list[jumps[jump][0]].z;
	tox = system_list[jumps[jump][1]].x;
	toy = system_list[jumps[jump][1]].y;
	toz = system_list[jumps[jump][1]].z;

	jumpgeo.vertices.push(new THREE.Vector3(fromx, fromy, fromz));
	jumpgeo.vertices.push(new THREE.Vector3(tox, toy, toz));
	var line = new THREE.Line( jumpgeo,  linematerial );
	scene.add(line);
}

var v = 0;
for (var system in system_list){
	systemSystemGeo.vertices.push(new THREE.Vector3(Number(system_list[system].x), Number(system_list[system].y), Number(system_list[system].z)));
	customAttributes.customColor.value[ v ]	= new THREE.Color( v * 10000 );
	v++;
}

 // systemMat = new THREE.ParticleBasicMaterial( {
	// color: 0x57A5FF,
	// size: 4,
	// map: THREE.ImageUtils.loadTexture(
	// 	"particle.png"
	// ),
	// transparent: true
// });

var systemMat = new THREE.ShaderMaterial (
	{
		uniforms: customUniforms,
		attributes: customAttributes,
		vertexShader: document.getElementById( 'vertexshader' ).textContent,
		fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
		transparent: true,
		alphaTest: 0.5
	});

systemSystem = new THREE.ParticleSystem( systemSystemGeo, systemMat );
systemSystem.sortParticles = true;
scene.add(systemSystem);

/////////////// Register Events ///////////////////

window.addEventListener( 'resize', onWindowResize, false );

function animate() {
	requestAnimationFrame( animate );

	update();

	render();
}

function update() {
	stats.update();

	updateInput();
}

function updateInput() {
	// kd.tick();

	// 	if (kd.W.isDown()){
	// 		camera.rotation.x += rotateSpeed;
	// 	}

	// 	if (kd.S.isDown()){
	// 		camera.rotation.x -= rotateSpeed;
	// 	}

	// 	if (kd.A.isDown()){
	// 		camera.rotation.y += rotateSpeed;
	// 	}

	// 	if (kd.D.isDown()){
	// 		camera.rotation.y -= rotateSpeed;
	// 	}

	// 	if (kd.Q.isDown()){
	// 		camera.rotation.z -= rotateSpeed;
	// 	}

	// 	if (kd.E.isDown()){
	// 		camera.rotation.z += rotateSpeed;
	// 	}
	var dt = 10;
	control.update(dt);
}

function render() {
	renderer.render(scene, camera);
}

function onWindowResize() {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize (window.innerWidth, window.innerHeight);
}

animate();<commit_msg>- Minor cosmetic changes<commit_after>/////////////// Set Variables //////////////////
var rotateSpeed = 0.03;
var scaleDivisor = Number("1e15");
var systemSystemGeo = new THREE.Geometry();
var systemJumpGeo = new THREE.Geometry();
var systemSystem;

/////////////// Create Objects ///////////////////

// Scene
var scene = new THREE.Scene();

// Camera
var camera = new THREE.PerspectiveCamera( 75 , window.innerWidth / window.innerHeight, 0.1, 500000 );
camera.position.y = 1000;
camera.rotation.x = -90;

// renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

//controls
var control = new THREE.OrbitControls( camera, renderer.domElement );

// Stats
var stats = new Stats();
		stats.domElement.style.position = 'absolute';
		stats.domElement.style.top = '0px';
		document.body.appendChild( stats.domElement );

/////////////// Create Geometry ///////////////////
var planetTexture = THREE.ImageUtils.loadTexture( 'images/disc.png' );
var customUniforms =
{
	texture: {type: "t", value: planetTexture },
};

var customAttributes =
{
	customColor: { type: "c", value: [] },
};

//lines
var linematerial = new THREE.LineBasicMaterial( { color: 0xcccccc, opacity: 0.4, linewidth: 0.1 } );

for (var jump in jumps){

	var tox, toy, toz, fromx, fromy, fromz;

	fromx = system_list[jumps[jump][0]].x;
	fromy = system_list[jumps[jump][0]].y;
	fromz = system_list[jumps[jump][0]].z;
	tox = system_list[jumps[jump][1]].x;
	toy = system_list[jumps[jump][1]].y;
	toz = system_list[jumps[jump][1]].z;

	systemJumpGeo.vertices.push(new THREE.Vector3(fromx, fromy, fromz));
	systemJumpGeo.vertices.push(new THREE.Vector3(tox, toy, toz));

	var line = new THREE.Line( systemJumpGeo,  linematerial );
	scene.add(line);
}

var v = 0;
for (var system in system_list){
	systemSystemGeo.vertices.push(new THREE.Vector3(Number(system_list[system].x), Number(system_list[system].y), Number(system_list[system].z)));
	customAttributes.customColor.value[ v ]	= new THREE.Color( v * 10000 );
	v++;
}

var systemMat = new THREE.ShaderMaterial (
	{
		uniforms: customUniforms,
		attributes: customAttributes,
		vertexShader: document.getElementById( 'vertexshader' ).textContent,
		fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
		transparent: true,
		alphaTest: 0.5
	});

systemSystem = new THREE.ParticleSystem( systemSystemGeo, systemMat );
systemSystem.sortParticles = true;
scene.add(systemSystem);

/////////////// Register Events ///////////////////

window.addEventListener( 'resize', onWindowResize, false );

function animate() {
	requestAnimationFrame( animate );

	update();

	render();
}

function update() {
	stats.update();

	updateInput();
}

function updateInput() {
	// kd.tick();

	// 	if (kd.W.isDown()){
	// 		camera.rotation.x += rotateSpeed;
	// 	}

	// 	if (kd.S.isDown()){
	// 		camera.rotation.x -= rotateSpeed;
	// 	}

	// 	if (kd.A.isDown()){
	// 		camera.rotation.y += rotateSpeed;
	// 	}

	// 	if (kd.D.isDown()){
	// 		camera.rotation.y -= rotateSpeed;
	// 	}

	// 	if (kd.Q.isDown()){
	// 		camera.rotation.z -= rotateSpeed;
	// 	}

	// 	if (kd.E.isDown()){
	// 		camera.rotation.z += rotateSpeed;
	// 	}
	var dt = 10;
	control.update(dt);
}

function render() {
	renderer.render(scene, camera);
}

function onWindowResize() {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize (window.innerWidth, window.innerHeight);
}

animate();<|endoftext|>


<commit_before>const execSync = require('child_process').execSync;
const fs = require('fs');
const os = require('os');
const readline = require('readline');

const packageJsonFile = './frontend/package.json';
const packageJsonLockFile = './frontend/package-lock.json';
const gradlePropertiesFile = './backend/gradle.properties';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

/**
 * Gets the current version from the package.json file.
 *
 * @returns {string} the version in x.y.z or x.y.z-SNAPSHOT format
 */
function getCurrentVersion() {
  const packageJsonContent = fs.readFileSync(packageJsonFile, 'utf8');
  const packageJson = JSON.parse(packageJsonContent);
  return packageJson.version;
}

/**
 * Increments the revision of the given release version. Ex. 1.0.0 becomes 1.0.1
 *
 * @param {string} version the current version
 * @returns {string} the next version revision
 */
function incrementVersion(version) {
  const [major, minor, revision] = version.split('.');

  const newRevision = parseInt(revision, 10) + 1;

  return `${major}.${minor}.${newRevision}`;
}

/**
 * Updates the version property of package.json and package-lock.json files.
 *
 * @param {string} version the release version
 */
function updatePackageJson(version) {
  console.log('updating package.json...');
  const packageJsonContent = fs.readFileSync(packageJsonFile, 'utf8');
  const packageJson = JSON.parse(packageJsonContent);
  packageJson.version = version;
  fs.writeFileSync(packageJsonFile, JSON.stringify(packageJson, null, 2));

  console.log('updating package-lock.json...');
  const packageJsonLockContent = fs.readFileSync(packageJsonLockFile, 'utf8');
  const packageJsonLock = JSON.parse(packageJsonLockContent);
  packageJsonLock.version = version;
  fs.writeFileSync(packageJsonLockFile, JSON.stringify(packageJsonLock, null, 2));
}

/**
 * Updates the buildVersion property of the gradle.properties file.
 *
 * @param {string} version the release version
 */
function updateGradleProperties(version) {
  console.log('updating gradle.properties...');
  const gradlePropertiesContent = fs.readFileSync(gradlePropertiesFile, 'utf8');

  const gradleProperties = gradlePropertiesContent.split(os.EOL);
  let newGradleProperties = '';

  for (const property of gradleProperties) {
    if (property) {
      const propertyParts = property.split('=');
      const key = propertyParts[0];
      const value = propertyParts[1];
      if (key === 'buildVersion') {
        newGradleProperties += `${key}=${version}`;
      } else {
        newGradleProperties += `${key}=${value}`;
      }
      newGradleProperties += os.EOL;
    }
  }

  fs.writeFileSync(gradlePropertiesFile, newGradleProperties);
}

/**
 * Performs the following git operations:
 *
 * ```
 * git add package.json package-lock.json gradle.properties
 * git commit -m "message"
 * ```
 * @param {string} version the release version
 */
function gitCommit(version) {
  let commitMsg = '';
  if (isSnapshotVersion(version)) {
    commitMsg = 'Next snapshot version';
  } else {
    commitMsg = `Release ${version}`;
  }
  console.log(`committing changes with message: '${commitMsg}'`);

  execSync(`git add ${packageJsonFile} ${packageJsonLockFile} ${gradlePropertiesFile}`);
  execSync(`git commit -m "${commitMsg}"`);
}

/**
 * Updates the necessary files to include - package.json, package-lock.json and gradle.properties as part of the next
 * release process.
 *
 * @param {string} version the release version
 */
function updateFiles(version) {
  updatePackageJson(version);
  updateGradleProperties(version);
  gitCommit(version);
}

/**
 * Prompts for the next release version, which is optional.
 *
 * @param {string} defaultNextVersion the next version to be used if one is not specified
 */
function promptForNextVersion(defaultNextVersion) {
  rl.prompt();

  rl.on('line', (line) => {
    const nextVersion = line.trim();
    if (nextVersion) {
      console.log(`Next version will be: '${nextVersion}'`);
      updateFiles(nextVersion);
    } else {
      console.log(`Next version will be: '${defaultNextVersion}'`);
      updateFiles(defaultNextVersion);
    }
    process.exit(0);
  }).on('close', () => {
    process.exit(0);
  });
}

/**
 * Determines if the given version is a SNAPSHOT or full release version
 *
 * @param {string} buildVersion
 * @returns {boolean} true if SNAPSHOT version, otherwise false
 */
function isSnapshotVersion(buildVersion) {
  return buildVersion.includes('SNAPSHOT');
}

/**
 * Prepares for the next release either by incrementing the next version as x.y.z-SNAPSHOT or removing SNAPSHOT.
 */
function prepareNextRelease() {
  const currentVersion = getCurrentVersion();

  if (isSnapshotVersion(currentVersion)) {
    makeRelease(currentVersion);
  } else {
    nextSnapshot(currentVersion);
  }
}

/**
 * Prepares for the next release with the next SNAPSHOT version.
 *
 * @param {string} snapshotVersion the SNAPSHOT version
 */
function makeRelease(snapshotVersion) {
  const releaseVersion = snapshotVersion.substring(0, snapshotVersion.indexOf('-SNAPSHOT'));

  console.log('Preparing for release...');
  console.log(`Current snapshot: '${snapshotVersion}'`);
  console.log(`Releasing version: '${releaseVersion}'`);

  updateFiles(releaseVersion);
  process.exit(0);
}

/**
 * Prepares for the next release with the next SNAPSHOT version.
 *
 * @param {string} currentVersion the current release version
 */
function nextSnapshot(currentVersion) {
  const defaultNextVersion = incrementVersion(currentVersion);

  const snapshotVersion = `${defaultNextVersion}-SNAPSHOT`;

  console.log('Preparing for next version...');
  console.log(`Current version: '${currentVersion}'`);
  console.log(`Optionally enter next version. Will use: '${defaultNextVersion}' (${snapshotVersion}) if not specified`);

  promptForNextVersion(snapshotVersion);
}

prepareNextRelease();
<commit_msg>destruct key, value from property split<commit_after>const execSync = require('child_process').execSync;
const fs = require('fs');
const os = require('os');
const readline = require('readline');

const packageJsonFile = './frontend/package.json';
const packageJsonLockFile = './frontend/package-lock.json';
const gradlePropertiesFile = './backend/gradle.properties';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

/**
 * Gets the current version from the package.json file.
 *
 * @returns {string} the version in x.y.z or x.y.z-SNAPSHOT format
 */
function getCurrentVersion() {
  const packageJsonContent = fs.readFileSync(packageJsonFile, 'utf8');
  const packageJson = JSON.parse(packageJsonContent);
  return packageJson.version;
}

/**
 * Increments the revision of the given release version. Ex. 1.0.0 becomes 1.0.1
 *
 * @param {string} version the current version
 * @returns {string} the next version revision
 */
function incrementVersion(version) {
  const [major, minor, revision] = version.split('.');

  const newRevision = parseInt(revision, 10) + 1;

  return `${major}.${minor}.${newRevision}`;
}

/**
 * Updates the version property of package.json and package-lock.json files.
 *
 * @param {string} version the release version
 */
function updatePackageJson(version) {
  console.log('updating package.json...');
  const packageJsonContent = fs.readFileSync(packageJsonFile, 'utf8');
  const packageJson = JSON.parse(packageJsonContent);
  packageJson.version = version;
  fs.writeFileSync(packageJsonFile, JSON.stringify(packageJson, null, 2));

  console.log('updating package-lock.json...');
  const packageJsonLockContent = fs.readFileSync(packageJsonLockFile, 'utf8');
  const packageJsonLock = JSON.parse(packageJsonLockContent);
  packageJsonLock.version = version;
  fs.writeFileSync(packageJsonLockFile, JSON.stringify(packageJsonLock, null, 2));
}

/**
 * Updates the buildVersion property of the gradle.properties file.
 *
 * @param {string} version the release version
 */
function updateGradleProperties(version) {
  console.log('updating gradle.properties...');
  const gradlePropertiesContent = fs.readFileSync(gradlePropertiesFile, 'utf8');

  const gradleProperties = gradlePropertiesContent.split(os.EOL);
  let newGradleProperties = '';

  for (const property of gradleProperties) {
    if (property) {
      const [key, value] = property.split('=');
      if (key === 'buildVersion') {
        newGradleProperties += `${key}=${version}`;
      } else {
        newGradleProperties += `${key}=${value}`;
      }
      newGradleProperties += os.EOL;
    }
  }

  fs.writeFileSync(gradlePropertiesFile, newGradleProperties);
}

/**
 * Performs the following git operations:
 *
 * ```
 * git add package.json package-lock.json gradle.properties
 * git commit -m "message"
 * ```
 * @param {string} version the release version
 */
function gitCommit(version) {
  let commitMsg = '';
  if (isSnapshotVersion(version)) {
    commitMsg = 'Next snapshot version';
  } else {
    commitMsg = `Release ${version}`;
  }
  console.log(`committing changes with message: '${commitMsg}'`);

  execSync(`git add ${packageJsonFile} ${packageJsonLockFile} ${gradlePropertiesFile}`);
  execSync(`git commit -m "${commitMsg}"`);
}

/**
 * Updates the necessary files to include - package.json, package-lock.json and gradle.properties as part of the next
 * release process.
 *
 * @param {string} version the release version
 */
function updateFiles(version) {
  updatePackageJson(version);
  updateGradleProperties(version);
  gitCommit(version);
}

/**
 * Prompts for the next release version, which is optional.
 *
 * @param {string} defaultNextVersion the next version to be used if one is not specified
 */
function promptForNextVersion(defaultNextVersion) {
  rl.prompt();

  rl.on('line', (line) => {
    const nextVersion = line.trim();
    if (nextVersion) {
      console.log(`Next version will be: '${nextVersion}'`);
      updateFiles(nextVersion);
    } else {
      console.log(`Next version will be: '${defaultNextVersion}'`);
      updateFiles(defaultNextVersion);
    }
    process.exit(0);
  }).on('close', () => {
    process.exit(0);
  });
}

/**
 * Determines if the given version is a SNAPSHOT or full release version
 *
 * @param {string} buildVersion
 * @returns {boolean} true if SNAPSHOT version, otherwise false
 */
function isSnapshotVersion(buildVersion) {
  return buildVersion.includes('SNAPSHOT');
}

/**
 * Prepares for the next release either by incrementing the next version as x.y.z-SNAPSHOT or removing SNAPSHOT.
 */
function prepareNextRelease() {
  const currentVersion = getCurrentVersion();

  if (isSnapshotVersion(currentVersion)) {
    makeRelease(currentVersion);
  } else {
    nextSnapshot(currentVersion);
  }
}

/**
 * Prepares for the next release with the next SNAPSHOT version.
 *
 * @param {string} snapshotVersion the SNAPSHOT version
 */
function makeRelease(snapshotVersion) {
  const releaseVersion = snapshotVersion.substring(0, snapshotVersion.indexOf('-SNAPSHOT'));

  console.log('Preparing for release...');
  console.log(`Current snapshot: '${snapshotVersion}'`);
  console.log(`Releasing version: '${releaseVersion}'`);

  updateFiles(releaseVersion);
  process.exit(0);
}

/**
 * Prepares for the next release with the next SNAPSHOT version.
 *
 * @param {string} currentVersion the current release version
 */
function nextSnapshot(currentVersion) {
  const defaultNextVersion = incrementVersion(currentVersion);

  const snapshotVersion = `${defaultNextVersion}-SNAPSHOT`;

  console.log('Preparing for next version...');
  console.log(`Current version: '${currentVersion}'`);
  console.log(`Optionally enter next version. Will use: '${defaultNextVersion}' (${snapshotVersion}) if not specified`);

  promptForNextVersion(snapshotVersion);
}

prepareNextRelease();
<|endoftext|>


<commit_before>/**
 * @fileoverview This demo is used for MarkerClusterer. It will show 100 markers
 * using MarkerClusterer and count the time to show the difference between using
 * MarkerClusterer and without MarkerClusterer.
 * @author Luke Mahe (v2 author: Xiaoxi Wu)
 */

function $(element) {
  return document.getElementById(element);
}

var speedTest = {};

speedTest.pics = null;
speedTest.map = null;
speedTest.markerClusterer = null;
speedTest.markers = [];
speedTest.infoWindow = null;

speedTest.init = function() {
  var latlng = new google.maps.LatLng(39.91, 116.38);
  var options = {
    'zoom': 2,
    'center': latlng,
    'mapTypeId': google.maps.MapTypeId.ROADMAP
  };

  speedTest.map = new google.maps.Map($('map'), options);
  speedTest.pics = data.photos;

  var useGmm = document.getElementById('usegmm');
  google.maps.event.addDomListener(useGmm, 'click', speedTest.change);

  var numMarkers = document.getElementById('nummarkers');
  google.maps.event.addDomListener(numMarkers, 'change', speedTest.change);

  speedTest.infoWindow = new google.maps.InfoWindow();

  speedTest.showMarkers();
};

speedTest.showMarkers = function() {
  speedTest.markers = [];

  var type = 1;
  if ($('usegmm').checked) {
    type = 0;
  }

  if (speedTest.markerClusterer) {
    speedTest.markerClusterer.clearMarkers();
  }

  var panel = $('markerlist');
  panel.innerHTML = '';
  var numMarkers = $('nummarkers').value;

  for (var i = 0; i < numMarkers; i++) {
    var titleText = speedTest.pics[i].photo_title;
    if (titleText == '') {
      titleText = 'No title';
    }

    var item = document.createElement('DIV');
    var title = document.createElement('A');
    title.href = '#';
    title.className = 'title';
    title.innerHTML = titleText;

    item.appendChild(title);
    panel.appendChild(item);

    var latLng = new google.maps.LatLng(speedTest.pics[i].latitude,
        speedTest.pics[i].longitude);

    var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=' +
        'FFFFFF,008CFF,000000&ext=.png';
    var markerImage = new google.maps.MarkerImage(imageUrl,
        new google.maps.Size(24, 32));

    var marker = new google.maps.Marker({
      'position': latLng,
      'icon': markerImage
    });

    var fn = speedTest.markerClickFunction(speedTest.pics[i], latLng);
    google.maps.event.addListener(marker, 'click', fn);
    google.maps.event.addDomListener(title, 'click', fn);
    speedTest.markers.push(marker);
  }

  window.setTimeout(speedTest.time, 0);
};

speedTest.markerClickFunction = function(pic, latlng) {
  return function(e) {
    e.preventDefault();
    var title = pic.photo_title;
    var url = pic.photo_url;
    var fileurl = pic.photo_file_url;

    var infoHtml = '

' + title +
      '

' +
      '
' +
      '' +
      '
' +
      '' + pic.owner_name +
      '

';

    speedTest.infoWindow.setContent(infoHtml);
    speedTest.infoWindow.setPosition(latlng);
    speedTest.infoWindow.open(speedTest.map);
  };
};

speedTest.clear = function() {
  $('timetaken').innerHTML = 'cleaning...';
  for (var i = 0, marker; marker = speedTest.markers[i]; i++) {
    marker.setMap(null);
  }
};

speedTest.change = function() {
  speedTest.clear();
  speedTest.showMarkers();
};

speedTest.time = function() {
  $('timetaken').innerHTML = 'timing...';
  var start = new Date();
  if ($('usegmm').checked) {
    speedTest.markerClusterer = new MarkerClusterer(speedTest.map, speedTest.markers);
  } else {
    for (var i = 0, marker; marker = speedTest.markers[i]; i++) {
      marker.setMap(speedTest.map);
    }
  }

  var end = new Date();
  $('timetaken').innerHTML = end - start;
};
<commit_msg>fixing prop bug<commit_after>/**
 * @fileoverview This demo is used for MarkerClusterer. It will show 100 markers
 * using MarkerClusterer and count the time to show the difference between using
 * MarkerClusterer and without MarkerClusterer.
 * @author Luke Mahe (v2 author: Xiaoxi Wu)
 */

function $(element) {
  return document.getElementById(element);
}

var speedTest = {};

speedTest.pics = null;
speedTest.map = null;
speedTest.markerClusterer = null;
speedTest.markers = [];
speedTest.infoWindow = null;

speedTest.init = function() {
  var latlng = new google.maps.LatLng(39.91, 116.38);
  var options = {
    'zoom': 2,
    'center': latlng,
    'mapTypeId': google.maps.MapTypeId.ROADMAP
  };

  speedTest.map = new google.maps.Map($('map'), options);
  speedTest.pics = data.photos;

  var useGmm = document.getElementById('usegmm');
  google.maps.event.addDomListener(useGmm, 'click', speedTest.change);

  var numMarkers = document.getElementById('nummarkers');
  google.maps.event.addDomListener(numMarkers, 'change', speedTest.change);

  speedTest.infoWindow = new google.maps.InfoWindow();

  speedTest.showMarkers();
};

speedTest.showMarkers = function() {
  speedTest.markers = [];

  var type = 1;
  if ($('usegmm').checked) {
    type = 0;
  }

  if (speedTest.markerClusterer) {
    speedTest.markerClusterer.clearMarkers();
  }

  var panel = $('markerlist');
  panel.innerHTML = '';
  var numMarkers = $('nummarkers').value;

  for (var i = 0; i < numMarkers; i++) {
    var titleText = speedTest.pics[i].photo_title;
    if (titleText == '') {
      titleText = 'No title';
    }

    var item = document.createElement('DIV');
    var title = document.createElement('A');
    title.href = '#';
    title.className = 'title';
    title.innerHTML = titleText;

    item.appendChild(title);
    panel.appendChild(item);

    var latLng = new google.maps.LatLng(speedTest.pics[i].latitude,
        speedTest.pics[i].longitude);

    var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=' +
        'FFFFFF,008CFF,000000&ext=.png';
    var markerImage = new google.maps.MarkerImage(imageUrl,
        new google.maps.Size(24, 32));

    var marker = new google.maps.Marker({
      'position': latLng,
      'icon': markerImage
    });

    var fn = speedTest.markerClickFunction(speedTest.pics[i], latLng);
    google.maps.event.addListener(marker, 'click', fn);
    google.maps.event.addDomListener(title, 'click', fn);
    speedTest.markers.push(marker);
  }

  window.setTimeout(speedTest.time, 0);
};

speedTest.markerClickFunction = function(pic, latlng) {
  return function(e) {
    e.cancelBubble = true;
    e.returnValue = false;
    if (e.stopPropagation) {
      e.stopPropagation();
      e.preventDefault();
    }
    var title = pic.photo_title;
    var url = pic.photo_url;
    var fileurl = pic.photo_file_url;

    var infoHtml = '

' + title +
      '

' +
      '
' +
      '' +
      '
' +
      '' + pic.owner_name +
      '

';

    speedTest.infoWindow.setContent(infoHtml);
    speedTest.infoWindow.setPosition(latlng);
    speedTest.infoWindow.open(speedTest.map);
  };
};

speedTest.clear = function() {
  $('timetaken').innerHTML = 'cleaning...';
  for (var i = 0, marker; marker = speedTest.markers[i]; i++) {
    marker.setMap(null);
  }
};

speedTest.change = function() {
  speedTest.clear();
  speedTest.showMarkers();
};

speedTest.time = function() {
  $('timetaken').innerHTML = 'timing...';
  var start = new Date();
  if ($('usegmm').checked) {
    speedTest.markerClusterer = new MarkerClusterer(speedTest.map, speedTest.markers);
  } else {
    for (var i = 0, marker; marker = speedTest.markers[i]; i++) {
      marker.setMap(speedTest.map);
    }
  }

  var end = new Date();
  $('timetaken').innerHTML = end - start;
};
<|endoftext|>


<commit_before>import Component from '@ember/component';
import layout from '../templates/components/x-tree-children';

export default Component.extend({
  layout,
  tagName: 'li',
  classNames: ['tree-node'],

  actions: {
    updateCheckbox() {
      if (this.get('recursiveCheck')) {
        let model = this.get('model');
        let children = model.get('children');

        if (children.length) {
          let isChecked = false;
          let isIndeterminate = false;

          if (children.every(x => x.isChecked)) {
            isChecked = true;
          } else if (children.some(x => x.isChecked || x.isIndeterminate)) {
            isIndeterminate = true;
          }

          model.setProperties({ isChecked, isIndeterminate });
        }

        this.sendAction('updateCheckbox');
      }
    }
  }
});
<commit_msg>`sendAction` is deprecated<commit_after>import Component from '@ember/component';
import layout from '../templates/components/x-tree-children';

export default Component.extend({
  layout,
  tagName: 'li',
  classNames: ['tree-node'],

  actions: {
    updateCheckbox() {
      if (this.get('recursiveCheck')) {
        let model = this.get('model');
        let children = model.get('children');

        if (children.length) {
          let isChecked = false;
          let isIndeterminate = false;

          if (children.every(x => x.isChecked)) {
            isChecked = true;
          } else if (children.some(x => x.isChecked || x.isIndeterminate)) {
            isIndeterminate = true;
          }

          model.setProperties({ isChecked, isIndeterminate });
        }

        if (this.updateCheckbox) {
          this.updateCheckbox();
        }
      }
    }
  }
});
<|endoftext|>


<commit_before>define(['text!./material-carousel.html', '../tools/animations'],
function(htmlString, animations) {

	function ViewModel(params) {
		this.frameCount = ko.observable();
		this.interval = params.interval || 10000; //10 seconds by default

		var self = this;
		this.frames = ko.pureComputed(function() {
			return new Array(self.frameCount());
		});
	}
	ViewModel.prototype = {
	};

	ko.bindingHandlers._material_carousel = {
		'init': function(element, valueAccessor) {
			var el = $(element),
				frames = el.find('.frame');

			if (!frames.length) {
				//the component template hasn't been injected yet, must wait
				var initFn = arguments.callee;
				setTimeout(function() {
					initFn(element, valueAccessor);
				}, 50);
				return;
			}

			var options = ko.unwrap(valueAccessor());
			options.frameCount(frames.length);

			setTimeout(function() { //wait for DOM update
				var controls = el.find('.control'),
					selection = 0;

				selectFrame(0);

				controls.each(function(index, el) {
					$(el).click(function() {
						if (interval) {
							clearInterval(interval);
							interval = null;
						}
						animateToFrame(index, animations.timing, true);
					});
				});

				var animating = false,
					interval = setInterval(tick, options.interval);

				ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
					clearInterval(interval);
					controls.each(function(el) {
						$(el).off('click');
					});
				});

				//#region Internal functions

				function tick() {
					animateToFrame((selection + 1) % frames.length, animations.carouselTiming);
				}

				function selectFrame(newSelection) {
					$(frames[newSelection]).addClass('selected');
					$(controls[newSelection]).addClass('selected');
					selection = newSelection;
				}

				function animateToFrame(newSelection, timing, correctDirection) {
					if (selection == newSelection || animating)
						return;

					animating = true;
					var overflowContainer = $(element).addClass('hide-overflow-x');
					$(element).data('selectedTab', newSelection);

					var selectedEl = el.find('.frames > .frame.selected'),
						newSelectedEl = el.find('.frames > .frame:nth-child(' + (newSelection + 1) + ')');

					var selectedElAnimation = animations.slideLeft,
						newSelectionAnimation = animations.slideFromRight;

					if (correctDirection && selection > newSelection) {
						selectedElAnimation = animations.slideRight;
						newSelectionAnimation = animations.slideFromLeft;
					}

					$(controls[selection]).removeClass('selected');
					$(controls[newSelection]).addClass('selected');
					controls.addClass('animating');

					selectedEl.addClass('animating').removeClass('selected');
					var anim1 = selectedEl[0].animate(selectedElAnimation, timing);
					anim1.onfinish = function() {
						selectedEl.removeClass('animating');
					};

					newSelectedEl.addClass('animating selected');
					var anim2 = newSelectedEl[0].animate(newSelectionAnimation, timing);
					anim2.onfinish = function() {
						controls.removeClass('animating');
						newSelectedEl.removeClass('animating');
						overflowContainer.removeClass('hide-overflow-x');
						selection = newSelection;
						animating = false;
					};
				}

				//#endregion
			});
		}
	};

    return {
		'viewModel': ViewModel,
		'template': htmlString
	};
});
<commit_msg>Added stopping ability for elements inside carousel<commit_after>define(['text!./material-carousel.html', '../tools/animations'],
function(htmlString, animations) {

	function ViewModel(params) {
		this.frameCount = ko.observable();
		this.interval = params.interval || 10000; //10 seconds by default

		var self = this;
		this.frames = ko.pureComputed(function() {
			return new Array(self.frameCount());
		});
	}
	ViewModel.prototype = {
	};

	ko.bindingHandlers._material_carousel = {
		'init': function(element, valueAccessor) {
			var el = $(element),
				frames = el.find('.frame');

			if (!frames.length) {
				//the component template hasn't been injected yet, must wait
				var initFn = arguments.callee;
				setTimeout(function() {
					initFn(element, valueAccessor);
				}, 50);
				return;
			}

			var options = ko.unwrap(valueAccessor());
			options.frameCount(frames.length);

			setTimeout(function() { //wait for DOM update
				var controls = el.find('.control'),
					stopOnClickFrames = el.find('.stop-on-click'),
					selection = 0,
					animating = false,
					interval = setInterval(tick, options.interval);

				selectFrame(0);

				controls.each(function(index, el) {
					$(el).click(function() {
						stop();
						animateToFrame(index, animations.timing, true);
					});
				});

				stopOnClickFrames.each(function(index, el) {
					if (!$(el).is('iframe'))
						$(el).click(stop);
					else {
						var listener = window.addEventListener('blur', function() {
							if (document.activeElement === el) {
								stop();
								window.removeEventListener('blur', listener);
							}
						});
					}
				});

				ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
					clearInterval(interval);
					controls.each(function(el) {
						$(el).off('click');
					});
				});

				//#region Internal functions

				function tick() {
					animateToFrame((selection + 1) % frames.length, animations.carouselTiming);
				}

				function selectFrame(newSelection) {
					$(frames[newSelection]).addClass('selected');
					$(controls[newSelection]).addClass('selected');
					selection = newSelection;
				}

				function animateToFrame(newSelection, timing, correctDirection) {
					if (selection == newSelection || animating)
						return;

					animating = true;
					var overflowContainer = $(element).addClass('hide-overflow-x');
					$(element).data('selectedTab', newSelection);

					var selectedEl = el.find('.frames > .frame.selected'),
						newSelectedEl = el.find('.frames > .frame:nth-child(' + (newSelection + 1) + ')');

					var selectedElAnimation = animations.slideLeft,
						newSelectionAnimation = animations.slideFromRight;

					if (correctDirection && selection > newSelection) {
						selectedElAnimation = animations.slideRight;
						newSelectionAnimation = animations.slideFromLeft;
					}

					$(controls[selection]).removeClass('selected');
					$(controls[newSelection]).addClass('selected');
					controls.addClass('animating');

					selectedEl.addClass('animating').removeClass('selected');
					var anim1 = selectedEl[0].animate(selectedElAnimation, timing);
					anim1.onfinish = function() {
						selectedEl.removeClass('animating');
					};

					newSelectedEl.addClass('animating selected');
					var anim2 = newSelectedEl[0].animate(newSelectionAnimation, timing);
					anim2.onfinish = function() {
						controls.removeClass('animating');
						newSelectedEl.removeClass('animating');
						overflowContainer.removeClass('hide-overflow-x');
						selection = newSelection;
						animating = false;
					};
				}

				function stop() {
					if (interval) {
						clearInterval(interval);
						interval = null;
					}
				}

				//#endregion
			});
		}
	};

    return {
		'viewModel': ViewModel,
		'template': htmlString
	};
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
module.exports = (function() {
    'use strict';
    var shell = require('shelljs');

    return doCopy;

    ///////////

    function doCopy(source, dest){
        //console.log(shell.pwd());
        shell.cp('-rf',source, dest);
    }
})();

<commit_msg>[DEL] step-copy: remove comment<commit_after>#!/usr/bin/env node
module.exports = (function() {
    'use strict';
    var shell = require('shelljs');

    return doCopy;

    ///////////

    function doCopy(source, dest){
        shell.cp('-rf', source, dest);
    }
})();

<|endoftext|>


<commit_before>
export default (app) => app.use(async (ctx, next) => {
	const start = Date.now();

	const getResponseTime = () => ({
		key: 'X-Response-Time',
		value: Math.ceil(Date.now() - start) + 'ms',
	});

	ctx.res._getResponseTime = getResponseTime;

	await next();

	if (ctx.respond) {
		const { key, value } = getResponseTime();
		ctx.set(key, value);
	}
});
<commit_msg>fix responseTime bug<commit_after>
export default (app) => app.use(async (ctx, next) => {
	const start = Date.now();

	const getResponseTime = () => ({
		key: 'X-Response-Time',
		value: Math.ceil(Date.now() - start) + 'ms',
	});

	ctx.res._getResponseTime = getResponseTime;

	await next();

	if (ctx.respond !== false) {
		const { key, value } = getResponseTime();
		ctx.set(key, value);
	}
});
<|endoftext|>


<commit_before>var rethink = require('rethinkdb')
var require = require('request')

module.exports = new (function(){
  var that = this

  this.setup = function(config) {
    return rethink.connect(config.rethinkdb)
  }

  this.exchanges = function() {
    return rethink.table('exchanges').run(that.conn)
  }

  this.poll = function(exchange) {

  }
})()
<commit_msg>grab and format market list<commit_after>var rethink = require('rethinkdb')
var request = require('request')

module.exports = new (function(){
  var that = this

  this.setup = function(config) {
    return rethink.connect(config.rethinkdb)
  }

  this.exchanges = function() {
    return rethink.table('exchanges').run(that.conn)
  }

  this.poll = function(exchange) {
    request.get({url: exchange.market_pairs.url, json: true}, function(err, resp, body) {
      console.log(resp)
      var format = eval(exchange.market_pairs.format)
      var pairs = format(body)
      console.log(pairs)
    })
  }
})()
<|endoftext|>


<commit_before>var libui = require('../../index');

var win = new libui.UiWindow('UiVerticalSeparator example', 320, 60, true);
win.margined = true;

var widget = new libui.UiHorizontalBox();
widget.padded = true;
widget.append(new libui.UiMultilineEntry(), false);
widget.append(new libui.UiVerticalSeparator(), false);
widget.append(new libui.UiMultilineEntry(), false);
win.setChild(widget);

win.onClosing(function () {
	win.close();
	libui.Ui.quit();
});

win.show();

libui.Ui.main();

<commit_msg>Fix UiVerticalSeparator example<commit_after>var libui = require('../../index');

var win = new libui.UiWindow('UiVerticalSeparator example', 320, 60, true);
win.margined = true;

var widget = new libui.UiHorizontalBox();
widget.padded = true;
widget.append(new libui.UiMultilineEntry(), true);
widget.append(new libui.UiVerticalSeparator(), false);
widget.append(new libui.UiMultilineEntry(), true);
win.setChild(widget);

win.onClosing(function () {
	win.close();
	libui.Ui.quit();
});

win.show();

libui.Ui.main();

<|endoftext|>


<commit_before>// const path = require("path");
const colors = require("./config/colors.json");
const icons = require("./config/icons.json");

//Generate colors file
const generateColorsVirtualFile = () => {
    const content = [];
    const colorsList = []; //Colors list
    Object.keys(colors).forEach((colorName) => {
        return Object.keys(colors[colorName]).forEach((colorIndex) => {
            return colorsList.push({
                "index": `${colorName}-${colorIndex}`,
                "value": colors[colorName][colorIndex]
            });
        });
    });
    content.push("$colors: (");
    colorsList.forEach((color) => {
        //const sep = (index === colorsList.length - 1) ? "" : ","; //Separator
        return content.push(`    "${color.index}": ${color.value},`);
    });
    //content.push(") !default;");
    content.push(");");
    return content.join("\n");
};

//Unicode parser
const parseUnicode = (value) => value.toString(16).toLowerCase();

//Generate icons file
const generateIconsVirtualFile = () => {
    const content = [];
    content.push("$icons: (");
    icons.forEach((item) => {
        return content.push(`    "${item.id}": "${parseUnicode(item.unicode)}",`);
    });
    //content.push(") !default;");
    content.push(");");
    //Return the file content
    return content.join("\n");
};

module.exports = {
    "name": "siimple",
    "cwd": __dirname,
    "output": "index.scss",
    "entry": [
        // Auto generated modules
        "./sass/colors.scss",
        "./sass/icons.scss",
        // Core modules
        "./sass/utils.scss",
        "./sass/constants.scss",
        "./sass/sheet.scss",
        "./sass/naming.scss",
        "./sass/scales.scss",
        "./sass/breakpoints.scss",
        "./sass/variants.scss",
        "./sass/selectors.scss",
        "./sass/api.scss",
        "./sass/theme.scss",
        // Components
        "./sass/components/*.scss",
        "./sass/experiments/*.scss",
        // Plugins
        "./sass/plugins/*.scss",
    ],
    "resolve": {},
    "virtualFiles": {
        "./sass/colors.scss": generateColorsVirtualFile(),
        "./sass/icons.scss": generateIconsVirtualFile(),
    },
};
<commit_msg>build: update bundle configuration<commit_after>// const path = require("path");
const colors = require("./config/colors.json");
const icons = require("./config/icons.json");

//Generate colors file
const generateColorsVirtualFile = () => {
    const content = [];
    const colorsList = []; //Colors list
    Object.keys(colors).forEach(colorName => {
        return Object.keys(colors[colorName]).forEach((colorIndex) => {
            return colorsList.push({
                "index": `${colorName}-${colorIndex}`,
                "value": colors[colorName][colorIndex]
            });
        });
    });
    content.push("$colors: (");
    colorsList.forEach(color => {
        //const sep = (index === colorsList.length - 1) ? "" : ","; //Separator
        return content.push(`    "${color.index}": ${color.value},`);
    });
    //content.push(") !default;");
    content.push(");");
    return content.join("\n");
};

//Unicode parser
const parseUnicode = value => value.toString(16).toLowerCase();

//Generate icons file
const generateIconsVirtualFile = () => {
    const content = [];
    content.push("$icons: (");
    icons.forEach(item => {
        return content.push(`    "${item.id}": "${parseUnicode(item.unicode)}",`);
    });
    //content.push(") !default;");
    content.push(");");
    //Return the file content
    return content.join("\n");
};

module.exports = Object.values({
    "index": {
        "output": "index.scss",
        "entry": [
            "./sass/index.scss",
        ],
        "resolve": {
            "siimple:lib": "./lib.scss",
            "siimple:plugins": "./plugins.scss",
        },
    },
    "colors": {
        "output": "colors.scss",
        "entry": [
            "./colors.scss",
            "./sass/addons/colors.scss",
        ],
        "resolve": {
            "siimple:lib": "./lib.scss",
        },
        "virtualFiles": {
            "./colors.scss": generateColorsVirtualFile(),
        },
    },
    "icons": {
        "output": "icons.scss",
        "entry": [
            "./icons.scss",
            "./sass/addons/icons.scss",
        ],
        "virtualFiles": {
            "./icons.scss": generateIconsVirtualFile(),
        },
    },
    "plugins": {
        "output": "plugins.scss",
        "entry": [
            "./sass/components/*.scss",
            "./sass/experiments/*.scss",
            "./sass/helpers/*.scss",
            "./sass/plugins/*.scss",
        ],
        "resolve": {
            "siimple:icons": "./icons.scss",
            "siimple:colors": "./colors.scss",
            "siimple:lib": "./lib.scss",
        },
    },
    "lib": {
        "output": "lib.scss",
        "entry": [
            "./sass/utils.scss",
            "./sass/constants.scss",
            "./sass/naming.scss",
            "./sass/scales.scss",
            "./sass/breakpoints.scss",
            "./sass/variants.scss",
            // "./sass/selectors.scss",
            "./sass/plugins.scss",
            "./sass/theme.scss",
            "./sass/sheet.scss",
        ],
        "resolve": {},
    },
});
<|endoftext|>