<commit_before>class RingArray {
  constructor(capacity) {
    this.capacity = capacity;
    this._entries = [];
    this._position = 0;
    this.available = 0;
    for (let i = 0; i < capacity; i++) {
      this._entries[i] = undefined;
    }
  }

  push(entry) {
    this._entries[this._position] = entry;
    this._position = (this._position + 1) % this.capacity;
    if (this.available < this.capacity) {
      this.available += 1;
    }
    return entry;
  }

  entries(n) {
    if (typeof n === 'undefined' || n >= this.available) {
      n = this.available;
    }
    const result = [];
    let pos = (this._position + this.capacity - n) % this.capacity;
    for (let i = 0; i < n; i++) {
      result[i] = this._entries[pos];
      pos = (pos + 1) % this.capacity;
    }
    return result;
  }
}

const URL = Npm.require('url'),
  defaultConfig = {
    hitSamples: 1024,
    openedSessions: 64,
    closedSessions: 64,
  },
  config = _.extend(defaultConfig, Meteor.settings.connstats),
  hitSamples = _.range(config.hitSamples).map(() => undefined),
  openedSessions = new RingArray(config.openedSessions),
  closedSessions = new RingArray(config.openedSessions),
  randBucket = () => _.random(config.hitSamples - 1),
  activeSessions = {},
  connDescr = (conn) => ({
    ua: conn.httpHeaders['user-agent'],
    ip: conn.httpHeaders['x-forwarded-for'],
    started: new Date(),
  });

WebApp.connectHandlers.use((req, res, next) => {
  if (req.url.indexOf('/.well-known/pcarrier/connstats') === 0) {
    res.setHeader('Content-Type', 'application/json');

    if (typeof config.secret !== 'undefined') {
      const query = URL.parse(req.url, true).query;
      if (config.secret !== query.secret) {
        res.statusCode = 403;
        return res.end(JSON.stringify({error:"secret needed"}));
      }
    }

    res.end(JSON.stringify({
      hitSamples: _.without(hitSamples, undefined),
      activeSessions: _.values(activeSessions),
      openedSessions: openedSessions.entries(),
      closedSessions: closedSessions.entries(),
    }));
  } else {
    hitSamples[randBucket()] = {
      ua: req.headers['user-agent'],
      ip: req.headers['x-forwarded-for'],
    };
    next();
  }
});

Meteor.onConnection(function(conn) {
  const descr = connDescr(conn);
  activeSessions[conn.id] = descr;
  openedSessions.push(descr);
  conn.onClose(function() {
    delete activeSessions[conn.id];
    descr.stopped = new Date();
    closedSessions.push(descr);
  });
});
<commit_msg>hitSamples: expose timestamp<commit_after>class RingArray {
  constructor(capacity) {
    this.capacity = capacity;
    this._entries = [];
    this._position = 0;
    this.available = 0;
    for (let i = 0; i < capacity; i++) {
      this._entries[i] = undefined;
    }
  }

  push(entry) {
    this._entries[this._position] = entry;
    this._position = (this._position + 1) % this.capacity;
    if (this.available < this.capacity) {
      this.available += 1;
    }
    return entry;
  }

  entries(n) {
    if (typeof n === 'undefined' || n >= this.available) {
      n = this.available;
    }
    const result = [];
    let pos = (this._position + this.capacity - n) % this.capacity;
    for (let i = 0; i < n; i++) {
      result[i] = this._entries[pos];
      pos = (pos + 1) % this.capacity;
    }
    return result;
  }
}

const URL = Npm.require('url'),
  defaultConfig = {
    hitSamples: 1024,
    openedSessions: 64,
    closedSessions: 64,
  },
  config = _.extend(defaultConfig, Meteor.settings.connstats),
  hitSamples = _.range(config.hitSamples).map(() => undefined),
  openedSessions = new RingArray(config.openedSessions),
  closedSessions = new RingArray(config.openedSessions),
  randBucket = () => _.random(config.hitSamples - 1),
  activeSessions = {},
  connDescr = (conn) => ({
    ua: conn.httpHeaders['user-agent'],
    ip: conn.httpHeaders['x-forwarded-for'],
    started: new Date(),
  });

WebApp.connectHandlers.use((req, res, next) => {
  if (req.url.indexOf('/.well-known/pcarrier/connstats') === 0) {
    res.setHeader('Content-Type', 'application/json');

    if (typeof config.secret !== 'undefined') {
      const query = URL.parse(req.url, true).query;
      if (config.secret !== query.secret) {
        res.statusCode = 403;
        return res.end(JSON.stringify({error:"secret needed"}));
      }
    }

    res.end(JSON.stringify({
      hitSamples: _.without(hitSamples, undefined),
      activeSessions: _.values(activeSessions),
      openedSessions: openedSessions.entries(),
      closedSessions: closedSessions.entries(),
    }));
  } else {
    hitSamples[randBucket()] = {
      ua: req.headers['user-agent'],
      ip: req.headers['x-forwarded-for'],
      ts: new Date(),
    };
    next();
  }
});

Meteor.onConnection(function(conn) {
  const descr = connDescr(conn);
  activeSessions[conn.id] = descr;
  openedSessions.push(descr);
  conn.onClose(function() {
    delete activeSessions[conn.id];
    descr.stopped = new Date();
    closedSessions.push(descr);
  });
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         RohBot Imperial to Metric
// @version      1.21
// @description  Converts imperial to metric if it finds any
// @author       Spans
// @match        https://rohbot.net
// @grant        none
// @updateURL	 https://raw.githubusercontent.com/Spanfile/RohBot-Imperial-to-Metric-Converter/master/converter.js
// ==/UserScript==

chatMgr.lineFilter.add(function (line, prepend, e) {
	line.Content = applyConversions(line.Content);
});

String.prototype.splice = function(idx, rem, s) {
	return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};

var prefixes = {
	"k": 1000,
	"m": 1000000,
	"b": 1000000000
}

var conversions = [
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(ft|feet|foot)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 3.2808 },
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(yd|yards|yard)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 1.0936 },
	{ name: "centimeters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(in|inches|inch|")(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.39370 },
	{ name: "kilometers", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(miles|mi)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.62137 },
	{ name: "Celsius", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(f|fahrenheit|degrees fahrenheit)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 1.8, subtract: 32},
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(lb|lbs|pounds|pound)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 2.2046 },
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(st|stone)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.157473 },
	{ name: "grams", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(oz|ounces|ounce)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.035274 },
	{ name: "liters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(gal|gallons|gallon)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.26417 },
	{ name: "KPH", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(mph|miles per hour)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 1/1.6093 },

	{ name: "meters", specialFunc: function(message) {
		// the ' there in the middle is for ' and " is for "
		var regex = /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])?'(?:([\d,]+(?:\.\d+)?)([kmb])?")?(?=\s|$|,|\.|!|\?|\*|\/)/ig;
		var m;
		var results = [];
		while ((m = regex.exec(message)) !== null) {
			if (m.index === regex.lastIndex) {
				regex.lastIndex++;
			}

			var feet = Number(m[1].replace(",", "")); // get rid of thousand separator commas
			var feetPrefix = m[2];
			var inches = 0;

			if (feetPrefix) {
				feet *= prefixes[feetPrefix.toLowerCase()];
			}

			if (m[3]) {
				inches = Number(m[3].replace(",", "")); // get rid of thousand separator commas

				if (m[4]) {
					inches *= prefixes[m[4].toLowerCase()];
				}
			}

			var convertedFeet = feet / 3.2808;
			var convertedInches = inches / 39.370;

			var total = Math.round((convertedFeet + convertedInches) * 100) / 100;
			results[results.length] = {original:m[0], index:m.index, conversion:total, unit:"meters"};
		}

		return results;
	}}
];

function applyConversions(message) {
	var results = [];

	// aggregate the results
	conversions.forEach(function(conversion) {
		var result = conversion.specialFunc ? conversion.specialFunc(message) : commonConversion(message, conversion.regex, conversion.divide, conversion.subtract || 0, conversion.name);

		if (result.length > 0) {
			//console.log(result);
			results[results.length] = result;
		}
	});

	// since the converters can return multiple conversions, flatten the results
	// the result looks like [[{stuff here}, {stuff here}], [{stuff here}, {stuff here}]]
	// flattening it turns it into [{stuff here}, {stuff here}, {stuff here}, {stuff here}]
	var flattened = [].concat.apply([], results);

	// sort them
	flattened.sort(function(a, b) {
		if (a.index > b.index) {
			return 1;
		}

		if (a.index < b.index) {
			return -1;
		}

		return 0;
	});

	var newMsg = message;
	var inserted = 0;
	// combine them all
	flattened.forEach(function(result) {
		var title = result.conversion.toLocaleString() + " " + result.unit;
		var original = result.original;
		var begin = "";

		// because the js regex engine doesn't support positive lookbehinds, the regexes return the whitespace before every match
		// most of the time they do it unless the match is at the start of the message
		// in case there is a whitespace, remove it and have one added before the  tag
		if (original.substring(0, 1) == " ") {
			original = original.substring(1);
			begin = " ";
		}

		var toInsert = begin + "" + original + "";
		newMsg = newMsg.splice(result.index + inserted, result.original.length, toInsert);
		inserted += toInsert.length - result.original.length;
	});

	return newMsg;
}

function commonConversion(message, regex, divide, subtract, unit) {
	var m;
	var results = [];
	while ((m = regex.exec(message)) !== null) {
		if (m.index === regex.lastIndex) {
			regex.lastIndex++;
		}

		var offset = 0;
		var amountStr = m[1];
		var prefix = m[2];

		// remove leading comma if found
		if (amountStr.substring(0, 1) == ",") {
			amountStr = amountStr.substring(1);
			m[0] = m[0].substring(1);
			offset = 1;
		}

		var amount = Number(amountStr.replace(",", "")); // get rid of thousand separator commas

		if (prefix) {
			amount *= prefixes[prefix.toLowerCase()];
		}

		var converted = Math.round(((amount - subtract) / divide) * 100) / 100;
		//console.log("Conversion: " + amount + " "  + m[2] + " to " + converted + " " + unit);
		results[results.length] = { original:m[0], index:m.index + offset, conversion:converted, unit:unit };
	}

	return results;
}
<commit_msg>Forgot to increase version<commit_after>// ==UserScript==
// @name         RohBot Imperial to Metric
// @version      1.22
// @description  Converts imperial to metric if it finds any
// @author       Spans
// @match        https://rohbot.net
// @grant        none
// @updateURL	 https://raw.githubusercontent.com/Spanfile/RohBot-Imperial-to-Metric-Converter/master/converter.js
// ==/UserScript==

chatMgr.lineFilter.add(function (line, prepend, e) {
	line.Content = applyConversions(line.Content);
});

String.prototype.splice = function(idx, rem, s) {
	return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};

var prefixes = {
	"k": 1000,
	"m": 1000000,
	"b": 1000000000
}

var conversions = [
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(ft|feet|foot)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 3.2808 },
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(yd|yards|yard)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 1.0936 },
	{ name: "centimeters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(in|inches|inch|")(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.39370 },
	{ name: "kilometers", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(miles|mi)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.62137 },
	{ name: "Celsius", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(f|fahrenheit|degrees fahrenheit)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 1.8, subtract: 32},
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(lb|lbs|pounds|pound)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 2.2046 },
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(st|stone)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.157473 },
	{ name: "grams", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(oz|ounces|ounce)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.035274 },
	{ name: "liters", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(gal|gallons|gallon)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 0.26417 },
	{ name: "KPH", regex: /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])? ?(mph|miles per hour)(?=\s|$|,|\.|!|\?|\*|\/)/ig, divide: 1/1.6093 },

	{ name: "meters", specialFunc: function(message) {
		// the ' there in the middle is for ' and " is for "
		var regex = /(?:\s|^|,|\.|!|\?|\*|\/)([\d,]+(?:\.\d+)?)([kmb])?'(?:([\d,]+(?:\.\d+)?)([kmb])?")?(?=\s|$|,|\.|!|\?|\*|\/)/ig;
		var m;
		var results = [];
		while ((m = regex.exec(message)) !== null) {
			if (m.index === regex.lastIndex) {
				regex.lastIndex++;
			}

			var feet = Number(m[1].replace(",", "")); // get rid of thousand separator commas
			var feetPrefix = m[2];
			var inches = 0;

			if (feetPrefix) {
				feet *= prefixes[feetPrefix.toLowerCase()];
			}

			if (m[3]) {
				inches = Number(m[3].replace(",", "")); // get rid of thousand separator commas

				if (m[4]) {
					inches *= prefixes[m[4].toLowerCase()];
				}
			}

			var convertedFeet = feet / 3.2808;
			var convertedInches = inches / 39.370;

			var total = Math.round((convertedFeet + convertedInches) * 100) / 100;
			results[results.length] = {original:m[0], index:m.index, conversion:total, unit:"meters"};
		}

		return results;
	}}
];

function applyConversions(message) {
	var results = [];

	// aggregate the results
	conversions.forEach(function(conversion) {
		var result = conversion.specialFunc ? conversion.specialFunc(message) : commonConversion(message, conversion.regex, conversion.divide, conversion.subtract || 0, conversion.name);

		if (result.length > 0) {
			//console.log(result);
			results[results.length] = result;
		}
	});

	// since the converters can return multiple conversions, flatten the results
	// the result looks like [[{stuff here}, {stuff here}], [{stuff here}, {stuff here}]]
	// flattening it turns it into [{stuff here}, {stuff here}, {stuff here}, {stuff here}]
	var flattened = [].concat.apply([], results);

	// sort them
	flattened.sort(function(a, b) {
		if (a.index > b.index) {
			return 1;
		}

		if (a.index < b.index) {
			return -1;
		}

		return 0;
	});

	var newMsg = message;
	var inserted = 0;
	// combine them all
	flattened.forEach(function(result) {
		var title = result.conversion.toLocaleString() + " " + result.unit;
		var original = result.original;
		var begin = "";

		// because the js regex engine doesn't support positive lookbehinds, the regexes return the whitespace before every match
		// most of the time they do it unless the match is at the start of the message
		// in case there is a whitespace, remove it and have one added before the  tag
		if (original.substring(0, 1) == " ") {
			original = original.substring(1);
			begin = " ";
		}

		var toInsert = begin + "" + original + "";
		newMsg = newMsg.splice(result.index + inserted, result.original.length, toInsert);
		inserted += toInsert.length - result.original.length;
	});

	return newMsg;
}

function commonConversion(message, regex, divide, subtract, unit) {
	var m;
	var results = [];
	while ((m = regex.exec(message)) !== null) {
		if (m.index === regex.lastIndex) {
			regex.lastIndex++;
		}

		var offset = 0;
		var amountStr = m[1];
		var prefix = m[2];

		// remove leading comma if found
		if (amountStr.substring(0, 1) == ",") {
			amountStr = amountStr.substring(1);
			m[0] = m[0].substring(1);
			offset = 1;
		}

		var amount = Number(amountStr.replace(",", "")); // get rid of thousand separator commas

		if (prefix) {
			amount *= prefixes[prefix.toLowerCase()];
		}

		var converted = Math.round(((amount - subtract) / divide) * 100) / 100;
		//console.log("Conversion: " + amount + " "  + m[2] + " to " + converted + " " + unit);
		results[results.length] = { original:m[0], index:m.index + offset, conversion:converted, unit:unit };
	}

	return results;
}
<|endoftext|>


<commit_before>'use strict'

const crypto = require('crypto');
const resolve = require('path').resolve;
const fs = require('fs');
const suffixTest = /\.json$/;
const root = resolve(process.argv[2] || '.') + '/';
const env_config = require(root + 'flow.json');
const path = root + 'composition/';
const states = {};
const files = fs.readdirSync(path);
const rdf_syntax = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
const hashids = {};
const hashlbs = {};
const envs = {};
const temp_index = {};

function write (subject, predicate, object) {
    process.stdout.write(subject + ' <' + predicate + '> ' + object + ' .\n');
}

function getMethodIri (module, method) {

    // git+https://github.com/ + module + .git
    let owner = 'jillix';
    switch (module) {
        case 'flow-view':
        case 'flow-auth':
        case 'flow-streams':
        case 'flow-visualizer':
        case 'flow-compress':
            owner = 'adioo';
            break;
        case 'flow-keypress':
        case 'flow-ace':
            owner = 'danandrei';
            break;
    }

    // TODO method descriptor
    return '<' + owner + '/' + module + '?' + method + '>';
}

function parseHandler (state, handler) {
    handler = handler.split('/');
    let parsed = {
        type: handler[0][0]
    };
    handler[0] = handler[0].substr(1);

    if (handler.length > 1) {
        parsed.state = handler[0];
        parsed.path = handler[1];
    } else {
        parsed.state = state;
        parsed.path = handler[0]
    }

    if (parsed.type !== '>') {
        parsed.path = getMethodIri(states[parsed.state].module, parsed.path);
    } else {
        parsed.path = '_:' + crypto.createHash('md5').update(parsed.state + parsed.path).digest('hex');
    }

    return parsed;
}

function UID (len) {
    len = len || 23;
    let i = 0, random = '';
    for (; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return '_:' + crypto.createHash('md5').update(random).digest('hex');
}

function getHash (string) {
    let hash = '_:' + crypto.createHash('md5').update(string).digest('hex');
    if (!hashids[hash]) {
        hashids[hash] = 1;
        write(hash, rdf_syntax + 'string', '"' + string.replace(/"/g, '\\"') + '"');
    }

    return hash;
}

// create network triple
const network_id = '_:' + crypto.createHash('md5').update(env_config.network).digest('hex');

// network name (Service)
write(
    network_id,
    'http://schema.org/name',
    getHash(env_config.network)
);

// network type
write(
    network_id,
    rdf_syntax + 'type',
    '<http://schema.jillix.net/vocab/Network>'
);

// Convert composition files to triples
files.forEach(file => {

    if (!suffixTest.test(file)) {
        return;
    }

    try {
        let state = JSON.parse(fs.readFileSync(path + file));
        states[state.name] = state;
    } catch (error) {
        throw new Error(path + file + '\n' + error);
    }
});

// create env objects
if (env_config) {

    if (env_config.environments) {
        env_config.environments.forEach(env => {
            envs[env.name] = getHash(env.name);

            // environment name
            write(
                envs[env.name],
                'http://schema.org/name',
                envs[env.name]
            );

            // environment vars
            write(
                envs[env.name],
                'http://schema.jillix.net/vocab/json',
                getHash(JSON.stringify(env.vars))
            );

            // environment type
            write(
                envs[env.name],
                rdf_syntax + 'type',
                '<http://schema.jillix.net/vocab/Environment>'
            );
        });
    }

    if (env_config.entrypoints) {
        env_config.entrypoints.forEach(ep => {

            const entrypoint_id = UID();

            // network entrypoint
            write(
                network_id,
                'http://schema.jillix.net/vocab/entrypoint',
                entrypoint_id
            );

            // entrypoint name
            write(
                entrypoint_id,
                'http://schema.org/name',
                getHash(ep.name)
            );

            // entrypoint type
            write(
                entrypoint_id,
                rdf_syntax + 'type',
                '<http://schema.jillix.net/vocab/Entrypoint>'
            );

            // entrypoint environment
            if (ep.env) {
                ep.env.forEach(env => {
                    if (envs[env]) {
                        write(
                            entrypoint_id,
                            'http://schema.jillix.net/vocab/environment',
                            envs[env]
                        );
                    }
                });
            }

            // entrypoint sequence
            write(
                entrypoint_id,
                'http://schema.jillix.net/vocab/sequence',
                '_:' + crypto.createHash('md5').update(ep.emit.replace('/', '')).digest('hex')
            );
        });
    }
}

for (let name in states) {
    let state = states[name];

    if (!state.flow) {
        continue;
    }

    for (let sequence in state.flow) {
        let sequence_id = '_:' + crypto.createHash('md5').update(state.name + sequence).digest('hex');

        // name
        write(
            sequence_id,
            'http://schema.org/name',
            getHash(state.name + '-' + sequence)
        );

        // type
        write(
            sequence_id,
            rdf_syntax + 'type',
            '<http://schema.jillix.net/vocab/Sequence>'
        );

        // roles
        if (state.roles) {
            for (let role in state.roles) {
                write(
                    sequence_id,
                    'http://schema.jillix.net/vocab/role',
                    getHash(role)
                );
            }
        }

        // end event
        if (state.flow[sequence].e) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onEnd',
                '_:' + crypto.createHash('md5').update(state.flow[sequence].e.replace('/', '')).digest('hex')
            );
        }

        // error event
        if (state.flow[sequence].r) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onError',
                '_:' + crypto.createHash('md5').update(state.flow[sequence].r.replace('/', '')).digest('hex')
            );
        }

        // sequence
        if (state.flow[sequence].d) {
            let previous;
            state.flow[sequence].d.forEach((handler, index) => {

                let handler_id = UID();
                let args;

                if (typeof handler === 'string') {
                    handler = handler;
                    args = null;
                } else {
                    args = handler[1];
                    handler = handler[0];
                }

                handler = parseHandler(state.name, handler);

                // type
                write(
                    handler_id,
                    rdf_syntax + 'type',
                    '<http://schema.jillix.net/vocab/Handler>'
                );

                // method args
                if (args) {
                    args = JSON.stringify(args);

                    // potential emits from args
                    let potential_emits = args.match(/\{FLOW\:([^\}]+)\}/g);
                    let emits = [];
                    if (potential_emits) {
                        potential_emits.forEach(emit => {
                            let replace = emit;
                            emit = emit.slice(6, -1).replace('/', '');
                            emit = '_:' + crypto.createHash('md5').update(emit).digest('hex');
                            args = args.replace(replace, emit);
                            emits.push(emit);
                        });
                    }

                    let args_hid = getHash(args);
                    let args_uid = UID();
                    let args_lbl = "Args";

                    // handler args connection
                    write(
                        handler_id,
                        'http://schema.jillix.net/vocab/args',
                        args_uid
                    );

                    // arg object
                    write(
                        args_uid,
                        'http://schema.jillix.net/vocab/json',
                        args_hid
                    );

                    // args type
                    write(
                        args_uid,
                        rdf_syntax + 'type',
                        '<http://schema.jillix.net/vocab/Arguments>'
                    );

                    // args name
                    write(
                        args_uid,
                        'http://schema.org/name',
                        getHash('Args')
                    );

                    emits.forEach(emit => {
                        let key = args_uid + emit;
                        if (!temp_index[key]) {
                            temp_index[key] = 1;
                            write(
                                args_uid,
                                'http://schema.jillix.net/vocab/emit',
                                emit
                            );
                        }
                    });
                }

                // state
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/state',
                    getHash(handler.state, [handler.state])
                );

                switch (handler.type) {
                    case '.':
                    case ':':
                        // method (data)
                        write(
                            handler_id,
                            'http://schema.jillix.net/vocab/data',
                            handler.path
                        );
                        break;
                    case '*':
                        // method (stream)
                        write(
                            handler_id,
                            'http://schema.jillix.net/vocab/stream',
                            handler.path
                        );
                        break;

                    case '>':
                        // emit
                        write(
                            handler_id,
                            'http://schema.jillix.net/vocab/emit',
                            handler.path
                        );
                        break;
                }

                // next
                write(
                    index === 0 ? sequence_id : previous,
                    'http://schema.jillix.net/vocab/next',
                    handler_id
                );

                previous = handler_id;

                // link back to sequence (owner)
                write(
                    sequence_id,
                    'http://schema.jillix.net/vocab/handler',
                    handler_id
                );
            });
        }
    }
}
<commit_msg>create type for each handler (data/stream/emit)<commit_after>'use strict'

const crypto = require('crypto');
const resolve = require('path').resolve;
const fs = require('fs');
const suffixTest = /\.json$/;
const root = resolve(process.argv[2] || '.') + '/';
const env_config = require(root + 'flow.json');
const path = root + 'composition/';
const states = {};
const files = fs.readdirSync(path);
const rdf_syntax = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
const hashids = {};
const hashlbs = {};
const envs = {};
const temp_index = {};

function write (subject, predicate, object) {
    process.stdout.write(subject + ' <' + predicate + '> ' + object + ' .\n');
}

function getMethodIri (module, method) {

    // git+https://github.com/ + module + .git
    let owner = 'jillix';
    switch (module) {
        case 'flow-view':
        case 'flow-auth':
        case 'flow-streams':
        case 'flow-visualizer':
        case 'flow-compress':
            owner = 'adioo';
            break;
        case 'flow-keypress':
        case 'flow-ace':
            owner = 'danandrei';
            break;
    }

    // TODO method descriptor
    return '<' + owner + '/' + module + '?' + method + '>';
}

function parseHandler (state, handler) {
    handler = handler.split('/');
    let parsed = {
        type: handler[0][0]
    };
    handler[0] = handler[0].substr(1);

    if (handler.length > 1) {
        parsed.state = handler[0];
        parsed.path = handler[1];
    } else {
        parsed.state = state;
        parsed.path = handler[0]
    }

    parsed.name = parsed.state.toLowerCase() + '/' + parsed.path.toUpperCase();
    parsed.name = parsed.name.trim().replace(/[^a-z0-9\.\/ ]/gi, ' ');

    if (parsed.type !== '>') {
        parsed.path = getMethodIri(states[parsed.state].module, parsed.path);
    } else {
        parsed.path = '_:' + crypto.createHash('md5').update(parsed.state + parsed.path).digest('hex');
    }

    return parsed;
}

function UID (len) {
    len = len || 23;
    let i = 0, random = '';
    for (; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return '_:' + crypto.createHash('md5').update(random).digest('hex');
}

function getHash (string) {
    let hash = '_:' + crypto.createHash('md5').update(string).digest('hex');
    if (!hashids[hash]) {
        hashids[hash] = 1;
        write(hash, rdf_syntax + 'string', '"' + string.replace(/"/g, '\\"') + '"');
    }

    return hash;
}

// create network triple
const network_id = '_:' + crypto.createHash('md5').update(env_config.network).digest('hex');

// network name (Service)
write(
    network_id,
    'http://schema.org/name',
    getHash(env_config.network)
);

// network type
write(
    network_id,
    rdf_syntax + 'type',
    '<http://schema.jillix.net/vocab/Network>'
);

// Convert composition files to triples
files.forEach(file => {

    if (!suffixTest.test(file)) {
        return;
    }

    try {
        let state = JSON.parse(fs.readFileSync(path + file));
        states[state.name] = state;
    } catch (error) {
        throw new Error(path + file + '\n' + error);
    }
});

// create env objects
if (env_config) {

    if (env_config.environments) {
        env_config.environments.forEach(env => {
            envs[env.name] = getHash(env.name);

            // environment name
            write(
                envs[env.name],
                'http://schema.org/name',
                envs[env.name]
            );

            // environment vars
            write(
                envs[env.name],
                'http://schema.jillix.net/vocab/json',
                getHash(JSON.stringify(env.vars))
            );

            // environment type
            write(
                envs[env.name],
                rdf_syntax + 'type',
                '<http://schema.jillix.net/vocab/Environment>'
            );
        });
    }

    if (env_config.entrypoints) {
        env_config.entrypoints.forEach(ep => {

            const entrypoint_id = UID();

            // network entrypoint
            write(
                network_id,
                'http://schema.jillix.net/vocab/entrypoint',
                entrypoint_id
            );

            // entrypoint name
            write(
                entrypoint_id,
                'http://schema.org/name',
                getHash(ep.name)
            );

            // entrypoint type
            write(
                entrypoint_id,
                rdf_syntax + 'type',
                '<http://schema.jillix.net/vocab/Entrypoint>'
            );

            // entrypoint environment
            if (ep.env) {
                ep.env.forEach(env => {
                    if (envs[env]) {
                        write(
                            entrypoint_id,
                            'http://schema.jillix.net/vocab/environment',
                            envs[env]
                        );
                    }
                });
            }

            // entrypoint sequence
            write(
                entrypoint_id,
                'http://schema.jillix.net/vocab/sequence',
                '_:' + crypto.createHash('md5').update(ep.emit.replace('/', '')).digest('hex')
            );
        });
    }
}

// sequences
for (let name in states) {
    let state = states[name];

    if (!state.flow) {
        continue;
    }

    // sequence
    for (let sequence in state.flow) {
        let sequence_id = '_:' + crypto.createHash('md5').update(state.name + sequence).digest('hex');

        // name
        write(
            sequence_id,
            'http://schema.org/name',
            getHash(state.name + '-' + sequence)
        );

        // type
        write(
            sequence_id,
            rdf_syntax + 'type',
            '<http://schema.jillix.net/vocab/Sequence>'
        );

        // roles
        if (state.roles) {
            for (let role in state.roles) {
                write(
                    sequence_id,
                    'http://schema.jillix.net/vocab/role',
                    getHash(role)
                );
            }
        }

        // end event
        if (state.flow[sequence].e) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onEnd',
                '_:' + crypto.createHash('md5').update(state.flow[sequence].e.replace('/', '')).digest('hex')
            );
        }

        // error event
        if (state.flow[sequence].r) {
            write(
                sequence_id,
                'http://schema.jillix.net/vocab/onError',
                '_:' + crypto.createHash('md5').update(state.flow[sequence].r.replace('/', '')).digest('hex')
            );
        }

        // handlers
        if (state.flow[sequence].d) {
            let previous;

            // handler
            state.flow[sequence].d.forEach((handler, index) => {

                let handler_id = UID();
                let args;

                if (typeof handler === 'string') {
                    handler = handler;
                    args = null;
                } else {
                    args = handler[1];
                    handler = handler[0];
                }

                handler = parseHandler(state.name, handler);

                // name
                write(
                    handler_id,
                    'http://schema.org/name',
                    getHash(handler.name)
                );

                // state
                write(
                    handler_id,
                    'http://schema.jillix.net/vocab/state',
                    getHash(handler.state)
                );

                switch (handler.type) {
                    case '.':
                    case ':':
                        // type data
                        write(
                            handler_id,
                            rdf_syntax + 'type',
                            '<http://schema.jillix.net/vocab/Data>'
                        );

                        // function
                        write(
                            handler_id,
                            'http://schema.jillix.net/vocab/fn',
                            handler.path
                        );
                        break;
                    case '*':
                        // type stream
                        write(
                            handler_id,
                            rdf_syntax + 'type',
                            '<http://schema.jillix.net/vocab/Stream>'
                        );

                        // function
                        write(
                            handler_id,
                            'http://schema.jillix.net/vocab/fn',
                            handler.path
                        );
                        break;

                    case '>':

                        // type Emit
                        write(
                            handler_id,
                            rdf_syntax + 'type',
                            '<http://schema.jillix.net/vocab/Emit>'
                        );

                        // sequence
                        write(
                            handler_id,
                            'http://schema.jillix.net/vocab/sequence',
                            handler.path
                        );
                        break;
                }

                // next
                write(
                    index === 0 ? sequence_id : previous,
                    'http://schema.jillix.net/vocab/next',
                    handler_id
                );

                previous = handler_id;

                // link back to sequence (owner)
                write(
                    sequence_id,
                    'http://schema.jillix.net/vocab/handler',
                    handler_id
                );

                // method args
                if (args) {
                    args = JSON.stringify(args);

                    // potential emits from args
                    let potential_emits = args.match(/\{FLOW\:([^\}]+)\}/g);
                    let emits = [];
                    if (potential_emits) {
                        potential_emits.forEach(emit => {
                            let replace = emit;
                            emit = emit.slice(6, -1).replace('/', '');
                            emit = '_:' + crypto.createHash('md5').update(emit).digest('hex');
                            args = args.replace(replace, emit);
                            emits.push(emit);
                        });
                    }

                    let args_hid = getHash(args);
                    let args_uid = UID();
                    let args_lbl = "Args";

                    // handler args connection
                    write(
                        handler_id,
                        'http://schema.jillix.net/vocab/args',
                        args_uid
                    );

                    // arg object
                    write(
                        args_uid,
                        'http://schema.jillix.net/vocab/json',
                        args_hid
                    );

                    // args type
                    write(
                        args_uid,
                        rdf_syntax + 'type',
                        '<http://schema.jillix.net/vocab/Arguments>'
                    );

                    // args name
                    write(
                        args_uid,
                        'http://schema.org/name',
                        getHash('Args')
                    );

                    emits.forEach(emit => {
                        let key = args_uid + emit;
                        if (!temp_index[key]) {
                            temp_index[key] = 1;
                            write(
                                args_uid,
                                'http://schema.jillix.net/vocab/sequence',
                                emit
                            );
                        }
                    });
                }
            });
        }
    }
}
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Famous Industries Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

'use strict';

/**
 * The Size class is responsible for processing Size from a node
 * @constructor {Size}
 */
function Size () {
    this._size = new Float32Array(3);
}

// an enumeration of the different types of size modes
Size.RELATIVE = 0;
Size.ABSOLUTE = 1;
Size.RENDER = 2;
Size.DEFAULT = Size.RELATIVE;

/**
 * fromSpecWithParent takes the parent node's size, the target nodes spec,
 * and a target array to write to. Using the node's size mode it calculates
 * a final size for the node from the node's spec. Returns whether or not
 * the final size has changed from its last value.
 *
 * @param {Array} parent node's calculated size
 * @param {Node.Spec} the target node's spec
 * @param {Array} an array to write the result to
 *
 * @return {Boolean} true if the size of the node has changed.
 */
Size.prototype.fromSpecWithParent = function fromSpecWithParent (parentSize, node, target) {
    var spec = node.getValue().spec;
    var components = node.getComponents();
    var mode = spec.size.sizeMode;
    var prev;
    var changed = false;
    var len = components.length;
    var j;
    for (var i = 0 ; i < 3 ; i++) {
        switch (mode[i]) {
            case Size.RELATIVE:
                prev = target[i];
                target[i] = parentSize[i] * spec.size.proportional[i] + spec.size.differential[i];
                break;
            case Size.ABSOLUTE:
                prev = target[i];
                target[i] = spec.size.absolute[i];
                break;
            case Size.RENDER:
                var candidate;
                for (j = 0; j < len ; j++) {
                    candidate = components[j].getRenderSize()[i];
                    prev = target[i];
                    target[i] = target[i] < candidate || target[i] === 0 ? candidate : target[i];
                }
                break;
        }
        changed = changed || prev !== target[i];
    }
    return changed;
};

module.exports = Size;
<commit_msg>fix: prevented bug when component doesn't have a getRenderSize method<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Famous Industries Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

'use strict';

/**
 * The Size class is responsible for processing Size from a node
 * @constructor {Size}
 */
function Size () {
    this._size = new Float32Array(3);
}

// an enumeration of the different types of size modes
Size.RELATIVE = 0;
Size.ABSOLUTE = 1;
Size.RENDER = 2;
Size.DEFAULT = Size.RELATIVE;

/**
 * fromSpecWithParent takes the parent node's size, the target nodes spec,
 * and a target array to write to. Using the node's size mode it calculates
 * a final size for the node from the node's spec. Returns whether or not
 * the final size has changed from its last value.
 *
 * @param {Array} parent node's calculated size
 * @param {Node.Spec} the target node's spec
 * @param {Array} an array to write the result to
 *
 * @return {Boolean} true if the size of the node has changed.
 */
Size.prototype.fromSpecWithParent = function fromSpecWithParent (parentSize, node, target) {
    var spec = node.getValue().spec;
    var components = node.getComponents();
    var mode = spec.size.sizeMode;
    var prev;
    var changed = false;
    var len = components.length;
    var j;
    for (var i = 0 ; i < 3 ; i++) {
        switch (mode[i]) {
            case Size.RELATIVE:
                prev = target[i];
                target[i] = parentSize[i] * spec.size.proportional[i] + spec.size.differential[i];
                break;
            case Size.ABSOLUTE:
                prev = target[i];
                target[i] = spec.size.absolute[i];
                break;
            case Size.RENDER:
                var candidate;
                for (j = 0; j < len ; j++) {
                    if (components[j].getRenderSize) {
                        candidate = components[j].getRenderSize()[i];
                        prev = target[i];
                        target[i] = target[i] < candidate || target[i] === 0 ? candidate : target[i];
                    }
                }
                break;
        }
        changed = changed || prev !== target[i];
    }
    return changed;
};

module.exports = Size;
<|endoftext|>


<commit_before>const Record = {};
const Trait = {};
const RecordType = {};
const Field = {};
const Module = {};
const TextType = 'TextType';
const NumberType = 'NumberType';
const BooleanType = 'BooleanType';

const RootModule = {
    id: 'Root',
    type: Module,
};

const Core = {
    id: 'Core',
    type: Module,
    parentModule: RootModule,
    Record: Record,
    Trait: Trait,
    RecordType: RecordType,
    Field: Field,
    Module: Module,
    RootModule: RootModule,
    TextType: TextType,
    NumberType: NumberType,
    BooleanType: BooleanType
};

module.exports = Core;
RootModule.Core = Core;

const TextField = require('./text-field');
const RecordField = require('./record-field');
const ListField = require('./list-field');
const NumberField = require('./number-field');
const BooleanField = require('./boolean-field');

const idField = TextField('id', {isRequired: true});
const parentModuleField = RecordField('module', Module);
const typeField = RecordField('type', RecordType, {isRequired: true});
const fieldsField = ListField('fields', Field, {isRequired: true});
const baseTypeField = ListField('baseType', Field, {isRequired: true});

Record.id = 'Record';
Record.type = RecordType;
Record.fields = [idField, typeField];
Record.baseType = Record;
Record.module = Core;

Module.id = 'Module';
Module.type = RecordType;
Module.fields = [idField, typeField, parentModuleField];
Module.baseType = Record;
Module.module = Core;

Trait.id = 'Trait';
Trait.type = RecordType;
Trait.fields = [idField, typeField, fieldsField];
Trait.baseType = Record;
Trait.module = Core;

RecordType.id = 'RecordType';
RecordType.type = RecordType;
RecordType.fields = [idField, typeField, fieldsField, baseTypeField];
RecordType.baseType = Trait;
RecordType.module = Core;

Field.id = 'Field';
Field.type = RecordType;
Field.fields = [];
Field.baseType = Record;
Field.module = Core;<commit_msg>Fixed parentModule fieldId<commit_after>const Record = {};
const Trait = {};
const RecordType = {};
const Field = {};
const Module = {};
const TextType = 'TextType';
const NumberType = 'NumberType';
const BooleanType = 'BooleanType';

const RootModule = {
    id: 'Root',
    type: Module,
};

const Core = {
    id: 'Core',
    type: Module,
    parentModule: RootModule,
    Record: Record,
    Trait: Trait,
    RecordType: RecordType,
    Field: Field,
    Module: Module,
    RootModule: RootModule,
    TextType: TextType,
    NumberType: NumberType,
    BooleanType: BooleanType
};

module.exports = Core;
RootModule.Core = Core;

const TextField = require('./text-field');
const RecordField = require('./record-field');
const ListField = require('./list-field');
const NumberField = require('./number-field');
const BooleanField = require('./boolean-field');

const idField = TextField('id', {isRequired: true});
const parentModuleField = RecordField('parentModule', Module);
const typeField = RecordField('type', RecordType, {isRequired: true});
const fieldsField = ListField('fields', Field, {isRequired: true});
const baseTypeField = ListField('baseType', Field, {isRequired: true});

Record.id = 'Record';
Record.type = RecordType;
Record.fields = [idField, typeField];
Record.baseType = Record;
Record.module = Core;

Module.id = 'Module';
Module.type = RecordType;
Module.fields = [idField, typeField, parentModuleField];
Module.baseType = Record;
Module.module = Core;

Trait.id = 'Trait';
Trait.type = RecordType;
Trait.fields = [idField, typeField, fieldsField];
Trait.baseType = Record;
Trait.module = Core;

RecordType.id = 'RecordType';
RecordType.type = RecordType;
RecordType.fields = [idField, typeField, fieldsField, baseTypeField];
RecordType.baseType = Trait;
RecordType.module = Core;

Field.id = 'Field';
Field.type = RecordType;
Field.fields = [];
Field.baseType = Record;
Field.module = Core;<|endoftext|>


<commit_before>/**
 * ANGLULAR APP
 **/

    /**
     * web_service_url for whole app
     */

    //var web_service_url = 'http://wwwdev.ebi.ac.uk/Tools/omicsdi/ws/';
    var web_service_url = 'http://localhost:9091/';
    var proteomics_list = "pride,peptideatlas,peptide_atlas,massive,PRIDE,PeptideAtlas,MassIVE, Massive";
    var metabolomics_list = "MetaboLights,metabolights,metabolights_dataset,MetabolomicsWorkbench, Metabolomics Workbench, metabolomics_workbench, metabolome_express";
    var transcriptomics_list = "ArrayExpress, arrayexpress-repository, ExpressionAtlas, expression-atlas, atlas-experiments, Expression Atlas Experiments, atlas-experiments";
    var genomics_list = "ega,EGA";
    var repositories = {
        "pride": "PRIDE",
        "PRIDE": "PRIDE",
        "peptideatlas": "PeptideAtlas",
        "peptide_atlas": "PeptideAtlas",
        "PeptideAtlas": "PeptideAtlas",
        "massive": "MassIVE",
        "MassIVE": "MassIVE",
        "Massive": "MassIVE",
        "metabolights": "MetaboLights",
        "metabolights_dataset": "MetaboLights",
        "MetaboLights": "MetaboLights",
        "metabolome_workbench": "MetabolomicsWorkbench",
        "metabolomics_workbench": "MetabolomicsWorkbench",
        "Metabolomics Workbench": "MetabolomicsWorkbench",
        "MetabolomicsWorkbench": "MetabolomicsWorkbench",
        "ega": "EGA",
        "EGA": "EGA",
        "GPMDB": "GPMDB",
        "gpmdb": "GPMDB",
        "GNPS":"GNPS",
        "metabolome_express": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress MetaPhenDB": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress":"MetabolomeExpress MetaPhenDB",
        "ArrayExpress":"ArrayExpress",
        "arrayexpress":"ArrayExpress",
        "arrayexpress-repository":"ArrayExpress",
        "expression-atlas":"ExpressionAtlas",
        "ExpressionAtlas":"ExpressionAtlas",
        "atlas-experiments":"ExpressionAtlas",
        "Expression Atlas Experiments": "ExpressionAtlas"

    };
    var database_urls = {
        "PRIDE": "http://www.ebi.ac.uk/pride/archive/",
        "MetaboLights": "http://www.ebi.ac.uk/metabolights/",
        "MetabolomicsWorkbench": "http://www.metabolomicsworkbench.org/",
        "PeptideAtlas": "http://www.peptideatlas.org/",
        "MassIVE": "https://massive.ucsd.edu/ProteoSAFe/datasets.jsp",
        "GPMDB":"http://gpmdb.thegpm.org/",
        "GNPS":"http://gnps.ucsd.edu/ProteoSAFe/static/gnps-splash.jsp",
        "EGA":"https://www.ebi.ac.uk/ega/",
        "MetabolomeExpress":"https://www.metabolome-express.org/",
        "ArrayExpress":"https://www.ebi.ac.uk/arrayexpress/",
        "ExpressionAtlas":"http://www.ebi.ac.uk/gxa/home"
    }

/**
 * Make it possible to include underscore as a dependency.
 */
var underscore = angular.module('underscore', []);
underscore.factory('_', function () {
    return window._;
});

var ddiApp = angular.module('ddiApp',['underscore','ngRoute','ngAnimate', 'autocomplete', 'ngCookies', 'ngProgress','ui.bootstrap', 'slick']);

// $.getJSON('http://api.metabolomexchange.org/providers', function(data) {
//     for (var i in data) {
//         console.log(data[i].name);
//     }
// });

/**
 * Turn on html5mode only in modern browsers because
 * in the older ones html5mode rewrites urls with Hangbangs
 * which break normal pages.
 * With html5mode off IE lt 10 will be able to navigate the site
 * but won't be able to open deep links to Angular pages
 * (for example, a link to a search result won't load in IE 9).
 */
// angular.module('ddiApp').config(['$locationProvider', function ($locationProvider) {
//       $locationProvider.html5Mode(false);
// }]);

/**
 * ANGLULAR CONFIG
 **/
ddiApp.config(function($routeProvider) {
    $routeProvider.
    when('/about', { templateUrl: 'app/views/about.html', controller: 'MainContentCtrl' }).
    when('/api', { templateUrl: 'app/views/api.html', controller: 'MainContentCtrl' }).
    when('/databases', { templateUrl: 'app/views/databases.html', controller: 'MainContentCtrl' }).
    when('/help', {  templateUrl: 'app/views/help.html', controller: 'MainContentCtrl' }).
    when('/', {  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
    when('/home', { templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
//    when('/search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/search?:searchstring', { templateUrl: 'app/views/browse.html', controller: 'MainContentCtrl' }).
//    when('/search/:search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/dataset/:domain/:acc', { templateUrl: 'app/views/dataset.html', controller: 'MainContentCtrl' }).
//    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'});
    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'}).
    otherwise({  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' });

});
/* ----------------------------*/

/**
 * ANGLULAR CONTROLLERS
 **/
//ddiApp.controller('MainContentCtrl', ['$scope', '$routeParams', '$location', '$anchorScroll',
//    function ($scope, $routeParams, $location, $anchorScroll){
//        if ($location.path() === '/about'){
//            $scope.show_top_search = 'true'
//        }else{
//            $scope.show_top_search = 'false'
//
//        }
//
//        // set focus to search
////        if (document.getElementById("search")) { document.getElementById("search").focus(); }
//    }
//]);

/*
ddiApp.factory('ddiAppApi', function($http) {

    var useCache = true;

    return {
        getDatasets: function() { return $http.get('http://api.metabolomexchange.org/datasets', { cache: useCache }); },
        getDataset: function(provider, accession) { return $http.get('http://api.metabolomexchange.org/provider/' + provider + '/' + accession, { cache: useCache }); },
        getProviders: function() { return $http.get('http://api.metabolomexchange.org/providers', { cache: useCache }); },
        getProvider: function(provider) { return $http.get('http://api.metabolomexchange.org/provider/' + provider, { cache: useCache }); },
        findDatasets: function(search) {
            var andMatch = search.replace(new RegExp(' ', 'g'), '&');
            var searchUrl = 'http://api.metabolomexchange.org/datasets/' + andMatch;
            return $http.get(searchUrl, { cache: useCache });
        }
    };
});
*/
/* ----------------------------*/
<commit_msg>some changes<commit_after>/**
 * ANGLULAR APP
 **/

    /**
     * web_service_url for whole app
     */

    //var web_service_url = 'http://wwwdev.ebi.ac.uk/Tools/omicsdi/ws/';
    var web_service_url = 'http://ves-hx-43.ebi.ac.uk:8090/Tools/omicsdi/ws/';
    var proteomics_list = "pride,peptideatlas,peptide_atlas,massive,PRIDE,PeptideAtlas,MassIVE, Massive";
    var metabolomics_list = "MetaboLights,metabolights,metabolights_dataset,MetabolomicsWorkbench, Metabolomics Workbench, metabolomics_workbench, metabolome_express";
    var transcriptomics_list = "ArrayExpress, arrayexpress-repository, ExpressionAtlas, expression-atlas, atlas-experiments, Expression Atlas Experiments, atlas-experiments";
    var genomics_list = "ega,EGA";
    var repositories = {
        "pride": "PRIDE",
        "PRIDE": "PRIDE",
        "peptideatlas": "PeptideAtlas",
        "peptide_atlas": "PeptideAtlas",
        "PeptideAtlas": "PeptideAtlas",
        "massive": "MassIVE",
        "MassIVE": "MassIVE",
        "Massive": "MassIVE",
        "metabolights": "MetaboLights",
        "metabolights_dataset": "MetaboLights",
        "MetaboLights": "MetaboLights",
        "metabolome_workbench": "MetabolomicsWorkbench",
        "metabolomics_workbench": "MetabolomicsWorkbench",
        "Metabolomics Workbench": "MetabolomicsWorkbench",
        "MetabolomicsWorkbench": "MetabolomicsWorkbench",
        "ega": "EGA",
        "EGA": "EGA",
        "GPMDB": "GPMDB",
        "gpmdb": "GPMDB",
        "GNPS":"GNPS",
        "metabolome_express": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress MetaPhenDB": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress":"MetabolomeExpress MetaPhenDB",
        "ArrayExpress":"ArrayExpress",
        "arrayexpress":"ArrayExpress",
        "arrayexpress-repository":"ArrayExpress",
        "expression-atlas":"ExpressionAtlas",
        "ExpressionAtlas":"ExpressionAtlas",
        "atlas-experiments":"ExpressionAtlas",
        "Expression Atlas Experiments": "ExpressionAtlas"

    };
    var database_urls = {
        "PRIDE": "http://www.ebi.ac.uk/pride/archive/",
        "MetaboLights": "http://www.ebi.ac.uk/metabolights/",
        "MetabolomicsWorkbench": "http://www.metabolomicsworkbench.org/",
        "PeptideAtlas": "http://www.peptideatlas.org/",
        "MassIVE": "https://massive.ucsd.edu/ProteoSAFe/datasets.jsp",
        "GPMDB":"http://gpmdb.thegpm.org/",
        "GNPS":"http://gnps.ucsd.edu/ProteoSAFe/static/gnps-splash.jsp",
        "EGA":"https://www.ebi.ac.uk/ega/",
        "MetabolomeExpress":"https://www.metabolome-express.org/",
        "ArrayExpress":"https://www.ebi.ac.uk/arrayexpress/",
        "ExpressionAtlas":"http://www.ebi.ac.uk/gxa/home"
    }

/**
 * Make it possible to include underscore as a dependency.
 */
var underscore = angular.module('underscore', []);
underscore.factory('_', function () {
    return window._;
});

var ddiApp = angular.module('ddiApp',['underscore','ngRoute','ngAnimate', 'autocomplete', 'ngCookies', 'ngProgress','ui.bootstrap', 'slick']);

// $.getJSON('http://api.metabolomexchange.org/providers', function(data) {
//     for (var i in data) {
//         console.log(data[i].name);
//     }
// });

/**
 * Turn on html5mode only in modern browsers because
 * in the older ones html5mode rewrites urls with Hangbangs
 * which break normal pages.
 * With html5mode off IE lt 10 will be able to navigate the site
 * but won't be able to open deep links to Angular pages
 * (for example, a link to a search result won't load in IE 9).
 */
// angular.module('ddiApp').config(['$locationProvider', function ($locationProvider) {
//       $locationProvider.html5Mode(false);
// }]);

/**
 * ANGLULAR CONFIG
 **/
ddiApp.config(function($routeProvider) {
    $routeProvider.
    when('/about', { templateUrl: 'app/views/about.html', controller: 'MainContentCtrl' }).
    when('/api', { templateUrl: 'app/views/api.html', controller: 'MainContentCtrl' }).
    when('/databases', { templateUrl: 'app/views/databases.html', controller: 'MainContentCtrl' }).
    when('/help', {  templateUrl: 'app/views/help.html', controller: 'MainContentCtrl' }).
    when('/', {  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
    when('/home', { templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
//    when('/search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/search?:searchstring', { templateUrl: 'app/views/browse.html', controller: 'MainContentCtrl' }).
//    when('/search/:search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/dataset/:domain/:acc', { templateUrl: 'app/views/dataset.html', controller: 'MainContentCtrl' }).
//    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'});
    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'}).
    otherwise({  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' });

});
/* ----------------------------*/

/**
 * ANGLULAR CONTROLLERS
 **/
//ddiApp.controller('MainContentCtrl', ['$scope', '$routeParams', '$location', '$anchorScroll',
//    function ($scope, $routeParams, $location, $anchorScroll){
//        if ($location.path() === '/about'){
//            $scope.show_top_search = 'true'
//        }else{
//            $scope.show_top_search = 'false'
//
//        }
//
//        // set focus to search
////        if (document.getElementById("search")) { document.getElementById("search").focus(); }
//    }
//]);

/*
ddiApp.factory('ddiAppApi', function($http) {

    var useCache = true;

    return {
        getDatasets: function() { return $http.get('http://api.metabolomexchange.org/datasets', { cache: useCache }); },
        getDataset: function(provider, accession) { return $http.get('http://api.metabolomexchange.org/provider/' + provider + '/' + accession, { cache: useCache }); },
        getProviders: function() { return $http.get('http://api.metabolomexchange.org/providers', { cache: useCache }); },
        getProvider: function(provider) { return $http.get('http://api.metabolomexchange.org/provider/' + provider, { cache: useCache }); },
        findDatasets: function(search) {
            var andMatch = search.replace(new RegExp(' ', 'g'), '&');
            var searchUrl = 'http://api.metabolomexchange.org/datasets/' + andMatch;
            return $http.get(searchUrl, { cache: useCache });
        }
    };
});
*/
/* ----------------------------*/
<|endoftext|>


<commit_before>
'use strict';

// Modules
var path            = require('path');
var logger          = require('morgan');
var body_parser     = require('body-parser');
var method_override = require('method-override');

var defaults = {
  port : 3000
};

// Exports
module.exports = {

  global : function (app, environment) {

    // Interpret Environment
    if (!environment) { environment = {}; }
    if (typeof environment === 'string') { environment = { NODE_ENV : environment }; }
    if (typeof environment !== 'object') { environment = {}; }

    // Assume Production
    if (!environment.NODE_ENV) { environment.NODE_ENV = 'PRODUCTION'; }

    // Set Port
    var port = defaults.port;
    if (environment.PORT) {
      var port_parsed = parseInt(environment.PORT, 10);
      if (!isNaN(port_parsed)) {
        port = port_parsed;
      }
    }
    app.set('port', port);

    // Set View Options
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    // Log Requests
    if (environment.NODE_ENV === 'DEVELOPMENT') {
      console.log('Starting Logger...');
      // Long version of { format : 'dev' }
      app.use(logger({ format : ':date :remote-addr :method :status :url' }));
    }

    // Accept Method Overrides
    // in order to be compatible
    // with limited clients/browsers
    app.use(method_override('_method'));

    // NOTE: This only parses JSON bodies (application/json)
    // If you need urlencoded (x-www-form-urlencoded)
    // or multipart (multipart/form-data), you'll need to add them
    // See README here: https://github.com/expressjs/body-parser

    // Parse POST/PUT Body
    app.use(body_parser.json());

    return environment.NODE_ENV;

  }

};
<commit_msg>Refactor: Updating deprecated use of morgan module<commit_after>
'use strict';

// Modules
var path            = require('path');
var logger          = require('morgan');
var body_parser     = require('body-parser');
var method_override = require('method-override');

var defaults = {
  port : 3000
};

// Exports
module.exports = {

  global : function (app, environment) {

    // Interpret Environment
    if (!environment) { environment = {}; }
    if (typeof environment === 'string') { environment = { NODE_ENV : environment }; }
    if (typeof environment !== 'object') { environment = {}; }

    // Assume Production
    if (!environment.NODE_ENV) { environment.NODE_ENV = 'PRODUCTION'; }

    // Set Port
    var port = defaults.port;
    if (environment.PORT) {
      var port_parsed = parseInt(environment.PORT, 10);
      if (!isNaN(port_parsed)) {
        port = port_parsed;
      }
    }
    app.set('port', port);

    // Set View Options
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    // Log Requests
    if (environment.NODE_ENV === 'DEVELOPMENT') {
      console.log('Starting Logger...');
      // Long version of 'dev'
      app.use(logger(':date :remote-addr :method :status :url'));
    }

    // Accept Method Overrides
    // in order to be compatible
    // with limited clients/browsers
    app.use(method_override('_method'));

    // NOTE: This only parses JSON bodies (application/json)
    // If you need urlencoded (x-www-form-urlencoded)
    // or multipart (multipart/form-data), you'll need to add them
    // See README here: https://github.com/expressjs/body-parser

    // Parse POST/PUT Body
    app.use(body_parser.json());

    return environment.NODE_ENV;

  }

};
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const electron = require('electron');
const {app, shell} = require('electron');
const electronLocalshortcut = require('electron-localshortcut');
const ipc = require('electron').ipcMain;
const Configstore = require('configstore');
const JsonDB = require('node-json-db');
const tray = require('./tray');
const link = require ('./link_helper');
const {linkIsInternal} = link;

const db = new JsonDB("domain", true, true);
const data = db.getData("/");

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
require('electron-context-menu')();

const conf = new Configstore("Zulip-Desktop");

// prevent window being garbage collected
let mainWindow;
let targetLink;

// Load this url in main window
const targetUrl = 'file://' + path.join(__dirname, '../renderer', 'index.html');

function checkWindowURL() {
	if (data["domain"] !== undefined) {
		return data["domain"]
	}
	return targetLink
}

const APP_ICON = path.join(__dirname, '../resources', 'Icon');

const iconPath = () => {
  return process.platform === 'win32'
    ? APP_ICON + '.ico'
    : APP_ICON + '.png'
};

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	mainWindow = null;
}

function createMainWindow() {
	const win = new electron.BrowserWindow({
		// This settings needs to be saved in config
		title: 'Zulip',
		width: conf.get('width') || 1000,
		height: conf.get('height') || 600,
		icon: iconPath(),
		minWidth: 600,
		minHeight: 400
	});

	win.loadURL(targetUrl);
	win.on('closed', onClosed);
	win.setTitle('Zulip');

	// Let's save browser window position
	if (conf.get('x') || conf.get('y')) {
	  win.setPosition(conf.get('x'), conf.get('y'));
	}

	if (conf.get('maximize')) {
	  win.maximize();
	}

	// Handle sizing events so we can persist them.
	win.on('maximize', function (event) {
	  conf.set('maximize', true);
	});

	win.on('unmaximize', function (event) {
	  conf.set('maximize', false);
	});

	win.on('resize', function (event) {
	  var size = this.getSize();
	  conf.set({
	    width: size[0],
	    height: size[1]
	  });
	});

	// on osx it's 'moved'
	win.on('move', function (event) {
	  var pos = this.getPosition();
	  conf.set({
	    x: pos[0],
	    y: pos[1]
	  });
	});

	// stop page to update it's title
	win.on('page-title-updated', (e) => {
	e.preventDefault();
	});

	// TODO - use global shortcut instead
	electronLocalshortcut.register(win, 'CommandOrControl+R', () => {
	   win.reload();
	 });

	return win;
}

// TODO
app.commandLine.appendSwitch('ignore-certificate-errors', 'true');

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();
	tray.create(mainWindow);

	const page = mainWindow.webContents;

	// let's find out back keycode
	// const back = () => {
	// 	if (process.platform !== 'darwin') {
	// 		return 'Backspace'
	// 	}
	// 	return 'Delete'
	// };

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+[', () => {
		if (page.canGoBack()) {
			page.goBack();
		}
	 });

    page.on('new-window', (event, url) => {
        if (mainWindow.useDefaultWindowBehaviour) {
            mainWindow.useDefaultWindowBehaviour = false;
            return;
        }
        if (linkIsInternal(checkWindowURL(), url)) {
        	event.preventDefault();
			return mainWindow.loadURL(url);
        }
        event.preventDefault();
        electron.shell.openExternal(url);
    });
});

ipc.on('new-domain', function (e, domain) {
	mainWindow.loadURL(domain);
	targetLink = domain;
});
<commit_msg>Use cmdOrctrl+Left to go back<commit_after>'use strict';
const path = require('path');
const electron = require('electron');
const {app, shell} = require('electron');
const electronLocalshortcut = require('electron-localshortcut');
const ipc = require('electron').ipcMain;
const Configstore = require('configstore');
const JsonDB = require('node-json-db');
const tray = require('./tray');
const link = require ('./link_helper');
const {linkIsInternal} = link;

const db = new JsonDB("domain", true, true);
const data = db.getData("/");

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
require('electron-context-menu')();

const conf = new Configstore("Zulip-Desktop");

// prevent window being garbage collected
let mainWindow;
let targetLink;

// Load this url in main window
const targetUrl = 'file://' + path.join(__dirname, '../renderer', 'index.html');

function checkWindowURL() {
	if (data["domain"] !== undefined) {
		return data["domain"]
	}
	return targetLink
}

const APP_ICON = path.join(__dirname, '../resources', 'Icon');

const iconPath = () => {
  return process.platform === 'win32'
    ? APP_ICON + '.ico'
    : APP_ICON + '.png'
};

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	mainWindow = null;
}

function createMainWindow() {
	const win = new electron.BrowserWindow({
		// This settings needs to be saved in config
		title: 'Zulip',
		width: conf.get('width') || 1000,
		height: conf.get('height') || 600,
		icon: iconPath(),
		minWidth: 600,
		minHeight: 400
	});

	win.loadURL(targetUrl);
	win.on('closed', onClosed);
	win.setTitle('Zulip');

	// Let's save browser window position
	if (conf.get('x') || conf.get('y')) {
	  win.setPosition(conf.get('x'), conf.get('y'));
	}

	if (conf.get('maximize')) {
	  win.maximize();
	}

	// Handle sizing events so we can persist them.
	win.on('maximize', function (event) {
	  conf.set('maximize', true);
	});

	win.on('unmaximize', function (event) {
	  conf.set('maximize', false);
	});

	win.on('resize', function (event) {
	  var size = this.getSize();
	  conf.set({
	    width: size[0],
	    height: size[1]
	  });
	});

	// on osx it's 'moved'
	win.on('move', function (event) {
	  var pos = this.getPosition();
	  conf.set({
	    x: pos[0],
	    y: pos[1]
	  });
	});

	// stop page to update it's title
	win.on('page-title-updated', (e) => {
	e.preventDefault();
	});

	// TODO - use global shortcut instead
	electronLocalshortcut.register(win, 'CommandOrControl+R', () => {
	   win.reload();
	 });

	return win;
}

// TODO
app.commandLine.appendSwitch('ignore-certificate-errors', 'true');

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();
	tray.create(mainWindow);

	const page = mainWindow.webContents;

	// let's find out back keycode
	// const back = () => {
	// 	if (process.platform !== 'darwin') {
	// 		return 'Backspace'
	// 	}
	// 	return 'Delete'
	// };

	electronLocalshortcut.register(mainWindow, 'CommandOrControl+Left', () => {
		if (page.canGoBack()) {
			page.goBack();
		}
	 });

    page.on('new-window', (event, url) => {
        if (mainWindow.useDefaultWindowBehaviour) {
            mainWindow.useDefaultWindowBehaviour = false;
            return;
        }
        if (linkIsInternal(checkWindowURL(), url)) {
        	event.preventDefault();
			return mainWindow.loadURL(url);
        }
        event.preventDefault();
        electron.shell.openExternal(url);
    });
});

ipc.on('new-domain', function (e, domain) {
	mainWindow.loadURL(domain);
	targetLink = domain;
});
<|endoftext|>


<commit_before>/**
 * @desc	Creates a grid based on correlation values from a json file and highlights the top X amount from results.
 * @params	jsonLocation: location where the json file that defines the correlation values for the grid
 * 			results: the array that contains the nodes that need to be highlighted the grid
 * 			container: the HTML element that will contain the grid
 *			options: configurable options for the grid, possible options include:
 *				{
 *					canvasSize: 225,	// size of canvas in pixels
 *					highlightCount: 10,	// top x to highlight from results
 *					highlightValue: function(d) { return d[0]; },	// function used to select items from the results array to highlight
 					highlightFunction: function(c) {},	// function performed on highlighted circles where c is the DOM path to them
 					highlightColor: #FFFFFF,	// Color of highlight circles
 					clusterFunction: function(z) {},	// function performed on the z-score of the cluster function
 					maxColor: #FF6666, 	// Grid ranges from black to this color using an exponential scale
 					cache: true	// Controls whether grids are cached
 *				}
 * @author	Edward Y. Chen
 * @since	9/17/2012
 */
d3.grid = {
	createGrid: function(jsonLocation, results, container, options) {
		// Don't create grid if nowhere to put it
		if (d3.select(container).empty())
			return;

		// Grid actually goes in svg-container
		if (d3.select(container + ' div.svg-container').empty())
			d3.select(container).append('div').classed('svg-container', true);
		container += ' div.svg-container';

		// Grid attributes
		var gridAttr = {
			canvasSize: 225,
			highlightCount: 10,
			highlightValue: function(d) { return d[0]; },
			highlightColor: '#FFFFFF',
			maxColor: '#FF6666',
			color: d3.scale.pow().exponent(5).interpolate(d3.interpolateRgb),
			cache: true
		};

		// Copy attributes from options to gridAttr
		for (var key in options)
			gridAttr[key] = options[key];

		d3.json(jsonLocation + (gridAttr.cache ? '' : '?_=' + new Date().getTime()), function(json) {	// Control caching
			gridAttr.width = Math.sqrt(json.length),
			gridAttr.pixels = 225 / gridAttr.width;
			gridAttr.color.domain([0, d3.max(json.map(function(d) { return d[1]; }))])
				.range(['#000000', gridAttr.maxColor]);

			d3.grid.drawCanvas(json, container, gridAttr);
			d3.grid.fill(results.filter(function(d, i) { return i < gridAttr.highlightCount; }), container, gridAttr);
			if (typeof gridAttr.clusterFunction != 'undefined')
				d3.grid.calcClustering(container, gridAttr);
		});
	},
	drawCanvas: function(nodes, container, gridAttr) {
		var canvas = d3.select(container)
					.append('svg:svg')
					.attr('width', gridAttr.canvasSize)
					.attr('height', gridAttr.canvasSize);

		canvas.selectAll('rect')
			.data(nodes)
			.enter()
			.append('svg:rect')
			.attr('x', function(d, i) { return i % gridAttr.width * gridAttr.pixels; })
			.attr('y', function(d, i) { return Math.floor(i / gridAttr.width) * gridAttr.pixels; })
			.attr('width', gridAttr.pixels)
			.attr('height', gridAttr.pixels)
			.attr('fill', function(d) { return gridAttr.color(d[1]); })
			.append('title')
			.text(function(d) { return d[0]; });

		canvas.selectAll('circle')
			.data(nodes)
			.enter()
			.append('svg:circle')
			.attr('cx', function(d, i) { return i % gridAttr.width * gridAttr.pixels + gridAttr.pixels/2; })
			.attr('cy', function(d, i) { return Math.floor(i / gridAttr.width) * gridAttr.pixels + gridAttr.pixels/2; })
			.attr('fill', gridAttr.highlightColor)
			.attr('fill-opacity', 0)
			.attr('r', Math.floor(gridAttr.pixels/3))
			.attr('label', function(d) { return d[0]; })
			.append('title')
			.text(function(d) { return d[0]; });
	},
	fill: function(elementList, container, gridAttr) {
		for (e in elementList) {
			d3.selectAll(container + ' circle[label="' + gridAttr.highlightValue(elementList[e]) + '"]')
				.datum(function() { return elementList[e]; })
				.attr('fill-opacity', 1)
				.classed('highlight', true);
		}

		if (typeof gridAttr.highlightFunction != 'undefined')
			gridAttr.highlightFunction(container + ' circle.highlight');
	},
	calcClustering: function(container, gridAttr) {
		var mean = 0.6291 * Math.pow(gridAttr.highlightCount / Math.pow(gridAttr.width, 2), -0.503301);
		var std = 0.328498 * Math.pow(gridAttr.highlightCount, -1.00728) * Math.pow(gridAttr.width, 1.00939);

		var getCoord = function(value) { return (value - gridAttr.pixels/2) / gridAttr.pixels; };
		var circles = d3.selectAll(container + ' circle.highlight')[0];
		var avg = d3.mean(circles, function(a) {
			return d3.min(circles, function(b) {	// Find nearest neighbor
				if (a != b) {
					return d3.grid.manhattanDistance(getCoord(a.getAttribute('cx')),
						getCoord(a.getAttribute('cy')),
						getCoord(b.getAttribute('cx')),
						getCoord(b.getAttribute('cy')),
						gridAttr);
				}
			});
		});

		gridAttr.clusterFunction((avg - mean) / std);	// Z-score
	},
	manhattanDistance: function(x1, y1, x2, y2, gridAttr) {
		var dx = Math.abs(x1 - x2);
		var dy = Math.abs(y1 - y2);

		// Correct x and y distances for torus
		return Math.min(dx, gridAttr.width - dx) + Math.min(dy, gridAttr.width - dy);
	}
}<commit_msg>Rename options to userOptions and gridAttr to options<commit_after>/**
 * @desc	Creates a grid based on correlation values from a json file and highlights the top X amount from results.
 * @params	jsonLocation: location where the json file that defines the correlation values for the grid
 * 			results: the array that contains the nodes that need to be highlighted the grid
 * 			container: the HTML element that will contain the grid
 *			options: configurable options for the grid, possible options include:
 *				{
 *					canvasSize: 225,	// size of canvas in pixels
 *					highlightCount: 10,	// top x to highlight from results
 *					highlightValue: function(d) { return d[0]; },	// function used to select items from the results array to highlight
 					highlightFunction: function(c) {},	// function performed on highlighted circles where c is the DOM path to them
 					highlightColor: #FFFFFF,	// Color of highlight circles
 					clusterFunction: function(z) {},	// function performed on the z-score of the cluster function
 					maxColor: #FF6666, 	// Grid ranges from black to this color using an exponential scale
 					cache: true	// Controls whether grids are cached
 *				}
 * @author	Edward Y. Chen
 * @since	9/17/2012
 */
d3.grid = {
	createGrid: function(jsonLocation, results, container, userOptions) {
		// Don't create grid if nowhere to put it
		if (d3.select(container).empty())
			return;

		// Grid actually goes in svg-container
		if (d3.select(container + ' div.svg-container').empty())
			d3.select(container).append('div').classed('svg-container', true);
		container += ' div.svg-container';

		// Grid attributes
		var options = {
			canvasSize: 225,
			highlightCount: 10,
			highlightValue: function(d) { return d[0]; },
			highlightColor: '#FFFFFF',
			maxColor: '#FF6666',
			color: d3.scale.pow().exponent(5).interpolate(d3.interpolateRgb),
			cache: true
		};

		// Copy attributes from userOptions to options
		for (var key in userOptions)
			options[key] = userOptions[key];

		d3.json(jsonLocation + (options.cache ? '' : '?_=' + new Date().getTime()), function(json) {	// Control caching
			options.width = Math.sqrt(json.length),
			options.pixels = 225 / options.width;
			options.color.domain([0, d3.max(json.map(function(d) { return d[1]; }))])
				.range(['#000000', options.maxColor]);

			d3.grid.drawCanvas(json, container, options);
			d3.grid.fill(results.filter(function(d, i) { return i < options.highlightCount; }), container, options);
			if (typeof options.clusterFunction != 'undefined')
				d3.grid.calcClustering(container, options);
		});
	},
	drawCanvas: function(nodes, container, options) {
		var canvas = d3.select(container)
					.append('svg:svg')
					.attr('width', options.canvasSize)
					.attr('height', options.canvasSize);

		canvas.selectAll('rect')
			.data(nodes)
			.enter()
			.append('svg:rect')
			.attr('x', function(d, i) { return i % options.width * options.pixels; })
			.attr('y', function(d, i) { return Math.floor(i / options.width) * options.pixels; })
			.attr('width', options.pixels)
			.attr('height', options.pixels)
			.attr('fill', function(d) { return options.color(d[1]); })
			.append('title')
			.text(function(d) { return d[0]; });

		canvas.selectAll('circle')
			.data(nodes)
			.enter()
			.append('svg:circle')
			.attr('cx', function(d, i) { return i % options.width * options.pixels + options.pixels/2; })
			.attr('cy', function(d, i) { return Math.floor(i / options.width) * options.pixels + options.pixels/2; })
			.attr('fill', options.highlightColor)
			.attr('fill-opacity', 0)
			.attr('r', Math.floor(options.pixels/3))
			.attr('label', function(d) { return d[0]; })
			.append('title')
			.text(function(d) { return d[0]; });
	},
	fill: function(elementList, container, options) {
		for (e in elementList) {
			d3.selectAll(container + ' circle[label="' + options.highlightValue(elementList[e]) + '"]')
				.datum(function() { return elementList[e]; })
				.attr('fill-opacity', 1)
				.classed('highlight', true);
		}

		if (typeof options.highlightFunction != 'undefined')
			options.highlightFunction(container + ' circle.highlight');
	},
	calcClustering: function(container, options) {
		var mean = 0.6291 * Math.pow(options.highlightCount / Math.pow(options.width, 2), -0.503301);
		var std = 0.328498 * Math.pow(options.highlightCount, -1.00728) * Math.pow(options.width, 1.00939);

		var getCoord = function(value) { return (value - options.pixels/2) / options.pixels; };
		var circles = d3.selectAll(container + ' circle.highlight')[0];
		var avg = d3.mean(circles, function(a) {
			return d3.min(circles, function(b) {	// Find nearest neighbor
				if (a != b) {
					return d3.grid.manhattanDistance(getCoord(a.getAttribute('cx')),
						getCoord(a.getAttribute('cy')),
						getCoord(b.getAttribute('cx')),
						getCoord(b.getAttribute('cy')),
						options);
				}
			});
		});

		options.clusterFunction((avg - mean) / std);	// Z-score
	},
	manhattanDistance: function(x1, y1, x2, y2, options) {
		var dx = Math.abs(x1 - x2);
		var dy = Math.abs(y1 - y2);

		// Correct x and y distances for torus
		return Math.min(dx, options.width - dx) + Math.min(dy, options.width - dy);
	}
}<|endoftext|>


<commit_before>
/*

  cli.js

*/

var program = require("commander"),
    chalk = require("chalk"),
    fs = require("fs"),
    path = require("path");

module.exports = function() {

  program
    .version("0.7.0")

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      listPipelines()
      listFolders("data");
      listFolders("scripts");
      listFolders("statics");
      listFolders("styles");
      listFolders("views");
    });

  program
    .command("data")
    .action(function() { listFolders("data"); });

  program
    .command("pipelines")
    .action(listPipelines);

  program
    .command("scripts")
    .action(function() { listFolders("scripts"); });

  program
    .command("statics")
    .action(function() { listFolders("statics"); });

  program
    .command("styles")
    .action(function() { listFolders("styles"); });

  program
    .command("views")
    .action(function() { listFolders("views"); });

  program
    .command("*")
    .action(function() { console.log("EMPTY!"); });

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "start";
  program.parse(process.argv);

};

function pad(str, len) {
  while (str.length < len) str += " ";
  return str;
}

function listCommand(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = pad(key, 35);

  // Replace <commands> with yellow
  key = key.replace(/\<[^\>]+\>/g, function(x) { return chalk.yellow(x) });;
  console.log("    " + key + "  " + command.description);
}

function showGrid(grid, options) {

  options = options || {};

  grid.sort(function(a, b) {
    return (a[0] < b[0]) ? -1 : (a[0] > b[0]) ? 1 : 0;
  });

  console.log("");

  if (options.title) {
    console.log(" " + chalk.cyan(options.title));
    console.log("");
  }

  if (options.headers)
    console.log(chalk.yellow("    " + pad(options.headers[0], options.len) + options.headers[1]));

  for (var i = 0, n = grid.length; i < n; i++)
    console.log("    " + pad(grid[i][0], options.len) + grid[i][1]);

  console.log("");

};

function readFile(p) {
  return require("fs").readFileSync(p, "utf8");
}

function showHelp() {

  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("sneakers") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  var help = JSON.parse(fs.readFileSync(path.join(__dirname, "./help/main.json"), "utf8"));

  help.forEach(listCommand);

}

function start() {

  console.log(chalk.green.bold("\nStarting server...\n"));
  require("../server/")();

}

function listFolders(type) {

  // Set up globals
  require("../server/globals")();

  var folders = global.config[type].slice(0),
      columns = [];

  folders.forEach(function(folder) {
    columns.push([folder.path, folder.url]);
  });

  type = type[0].toUpperCase() + type.slice(1) + ":";
  showGrid(columns, {
    title   : type,
    len     : 20,
    headers : ["Directory", "Route"]
   });

}

function listPipelines() {

  // Set up globals
  require("../server/globals")();

  var pipelines = Object.assign({}, global.config.engines),
      columns = [];

  for (var key in pipelines)
    columns.push(["*." + key, pipelines[key]])

  showGrid(columns, {
    title   : "Pipelines:",
    len     : 20,
    headers : ["Extension", "Pipeline"]
  });

};
<commit_msg>cli: adds #readHelpFile helper<commit_after>
/*

  cli.js

*/

var program = require("commander"),
    chalk = require("chalk"),
    fs = require("fs"),
    path = require("path");

module.exports = function() {

  program
    .version("0.7.0")

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      listPipelines()
      listFolders("data");
      listFolders("scripts");
      listFolders("statics");
      listFolders("styles");
      listFolders("views");
    });

  program
    .command("data")
    .action(function() { listFolders("data"); });

  program
    .command("pipelines")
    .action(listPipelines);

  program
    .command("scripts")
    .action(function() { listFolders("scripts"); });

  program
    .command("statics")
    .action(function() { listFolders("statics"); });

  program
    .command("styles")
    .action(function() { listFolders("styles"); });

  program
    .command("views")
    .action(function() { listFolders("views"); });

  program
    .command("*")
    .action(function() { console.log("EMPTY!"); });

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "start";
  program.parse(process.argv);

};

function pad(str, len) {
  while (str.length < len) str += " ";
  return str;
}

function listCommand(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = pad(key, 35);

  // Replace <commands> with yellow
  key = key.replace(/\<[^\>]+\>/g, function(x) { return chalk.yellow(x) });;
  console.log("    " + key + "  " + command.description);
}

function showGrid(grid, options) {

  options = options || {};

  grid.sort(function(a, b) {
    return (a[0] < b[0]) ? -1 : (a[0] > b[0]) ? 1 : 0;
  });

  console.log("");

  if (options.title) {
    console.log(" " + chalk.cyan(options.title));
    console.log("");
  }

  if (options.headers)
    console.log(chalk.yellow("    " + pad(options.headers[0], options.len) + options.headers[1]));

  for (var i = 0, n = grid.length; i < n; i++)
    console.log("    " + pad(grid[i][0], options.len) + grid[i][1]);

  console.log("");

};

function readFile(p) {
  return require("fs").readFileSync(p, "utf8");
}

function readHelpFile(p) {
  return JSON.parse(readFile(require("path").join(__dirname, "help", "main.json"), "utf8"));
}

function showHelp() {

  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("sneakers") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  var help = JSON.parse(fs.readFileSync(path.join(__dirname, "./help/main.json"), "utf8"));

  help.forEach(listCommand);

}

function start() {

  console.log(chalk.green.bold("\nStarting server...\n"));
  require("../server/")();

}

function listFolders(type) {

  // Set up globals
  require("../server/globals")();

  var folders = global.config[type].slice(0),
      columns = [];

  folders.forEach(function(folder) {
    columns.push([folder.path, folder.url]);
  });

  type = type[0].toUpperCase() + type.slice(1) + ":";
  showGrid(columns, {
    title   : type,
    len     : 20,
    headers : ["Directory", "Route"]
   });

}

function listPipelines() {

  // Set up globals
  require("../server/globals")();

  var pipelines = Object.assign({}, global.config.engines),
      columns = [];

  for (var key in pipelines)
    columns.push(["*." + key, pipelines[key]])

  showGrid(columns, {
    title   : "Pipelines:",
    len     : 20,
    headers : ["Extension", "Pipeline"]
  });

};
<|endoftext|>


<commit_before>var
	mkdirp = require('mkdirp')
	, path = require('path')
	, fs = require('fs')
;

/**
 * TODO: configuration profiles
 */

module.exports = function config(ninja, app) {

	if((!ninja) || !ninja.opts) {

		return false;
	}
	// default arduino device path
	if(!ninja.opts.client || ninja.opts.client == 'beagle') {

		ninja.opts.device = '/dev/ttyO1';
	}

	loadPlatform(ninja, app); // embedded arduino

	var
		modPath = path.resolve(process.cwd(), 'ninja_modules')
		, read = function read() {

			fs.readdir(modPath, load);
		}
		, load = function load(err, mods) {

			if(err) {

				return app.log.error("config: Error loading modules (%s)", err);
			}

			mods.map(function(mod) {

				ninja.loadModule(

					mod
					, config(mod)
					, app
				);
			});
		}
		, config = function config(mod) {

			/**
			 * get config file for module
			 * either config/<mod>/config.json
			 * or (default) config parameter from its package.json
			 */
			 return { };
		}
	;

	mkdirp(modPath, read);

	ninja.emit('loaded'); // done loading modules
	ninja.connect();

	return ninja;
};

/**
 * Load ninja cape & arduino modules if present
 * at the moment these modules rely on a proper load order
 * TODO: fix this so they can load asynchronously.
 */
function loadPlatform(ninja, app) {

	if(ninja.opts.device) {

		// arduino controller
		ninja.loadModule(

			'platform'
			, { id : 'arduino' }
			, app
		);

		// serial device
		ninja.loadModule(

			'serial'
			, { device : ninja.opts.device, id : 'arduino' }
			, app
		);
	}
};<commit_msg>Added loadModule filter for 'embedded' modules (serial & platform)<commit_after>var
	mkdirp = require('mkdirp')
	, path = require('path')
	, fs = require('fs')
;

/**
 * TODO: configuration profiles
 */

module.exports = function config(ninja, app) {

	if((!ninja) || !ninja.opts) {

		return false;
	}
	// default arduino device path
	if(!ninja.opts.client || ninja.opts.client == 'beagle') {

		ninja.opts.device = '/dev/ttyO1';
	}

	loadPlatform(ninja, app); // embedded arduino

	var
		modPath = path.resolve(process.cwd(), 'ninja_modules')
		, read = function read() {

			fs.readdir(modPath, load);
		}
		, load = function load(err, mods) {

			if(err) {

				return app.log.error("config: Error loading modules (%s)", err);
			}

			mods
				.filter(embedded)
				.map(function(mod) {

					console.log(">> %s", mod)
					ninja.loadModule(

						mod
						, config(mod)
						, app
					);
				})
			;
		}
		, config = function config(mod) {

			/**
			 * get config file for module
			 * either config/<mod>/config.json
			 * or (default) config parameter from its package.json
			 */

			 return { };
		}
		, embedded = function embedded(mod) {

			return mod == "serial" ? false : mod == "platform" ? false : true
		}
	;

	mkdirp(modPath, read);

	ninja.emit('loaded'); // done loading modules
	ninja.connect();

	return ninja;
};

/**
 * Load ninja cape & arduino modules if present
 * at the moment these modules rely on a proper load order
 * TODO: fix this so they can load asynchronously.
 */
function loadPlatform(ninja, app) {

	if(ninja.opts.device) {

		// arduino controller
		ninja.loadModule(

			'platform'
			, { id : 'arduino' }
			, app
		);

		// serial device
		ninja.loadModule(

			'serial'
			, { device : ninja.opts.device, id : 'arduino' }
			, app
		);
	}
};<|endoftext|>