<commit_before>/**
 * UCSC Xena Client
 * http://xena.ucsc.edu
 *
 * Navigation component.
 *
 * This is a light wrapper component around React Toolbox's AppBar component.
 */

'use strict';

// Core dependencies, components
var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('./underscore_ext');
import AppBar from 'react-toolbox/lib/app_bar';
import Navigation from 'react-toolbox/lib/navigation';
import {ThemeProvider} from 'react-css-themr';
import Link from 'react-toolbox/lib/link';
var navTheme = require('./navTheme');
var BookmarkMenu = require('./views/BookmarkMenu');
var {servers: {localHub}} = require('./defaultServers');

// Styles
var compStyles = require('./nav.module.css');

// Images
var logoSantaCruzImg = require('../images/logoSantaCruz.png');
var logoSantaCruz2xImg = require('../images/logoSantaCruz@2x.png');
var logoSantaCruz3xImg = require('../images/logoSantaCruz@3x.png');

// Locals
var links = [
	{label: 'Data Sets', nav: 'datapages'},
	{label: 'Visualization', nav: 'heatmap'},
	{label: 'Transcripts', nav: 'transcripts'},
	{label: 'Data Hubs', nav: 'hub'},
	// {href: 'https://genome-cancer.ucsc.edu/download/public/get-xena/index.html', label: 'Local Xena'},
	{label: 'View My Data', nav: 'datapages', params: {addHub: localHub, host: localHub}},
	{href: 'http://xena.ucsc.edu/xena-python-api/', label: 'Python'},
];

var helpLink = {
	href: 'https://ucsc-xena.gitbook.io/project/',
	label: 'Help',
	target: '_blank'
};

var active = (l, activeLink) => l.nav === activeLink;

class XenaNav extends React.Component {
	render() {
		let {isPublic, activeLink, getState, onImport} = this.props;
		let routes = _.map(links, l => {
			var {nav, params, ...others} = l,
			onClick = nav ? () => this.props.onNavigate(nav, params) : undefined;
			return {...others, onClick, active: active(l, activeLink)};
		});
		let logoSrcSet = `${logoSantaCruz2xImg} 2x, ${logoSantaCruz3xImg} 3x`;
		return (
			<AppBar className={compStyles.NavAppBar}>

				<Navigation type="horizontal" routes={routes}>
					{getState ? <BookmarkMenu isPublic={isPublic} getState={getState} onImport={onImport}/> : null}
					<Link {...helpLink} />
				</Navigation>
			</AppBar>
		);
	}
}

class ThemedNav extends React.Component {
	render() {
		return (
			<ThemeProvider theme={navTheme}>
				<XenaNav {...this.props}/>
			</ThemeProvider>);
	}
}

var nav = document.getElementById('navMenuMain');

module.exports = props => ReactDOM.render(<ThemedNav {...props} />, nav);
<commit_msg>added a nav link for geneSets<commit_after>/**
 * UCSC Xena Client
 * http://xena.ucsc.edu
 *
 * Navigation component.
 *
 * This is a light wrapper component around React Toolbox's AppBar component.
 */

'use strict';

// Core dependencies, components
var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('./underscore_ext');
import AppBar from 'react-toolbox/lib/app_bar';
import Navigation from 'react-toolbox/lib/navigation';
import {ThemeProvider} from 'react-css-themr';
import Link from 'react-toolbox/lib/link';
var navTheme = require('./navTheme');
var BookmarkMenu = require('./views/BookmarkMenu');
var {servers: {localHub}} = require('./defaultServers');

// Styles
var compStyles = require('./nav.module.css');

// Images
var logoSantaCruzImg = require('../images/logoSantaCruz.png');
var logoSantaCruz2xImg = require('../images/logoSantaCruz@2x.png');
var logoSantaCruz3xImg = require('../images/logoSantaCruz@3x.png');

// Locals
var links = [
	{label: 'Data Sets', nav: 'datapages'},
	{label: 'Visualization', nav: 'heatmap'},
	{label: 'Transcripts', nav: 'transcripts'},
	{label: 'Data Hubs', nav: 'hub'},
	// {href: 'https://genome-cancer.ucsc.edu/download/public/get-xena/index.html', label: 'Local Xena'},
	{label: 'View My Data', nav: 'datapages', params: {addHub: localHub, host: localHub}},
	{href: 'http://xena.ucsc.edu/xena-python-api/', label: 'Python'},
];

var helpLink = {
	href: 'https://ucsc-xena.gitbook.io/project/',
	label: 'Help',
	target: '_blank'
};

var geneSetsLink = {
    // href: 'https://xenageneset.berkeleybop.io/xena/',
    href: 'http://xenademo.berkeleybop.io/xena/',
    label: 'Gene Sets',
    target: '_blank'
};

var active = (l, activeLink) => l.nav === activeLink;

class XenaNav extends React.Component {
	render() {
		let {isPublic, activeLink, getState, onImport} = this.props;
		let routes = _.map(links, l => {
			var {nav, params, ...others} = l,
			onClick = nav ? () => this.props.onNavigate(nav, params) : undefined;
			return {...others, onClick, active: active(l, activeLink)};
		});
		let logoSrcSet = `${logoSantaCruz2xImg} 2x, ${logoSantaCruz3xImg} 3x`;
		return (
			<AppBar className={compStyles.NavAppBar}>

				<Navigation type="horizontal" routes={routes}>
					{getState ? <BookmarkMenu isPublic={isPublic} getState={getState} onImport={onImport}/> : null}
					<Link {...geneSetsLink} />
                    <Link {...helpLink} />
				</Navigation>
			</AppBar>
		);
	}
}

class ThemedNav extends React.Component {
	render() {
		return (
			<ThemeProvider theme={navTheme}>
				<XenaNav {...this.props}/>
			</ThemeProvider>);
	}
}

var nav = document.getElementById('navMenuMain');

module.exports = props => ReactDOM.render(<ThemedNav {...props} />, nav);
<|endoftext|>


<commit_before>(function(exports) {
  var commitTreeURL = "https://api.github.com/repos/caskroom/homebrew-cask/commits?per_page=1";
  var isCaskFile = function isCaskfile(el) { return /^Casks\/.+\.rb/.test(el.path) };

  var indexCaskData = function indexCaskData(data) {
    var toEntry = function(el, i) {
      var caskFileName = /^Casks\/(.+).rb/.exec(el.path)[1];
      return { id: i,
               caskName: caskFileName,
               appName: caskFileName.replace(/-/g, " "),
               entryName: caskFileName.replace(/[^A-Za-z0-9]/g, ""),
               caskUrl: el.url }
    };

    var casks = data.tree.filter(isCaskFile).map(toEntry);
    return casks;
  }

  var request = function request(url) { return $.ajax({ url: url, type: "GET" })};

  var latestTreeURL = function latestTreeURL(data) {
    return "https://api.github.com/repos/caskroom/homebrew-cask/git/trees/"
            + data[0].sha
            + "?recursive=1";
  }

  var retrieveCaskData = function retrieveCaskData(cb, err) {
    request(commitTreeURL)
      .done(function (commits) {
        request(latestTreeURL(commits))
          .done(function (tree) { cb(tree) })
          .fail(function (jqXHR, _, errorThrown) { err(jqXHR, errorThrown) })})
      .fail(function (jqXHR, _, errorThrown) { err(jqXHR, errorThrown) });
  }

  exports.commitTreeURL = commitTreeURL;
  exports.contribURL = "https://api.github.com/repos/caskroom/homebrew-cask/contributors?per_page=1";
  exports.retrieveCaskData = retrieveCaskData;
  exports.isCaskFile = isCaskFile;
  exports.indexCaskData = indexCaskData;
  exports.request = request;
})(this.pre = {});
<commit_msg>Preserve hyphens in search results<commit_after>(function(exports) {
  var commitTreeURL = "https://api.github.com/repos/caskroom/homebrew-cask/commits?per_page=1";
  var isCaskFile = function isCaskfile(el) { return /^Casks\/.+\.rb/.test(el.path) };

  var indexCaskData = function indexCaskData(data) {
    var toEntry = function(el, i) {
      var caskFileName = /^Casks\/(.+).rb/.exec(el.path)[1];
      return { id: i,
               caskName: caskFileName,
               appName: caskFileName,
               entryName: caskFileName.replace(/[^A-Za-z0-9]/g, ""),
               caskUrl: el.url }
    };

    var casks = data.tree.filter(isCaskFile).map(toEntry);
    return casks;
  }

  var request = function request(url) { return $.ajax({ url: url, type: "GET" })};

  var latestTreeURL = function latestTreeURL(data) {
    return "https://api.github.com/repos/caskroom/homebrew-cask/git/trees/"
            + data[0].sha
            + "?recursive=1";
  }

  var retrieveCaskData = function retrieveCaskData(cb, err) {
    request(commitTreeURL)
      .done(function (commits) {
        request(latestTreeURL(commits))
          .done(function (tree) { cb(tree) })
          .fail(function (jqXHR, _, errorThrown) { err(jqXHR, errorThrown) })})
      .fail(function (jqXHR, _, errorThrown) { err(jqXHR, errorThrown) });
  }

  exports.commitTreeURL = commitTreeURL;
  exports.contribURL = "https://api.github.com/repos/caskroom/homebrew-cask/contributors?per_page=1";
  exports.retrieveCaskData = retrieveCaskData;
  exports.isCaskFile = isCaskFile;
  exports.indexCaskData = indexCaskData;
  exports.request = request;
})(this.pre = {});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Intel Corporation, Jaguar Land Rover
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */

/**
 * @module Services
 */

function RVI() {

    console.log("Starting up service RVI");
    RVI.instance = this

    this.is_connected = false;
    this.trans_id = 1;
    this.service_map = {};

    this.OK = 0;
    this.NOT_CONNECTED = 1;
    this.on_service_available = function () {
    }
    this.on_service_unavailable = function () {
    }
    this.on_error = function () {
    }

    this.next_trans_id = function () {
        this.trans_id = this.trans_id + 1;
        return this.trans_id;
    }

    // Connect to an RVI node using
    // websockets
    this.connect = function (url) {
        if (this.is_connected)
            return;

        this.url = url;
        this.ws = new WebSocket(url);
        this.ws.onerror = this.on_error;
        this.ws.binaryType = "arraybuffer";
        this.ws.parent = this;

        this.ws.onopen = function (evt) {
            console.log("RVI connected to: " + this.url);

            this.parent.is_connected = true;

            // Register all services that have been
            // setup with register_service()
            for (svc in this.parent.service_map) {
                console.log("Will reg: " + JSON.stringify(svc));
                this.parent.register_service(svc, this.parent.service_map[svc].cb_fun)
            }
            // Invoke connect cb, if defined
            if (typeof this.parent.on_connect != "undefined")
                this.parent.on_connect(this.parent);
        }

        this.ws.close = function (evt) {
            console.log("RVI disconnected.");
            this.connected = false;
        }

        this.ws.onmessage = function (evt) {
            console.log("onmessage(): Got: " + JSON.stringify(evt));
            this.parent.dispatch_message(evt);
        }

        this.ws.onerror = this.on_error;
    }

    // Register a service.
    this.register_service = function (service, service_fun) {
        // Add a leading slash if necessar
        console.log("Registering service: " + service);
        if (service[0] != '/')
            service = '/' + service;

        // If we are not connected, then just update the
        // service map and return.
        // Once the connection goes through, we will register
        // all services
        if (!this.is_connected) {
            console.log("RVI: Deferring service registration: " + service);
            this.service_map[service] = {
                cb_fun: service_fun,
                full_name: undefined
            };
            return this.OK
        }

        console.log("RVI: Registering RVI service: " + service);
        console.log("RVI: Registering callback: " + service_fun);

        //
        // Redirect ws.onmessage to handle service registration replies
        //
        this.ws.onmessage = function (evt) {
            console.log("RVI: Register service result: " + JSON.parse(evt.data).service);

            // If this is a new service, set it up
            if (typeof this.parent.service_map[service] === "undefined") {
                this.service_map[service] = {
                    cb_fun: service_fun,
                    full_name: JSON.parse(evt.data).service
                };
            } else // Update full name of existing service.
                this.parent.service_map[service].full_name = JSON.parse(evt.data).service;

            // Reset the onmessage handler
            this.onmessage = function (evt) {
                this.parent.dispatch_message(evt);
            }
        }

        this.ws.send(JSON.stringify({
            'json-rpc': "2.0",
            'id': this.next_trans_id(),
            method: "register_service",
            params: {
                service_name: service
            }
        }));
        return this.OK;
    }

    // Unregister a service
    this.unregister_service = function (service) {
        if (service[0] != '/')
            service = '/' + service;

        if (!this.is_connected)
            return this.NOT_CONNECTED;

        console.log("RVI: unregistering: " + service);

        this.ws.send(JSON.stringify({
            'json-rpc': "2.0",
            'id': this.next_trans_id(),
            method: "unregister_service",
            params: {
                service_name: service
            }
        }));

        delete this.service_map[service];

        return this.OK;
    }

    this.disconnect = function () {
        if (!this.is_connected)
            return this.NOT_CONNECTED;

        this.ws.close(); // Server will unregister all services on its end
        return this.OK;
    }

    this.send_message = function (service, timeout, payload, cb) {
        console.log("RVI: message:  " + service);
        console.log("RVI: timeout:  " + timeout);
        console.log("RVI: params:   " + JSON.stringify(payload));
        console.log("RVI: callback: " + cb);

        // Redirect ws.onmessage to handle replies.

        if (!this.is_connected)
            return this.NOT_CONNECTED;

        this.ws.onmessage = function (evt) {
            console.log("RVI: message result: " + JSON.parse(evt.data).status);
            console.log("RVI: message TID: " + JSON.parse(evt.data).transaction_id);

            // Invoke provided callback
            //cb(JSON.parse(evt.data).result, JSON.parse(evt.data).transaction_id);

            // Reset the onmessage handler
            this.onmessage = function (evt) {
                this.parent.dispatch_message(evt);
            }
        }

        this.ws.send(JSON.stringify({
            'json-rpc': "2.0",
            'id': this.next_trans_id(),
            method: "message",
            params: {
                service_name: service,
                timeout: timeout,
                parameters: payload,
            }
        }));
    }

    // Retrieve the full service name for a service
    this.get_full_service_name = function (local_service_name) {
        return this.service_name[local_service_name].full_name;
    }

    this.dispatch_message = function (evt) {
        dt = JSON.parse(evt.data);

        if (dt.method === "message") {
            svc = dt.params.service_name;
            parameters = dt.params.parameters;
            console.log("RVI: dispatch_message: " + JSON.stringify(dt));
            console.log("RVI: dispatch_message: " + svc);
            console.log("RVI: dispatch_message: " + parameters);

            // CHECK USE of window
            if (this.service_map[svc]) {
                // Original tizen code had
                // window[this.service_map[svc].cb_fun](parameters);
                this.service_map[svc].cb_fun(parameters);

            } else {
                console.warn("Service: " + svc + " not mapped to any callback. Ignore");
                console.log("Service: " + JSON.stringify(this.service_map));
            }

            console.log("RVI Message completed");
            return;
        }

        if (dt.method === "services_available") {
            console.log("RVI service_available");
            this.on_service_available(dt.params.services);
            return;
        }

        if (dt.method === "services_unavailable") {
            console.log("RVI service_unavailable");
            this.on_service_unavailable(dt.params.services);
            return;
        }
    }
}

//// "ws://10.0.0.36:1234/websession"
function message() {
	args = {};

    for (var i = 0; i < arguments.length; ++i) {
    	if(i%2 == 0){
    		args[arguments[i]] = arguments[i+1];
    	}
    }
    console.log("RVI message Arguments ");
    console.log(args);

    return rvi.rvi_message.apply(rvi,arguments);
}
<commit_msg>[40610] Added missing semicolons<commit_after>/*
 * Copyright (c) 2013, Intel Corporation, Jaguar Land Rover
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */

/**
 * @module Services
 */

function RVI() {

    console.log("Starting up service RVI");
    RVI.instance = this;

    this.is_connected = false;
    this.trans_id = 1;
    this.service_map = {};

    this.OK = 0;
    this.NOT_CONNECTED = 1;
    this.on_service_available = function () {
    };
    this.on_service_unavailable = function () {
    };
    this.on_error = function () {
    };

    this.next_trans_id = function () {
        this.trans_id = this.trans_id + 1;
        return this.trans_id;
    };

    // Connect to an RVI node using
    // websockets
    this.connect = function (url) {
        if (this.is_connected)
            return;

        this.url = url;
        this.ws = new WebSocket(url);
        this.ws.onerror = this.on_error;
        this.ws.binaryType = "arraybuffer";
        this.ws.parent = this;

        this.ws.onopen = function (evt) {
            console.log("RVI connected to: " + this.url);

            this.parent.is_connected = true;

            // Register all services that have been
            // setup with register_service()
            for (svc in this.parent.service_map) {
                console.log("Will reg: " + JSON.stringify(svc));
                this.parent.register_service(svc, this.parent.service_map[svc].cb_fun)
            }
            // Invoke connect cb, if defined
            if (typeof this.parent.on_connect != "undefined")
                this.parent.on_connect(this.parent);
        };

        this.ws.close = function (evt) {
            console.log("RVI disconnected.");
            this.connected = false;
        };

        this.ws.onmessage = function (evt) {
            console.log("onmessage(): Got: " + JSON.stringify(evt));
            this.parent.dispatch_message(evt);
        };

        this.ws.onerror = this.on_error;
    };

    // Register a service.
    this.register_service = function (service, service_fun) {
        // Add a leading slash if necessar
        console.log("Registering service: " + service);
        if (service[0] != '/')
            service = '/' + service;

        // If we are not connected, then just update the
        // service map and return.
        // Once the connection goes through, we will register
        // all services
        if (!this.is_connected) {
            console.log("RVI: Deferring service registration: " + service);
            this.service_map[service] = {
                cb_fun: service_fun,
                full_name: undefined
            };
            return this.OK
        }

        console.log("RVI: Registering RVI service: " + service);
        console.log("RVI: Registering callback: " + service_fun);

        //
        // Redirect ws.onmessage to handle service registration replies
        //
        this.ws.onmessage = function (evt) {
            console.log("RVI: Register service result: " + JSON.parse(evt.data).service);

            // If this is a new service, set it up
            if (typeof this.parent.service_map[service] === "undefined") {
                this.service_map[service] = {
                    cb_fun: service_fun,
                    full_name: JSON.parse(evt.data).service
                };
            } else // Update full name of existing service.
                this.parent.service_map[service].full_name = JSON.parse(evt.data).service;

            // Reset the onmessage handler
            this.onmessage = function (evt) {
                this.parent.dispatch_message(evt);
            }
        };

        this.ws.send(JSON.stringify({
            'json-rpc': "2.0",
            'id': this.next_trans_id(),
            method: "register_service",
            params: {
                service_name: service
            }
        }));
        return this.OK;
    };

    // Unregister a service
    this.unregister_service = function (service) {
        if (service[0] != '/')
            service = '/' + service;

        if (!this.is_connected)
            return this.NOT_CONNECTED;

        console.log("RVI: unregistering: " + service);

        this.ws.send(JSON.stringify({
            'json-rpc': "2.0",
            'id': this.next_trans_id(),
            method: "unregister_service",
            params: {
                service_name: service
            }
        }));

        delete this.service_map[service];

        return this.OK;
    };

    this.disconnect = function () {
        if (!this.is_connected)
            return this.NOT_CONNECTED;

        this.ws.close(); // Server will unregister all services on its end
        return this.OK;
    };

    this.send_message = function (service, timeout, payload, cb) {
        console.log("RVI: message:  " + service);
        console.log("RVI: timeout:  " + timeout);
        console.log("RVI: params:   " + JSON.stringify(payload));
        console.log("RVI: callback: " + cb);

        // Redirect ws.onmessage to handle replies.

        if (!this.is_connected)
            return this.NOT_CONNECTED;

        this.ws.onmessage = function (evt) {
            console.log("RVI: message result: " + JSON.parse(evt.data).status);
            console.log("RVI: message TID: " + JSON.parse(evt.data).transaction_id);

            // Invoke provided callback
            //cb(JSON.parse(evt.data).result, JSON.parse(evt.data).transaction_id);

            // Reset the onmessage handler
            this.onmessage = function (evt) {
                this.parent.dispatch_message(evt);
            }
        };

        this.ws.send(JSON.stringify({
            'json-rpc': "2.0",
            'id': this.next_trans_id(),
            method: "message",
            params: {
                service_name: service,
                timeout: timeout,
                parameters: payload,
            }
        }));
    };

    // Retrieve the full service name for a service
    this.get_full_service_name = function (local_service_name) {
        return this.service_name[local_service_name].full_name;
    };

    this.dispatch_message = function (evt) {
        dt = JSON.parse(evt.data);

        if (dt.method === "message") {
            svc = dt.params.service_name;
            parameters = dt.params.parameters;
            console.log("RVI: dispatch_message: " + JSON.stringify(dt));
            console.log("RVI: dispatch_message: " + svc);
            console.log("RVI: dispatch_message: " + parameters);

            // CHECK USE of window
            if (this.service_map[svc]) {
                // Original tizen code had
                // window[this.service_map[svc].cb_fun](parameters);
                this.service_map[svc].cb_fun(parameters);

            } else {
                console.warn("Service: " + svc + " not mapped to any callback. Ignore");
                console.log("Service: " + JSON.stringify(this.service_map));
            }

            console.log("RVI Message completed");
            return;
        }

        if (dt.method === "services_available") {
            console.log("RVI service_available");
            this.on_service_available(dt.params.services);
            return;
        }

        if (dt.method === "services_unavailable") {
            console.log("RVI service_unavailable");
            this.on_service_unavailable(dt.params.services);
            return;
        }
    }
}

//// "ws://10.0.0.36:1234/websession"
function message() {
	args = {};

    for (var i = 0; i < arguments.length; ++i) {
    	if(i%2 == 0){
    		args[arguments[i]] = arguments[i+1];
    	}
    }
    console.log("RVI message Arguments ");
    console.log(args);

    return rvi.rvi_message.apply(rvi,arguments);
}
<|endoftext|>


<commit_before>const format = JSON.stringify;
const path = require("path");
const fse = require("fs-extra");

const command = {
  command: "compile",
  description: "Compile contract source files",
  builder: {
    all: {
      type: "boolean",
      default: false
    },
    compiler: {
      type: "string",
      default: null
    },
    list: {
      type: "string"
    },
    help: {
      type: "boolean",
      default: "false"
    }
  },
  help: {
    usage:
      "truffle compile [--list <filter>] [--all] [--network <name>] [--quiet] [--save-intermediate <output-file>]",
    options: [
      {
        option: "--all",
        description:
          "Compile all contracts instead of only the contracts changed since last compile."
      },
      {
        option: "--network <name>",
        description:
          "Specify the network to use, saving artifacts specific to that network. " +
          " Network name must exist in the\n                    configuration."
      },
      {
        option: "--list <filter>",
        description:
          "List all recent stable releases from solc-bin.  If filter is specified then it will display only " +
          "that\n                    type of release or docker tags. The filter parameter must be one of the following: " +
          "prereleases,\n                    releases, latestRelease or docker."
      },
      {
        option: "--quiet",
        description: "Suppress all compilation output."
      },
      {
        option: "--compiler <compiler-name>",
        description:
          "Specify a single compiler to use (e.g. `--compiler=solc`). Specify `none` to skip compilation."
      },
      {
        option: "--save-intermediate <output-file>",
        description:
          "Save the raw compiler results into <output-file>, overwriting any existing content."
      }
    ]
  },
  run: function (options, done) {
    const TruffleError = require("@truffle/error");
    const Contracts = require("@truffle/workflow-compile/new");
    const Config = require("@truffle/config");
    const config = Config.detect(options);

    if (config.list !== undefined) {
      command
        .listVersions(config)
        .then(() => done())
        .catch(done);
    } else {
      if (
        options.saveIntermediate === true ||
        (typeof options.saveIntermediate === "string" &&
          options.saveIntermediate.trim() === "")
      ) {
        // user asked to save the intermediate compilation results
        // but didn't provide the file to save the results to
        return done(
          new TruffleError(
            "You must provide a file to save compilation results to."
          )
        );
      }

      Contracts.compile(config)
        .then(async compilationOutput => {
          if (options.saveIntermediate) {
            // Get the filename the user provided to save the compilation results to
            const compilationOutputFile = path.resolve(
              options.saveIntermediate
            );

            await fse.writeFile(
              compilationOutputFile,
              JSON.stringify(compilationOutput),
              { encoding: "utf8" }
            );
          }

          return Contracts.save(config, compilationOutput.contracts);
        })
        .then(() => done())
        .catch(done);
    }
  },

  listVersions: async function (options) {
    const { CompilerSupplier } = require("@truffle/compile-solidity");
    const supplier = new CompilerSupplier({
      solcConfig: options.compilers.solc,
      events: options.events
    });

    const log = options.logger.log;
    options.list = options.list.length ? options.list : "releases";

    // Docker tags
    if (options.list === "docker") {
      const tags = await supplier.getDockerTags();
      tags.push("See more at: hub.docker.com/r/ethereum/solc/tags/");
      log(format(tags, null, " "));
      return;
    }

    // Solcjs releases
    const releases = await supplier.getReleases();
    const shortener = options.all ? null : command.shortener;
    const list = format(releases[options.list], shortener, " ");
    log(list);
    return;
  },

  shortener: function (key, val) {
    const defaultLength = 10;

    if (Array.isArray(val) && val.length > defaultLength) {
      const length = val.length;
      const remaining = length - defaultLength;
      const more =
        ".. and " + remaining + " more. Use `--all` to see full list.";
      val.length = defaultLength;
      val.push(more);
    }

    return val;
  }
};

module.exports = command;
<commit_msg>Mark --save-intermediate as internal<commit_after>const format = JSON.stringify;
const path = require("path");
const fse = require("fs-extra");

const command = {
  command: "compile",
  description: "Compile contract source files",
  builder: {
    all: {
      type: "boolean",
      default: false
    },
    compiler: {
      type: "string",
      default: null
    },
    list: {
      type: "string"
    },
    help: {
      type: "boolean",
      default: "false"
    }
  },
  help: {
    usage:
      "truffle compile [--list <filter>] [--all] [--network <name>] [--quiet]",
    options: [
      {
        option: "--all",
        description:
          "Compile all contracts instead of only the contracts changed since last compile."
      },
      {
        option: "--network <name>",
        description:
          "Specify the network to use, saving artifacts specific to that network. " +
          " Network name must exist in the\n                    configuration."
      },
      {
        option: "--list <filter>",
        description:
          "List all recent stable releases from solc-bin.  If filter is specified then it will display only " +
          "that\n                    type of release or docker tags. The filter parameter must be one of the following: " +
          "prereleases,\n                    releases, latestRelease or docker."
      },
      {
        option: "--quiet",
        description: "Suppress all compilation output."
      },
      {
        option: "--compiler <compiler-name>",
        description:
          "Specify a single compiler to use (e.g. `--compiler=solc`). Specify `none` to skip compilation."
      },
      {
        option: "--save-intermediate <output-file>",
        internal: true,
        description:
          "Save the raw compiler results into <output-file>, overwriting any existing content."
      }
    ]
  },
  run: function (options, done) {
    const TruffleError = require("@truffle/error");
    const Contracts = require("@truffle/workflow-compile/new");
    const Config = require("@truffle/config");
    const config = Config.detect(options);

    if (config.list !== undefined) {
      command
        .listVersions(config)
        .then(() => done())
        .catch(done);
    } else {
      if (
        options.saveIntermediate === true ||
        (typeof options.saveIntermediate === "string" &&
          options.saveIntermediate.trim() === "")
      ) {
        // user asked to save the intermediate compilation results
        // but didn't provide the file to save the results to
        return done(
          new TruffleError(
            "You must provide a file to save compilation results to."
          )
        );
      }

      Contracts.compile(config)
        .then(async compilationOutput => {
          if (options.saveIntermediate) {
            // Get the filename the user provided to save the compilation results to
            const compilationOutputFile = path.resolve(
              options.saveIntermediate
            );

            await fse.writeFile(
              compilationOutputFile,
              JSON.stringify(compilationOutput),
              { encoding: "utf8" }
            );
          }

          return Contracts.save(config, compilationOutput.contracts);
        })
        .then(() => done())
        .catch(done);
    }
  },

  listVersions: async function (options) {
    const { CompilerSupplier } = require("@truffle/compile-solidity");
    const supplier = new CompilerSupplier({
      solcConfig: options.compilers.solc,
      events: options.events
    });

    const log = options.logger.log;
    options.list = options.list.length ? options.list : "releases";

    // Docker tags
    if (options.list === "docker") {
      const tags = await supplier.getDockerTags();
      tags.push("See more at: hub.docker.com/r/ethereum/solc/tags/");
      log(format(tags, null, " "));
      return;
    }

    // Solcjs releases
    const releases = await supplier.getReleases();
    const shortener = options.all ? null : command.shortener;
    const list = format(releases[options.list], shortener, " ");
    log(list);
    return;
  },

  shortener: function (key, val) {
    const defaultLength = 10;

    if (Array.isArray(val) && val.length > defaultLength) {
      const length = val.length;
      const remaining = length - defaultLength;
      const more =
        ".. and " + remaining + " more. Use `--all` to see full list.";
      val.length = defaultLength;
      val.push(more);
    }

    return val;
  }
};

module.exports = command;
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.8.0
(function() {

  var BubbleChart, root,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  BubbleChart = (function() {
    function BubbleChart(container, data, config) {
      this.hide_details = __bind(this.hide_details, this);
      this.show_details = __bind(this.show_details, this);
      this.move_towards_year = __bind(this.move_towards_year, this);
      this.display_by_group = __bind(this.display_by_group, this);
      this.start = __bind(this.start, this);
      this.render = __bind(this.render, this);
      this.create_nodes = __bind(this.create_nodes, this);

      var max_amount;
      this.container = container;
      this.data = data;
      this.width = config.width;
      this.height = config.height;
      this.tooltip = CustomTooltip("startup_funding_tooltip", 210);

      this.center = {
        x: this.width / 2 ,
        y: this.height / 2
      };

      this.off_screen = {
        x: this.width + 300,
        y: this.height / 2
      };

      this.layout_gravity = -0.01;
      this.damper = 0.1;
      this.vis = null;
      this.nodes = [];
      this.force = null;
      this.circles = null;
      this.selected = false;
      this.investorSelected = false;
      this.currentSelection = null;

      this.colorRange = d3.scale.linear()
        .domain(config.colorRange.domain)
        .range(config.colorRange.range)

      max_amount = d3.max(this.data, function(d) {
        return parseInt(d.amount);
      });

      this.radius_scale = d3.scale.pow().exponent(0.5).domain([0, max_amount]).range([4, 60]);
      this.create_nodes();
      this.render();
    }

    BubbleChart.prototype.create_nodes = function() {
      var self = this;

      this.data.forEach(function(d) {
          var node;
          if(parseInt(d.amount) <= 0) {
            return;
          }

          node = {
            id: d.id,
            radius: self.radius_scale(parseInt(d.amount)),
            value: d.amount,
            name: d.name,
            org: d.vc_list,
            group: d.stage,
            year: d.year,
            x: Math.random() * 900,
            y: Math.random() * 800
          };

          return self.nodes.push(node);
      });

      return this.nodes.sort(function(a, b) {
        return b.value - a.value;
      });
    };

    BubbleChart.prototype.render = function() {
      var self = this;

      this.vis = d3.select(this.container).append("svg").attr("width", "100%").attr("height", this.height).attr("id", "svg_vis");

      this.vis.on("click", function() {
        //self.selected = false;
      });

      this.circles = this.vis.selectAll("circle").data(this.nodes, function(d) {
        return d.id;
      });

      this.circles.enter()
      .append("circle")
      .each(function (d) {
        var strokeColor = d3.rgb(self.colorRange(d.org.length)).darker(),
            fillColor = self.colorRange(d.org.length);

        d3.select(this).attr({
          r: 0,
          "fill": fillColor,
          "fill-opacity": 0.8,
          "stroke-width": 1,
          "stroke": strokeColor,
          "id": "bubble_" + d.id,
          "class": "bubble"

        });

      })
      .on("mouseover", function(d, i) {
        if(!self.selected) {
          showBubbleDetails(self, this, d)
        }
      })
      .on("mouseout", function(d, i) {
        if(!self.selected) {
          hideBubbleDetails(self, this, d)
        }
      })
      .on("click", function(d, i) {
        if(!self.selected) {
          self.currentSelection = this;
          self.selected = true;
          var counter = 0

          d.org.forEach(function(name){
            counter = counter + 1;
            d3.select("text#vc-title-" + counter).text(name);
            return true;
          });

          d3.selectAll(".bubble")
            .attr({
              "fill-opacity": 0.2,
            });
          d3.select(this).attr({
            "fill-opacity": 0.8,
          });

        } else {
          self.selected = false;
          d3.selectAll(".bubble").each(function(data){
            d3.select(this).attr({
              "fill-opacity": 0.8,
            });
          });

          self.hide_details(d, i, self.currentSelection);
          return self.show_details(d, i, this);
        }

      });

      // Total investment
      this.vis.append("text")
        .attr("x", 20)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "money")
        .attr("fill", "black");

      // Total investment
      this.vis.append("text")
        .attr("x", 900)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "quantity")
        .attr("fill", "black");

      return this.circles.transition().duration(2000).attr("r", function(d) {
        return d.radius;
      });

    };

    function showBubbleDetails(inst, elem, data) {
      var counter = 0

      data.org.forEach(function(name){
        counter = counter + 1;
        d3.select("text#vc-title-" + counter).text(name);
        return true;
      });

      d3.select(elem).attr("fill-opacity", 0.8);

      return inst.show_details(data, 1, elem);

    }

    function hideBubbleDetails(inst, elem, data) {
      // TODO: mark previuosly on hover elem
      d3.selectAll(".vc-lable__text")
        .each(function(data){
            d3.select(this).text("");
        });

      return inst.hide_details(data, 1, elem);
    }

    BubbleChart.prototype.charge = function(d) {
      return -Math.pow(d.radius, 2.0) / 7 ;
    };

    BubbleChart.prototype.start = function() {
      return this.force = d3.layout.force().nodes(this.nodes).size([this.width, this.height]);
    };

    BubbleChart.prototype.display_by_group = function(list) {
      var self = this;

      var dic =  {
        "seed": ["Angel Round", "Seed Round"],
        "series-a": ["Series A"],
        "series-b": ["Series B", "Series C"],
        "series-d": ["Series D", "Series E", "Series F", "Series G"],
        "private": ["Private Equity"]
      }

      var group = [];

      list.forEach(function (item) {
        group = group.concat(dic[item]);
        return group;
      });

      this.force.gravity(this.layout_gravity)
        .charge(this.charge)
        .friction(0.9)
        .on("tick", function(e) {
          return self.circles
            .each(self.move_towards_target(
                e.alpha,
                function(d) {

                  if(group.indexOf(d.group) >= 0){
                    return self.center;
                  } else {
                    return self.off_screen;
                  }

                })
            )
            .attr("cx", function(d) {
              return d.x;
            })
            .attr("cy", function(d) {
              return d.y;
            });
      });

      var sum = 0;
      var count = 0;
      this.nodes.forEach( function (d) {

        if(group.indexOf(d.group) >= 0){
          count = count + 1;
          sum = sum + parseInt(d.value);
        }
      });

      d3.select("#money").text('$' + addScale(sum));
      d3.select("#quantity").text('#' + addCommas(count));
      return this.force.start();

    };

    BubbleChart.prototype.move_towards_target = function(alpha, target) {
      var self = this;

      return function(d) {
          d.x = d.x + (target(d).x - d.x) * (self.damper + 0.02) * alpha * 1.1;
          return d.y = d.y + (target(d).y - d.y) * (self.damper + 0.02) * alpha * 1.1;
      };

    };

    BubbleChart.prototype.show_details = function(data, i, element) {

      var content1, content2;
      d3.select(element).attr("stroke", "black");
      content1 = data.name;
      content2 = data.group + ", $" + (addScale(data.value));

      d3.select("text#company-title-2").text(content2);
      return d3.select("text#company-title-1").text(content1);

    };

    BubbleChart.prototype.hide_details = function(data, i, element) {
      d3.select(element).attr("stroke", (function(_this) {
        return function(d) {
          return d3.rgb(_this.colorRange(d.org.length)).darker();
        };
      })(this));
      return this.tooltip.hideTooltip();
    };

    BubbleChart.prototype.lables_placeholder = function(json) {

      var self = this;

      // Holdes the data
      var data = json;
      var startPointY = 50;

      function drawTitle(vis, x, y, text) {

        // Title
        vis.append("text")
          .attr("x", x)
          .attr("y",y)
          .text(text)
          .attr("class","title system-font")
          .attr("fill", "black");
      }

      function companySelector(element) {
        var content = element.textContent;
        var counter = 1;
        if(!self.investorSelected) {
          self.investorSelected = true;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                counter = counter + 1;
                d3.select(this).attr({
                  "fill-opacity": 1,
                  fill: self.fill_color(d.org.length)
                });
                self.show_details(data, counter, this);
              }
            });
        } else {

          self.investorSelected = false;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                d3.select(this).attr({
                  "fill-opacity": 0.2,
                  fill: self.fill_color(d.org.length)
                });

              }
            });
        }
      }

      function generatelablesContainer(vis, data, css, itemId, x, y, clickExecutor) {

        var lablesContainer = vis
                        .selectAll("g." + css)
                        .data(data, function(d) {
                          return d.id;
                        })
                        .enter().append("g")
                        .attr("class",css);

        var currentY = y + 10,
            counter = 0;

        /*lablesContainer.append("title")
            .text(function(d) { return d.name; });*/

        lablesContainer.append("text")
            .attr("x", x)
            .each(function (d){
                counter = counter + 1;
                title_class_pos = "odd";
                if( counter % 2  == 0) {
                  title_class_pos = "even";
                }
                var tempY = currentY;
                currentY= currentY + 32;

                d3.select(this).attr({
                    y: currentY,
                    "class":  css + "__text" + " " + title_class_pos,
                    id: itemId + counter
                }).text("");
            })
            .on("click", function(d, i){

              if(clickExecutor !== 'undefined') {
                clickExecutor(this);
              }
            });
      }

      drawTitle(this.vis, 20, startPointY, "INVESTORS:");
      drawTitle(this.vis, 795, startPointY, "COMPANY:");
      generatelablesContainer(this.vis, data, "vc-lable","vc-title-", 25, startPointY);
      generatelablesContainer(this.vis, [{ id: 1},{ id:2 }], "company-lable","company-title-", 800, startPointY);

    }

    return BubbleChart;

  })();

  root = typeof exports !== "undefined" && exports !== null ? exports : this;

  $(function() {
    var chart, render_vis, render_lbl;
    var active_groups = ["seed", "series-a", "series-b", "series-d", "private"];
    var inactive_groups = [];
    chart = null;

    render_vis = function (data) {
      config = {
        width: 1040,
        height: 600,
        colorRange: {
          domain: [1, 3, 5, 8],
          //range: ["#143642", "#558C8C", "#F7941D", "#A8201A"]
          range: ["#6CD4FF", "#143642", "#A8201A"]
        }
      };
      chart = new BubbleChart("#viz", data, config);

      chart.start();
      return chart.display_by_group(active_groups);
    };

    render_lable = function(json) {
      return chart.lables_placeholder(json);
    }
    root.display_group = (function(_this) {
      return function(list) {
        return chart.display_by_group(list);
      };
    })(this);

    root.toggle_view = (function(_this) {
      return function(view_type) {
        var active_pos = active_groups.indexOf(view_type)

        if (active_pos >= 0) {
          inactive_groups.push(view_type);
          active_groups.splice(active_pos, 1);
        } else {
          inactive_groups.splice(inactive_groups.indexOf(view_type), 1);
          active_groups.push(view_type);
        }

        return root.display_group(active_groups);

      };
    })(this);

    // Render visualisation
    //var v = d3.csv("data/test.csv", render_vis);
    var v = d3.json("data/funding.json", function(data) {

      render_vis(data);
      // Render label
      d3.json("data/labels.json", render_lable);

    });

    return v;
  });

}).call(this);
<commit_msg>changed color<commit_after>// Generated by CoffeeScript 1.8.0
(function() {

  var BubbleChart, root,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  BubbleChart = (function() {
    function BubbleChart(container, data, config) {
      this.hide_details = __bind(this.hide_details, this);
      this.show_details = __bind(this.show_details, this);
      this.move_towards_year = __bind(this.move_towards_year, this);
      this.display_by_group = __bind(this.display_by_group, this);
      this.start = __bind(this.start, this);
      this.render = __bind(this.render, this);
      this.create_nodes = __bind(this.create_nodes, this);

      var max_amount;
      this.container = container;
      this.data = data;
      this.width = config.width;
      this.height = config.height;
      this.tooltip = CustomTooltip("startup_funding_tooltip", 210);

      this.center = {
        x: this.width / 2 ,
        y: this.height / 2
      };

      this.off_screen = {
        x: this.width + 300,
        y: this.height / 2
      };

      this.layout_gravity = -0.01;
      this.damper = 0.1;
      this.vis = null;
      this.nodes = [];
      this.force = null;
      this.circles = null;
      this.selected = false;
      this.investorSelected = false;
      this.currentSelection = null;

      this.colorRange = d3.scale.linear()
        .domain(config.colorRange.domain)
        .range(config.colorRange.range)

      max_amount = d3.max(this.data, function(d) {
        return parseInt(d.amount);
      });

      this.radius_scale = d3.scale.pow().exponent(0.5).domain([0, max_amount]).range([4, 60]);
      this.create_nodes();
      this.render();
    }

    BubbleChart.prototype.create_nodes = function() {
      var self = this;

      this.data.forEach(function(d) {
          var node;
          if(parseInt(d.amount) <= 0) {
            return;
          }

          node = {
            id: d.id,
            radius: self.radius_scale(parseInt(d.amount)),
            value: d.amount,
            name: d.name,
            org: d.vc_list,
            group: d.stage,
            year: d.year,
            x: Math.random() * 900,
            y: Math.random() * 800
          };

          return self.nodes.push(node);
      });

      return this.nodes.sort(function(a, b) {
        return b.value - a.value;
      });
    };

    BubbleChart.prototype.render = function() {
      var self = this;

      this.vis = d3.select(this.container).append("svg").attr("width", "100%").attr("height", this.height).attr("id", "svg_vis");

      this.vis.on("click", function() {
        //self.selected = false;
      });

      this.circles = this.vis.selectAll("circle").data(this.nodes, function(d) {
        return d.id;
      });

      this.circles.enter()
      .append("circle")
      .each(function (d) {
        var strokeColor = d3.rgb(self.colorRange(d.org.length)).darker(),
            fillColor = self.colorRange(d.org.length);

        d3.select(this).attr({
          r: 0,
          "fill": fillColor,
          "fill-opacity": 0.8,
          "stroke-width": 1,
          "stroke": strokeColor,
          "id": "bubble_" + d.id,
          "class": "bubble"

        });

      })
      .on("mouseover", function(d, i) {
        if(!self.selected) {
          showBubbleDetails(self, this, d)
        }
      })
      .on("mouseout", function(d, i) {
        if(!self.selected) {
          hideBubbleDetails(self, this, d)
        }
      })
      .on("click", function(d, i) {
        if(!self.selected) {
          self.currentSelection = this;
          self.selected = true;
          var counter = 0

          d.org.forEach(function(name){
            counter = counter + 1;
            d3.select("text#vc-title-" + counter).text(name);
            return true;
          });

          d3.selectAll(".bubble")
            .attr({
              "fill-opacity": 0.2,
            });
          d3.select(this).attr({
            "fill-opacity": 0.8,
          });

        } else {
          self.selected = false;
          d3.selectAll(".bubble").each(function(data){
            d3.select(this).attr({
              "fill-opacity": 0.8,
            });
          });

          self.hide_details(d, i, self.currentSelection);
          return self.show_details(d, i, this);
        }

      });

      // Total investment
      this.vis.append("text")
        .attr("x", 20)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "money")
        .attr("fill", "black");

      // Total investment
      this.vis.append("text")
        .attr("x", 900)
        .attr("y",500)
        .text("$0")
        .attr("class","system-font sum")
        .attr("id", "quantity")
        .attr("fill", "black");

      return this.circles.transition().duration(2000).attr("r", function(d) {
        return d.radius;
      });

    };

    function showBubbleDetails(inst, elem, data) {
      var counter = 0

      data.org.forEach(function(name){
        counter = counter + 1;
        d3.select("text#vc-title-" + counter).text(name);
        return true;
      });

      d3.select(elem).attr("fill-opacity", 0.8);

      return inst.show_details(data, 1, elem);

    }

    function hideBubbleDetails(inst, elem, data) {
      // TODO: mark previuosly on hover elem
      d3.selectAll(".vc-lable__text")
        .each(function(data){
            d3.select(this).text("");
        });

      return inst.hide_details(data, 1, elem);
    }

    BubbleChart.prototype.charge = function(d) {
      return -Math.pow(d.radius, 2.0) / 7 ;
    };

    BubbleChart.prototype.start = function() {
      return this.force = d3.layout.force().nodes(this.nodes).size([this.width, this.height]);
    };

    BubbleChart.prototype.display_by_group = function(list) {
      var self = this;

      var dic =  {
        "seed": ["Angel Round", "Seed Round"],
        "series-a": ["Series A"],
        "series-b": ["Series B", "Series C"],
        "series-d": ["Series D", "Series E", "Series F", "Series G"],
        "private": ["Private Equity"]
      }

      var group = [];

      list.forEach(function (item) {
        group = group.concat(dic[item]);
        return group;
      });

      this.force.gravity(this.layout_gravity)
        .charge(this.charge)
        .friction(0.9)
        .on("tick", function(e) {
          return self.circles
            .each(self.move_towards_target(
                e.alpha,
                function(d) {

                  if(group.indexOf(d.group) >= 0){
                    return self.center;
                  } else {
                    return self.off_screen;
                  }

                })
            )
            .attr("cx", function(d) {
              return d.x;
            })
            .attr("cy", function(d) {
              return d.y;
            });
      });

      var sum = 0;
      var count = 0;
      this.nodes.forEach( function (d) {

        if(group.indexOf(d.group) >= 0){
          count = count + 1;
          sum = sum + parseInt(d.value);
        }
      });

      d3.select("#money").text('$' + addScale(sum));
      d3.select("#quantity").text('#' + addCommas(count));
      return this.force.start();

    };

    BubbleChart.prototype.move_towards_target = function(alpha, target) {
      var self = this;

      return function(d) {
          d.x = d.x + (target(d).x - d.x) * (self.damper + 0.02) * alpha * 1.1;
          return d.y = d.y + (target(d).y - d.y) * (self.damper + 0.02) * alpha * 1.1;
      };

    };

    BubbleChart.prototype.show_details = function(data, i, element) {

      var content1, content2;
      d3.select(element).attr("stroke", "black");
      content1 = data.name;
      content2 = data.group + ", $" + (addScale(data.value));

      d3.select("text#company-title-2").text(content2);
      return d3.select("text#company-title-1").text(content1);

    };

    BubbleChart.prototype.hide_details = function(data, i, element) {
      d3.select(element).attr("stroke", (function(_this) {
        return function(d) {
          return d3.rgb(_this.colorRange(d.org.length)).darker();
        };
      })(this));
      return this.tooltip.hideTooltip();
    };

    BubbleChart.prototype.lables_placeholder = function(json) {

      var self = this;

      // Holdes the data
      var data = json;
      var startPointY = 50;

      function drawTitle(vis, x, y, text) {

        // Title
        vis.append("text")
          .attr("x", x)
          .attr("y",y)
          .text(text)
          .attr("class","title system-font")
          .attr("fill", "black");
      }

      function companySelector(element) {
        var content = element.textContent;
        var counter = 1;
        if(!self.investorSelected) {
          self.investorSelected = true;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                counter = counter + 1;
                d3.select(this).attr({
                  "fill-opacity": 1,
                  fill: self.fill_color(d.org.length)
                });
                self.show_details(data, counter, this);
              }
            });
        } else {

          self.investorSelected = false;
          d3.selectAll("circle")
            .each(function(data) {

              if(data.org.indexOf(content) >= 0){
                d3.select(this).attr({
                  "fill-opacity": 0.2,
                  fill: self.fill_color(d.org.length)
                });

              }
            });
        }
      }

      function generatelablesContainer(vis, data, css, itemId, x, y, clickExecutor) {

        var lablesContainer = vis
                        .selectAll("g." + css)
                        .data(data, function(d) {
                          return d.id;
                        })
                        .enter().append("g")
                        .attr("class",css);

        var currentY = y + 10,
            counter = 0;

        /*lablesContainer.append("title")
            .text(function(d) { return d.name; });*/

        lablesContainer.append("text")
            .attr("x", x)
            .each(function (d){
                counter = counter + 1;
                title_class_pos = "odd";
                if( counter % 2  == 0) {
                  title_class_pos = "even";
                }
                var tempY = currentY;
                currentY= currentY + 32;

                d3.select(this).attr({
                    y: currentY,
                    "class":  css + "__text" + " " + title_class_pos,
                    id: itemId + counter
                }).text("");
            })
            .on("click", function(d, i){

              if(clickExecutor !== 'undefined') {
                clickExecutor(this);
              }
            });
      }

      drawTitle(this.vis, 20, startPointY, "INVESTORS:");
      drawTitle(this.vis, 795, startPointY, "COMPANY:");
      generatelablesContainer(this.vis, data, "vc-lable","vc-title-", 25, startPointY);
      generatelablesContainer(this.vis, [{ id: 1},{ id:2 }], "company-lable","company-title-", 800, startPointY);

    }

    return BubbleChart;

  })();

  root = typeof exports !== "undefined" && exports !== null ? exports : this;

  $(function() {
    var chart, render_vis, render_lbl;
    var active_groups = ["seed", "series-a", "series-b", "series-d", "private"];
    var inactive_groups = [];
    chart = null;

    render_vis = function (data) {
      config = {
        width: 1040,
        height: 600,
        colorRange: {
          domain: [1, 3, 6, 9],
          //range: ["#143642", "#558C8C", "#F7941D", "#A8201A"]
          range: ["#6CD4FF", "#143642", "#BF4E30", "#A8201A"]
        }
      };
      chart = new BubbleChart("#viz", data, config);

      chart.start();
      return chart.display_by_group(active_groups);
    };

    render_lable = function(json) {
      return chart.lables_placeholder(json);
    }
    root.display_group = (function(_this) {
      return function(list) {
        return chart.display_by_group(list);
      };
    })(this);

    root.toggle_view = (function(_this) {
      return function(view_type) {
        var active_pos = active_groups.indexOf(view_type)

        if (active_pos >= 0) {
          inactive_groups.push(view_type);
          active_groups.splice(active_pos, 1);
        } else {
          inactive_groups.splice(inactive_groups.indexOf(view_type), 1);
          active_groups.push(view_type);
        }

        return root.display_group(active_groups);

      };
    })(this);

    // Render visualisation
    //var v = d3.csv("data/test.csv", render_vis);
    var v = d3.json("data/funding.json", function(data) {

      render_vis(data);
      // Render label
      d3.json("data/labels.json", render_lable);

    });

    return v;
  });

}).call(this);
<|endoftext|>


<commit_before>if (! window.AudioContext) {
	if (! window.webkitAudioContext) {
		alert('Could not get audio context! (Are you using IE?)');
	}
	window.AudioContext = window.webkitAudioContext;
}

var colors = {
	'EDM': '#C2C2C2',
	'House': '#EA8C00',
	'Drumstep': '#F12188',
	'Drum & Bass': '#F71A00',
	'Trance': '#0785E4',
	'Electro': '#E6CE00',
	'Glitch Hop': '#0B9753',
	'Hardcore': '#009800',
	'Nu Disco': '#1CABB1',
	'Dubstep': '#951EF5',
	'Trap': '#8C0F29',
	'Future Bass': '#B8B8FF'
};
var color;

var song;
var context = new AudioContext();
var audioBuffer;
var bufferSource;
var analyzer;
var scriptProcessor;
//var barWidth = 16;
var width = $(document).width() * 0.9;
var barCount = 80;
var barMargin = 4;
var barWidth = width / (barCount + barMargin * 2);
width -= width % (barWidth + barMargin * 2);
var spectrumSize = width / (barWidth + barMargin * 2); // the size of the visible spectrum
var spectrumStart = 5; // the first bin rendered in the spectrum
var height = width / 5;
var headMargin = 8;
var tailMargin = 8;
var marginDecay = 1.3;

var velMult = 0;

var amplitudeScalar = 5; // the multiplier for the particle system velocity
var ampLower = 4; // the lower bound for amplitude analysis (inclusive)
var ampUpper = 30; // the upper bound for amplitude analysis (exclusive)
var quadraticCurve = 1.5; // the power to raise velMult to after initial computation

// dudududududu
var red = 255;
var green = 0;
var blue = 0;
var stage = 0;
var cycleSpeed = 4;

var begun = false;
var ended = false;
var isPlaying = false;
var bufferInterval = 1024;
var started = 0;
var currentTime = 0;
var minProcessPeriod = 18; // ms between calls to the process function

var blockSize = 140;
var blockMargin = 15;
var blockWidthRatio = 0.82;
var blockHeightRatio = 0.93;

var lastMouseMove = Date.now();
var mouseSleepTime = 3000;
var textHidden = false;

$('#canvas').attr('width', width);
$('#canvas').attr('height', height + blockSize + 2 * blockMargin);
$('#songinfo').css('margin-top', -blockSize - blockMargin - 12);
$('#songinfo').css('margin-left', blockSize + blockMargin);
$('#songinfo').css('width', width - blockSize - blockMargin);
var ctx = $("#canvas").get()[0].getContext("2d");

function centerContent() {
	console.log($(document).width() + ', ' + $('.content').width() + ', ');
	$('.content').css('margin-top', ($(document).height() - $('.content').height()) / 2);
	$('.content').css('margin-left', ($(document).width() - $('.content').width()) / 2);
};

$(window).resize(function() {
	centerContent();
});

loadSong();
setupAudioNodes();
loadSound('music/' + song.getFileName()); // music file
centerContent();

if (song.getGenre() == 'ayy lmao') {
	$('.ayylmao').show();
	$('.kitty').css('margin-top', -blockSize + 4);
	$('.kitty').attr('height', blockSize);
}

$('html').mousemove(function(event) {
	if (textHidden) {
		$('.hide').show();
		textHidden = false;
	}
	lastMouseMove = Date.now();
});

function loadSong() {
	var songs = [];
	var count = 0;
	var loc = window.location.pathname;
	var prefix = 'http://' + window.location.hostname + loc.substring(0, loc.lastIndexOf('/'));
	var path = prefix + '/songs.csv';
	$.ajax({
		url:		path,
		success:	function(csv) {
						var lines = csv.split('\n');
						for (var i = 0; i < lines.length; i++) {
							try {
								var s = new Song(lines[i]);
								songs[s.getId()] = s;
								count = count + 1;
							} catch (ex) {} // not a song
						}
						songs.splice('undefined', 1);
					},
		async:		false
	});
	if (songName !== undefined) {
		song = songs[songName];
	} else {
		var keys = Object.keys(songs);
		var key = keys[Math.floor(Math.random() * count)];
		song = songs[key];
	}
	document.getElementById('artist').innerHTML = '???';
	document.getElementById('title').innerHTML = '???';
	document.title = '??? \u2014 ???';
	if (song != undefined) {
		var baseHeight = $('#artist').height();
		document.getElementById('artist').innerHTML = song.getArtist().toUpperCase();
		while ($('#artist').height() > baseHeight) {
			$('#artist').css('font-size', ($('#artist').css('font-size').replace('px', '') - 1) + 'px');
		}
		document.getElementById('title').innerHTML =
				(song.getLink() != null ? '' : '')
				+ song.getTitle().toUpperCase()
				+ (song.getLink() != null ? '' : '');
		document.title = song.getArtist() + ' \u2014 ' + song.getTitle();
		color = colors[song.getGenre()];
	}
	if (color == undefined) {
		color = colors['EDM']
	}

	if (!song || song.getGenre() != 'ayy lmao') {
		drawBlock();
	}
}

function drawBlock() {
	ctx.fillStyle = color;
	ctx.fillRect(0, height + blockMargin, blockSize, blockSize);
	var img = new Image();
	img.onload = function() {
		ctx.fillStyle = 'white';
		ctx.drawImage(
			img,
			blockSize * (1 - blockWidthRatio) / 2,
			height + blockMargin + (blockSize * (1 - blockHeightRatio) / 2),
			blockSize * blockWidthRatio,
			blockSize * blockHeightRatio
		);
	}
	var loc = window.location.pathname;
	var prefix = 'http://' + window.location.hostname + loc.substring(0, loc.lastIndexOf('/'));
	img.src = prefix + '/img/mcat.svg';
}

function setupAudioNodes() {
	scriptProcessor = context.createScriptProcessor(bufferInterval, 1, 1);
	scriptProcessor.connect(context.destination);

	analyzer = context.createAnalyser();
	analyzer.connect(scriptProcessor);
	analyzer.smoothingTimeConstant = 0.7;
	analyzer.minDecibels = -65;
	//analyzer.maxDecibels = -28;
	try {
		analyzer.fftSize = 8192; // ideal bin count
		console.log('Using fftSize of 8192 (woot!)');
	} catch (ex) {
		analyzer.fftSize = 2048; // this will work for most if not all systems
		console.log('Using fftSize of 2048');
	}

	bufferSource = context.createBufferSource();
	bufferSource.connect(analyzer);
	bufferSource.connect(context.destination);
}

$(document).keypress(function(event) {
	if (event.which == 80 || event.which == 112) {
		if (isPlaying) {
			bufferSource.stop();
			currentTime += Date.now() - started;
			velMult = 0;
		} else {
			var newSource = context.createBufferSource();
			newSource.buffer = bufferSource.buffer;
			bufferSource = newSource
			bufferSource.connect(analyzer);
			bufferSource.connect(context.destination);
			bufferSource.start(0, currentTime / 1000);
			started = Date.now();
		}
		isPlaying = !isPlaying;
	}
});

function loadSound(url) {
	var request = new XMLHttpRequest();
	request.open('GET', url, true);
	request.responseType = 'arraybuffer';

	request.onload = function() {
		context.decodeAudioData(request.response, function(buffer) {
			playSound(buffer);
		}, onError);
	}
	request.send();
}

function playSound(buffer) {
	bufferSource.buffer = buffer;
	bufferSource.start(0);
	$('#loading').hide();
	$('#pause-info').show();
	isPlaying = true;
	begun = true;
	started = Date.now();
}

function onError(e) {
	console.log(e);
}

var lastLowest = -1;

var lastProcess = Date.now();
scriptProcessor.onaudioprocess = function() {
	var now = Date.now();
	do { now = Date.now(); } while (now - lastProcess < minProcessPeriod);
	lastProcess = Date.now();

	if (started && !textHidden && Date.now() - lastMouseMove >= mouseSleepTime) {
		$('.hide').fadeOut(500);
		textHidden = true;
	}

	var array =  new Uint8Array(analyzer.frequencyBinCount);
	analyzer.getByteFrequencyData(array);
	ctx.clearRect(0, 0, width, height);
	if (song.getGenre() == 'ayy lmao') {
		switch (stage) {
			case 0:
				if (green < 255) green = Math.min(green + cycleSpeed, 255);
				else ++stage;
				break;
			case 1:
				if (red > 0) red = Math.max(red - cycleSpeed, 0);
				else ++stage;
				break;
			case 2:
				if (blue < 255) blue = Math.min(blue + cycleSpeed, 255);
				else ++stage;
				break;
			case 3:
				if (green > 0) green = Math.max(green - cycleSpeed, 0);
				else ++stage;
				break;
			case 4:
				if (red < 255) red = Math.min(red + cycleSpeed, 255);
				else ++stage;
				break;
			case 5:
				if (blue > 0) blue = Math.max(blue - cycleSpeed, 0);
				else ++stage;
				break;
		}
		if (stage > 5) stage = 0;
		color = 'rgb(' + red + ',' + green + ',' + blue + ')';
	}
	ctx.fillStyle = color; // bar color

	if (isPlaying) {
		var sum = 0;
		for (var i = ampLower; i < ampUpper; i++) {
			sum += array[i] / height;
		}
		// the next line effecitvely uses the weighted sum to generate a float between 0.0 and 1.0, 1 meaning all
		// amplitude points in the observed range are at 100% of their potential value
		velMult = sum / (ampUpper - ampLower);
		velMult = Math.pow(velMult, quadraticCurve);
		velMult *= amplitudeScalar;
	}

	drawSpectrum(array);
}

var lastSpectrum = [];
var prevPeak = -1;

function drawSpectrum(array) {
	if (isPlaying && lastSpectrum.length == 1) {
		lastSpectrum = array;
	}
	var lowest = height;
	for (var i = 0; i < spectrumSize; i++) {
		var abs = i + spectrumStart;
		if (array[i + abs] < lowest) {
			lowest = array[abs];
		}
	}
	lowest /= 2;
	if (lastLowest == -1) {
		lastLowest = lowest;
	} else if (lowest < lastLowest) {
		lastLowest -= Math.min(lastLowest - lowest, 1);
	} else {
		lastLowest += Math.min(lowest - lastLowest, 1);
	}
	for (var i = 0; i < spectrumSize; i++) {
		var abs = i + spectrumStart;
		if (array[abs] >= lastLowest) {
			array[abs] = height * ((array[abs] - lastLowest) / (height - lastLowest));
		} else {
			array[abs] = 0;
		}
	}

	values = [];

	for (var i = 0; i < spectrumSize; i++) {
		var abs = i + spectrumStart;
		if (begun) {
			if (i == 0) {
				var value = array[abs] / 255 * height;
			}
			else if (i == spectrumSize - 1) {
				var value = (array[abs - 1] + array[abs]) / 2  / 255 * height;
			}
			else {
				var value = (array[abs - 1] + array[abs] + array[abs + 1]) / 3  / 255 * height;
			}
			value = Math.min(value + 1, height);
		} else {
			value = 1;
		}
		// create linear slope at head and tail of spectrum
		if (i < headMargin) {
			value *= Math.pow(i + 1, marginDecay) / Math.pow(headMargin, marginDecay);
		} else if (spectrumSize - i <= tailMargin) {
			value *= Math.pow(spectrumSize - i, marginDecay) / Math.pow(tailMargin, marginDecay);
		}

		values[i] = Math.max(Math.pow(value / height, 2.5) * height, 1);
	}

	// drawing pass
	for (var i = 0; i < spectrumSize; i++) {
		var value = values[i];
		ctx.fillRect(i * (barWidth + barMargin * 2), height - value, barWidth, value, value);
	}
};
<commit_msg>Reduce severity of extreme margin weighting<commit_after>if (! window.AudioContext) {
	if (! window.webkitAudioContext) {
		alert('Could not get audio context! (Are you using IE?)');
	}
	window.AudioContext = window.webkitAudioContext;
}

var colors = {
	'EDM': '#C2C2C2',
	'House': '#EA8C00',
	'Drumstep': '#F12188',
	'Drum & Bass': '#F71A00',
	'Trance': '#0785E4',
	'Electro': '#E6CE00',
	'Glitch Hop': '#0B9753',
	'Hardcore': '#009800',
	'Nu Disco': '#1CABB1',
	'Dubstep': '#951EF5',
	'Trap': '#8C0F29',
	'Future Bass': '#B8B8FF'
};
var color;

var song;
var context = new AudioContext();
var audioBuffer;
var bufferSource;
var analyzer;
var scriptProcessor;
//var barWidth = 16;
var width = $(document).width() * 0.9;
var barCount = 80;
var barMargin = 4;
var barWidth = width / (barCount + barMargin * 2);
width -= width % (barWidth + barMargin * 2);
var spectrumSize = width / (barWidth + barMargin * 2); // the size of the visible spectrum
var spectrumStart = 5; // the first bin rendered in the spectrum
var height = width / 5;
var headMargin = 8;
var tailMargin = 8;
var marginDecay = 2;
var minMarginWeight = 0.3;
// margin weighting follows a quadratic slope passing through (0, minMarginWeight) and (marginSize, 1)
var headMarginSlope = (1 - minMarginWeight) / Math.pow(headMargin, marginDecay);
var tailMarginSlope = (1 - minMarginWeight) / Math.pow(tailMargin, marginDecay);

var velMult = 0;

var amplitudeScalar = 5; // the multiplier for the particle system velocity
var ampLower = 4; // the lower bound for amplitude analysis (inclusive)
var ampUpper = 30; // the upper bound for amplitude analysis (exclusive)
var quadraticCurve = 1.5; // the power to raise velMult to after initial computation

// dudududududu
var red = 255;
var green = 0;
var blue = 0;
var stage = 0;
var cycleSpeed = 4;

var begun = false;
var ended = false;
var isPlaying = false;
var bufferInterval = 1024;
var started = 0;
var currentTime = 0;
var minProcessPeriod = 18; // ms between calls to the process function

var blockSize = 140;
var blockMargin = 15;
var blockWidthRatio = 0.82;
var blockHeightRatio = 0.93;

var lastMouseMove = Date.now();
var mouseSleepTime = 3000;
var textHidden = false;

$('#canvas').attr('width', width);
$('#canvas').attr('height', height + blockSize + 2 * blockMargin);
$('#songinfo').css('margin-top', -blockSize - blockMargin - 12);
$('#songinfo').css('margin-left', blockSize + blockMargin);
$('#songinfo').css('width', width - blockSize - blockMargin);
var ctx = $("#canvas").get()[0].getContext("2d");

function centerContent() {
	console.log($(document).width() + ', ' + $('.content').width() + ', ');
	$('.content').css('margin-top', ($(document).height() - $('.content').height()) / 2);
	$('.content').css('margin-left', ($(document).width() - $('.content').width()) / 2);
};

$(window).resize(function() {
	centerContent();
});

loadSong();
setupAudioNodes();
loadSound('music/' + song.getFileName()); // music file
centerContent();

if (song.getGenre() == 'ayy lmao') {
	$('.ayylmao').show();
	$('.kitty').css('margin-top', -blockSize + 4);
	$('.kitty').attr('height', blockSize);
}

$('html').mousemove(function(event) {
	if (textHidden) {
		$('.hide').show();
		textHidden = false;
	}
	lastMouseMove = Date.now();
});

function loadSong() {
	var songs = [];
	var count = 0;
	var loc = window.location.pathname;
	var prefix = 'http://' + window.location.hostname + loc.substring(0, loc.lastIndexOf('/'));
	var path = prefix + '/songs.csv';
	$.ajax({
		url:		path,
		success:	function(csv) {
						var lines = csv.split('\n');
						for (var i = 0; i < lines.length; i++) {
							try {
								var s = new Song(lines[i]);
								songs[s.getId()] = s;
								count = count + 1;
							} catch (ex) {} // not a song
						}
						songs.splice('undefined', 1);
					},
		async:		false
	});
	if (songName !== undefined) {
		song = songs[songName];
	} else {
		var keys = Object.keys(songs);
		var key = keys[Math.floor(Math.random() * count)];
		song = songs[key];
	}
	document.getElementById('artist').innerHTML = '???';
	document.getElementById('title').innerHTML = '???';
	document.title = '??? \u2014 ???';
	if (song != undefined) {
		var baseHeight = $('#artist').height();
		document.getElementById('artist').innerHTML = song.getArtist().toUpperCase();
		while ($('#artist').height() > baseHeight) {
			$('#artist').css('font-size', ($('#artist').css('font-size').replace('px', '') - 1) + 'px');
		}
		document.getElementById('title').innerHTML =
				(song.getLink() != null ? '' : '')
				+ song.getTitle().toUpperCase()
				+ (song.getLink() != null ? '' : '');
		document.title = song.getArtist() + ' \u2014 ' + song.getTitle();
		color = colors[song.getGenre()];
	}
	if (color == undefined) {
		color = colors['EDM']
	}

	if (!song || song.getGenre() != 'ayy lmao') {
		drawBlock();
	}
}

function drawBlock() {
	ctx.fillStyle = color;
	ctx.fillRect(0, height + blockMargin, blockSize, blockSize);
	var img = new Image();
	img.onload = function() {
		ctx.fillStyle = 'white';
		ctx.drawImage(
			img,
			blockSize * (1 - blockWidthRatio) / 2,
			height + blockMargin + (blockSize * (1 - blockHeightRatio) / 2),
			blockSize * blockWidthRatio,
			blockSize * blockHeightRatio
		);
	}
	var loc = window.location.pathname;
	var prefix = 'http://' + window.location.hostname + loc.substring(0, loc.lastIndexOf('/'));
	img.src = prefix + '/img/mcat.svg';
}

function setupAudioNodes() {
	scriptProcessor = context.createScriptProcessor(bufferInterval, 1, 1);
	scriptProcessor.connect(context.destination);

	analyzer = context.createAnalyser();
	analyzer.connect(scriptProcessor);
	analyzer.smoothingTimeConstant = 0.7;
	analyzer.minDecibels = -65;
	//analyzer.maxDecibels = -28;
	try {
		analyzer.fftSize = 8192; // ideal bin count
		console.log('Using fftSize of 8192 (woot!)');
	} catch (ex) {
		analyzer.fftSize = 2048; // this will work for most if not all systems
		console.log('Using fftSize of 2048');
	}

	bufferSource = context.createBufferSource();
	bufferSource.connect(analyzer);
	bufferSource.connect(context.destination);
}

$(document).keypress(function(event) {
	if (event.which == 80 || event.which == 112) {
		if (isPlaying) {
			bufferSource.stop();
			currentTime += Date.now() - started;
			velMult = 0;
		} else {
			var newSource = context.createBufferSource();
			newSource.buffer = bufferSource.buffer;
			bufferSource = newSource
			bufferSource.connect(analyzer);
			bufferSource.connect(context.destination);
			bufferSource.start(0, currentTime / 1000);
			started = Date.now();
		}
		isPlaying = !isPlaying;
	}
});

function loadSound(url) {
	var request = new XMLHttpRequest();
	request.open('GET', url, true);
	request.responseType = 'arraybuffer';

	request.onload = function() {
		context.decodeAudioData(request.response, function(buffer) {
			playSound(buffer);
		}, onError);
	}
	request.send();
}

function playSound(buffer) {
	bufferSource.buffer = buffer;
	bufferSource.start(0);
	$('#loading').hide();
	$('#pause-info').show();
	isPlaying = true;
	begun = true;
	started = Date.now();
}

function onError(e) {
	console.log(e);
}

var lastLowest = -1;

var lastProcess = Date.now();
scriptProcessor.onaudioprocess = function() {
	var now = Date.now();
	do { now = Date.now(); } while (now - lastProcess < minProcessPeriod);
	lastProcess = Date.now();

	if (started && !textHidden && Date.now() - lastMouseMove >= mouseSleepTime) {
		$('.hide').fadeOut(500);
		textHidden = true;
	}

	var array =  new Uint8Array(analyzer.frequencyBinCount);
	analyzer.getByteFrequencyData(array);
	ctx.clearRect(0, 0, width, height);
	if (song.getGenre() == 'ayy lmao') {
		switch (stage) {
			case 0:
				if (green < 255) green = Math.min(green + cycleSpeed, 255);
				else ++stage;
				break;
			case 1:
				if (red > 0) red = Math.max(red - cycleSpeed, 0);
				else ++stage;
				break;
			case 2:
				if (blue < 255) blue = Math.min(blue + cycleSpeed, 255);
				else ++stage;
				break;
			case 3:
				if (green > 0) green = Math.max(green - cycleSpeed, 0);
				else ++stage;
				break;
			case 4:
				if (red < 255) red = Math.min(red + cycleSpeed, 255);
				else ++stage;
				break;
			case 5:
				if (blue > 0) blue = Math.max(blue - cycleSpeed, 0);
				else ++stage;
				break;
		}
		if (stage > 5) stage = 0;
		color = 'rgb(' + red + ',' + green + ',' + blue + ')';
	}
	ctx.fillStyle = color; // bar color

	if (isPlaying) {
		var sum = 0;
		for (var i = ampLower; i < ampUpper; i++) {
			sum += array[i] / height;
		}
		// the next line effecitvely uses the weighted sum to generate a float between 0.0 and 1.0, 1 meaning all
		// amplitude points in the observed range are at 100% of their potential value
		velMult = sum / (ampUpper - ampLower);
		velMult = Math.pow(velMult, quadraticCurve);
		velMult *= amplitudeScalar;
	}

	drawSpectrum(array);
}

var lastSpectrum = [];
var prevPeak = -1;

function drawSpectrum(array) {
	if (isPlaying && lastSpectrum.length == 1) {
		lastSpectrum = array;
	}
	var lowest = height;
	for (var i = 0; i < spectrumSize; i++) {
		var abs = i + spectrumStart;
		if (array[i + abs] < lowest) {
			lowest = array[abs];
		}
	}
	lowest /= 2;
	if (lastLowest == -1) {
		lastLowest = lowest;
	} else if (lowest < lastLowest) {
		lastLowest -= Math.min(lastLowest - lowest, 1);
	} else {
		lastLowest += Math.min(lowest - lastLowest, 1);
	}
	for (var i = 0; i < spectrumSize; i++) {
		var abs = i + spectrumStart;
		if (array[abs] >= lastLowest) {
			array[abs] = height * ((array[abs] - lastLowest) / (height - lastLowest));
		} else {
			array[abs] = 0;
		}
	}

	values = [];

	for (var i = 0; i < spectrumSize; i++) {
		var abs = i + spectrumStart;
		if (begun) {
			if (i == 0) {
				var value = array[abs] / 255 * height;
			}
			else if (i == spectrumSize - 1) {
				var value = (array[abs - 1] + array[abs]) / 2  / 255 * height;
			}
			else {
				var value = (array[abs - 1] + array[abs] + array[abs + 1]) / 3  / 255 * height;
			}
			value = Math.min(value + 1, height);
		} else {
			value = 1;
		}
		// create linear slope at head and tail of spectrum
		if (i < headMargin) {
			//value *= Math.pow(i + 1, marginDecay) / Math.pow(headMargin, marginDecay);
			value *= headMarginSlope * Math.pow(i + 1, marginDecay) + minMarginWeight;
		} else if (spectrumSize - i <= tailMargin) {
			//value *= Math.pow(spectrumSize - i, marginDecay) / Math.pow(tailMargin, marginDecay);
			value *= tailMarginSlope * Math.pow(spectrumSize - i, marginDecay) + minMarginWeight;
		}

		values[i] = Math.max(Math.pow(value / height, 2.5) * height, 1);
	}

	// drawing pass
	for (var i = 0; i < spectrumSize; i++) {
		var value = values[i];
		ctx.fillRect(i * (barWidth + barMargin * 2), height - value, barWidth, value, value);
	}
};
<|endoftext|>


<commit_before>// eslint-disable-next-line no-unused-vars
const viz = {
  scalingFactor: 2,
  circleRadius: 5,
  resizeTimer: null,

  init(nodes, links) {
    const { width, height } = this.getDimensions('visualization');
    const { canvas, context } = this.createCanvas();

    this.canvas = canvas;
    this.context = context;
    this.tooltip = document.getElementById('tooltip');
    this.circleRadius = this.circleRadius * this.scalingFactor;
    this.scale = (window.devicePixelRatio || 1) * this.scalingFactor;

    this.updateCanvas(width, height);
    this.draw(nodes, links);
    this.addListeners();
  },

  draw(nodes, links) {
    this.nodes = nodes;
    this.links = links;

    this.simulate();
    this.drawOnCanvas();
  },

  simulate() {
    this.simulation = this.simulateForce();
    this.simulation.tick();
  },

  simulateForce() {
    let simulation;

    if (!this.simulation) {
      simulation = d3.forceSimulation(this.nodes);
    } else {
      simulation = this.simulation;
      simulation.nodes(this.nodes);
    }

    const linkForce = d3.forceLink(this.links);
    linkForce.id((d) => d.hostname);
    linkForce.distance(100);
    simulation.force('link', linkForce);

    const centerForce = d3.forceCenter(this.width/2, this.height/2);
    centerForce.x(this.width/2);
    centerForce.y(this.height/2);
    simulation.force('center', centerForce);

    simulation.force('charge', d3.forceManyBody());
    simulation.force('collide', d3.forceCollide(50));
    simulation.alphaTarget(1);
    simulation.stop();

    return simulation;
  },

  createCanvas() {
    const base = document.getElementById('visualization');
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');

    base.appendChild(canvas);

    return {
      canvas,
      context
    };
  },

  updateCanvas(width, height) {
    this.width = width;
    this.height = height;
    this.canvas.setAttribute('width', width * this.scale);
    this.canvas.setAttribute('height', height * this.scale);
    this.canvas.style.width = `${width}px`;
    this.canvas.style.height = `${height}px`;
    this.context.scale(this.scale, this.scale);
  },

  getDimensions(id) {
    const element = document.getElementById(id);
    const { width, height } = element.getBoundingClientRect();

    return {
      width,
      height
    };
  },

  drawOnCanvas() {
    this.context.clearRect(0, 0, this.width, this.height);
    this.context.save();
    this.drawLinks();
    this.drawNodes();
    this.context.restore();
  },

  drawNodes() {
    for (const node of this.nodes) {
      this.context.beginPath();
      this.context.moveTo(node.x, node.y);
      if (node.firstParty) {
        this.drawFirstParty(node);
      } else {
        this.drawThirdParty(node);
      }
      this.context.fillStyle = 'white';
      this.context.closePath();
      this.context.fill();
    }
  },

  drawFirstParty(node) {
    this.context.arc(node.x, node.y, this.circleRadius, 0, 2 * Math.PI);
  },

  drawThirdParty(node) {
    // draw third party as equilateral triangle
    const deltaY = this.circleRadius / 2;
    const deltaX = deltaY * Math.sqrt(3);
    this.context.moveTo(node.x - deltaX, node.y + deltaY);
    this.context.lineTo(node.x, node.y - this.circleRadius);
    this.context.lineTo(node.x + deltaX, node.y + deltaY);
  },

  showTooltip(title, x, y) {
    this.tooltip.innerText = title;
    this.tooltip.style.left = `${x + this.circleRadius}px`;
    this.tooltip.style.top = `${y + this.circleRadius}px`;
    this.tooltip.style.display = 'block';
  },

  hideTooltip() {
    this.tooltip.style.display = 'none';
  },

  drawLinks() {
    this.context.beginPath();
    for (const d of this.links) {
      this.context.moveTo(d.source.x, d.source.y);
      this.context.lineTo(d.target.x, d.target.y);
    }
    this.context.closePath();
    this.context.strokeStyle = '#ccc';
    this.context.stroke();
  },

  isPointInsideCircle(x, y, cx, cy) {
    const dx = Math.abs(x - cx);
    const dy = Math.abs(y - cy);
    const d = dx*dx + dy*dy;
    const r = this.circleRadius;

    return d <= r*r;
  },

  getNodeAtCoordinates(x, y) {
    for (const node of this.nodes) {
      if (this.isPointInsideCircle(x, y, node.x, node.y)) {
        return node;
      }
    }
    return null;
  },

  getMousePosition(event) {
    const { left, top } = this.canvas.getBoundingClientRect();

    return {
      mouseX: event.clientX - left,
      mouseY: event.clientY - top
    };
  },

  addListeners() {
    this.addMouseMove();
    this.addWindowResize();
    this.addDrag();
  },

  addMouseMove() {
    this.canvas.addEventListener('mousemove', (event) => {
      const { mouseX, mouseY } = this.getMousePosition(event);
      const node = this.getNodeAtCoordinates(mouseX, mouseY);

      if (node) {
        this.showTooltip(node.hostname, mouseX, mouseY);
      } else {
        this.hideTooltip();
      }
    });
  },

  addWindowResize() {
    window.addEventListener('resize', () => {
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.onResize();
      }, 250);
    });
  },

  onResize() {
    this.canvas.style.width = 0;
    this.canvas.style.height = 0;

    const { width, height } = this.getDimensions('visualization');
    this.updateCanvas(width, height);
    this.draw(this.nodes, this.links);
  },

  addDrag() {
    const drag = d3.drag();
    drag.container(this.canvas);
    drag.subject(() => this.dragSubject());
    drag.on('start', () => this.dragStarted());
    drag.on('drag', () => this.dragged());
    drag.on('end', () => this.dragEnded());

    d3.select(this.canvas)
      .call(drag);
  },

  dragSubject() {
    return this.simulation.find(d3.event.x, d3.event.y);
  },

  dragStarted() {
    d3.event.subject.fx = d3.event.subject.x;
    d3.event.subject.fy = d3.event.subject.y;
  },

  dragged() {
    d3.event.subject.fx = d3.event.x;
    d3.event.subject.fy = d3.event.y;
  },

  dragEnded() {
    this.nodes.find((node) => {
      if (node.hostname === d3.event.subject.hostname) {
        node.x = d3.event.x;
        node.y = d3.event.y;
      }
    });
    this.draw(this.nodes, this.links);
  }
};
<commit_msg>d3 zoom added<commit_after>// eslint-disable-next-line no-unused-vars
const viz = {
  scalingFactor: 2,
  circleRadius: 5,
  resizeTimer: null,
  minZoom: 0.5,
  maxZoom: 1,

  init(nodes, links) {
    const { width, height } = this.getDimensions('visualization');
    const { canvas, context } = this.createCanvas();

    this.canvas = canvas;
    this.context = context;
    this.tooltip = document.getElementById('tooltip');
    this.circleRadius = this.circleRadius * this.scalingFactor;
    this.scale = (window.devicePixelRatio || 1) * this.scalingFactor;

    this.updateCanvas(width, height);
    this.draw(nodes, links);
    this.addListeners();
  },

  draw(nodes, links) {
    this.nodes = nodes;
    this.links = links;

    this.simulate();
    this.drawOnCanvas();
  },

  simulate() {
    this.simulation = this.simulateForce();
    this.simulation.tick();
  },

  simulateForce() {
    let simulation;

    if (!this.simulation) {
      simulation = d3.forceSimulation(this.nodes);
    } else {
      simulation = this.simulation;
      simulation.nodes(this.nodes);
    }

    const linkForce = d3.forceLink(this.links);
    linkForce.id((d) => d.hostname);
    linkForce.distance(100);
    simulation.force('link', linkForce);

    const centerForce = d3.forceCenter(this.width/2, this.height/2);
    centerForce.x(this.width/2);
    centerForce.y(this.height/2);
    simulation.force('center', centerForce);

    simulation.force('charge', d3.forceManyBody());
    simulation.force('collide', d3.forceCollide(50));
    simulation.alphaTarget(1);
    simulation.stop();

    return simulation;
  },

  createCanvas() {
    const base = document.getElementById('visualization');
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');

    base.appendChild(canvas);

    return {
      canvas,
      context
    };
  },

  updateCanvas(width, height) {
    this.width = width;
    this.height = height;
    this.canvas.setAttribute('width', width * this.scale);
    this.canvas.setAttribute('height', height * this.scale);
    this.canvas.style.width = `${width}px`;
    this.canvas.style.height = `${height}px`;
    this.context.scale(this.scale, this.scale);
  },

  getDimensions(id) {
    const element = document.getElementById(id);
    const { width, height } = element.getBoundingClientRect();

    return {
      width,
      height
    };
  },

  drawOnCanvas() {
    this.context.clearRect(0, 0, this.width, this.height);
    this.context.save();
    this.drawLinks();
    this.drawNodes();
    this.context.restore();
  },

  drawNodes() {
    for (const node of this.nodes) {
      this.context.beginPath();
      this.context.moveTo(node.x, node.y);
      if (node.firstParty) {
        this.drawFirstParty(node);
      } else {
        this.drawThirdParty(node);
      }
      this.context.fillStyle = 'white';
      this.context.closePath();
      this.context.fill();
    }
  },

  drawFirstParty(node) {
    this.context.arc(node.x, node.y, this.circleRadius, 0, 2 * Math.PI);
  },

  drawThirdParty(node) {
    // draw third party as equilateral triangle
    const deltaY = this.circleRadius / 2;
    const deltaX = deltaY * Math.sqrt(3);
    this.context.moveTo(node.x - deltaX, node.y + deltaY);
    this.context.lineTo(node.x, node.y - this.circleRadius);
    this.context.lineTo(node.x + deltaX, node.y + deltaY);
  },

  showTooltip(title, x, y) {
    this.tooltip.innerText = title;
    this.tooltip.style.left = `${x + this.circleRadius}px`;
    this.tooltip.style.top = `${y + this.circleRadius}px`;
    this.tooltip.style.display = 'block';
  },

  hideTooltip() {
    this.tooltip.style.display = 'none';
  },

  drawLinks() {
    this.context.beginPath();
    for (const d of this.links) {
      this.context.moveTo(d.source.x, d.source.y);
      this.context.lineTo(d.target.x, d.target.y);
    }
    this.context.closePath();
    this.context.strokeStyle = '#ccc';
    this.context.stroke();
  },

  isPointInsideCircle(x, y, cx, cy) {
    const dx = Math.abs(x - cx);
    const dy = Math.abs(y - cy);
    const d = dx*dx + dy*dy;
    const r = this.circleRadius;

    return d <= r*r;
  },

  getNodeAtCoordinates(x, y) {
    for (const node of this.nodes) {
      if (this.isPointInsideCircle(x, y, node.x, node.y)) {
        return node;
      }
    }
    return null;
  },

  getMousePosition(event) {
    const { left, top } = this.canvas.getBoundingClientRect();

    return {
      mouseX: event.clientX - left,
      mouseY: event.clientY - top
    };
  },

  addListeners() {
    this.addMouseMove();
    this.addWindowResize();
    // this.addDrag();
    this.addZoom();
  },

  addMouseMove() {
    this.canvas.addEventListener('mousemove', (event) => {
      const { mouseX, mouseY } = this.getMousePosition(event);
      const node = this.getNodeAtCoordinates(mouseX, mouseY);

      if (node) {
        this.showTooltip(node.hostname, mouseX, mouseY);
      } else {
        this.hideTooltip();
      }
    });
  },

  addWindowResize() {
    window.addEventListener('resize', () => {
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.onResize();
      }, 250);
    });
  },

  onResize() {
    this.canvas.style.width = 0;
    this.canvas.style.height = 0;

    const { width, height } = this.getDimensions('visualization');
    this.updateCanvas(width, height);
    this.draw(this.nodes, this.links);
  },

  addDrag() {
    const drag = d3.drag();
    drag.container(this.canvas);
    drag.subject(() => this.dragSubject());
    drag.on('start', () => this.dragStarted());
    drag.on('drag', () => this.dragged());
    drag.on('end', () => this.dragEnded());

    d3.select(this.canvas)
      .call(drag);
  },

  dragSubject() {
    return this.simulation.find(d3.event.x, d3.event.y);
  },

  dragStarted() {
    d3.event.subject.fx = d3.event.subject.x;
    d3.event.subject.fy = d3.event.subject.y;
  },

  dragged() {
    d3.event.subject.fx = d3.event.x;
    d3.event.subject.fy = d3.event.y;
  },

  dragEnded() {
    this.nodes.find((node) => {
      if (node.hostname === d3.event.subject.hostname) {
        node.x = d3.event.x;
        node.y = d3.event.y;
      }
    });
    this.draw(this.nodes, this.links);
  },

  addZoom() {
    const zoom = d3.zoom().scaleExtent([this.minZoom, this.maxZoom]);
    zoom.on('start', () => this.zoomStarted());
    zoom.on('zoom', () => this.zoomed());
    zoom.on('end', () => this.zoomEnded());
    this.transform = d3.zoomTransform(this);

    d3.select(this.canvas)
      .call(zoom);
  },

  zoomStarted() {
    // console.log('zoom start:', d3.event.transform);
  },

  zoomed() {
    // console.log('zoomed', d3.event.transform);
    // this.context.translate(this.transform.x, this.transform.y);
    // this.draw(this.nodes, this.links);
  },

  zoomEnded() {
    // console.log('zoom end', d3.event);
    this.context.translate(d3.event.transform.x, d3.event.transform.y);
    this.context.scale(d3.event.transform.k, d3.event.transform.k);
    this.draw(this.nodes, this.links);
  }
};
<|endoftext|>


<commit_before>// Imports
const { IS_PROD } = require('./globals')

function capitalize (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

function genTableHeader (headers) {
  const headerLine = []
  const dividerLine = []

  for (const header of headers) {
    headerLine.push(`${capitalize(header)}`)
    dividerLine.push('---')
  }

  return [
    genRowString(headerLine),
    genRowString(dividerLine),
  ]
}

function genTableRow (headers, row) {
  const headerRow = []

  for (const header of headers) {
    if (header === 'source' && IS_PROD) continue

    let value = row[header]

    if (['default', 'value', 'signature'].includes(header)) {
      value = `\`${row[header]}\``
    } else if (header === 'name') {
      value = `<div class="font-weight-bold text-mono">${row[header]}</div>`
    } else if (header === 'type') {
      value = `<div class="text-mono">${row[header]}</div>`
    }

    headerRow.push(value || '')
  }

  return genRowString(headerRow)
}

function genRowString (row) {
  return `| ${row.join(' | ')} |`
}

function genTable (tableData) {
  const headers = Object.keys(tableData[0])
  const table = genTableHeader(headers)

  for (const row of tableData) {
    table.push(genTableRow(headers, row))
  }

  return `${table.join('\n')}\n\n`
}

module.exports = genTable
<commit_msg>fix(api): remove source header in production<commit_after>// Imports
const { IS_PROD } = require('./globals')

function capitalize (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

function genTableHeader (headers) {
  const headerLine = []
  const dividerLine = []

  for (const header of headers) {
    if (header === 'source' && IS_PROD) continue

    headerLine.push(`${capitalize(header)}`)
    dividerLine.push('---')
  }

  return [
    genRowString(headerLine),
    genRowString(dividerLine),
  ]
}

function genTableRow (headers, row) {
  const headerRow = []

  for (const header of headers) {
    if (header === 'source' && IS_PROD) continue

    let value = row[header]

    if (['default', 'value', 'signature'].includes(header)) {
      value = `\`${row[header]}\``
    } else if (header === 'name') {
      value = `<div class="font-weight-bold text-mono">${row[header]}</div>`
    } else if (header === 'type') {
      value = `<div class="text-mono">${row[header]}</div>`
    }

    headerRow.push(value || '')
  }

  return genRowString(headerRow)
}

function genRowString (row) {
  return `| ${row.join(' | ')} |`
}

function genTable (tableData) {
  const headers = Object.keys(tableData[0])
  const table = genTableHeader(headers)

  for (const row of tableData) {
    table.push(genTableRow(headers, row))
  }

  return `${table.join('\n')}\n\n`
}

module.exports = genTable
<|endoftext|>