<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2014  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

// add drag&drop functionality
// Tested with Firefox and Chrome

// TODO: one can still drop images into a codecell, if the cell type is changed interactively

"using strict";

drag_and_drop = function() {

    /* the dragover event needs to be canceled to allow firing the drop event */
    window.addEventListener('dragover', function(event){
        if (event.preventDefault) { event.preventDefault(); };
    });

    /* allow dropping an image in notebook */
    window.addEventListener('drop', function(event){
        var cell = IPython.notebook.get_selected_cell();
        event.preventDefault();
        if(event.stopPropagation) {event.stopPropagation();}
        if (cell.mode == "command") {
            if (event.dataTransfer.items != undefined) {
                /* Chrome here */
                var items = event.dataTransfer.items;
                for (var i = 0; i < items.length; ++i) {
                    /* data coming from local file system, must be an image to allow dropping*/
                    if (items[i].kind == 'file' && items[i].type.indexOf('image/') !== -1) {
                        var blob = items[i].getAsFile();
                        if (blob.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                        var reader = new FileReader();
                        reader.onload = ( function(evt) {
                            var new_cell = IPython.notebook.insert_cell_below('markdown');
                            var str = '<embed src="' + evt.target.result + '"/>';
                            new_cell.set_text(str);
                            new_cell.rendered = false;
                            new_cell.read_only = true;
                            new_cell.render();
                            event.preventDefault();
                            } );
                        reader.readAsDataURL(blob);
                    } else if (items[i].kind == 'string') {
                        /* base64 data coming from browser */
                        var new_cell = IPython.notebook.insert_cell_below('markdown');
                        var data = event.dataTransfer.getData('text/plain');
                        if (data.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                        var str = '<embed  src="' + data + '"/>';
                        new_cell.set_text(str);
                        new_cell.rendered = false;
                        new_cell.read_only = true;
                        new_cell.render();
                        event.preventDefault();
                        return;
                    }
                }
            } else {
                /* Firefox here */
                var files = event.dataTransfer.files;
                if (files.length == 0) {
                    /* base64 data coming from browser */
                    var new_cell = IPython.notebook.insert_cell_below('markdown');
                    var data = event.dataTransfer.getData('text/plain');
                    if (data.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                    var str = '<embed  src="' + data + '"/>';
                    new_cell.set_text(str);
                    new_cell.rendered = false;
                    new_cell.read_only = true;
                    new_cell.render();
                    event.preventDefault();
                    return;
                    }
                /* data coming from local file system, must be an image to allow dropping*/
                for (var i=0; i < files.length; i++) {
                    var blob = event.dataTransfer.files[0];
                    if (blob.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                    if (blob.type.indexOf('image/') !== -1) {
                        var reader = new FileReader();
                            reader.onload = ( function(evt) {
                                var new_cell = IPython.notebook.insert_cell_below('markdown');
                                var str = '<embed  src="' + evt.target.result + '"/>';
                                new_cell.set_text(str);
                                new_cell.rendered = false;
                                new_cell.read_only = true;
                                new_cell.render();
                                event.preventDefault();
                                } );
                        reader.readAsDataURL(blob);
                    }
                }
            }
        }
    });

    /*
     * make sure we do not drop images into a codemirror text field
     */
    checktype = function(cm,evt) {
        if (event.dataTransfer.items != undefined)
            {
            evt.codemirrorIgnore = true;
            }
        var blob = evt.dataTransfer.files[0];

        if (blob.type.indexOf('image/') !== -1) {
            evt.codemirrorIgnore = true;
            }
    }

    create_cell = function (event,nbcell,nbindex) {
        var cell = nbcell.cell;
        if ((cell instanceof IPython.CodeCell)) {
            cell.code_mirror.on('drop', checktype);
        }
    };

    var cells = IPython.notebook.get_cells();
    for(var i in cells){
        var cell = cells[i];
        if ((cell instanceof IPython.CodeCell)) {
            cell.code_mirror.on('drop', checktype);
        }
    };

    $([IPython.events]).on('create.Cell',create_cell);
}();
<commit_msg>Use  instead of <embed><commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2014  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

// add drag&drop functionality
// Tested with Firefox and Chrome

// TODO: one can still drop images into a codecell, if the cell type is changed interactively

"using strict";

drag_and_drop = function() {

    /* the dragover event needs to be canceled to allow firing the drop event */
    window.addEventListener('dragover', function(event){
        if (event.preventDefault) { event.preventDefault(); };
    });

    /* allow dropping an image in notebook */
    window.addEventListener('drop', function(event){
        var cell = IPython.notebook.get_selected_cell();
        event.preventDefault();
        if(event.stopPropagation) {event.stopPropagation();}
        if (cell.mode == "command") {
            if (event.dataTransfer.items != undefined) {
                /* Chrome here */
                var items = event.dataTransfer.items;
                for (var i = 0; i < items.length; ++i) {
                    /* data coming from local file system, must be an image to allow dropping*/
                    if (items[i].kind == 'file' && items[i].type.indexOf('image/') !== -1) {
                        var blob = items[i].getAsFile();
                        if (blob.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                        var reader = new FileReader();
                        reader.onload = ( function(evt) {
                            var new_cell = IPython.notebook.insert_cell_below('markdown');
                            var str = '';
                            new_cell.set_text(str);
                            new_cell.rendered = false;
                            new_cell.read_only = true;
                            new_cell.render();
                            event.preventDefault();
                            } );
                        reader.readAsDataURL(blob);
                    } else if (items[i].kind == 'string') {
                        /* base64 data coming from browser */
                        var new_cell = IPython.notebook.insert_cell_below('markdown');
                        var data = event.dataTransfer.getData('text/plain');
                        if (data.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                        var str = '';
                        new_cell.set_text(str);
                        new_cell.rendered = false;
                        new_cell.read_only = true;
                        new_cell.render();
                        event.preventDefault();
                        return;
                    }
                }
            } else {
                /* Firefox here */
                var files = event.dataTransfer.files;
                if (files.length == 0) {
                    /* base64 data coming from browser */
                    var new_cell = IPython.notebook.insert_cell_below('markdown');
                    var data = event.dataTransfer.getData('text/plain');
                    if (data.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                    var str = '';
                    new_cell.set_text(str);
                    new_cell.rendered = false;
                    new_cell.read_only = true;
                    new_cell.render();
                    event.preventDefault();
                    return;
                    }
                /* data coming from local file system, must be an image to allow dropping*/
                for (var i=0; i < files.length; i++) {
                    var blob = event.dataTransfer.files[0];
                    if (blob.size > 100000 ) { alert('Size exceeds 100K, not reccomended'); }
                    if (blob.type.indexOf('image/') !== -1) {
                        var reader = new FileReader();
                            reader.onload = ( function(evt) {
                                var new_cell = IPython.notebook.insert_cell_below('markdown');
                                var str = '';
                                new_cell.set_text(str);
                                new_cell.rendered = false;
                                new_cell.read_only = true;
                                new_cell.render();
                                event.preventDefault();
                                } );
                        reader.readAsDataURL(blob);
                    }
                }
            }
        }
    });

    /*
     * make sure we do not drop images into a codemirror text field
     */
    checktype = function(cm,evt) {
        if (event.dataTransfer.items != undefined)
            {
            evt.codemirrorIgnore = true;
            }
        var blob = evt.dataTransfer.files[0];

        if (blob.type.indexOf('image/') !== -1) {
            evt.codemirrorIgnore = true;
            }
    }

    create_cell = function (event,nbcell,nbindex) {
        var cell = nbcell.cell;
        if ((cell instanceof IPython.CodeCell)) {
            cell.code_mirror.on('drop', checktype);
        }
    };

    var cells = IPython.notebook.get_cells();
    for(var i in cells){
        var cell = cells[i];
        if ((cell instanceof IPython.CodeCell)) {
            cell.code_mirror.on('drop', checktype);
        }
    };

    $([IPython.events]).on('create.Cell',create_cell);
}();
<|endoftext|>


<commit_before>import mean from "./mean";
import sampleVariance from "./sample_variance";

/**
 * This is to compute [two sample t-test](http://en.wikipedia.org/wiki/Student's_t-test).
 * Tests whether "mean(X)-mean(Y) = difference", (
 * in the most common case, we often have `difference == 0` to test if two samples
 * are likely to be taken from populations with the same mean value) with
 * no prior knowledge on standard deviations of both samples
 * other than the fact that they have the same standard deviation.
 *
 * Usually the results here are used to look up a
 * [p-value](http://en.wikipedia.org/wiki/P-value), which, for
 * a certain level of significance, will let you determine that the
 * null hypothesis can or cannot be rejected.
 *
 * `diff` can be omitted if it equals 0.
 *
 * [This is used to confirm or deny](http://www.monarchlab.org/Lab/Research/Stats/2SampleT.aspx)
 * a null hypothesis that the two populations that have been sampled into
 * `sampleX` and `sampleY` are equal to each other.
 *
 * @param {Array<number>} sampleX a sample as an array of numbers
 * @param {Array<number>} sampleY a sample as an array of numbers
 * @param {number} [difference=0]
 * @returns {number|null} test result
 *
 * @example
 * tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6], 0); // => -2.1908902300206643
 */
function tTestTwoSample(sampleX, sampleY, difference) {
    const n = sampleX.length;
    const m = sampleY.length;

    // If either sample doesn't actually have any values, we can't
    // compute this at all, so we return `null`.
    if (!n || !m) {
        return null;
    }

    // default difference (mu) is zero
    if (!difference) {
        difference = 0;
    }

    const meanX = mean(sampleX);
    const meanY = mean(sampleY);
    const sampleVarianceX = sampleVariance(sampleX);
    const sampleVarianceY = sampleVariance(sampleY);

    if (
        typeof meanX === "number" &&
        typeof meanY === "number" &&
        typeof sampleVarianceX === "number" &&
        typeof sampleVarianceY === "number"
    ) {
        const weightedVariance =
            ((n - 1) * sampleVarianceX + (m - 1) * sampleVarianceY) /
            (n + m - 2);

        return (
            (meanX - meanY - difference) /
            Math.sqrt(weightedVariance * (1 / n + 1 / m))
        );
    }
}

export default tTestTwoSample;
<commit_msg>docs: Modify t-test doc text and link (#564)<commit_after>import mean from "./mean";
import sampleVariance from "./sample_variance";

/**
 * This is to compute [two sample t-test](http://en.wikipedia.org/wiki/Student's_t-test).
 * Tests whether "mean(X)-mean(Y) = difference", (
 * in the most common case, we often have `difference == 0` to test if two samples
 * are likely to be taken from populations with the same mean value) with
 * no prior knowledge on standard deviations of both samples
 * other than the fact that they have the same standard deviation.
 *
 * Usually the results here are used to look up a
 * [p-value](http://en.wikipedia.org/wiki/P-value), which, for
 * a certain level of significance, will let you determine that the
 * null hypothesis can or cannot be rejected.
 *
 * `diff` can be omitted if it equals 0.
 *
 * [This is used to reject](https://en.wikipedia.org/wiki/Exclusion_of_the_null_hypothesis)
 * a null hypothesis that the two populations that have been sampled into
 * `sampleX` and `sampleY` are equal to each other.
 *
 * @param {Array<number>} sampleX a sample as an array of numbers
 * @param {Array<number>} sampleY a sample as an array of numbers
 * @param {number} [difference=0]
 * @returns {number|null} test result
 *
 * @example
 * tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6], 0); // => -2.1908902300206643
 */
function tTestTwoSample(sampleX, sampleY, difference) {
    const n = sampleX.length;
    const m = sampleY.length;

    // If either sample doesn't actually have any values, we can't
    // compute this at all, so we return `null`.
    if (!n || !m) {
        return null;
    }

    // default difference (mu) is zero
    if (!difference) {
        difference = 0;
    }

    const meanX = mean(sampleX);
    const meanY = mean(sampleY);
    const sampleVarianceX = sampleVariance(sampleX);
    const sampleVarianceY = sampleVariance(sampleY);

    if (
        typeof meanX === "number" &&
        typeof meanY === "number" &&
        typeof sampleVarianceX === "number" &&
        typeof sampleVarianceY === "number"
    ) {
        const weightedVariance =
            ((n - 1) * sampleVarianceX + (m - 1) * sampleVarianceY) /
            (n + m - 2);

        return (
            (meanX - meanY - difference) /
            Math.sqrt(weightedVariance * (1 / n + 1 / m))
        );
    }
}

export default tTestTwoSample;
<|endoftext|>


<commit_before>AppVersionProxy = {
  getVersionNumber: function (successCallback, failCallback, args) {
    var version = Windows.ApplicationModel.Package.current.id.version;
    successCallback([version.major, version.minor, version.build, version.revision].join('.'));
  },
  getAppName: function (successCallback, failCallback, args) {
    var name = Windows.ApplicationModel.Package.current.displayName;
    successCallback(name);
  },
  getPackageName: function (successCallback, failCallback, args) {
    var name = Windows.ApplicationModel.Package.current.id.name;
    successCallback(name);
  },
  getVersionCode: function (successCallback, failCallback, args) {
    var build = Windows.ApplicationModel.Package.current.id.version.build;
    successCallback(build);
  }
};
cordova.commandProxy.add("AppVersion", AppVersionProxy);
<commit_msg>Fallback for UWA on Windows Phone 8.1<commit_after>AppVersionProxy = {
  getVersionNumber: function (successCallback, failCallback, args) {
    var version = Windows.ApplicationModel.Package.current.id.version;
    successCallback([version.major, version.minor, version.build, version.revision].join('.'));
  },
  getAppName: function (successCallback, failCallback, args) {
    if(Windows.ApplicationModel.Package.current && Windows.ApplicationModel.Package.current.displayName){
      var name = Windows.ApplicationModel.Package.current.displayName;
      successCallback(name);
    } else {
      Windows.ApplicationModel.Package.current.installedLocation.getFileAsync("AppxManifest.xml").then(function (file) {
          Windows.Data.Xml.Dom.XmlDocument.loadFromFileAsync(file).then(function (xdoc) {
              var displayName = xdoc.getElementsByTagName("DisplayName");
              if (displayName && displayName.length === 1) {
                  var name = displayName[0].innerText;
                  successCallback(name);
              } else {
                  (failCallback || function(){})({ code: -1, message: "ERR_DISPLAY_NAME_NOT_FOUND" });
              }
          }, (failCallback || function(){}));
      }, (failCallback || function(){}));
    }
  },
  getPackageName: function (successCallback, failCallback, args) {
    var name = Windows.ApplicationModel.Package.current.id.name;
    successCallback(name);
  },
  getVersionCode: function (successCallback, failCallback, args) {
    var build = Windows.ApplicationModel.Package.current.id.version.build;
    successCallback(build);
  }
};
cordova.commandProxy.add("AppVersion", AppVersionProxy);
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/*
 * IMPORTANT: This file was auto-generated by "grunt generate-config". Please do not modify this directly. Instead
 * please modify kite/package.json to control dependencies.
 *
 * RequireJS configuration file for the kite sim.
 * Paths are relative to the location of this file.
 */

require.config( {

  deps: [ 'kite-tests' ],

  paths: {

    // Third-party libs
    text: '../../sherpa/lib/text-2.0.12',

    // PhET plugins
    audio: '../../chipper/js/requirejs-plugins/audio',
    image: '../../chipper/js/requirejs-plugins/image',
    mipmap: '../../chipper/js/requirejs-plugins/mipmap',
    string: '../../chipper/js/requirejs-plugins/string',
    ifphetio: '../../chipper/js/requirejs-plugins/ifphetio',

    // PhET libs, uppercase names to identify them in require.js imports.
    // IMPORTANT: DO NOT modify. This file is auto-generated. See documentation at the top.
    AXON: '../../axon/js',
    BRAND: '../../brand/' + phet.chipper.brand + '/js',
    DOT: '../../dot/js',
    JOIST: '../../joist/js',
    KITE: '.',
    PHETCOMMON: '../../phetcommon/js',
    PHET_CORE: '../../phet-core/js',
    PHET_IO: '../../phet-io/js',
    REPOSITORY: '..',
    SCENERY: '../../scenery/js',
    SCENERY_PHET: '../../scenery-phet/js',
    SUN: '../../sun/js',
    TANDEM: '../../tandem/js'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()
} );
<commit_msg>Added tambo dependency, see https://github.com/phetsims/joist/issues/497<commit_after>// Copyright 2018, University of Colorado Boulder

/*
 * IMPORTANT: This file was auto-generated by "grunt generate-config". Please do not modify this directly. Instead
 * please modify kite/package.json to control dependencies.
 *
 * RequireJS configuration file for the kite sim.
 * Paths are relative to the location of this file.
 */

require.config( {

  deps: [ 'kite-tests' ],

  paths: {

    // Third-party libs
    text: '../../sherpa/lib/text-2.0.12',

    // PhET plugins
    audio: '../../chipper/js/requirejs-plugins/audio',
    image: '../../chipper/js/requirejs-plugins/image',
    mipmap: '../../chipper/js/requirejs-plugins/mipmap',
    string: '../../chipper/js/requirejs-plugins/string',
    ifphetio: '../../chipper/js/requirejs-plugins/ifphetio',

    // PhET libs, uppercase names to identify them in require.js imports.
    // IMPORTANT: DO NOT modify. This file is auto-generated. See documentation at the top.
    AXON: '../../axon/js',
    BRAND: '../../brand/' + phet.chipper.brand + '/js',
    DOT: '../../dot/js',
    JOIST: '../../joist/js',
    KITE: '.',
    PHETCOMMON: '../../phetcommon/js',
    PHET_CORE: '../../phet-core/js',
    PHET_IO: '../../phet-io/js',
    REPOSITORY: '..',
    SCENERY: '../../scenery/js',
    SCENERY_PHET: '../../scenery-phet/js',
    SUN: '../../sun/js',
    TAMBO: '../../tambo/js',
    TANDEM: '../../tandem/js'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()
} );
<|endoftext|>


<commit_before>'use strict';

var notifier = require('node-notifier');
var argv = require('yargs').argv;
var path = require('path');

module.exports = (function () {
    var projectPath = "./"; // path for the source files
    var assetPath = projectPath + "assets/"; // path for fractal assets such as images, icons and more
    var webPath = projectPath + ""; // path for the website - usually path to livereload views, and used for distPath
    var vendorPath = projectPath + "node_modules/"; // path for vendor scripts
    var distPath = webPath + "dist/"; // path for production files
    var cleanPaths = [distPath]; // files/folders to be removed with "clean"-task
    var faviconsPath = projectPath + "/favicons";

    /*
     * App manifest and favicon variables
     */
    var appName = "Novicell Frontend"; // name for webapp
    var appColor = "#ffffff"; // color for webapp icons
    var appDescription = "Novicell Progressive WebApp";

    return {
        // ------------- Bundles -------------
        bundles: [
            {
                name: 'vendor',
                ignorePlugins: ['jscs', 'jshint', 'watch', 'babel'], // add 'minify', to ignore minifaction on a bundle
                scripts: [
                    vendorPath + "svg4everybody/dist/svg4everybody.js",
                    vendorPath + "validate/dist/validate.js",
                    vendorPath + "vanilla-text-mask/dist/vanillaTextMask.js",
                    vendorPath + "priority-nav/dist/priority-nav.js",
                    vendorPath + "novicell-debounce/js/novicell.debounce.js",
                    vendorPath + "novicell-lazyload/js/novicell.dynamic-image.js",
                    vendorPath + "novicell-lazyload/js/lazy-images.js",
                    vendorPath + "lazysizes/lazysizes.js",
                    vendorPath + "flickity/dist/flickity.pkgd.js",
                    vendorPath + "scrollprogress/dist/scrollProgress.js",
		            vendorPath + "novicell-cookie-info/js/novicell.cookieinfo.js"
                ]
            },
            {
                name: 'master',
                scripts: [
                    assetPath + "scripts/components/**/*.js",
                    projectPath + "patterns/**/*.js",
                    assetPath + "scripts/master.js"
                ],
                styles: [
                    projectPath + "patterns/_base/master.css"
                ],
                images: [ assetPath + "images/**/*.{jpg,png,svg,gif}"]
            },
            {
                name: "icons",
                icons: [ assetPath + "icons/**/*.svg" ]
            }
        ],

        // ------------- Styles -------------
        stylesDist: distPath + "css",

        // ------------- Scripts -------------
        scriptsDist: distPath + "scripts",

        // ------------- Icons ---------------
        iconsDist: distPath + "icons/",

        // ------------- Fonts -------------
        fontsDist: distPath + "fonts",

        // ------------- Images -------------
        imagesDist: distPath + "images",

        // ------------- Livereload ---------
        livereloadPort: 35729,
        livereloadPaths: [
            distPath + "**/*.*",
            webPath + "Views/**/*.cshtml", // Umbraco, Sitecore
            webPath + "Files/Templates/Designs/**/*.cshtml", // Dynamicweb
            webPath + "**/*.php" // Wordpress, Drupal
        ],

        // ------------- Watch -------------
        watchImages: [ assetPath + 'images/**/*' ],
        watchIcons: [ assetPath + 'icons/*' ],
        watchFonts: [ assetPath + 'fonts/*' ],
        watchScripts: [
            assetPath + 'scripts/**/*.js',
            projectPath + "/patterns/**/*.js"
        ],
        watchStyles: [
            projectPath + "/patterns/**/*.css"
        ],

        // ------------- Deploy task --------
        deployHost: "",
        deployUser: "",
        deployPass: "",
        deployDest: "/public_html/",
        deployGlobs: [ distPath + '**' ],

        // ------------- Copy on build --------
        buildCopy: [{
            from: assetPath + "fonts/**/*",
            to: distPath  + "fonts"
        }],

        // ------------- Tasks -------------
        loadTasks: [
            "styles", "scripts", "images", "icons", "copy", "build", "favicons", "watch", "deploy", "fractal"
        ],
        buildTasks: [
            "styles", "scripts", "images", "icons", "copy"
        ],

        // ------------- Return Paths -------------
        projectPath: projectPath,
        vendorPath: vendorPath,
        cleanPaths: cleanPaths,
        distPath: distPath,
        assetPath: assetPath,
        webPath: webPath,
        faviconsPath: faviconsPath,

        // ------------- Return Variables -------------
        appName: appName,
        appColor: appColor,
        appDescription: appDescription,

        // ---------- Errorhandler ------
        errorHandler: function(taskName)
        {
            return function (e) {
                notifier.notify({
                    'title': taskName,
                    'message': 'An error occured in the ' + e.plugin + ' plugin.'
                });
                console.error(e.message);
                this.emit('end');
            };
        }
    }
})();
<commit_msg>BuildCopy for favicon.ico<commit_after>'use strict';

var notifier = require('node-notifier');
var argv = require('yargs').argv;
var path = require('path');

module.exports = (function () {
    var projectPath = "./"; // path for the source files
    var assetPath = projectPath + "assets/"; // path for fractal assets such as images, icons and more
    var webPath = projectPath + ""; // path for the website - usually path to livereload views, and used for distPath
    var vendorPath = projectPath + "node_modules/"; // path for vendor scripts
    var distPath = webPath + "dist/"; // path for production files
    var cleanPaths = [distPath]; // files/folders to be removed with "clean"-task
    var faviconsPath = projectPath + "/favicons";

    /*
     * App manifest and favicon variables
     */
    var appName = "Novicell Frontend"; // name for webapp
    var appColor = "#ffffff"; // color for webapp icons
    var appDescription = "Novicell Progressive WebApp";

    return {
        // ------------- Bundles -------------
        bundles: [
            {
                name: 'vendor',
                ignorePlugins: ['jscs', 'jshint', 'watch', 'babel'], // add 'minify', to ignore minifaction on a bundle
                scripts: [
                    vendorPath + "svg4everybody/dist/svg4everybody.js",
                    vendorPath + "validate/dist/validate.js",
                    vendorPath + "vanilla-text-mask/dist/vanillaTextMask.js",
                    vendorPath + "priority-nav/dist/priority-nav.js",
                    vendorPath + "novicell-debounce/js/novicell.debounce.js",
                    vendorPath + "novicell-lazyload/js/novicell.dynamic-image.js",
                    vendorPath + "novicell-lazyload/js/lazy-images.js",
                    vendorPath + "lazysizes/lazysizes.js",
                    vendorPath + "flickity/dist/flickity.pkgd.js",
                    vendorPath + "scrollprogress/dist/scrollProgress.js",
		            vendorPath + "novicell-cookie-info/js/novicell.cookieinfo.js"
                ]
            },
            {
                name: 'master',
                scripts: [
                    assetPath + "scripts/components/**/*.js",
                    projectPath + "patterns/**/*.js",
                    assetPath + "scripts/master.js"
                ],
                styles: [
                    projectPath + "patterns/_base/master.css"
                ],
                images: [ assetPath + "images/**/*.{jpg,png,svg,gif}"]
            },
            {
                name: "icons",
                icons: [ assetPath + "icons/**/*.svg" ]
            }
        ],

        // ------------- Styles -------------
        stylesDist: distPath + "css",

        // ------------- Scripts -------------
        scriptsDist: distPath + "scripts",

        // ------------- Icons ---------------
        iconsDist: distPath + "icons/",

        // ------------- Fonts -------------
        fontsDist: distPath + "fonts",

        // ------------- Images -------------
        imagesDist: distPath + "images",

        // ------------- Livereload ---------
        livereloadPort: 35729,
        livereloadPaths: [
            distPath + "**/*.*",
            webPath + "Views/**/*.cshtml", // Umbraco, Sitecore
            webPath + "Files/Templates/Designs/**/*.cshtml", // Dynamicweb
            webPath + "**/*.php" // Wordpress, Drupal
        ],

        // ------------- Watch -------------
        watchImages: [ assetPath + 'images/**/*' ],
        watchIcons: [ assetPath + 'icons/*' ],
        watchFonts: [ assetPath + 'fonts/*' ],
        watchScripts: [
            assetPath + 'scripts/**/*.js',
            projectPath + "/patterns/**/*.js"
        ],
        watchStyles: [
            projectPath + "/patterns/**/*.css"
        ],

        // ------------- Deploy task --------
        deployHost: "",
        deployUser: "",
        deployPass: "",
        deployDest: "/public_html/",
        deployGlobs: [ distPath + '**' ],

        // ------------- Copy on build --------
        buildCopy: [
            {
                from: assetPath + "fonts/**/*",
                to: distPath  + "fonts"
            },
            {
                from: faviconsPath + "/favicon.ico",
                to: projectPath
            }
        ],

        // ------------- Tasks -------------
        loadTasks: [
            "styles", "scripts", "images", "icons", "copy", "build", "favicons", "watch", "deploy", "fractal"
        ],
        buildTasks: [
            "styles", "scripts", "images", "icons", "copy"
        ],

        // ------------- Return Paths -------------
        projectPath: projectPath,
        vendorPath: vendorPath,
        cleanPaths: cleanPaths,
        distPath: distPath,
        assetPath: assetPath,
        webPath: webPath,
        faviconsPath: faviconsPath,

        // ------------- Return Variables -------------
        appName: appName,
        appColor: appColor,
        appDescription: appDescription,

        // ---------- Errorhandler ------
        errorHandler: function(taskName)
        {
            return function (e) {
                notifier.notify({
                    'title': taskName,
                    'message': 'An error occured in the ' + e.plugin + ' plugin.'
                });
                console.error(e.message);
                this.emit('end');
            };
        }
    }
})();
<|endoftext|>


<commit_before>/**
 *
 * Copyright 2016, Institute for Systems Biology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

var MAX_URL_LEN = 2000;

define(['jquery', 'tree_graph', 'stack_bar_chart', 'draw_parsets'],
function($, tree_graph, stack_bar_chart, draw_parsets) {

    var tree_graph_obj = Object.create(tree_graph, {});
    var parsets_obj = Object.create(draw_parsets, {});

    var clin_tree_attr = {
        Disease_Code: 'Disease Code',
        vital_status: 'Vital Status',
        SampleTypeCode: 'Sample Type',
        tumor_tissue_site: 'Tumor Tissue Site',
        gender: 'Gender',
        age_at_initial_pathologic_diagnosis: 'Age at Initial Pathologic Diagnosis'
    };

    var user_data_attr = {
        user_project: 'Project',
        user_study: 'Study'
    };

    return  {

        filter_data_for_clin_trees: function(attr_counts, these_attr) {
            var filtered_clin_trees = {};
            var attr_counts_clin_trees = null;
            var filters = this.format_filters();
            var tree_attr_map = {};

            Object.keys(these_attr).map(function(attr){
                tree_attr_map[attr] = 1;
            });
            for(var i in filters) {
                if(filters.hasOwnProperty(i)) {
                    var fname = (i.indexOf(":") >= 0) ? i.split(/:/)[1] : i;
                    if (tree_attr_map[fname]) {
                        if (!filtered_clin_trees[fname]) {
                            filtered_clin_trees[fname] = {};
                        }
                        filters[i].map(function(val){
                            filtered_clin_trees[fname][val] = 1;
                        });
                    }
                }
            }
            if(Object.keys(filtered_clin_trees).length > 0) {
                attr_counts_clin_trees = JSON.parse(JSON.stringify(attr_counts));
                for(var i=0; i < attr_counts_clin_trees.length; i++) {
                    if(filtered_clin_trees[attr_counts_clin_trees[i].name]) {
                        attr_counts_clin_trees[i].total = 0;
                        var new_values = [];
                        for(var j=0; j < attr_counts_clin_trees[i].values.length; j++) {
                            if(filtered_clin_trees[attr_counts_clin_trees[i].name][attr_counts_clin_trees[i].values[j].value]) {
                                new_values.push(attr_counts_clin_trees[i].values[j]);
                                attr_counts_clin_trees[i].total += attr_counts_clin_trees[i].values[j].count;
                            }
                        }
                        attr_counts_clin_trees[i].values = new_values;
                    }
                }
            }
            return (attr_counts_clin_trees || attr_counts);
        },

        update_counts_parsets_direct: function(filters) {

            $('.clinical-trees .spinner').show();
            $('.user-data-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            var context = this;

            attr_counts = metadata_counts['count'];

            $('#isb-cgc-data-total-samples').html(metadata_counts['total']);
            $('#isb-cgc-data-total-participants').html(metadata_counts['cases']);
            $('#user-data-total-samples').html(user_data && metadata_counts['user_data_total'] !== null ? metadata_counts['user_data_total'] : "NA");
            $('#user-data-total-participants').html(user_data && metadata_counts['user_data_participants'] !== null ? metadata_counts['user_data_participants'] : "NA");

            this.update_filter_counts(attr_counts);
            // If there were filters, we need to adjust their counts so the barchart reflects what
            // was actually filtered
            var filters = this.format_filters();
            var clin_tree_attr_counts = Object.keys(filters).length > 0 ? this.filter_data_for_clin_trees(attr_counts, clin_tree_attr) : attr_counts;
            tree_graph_obj.draw_trees(clin_tree_attr_counts,clin_tree_attr,'#isb-cgc-tree-graph-clinical');

            if (metadata_counts.hasOwnProperty('items')) {
                var features = [
                    'cnvrPlatform',
                    'DNAseq_data',
                    'methPlatform',
                    'gexpPlatform',
                    'mirnPlatform',
                    'rppaPlatform'
                ];

                var plot_features = [
                    context.get_readable_name(features[0]),
                    context.get_readable_name(features[1]),
                    context.get_readable_name(features[2]),
                    context.get_readable_name(features[3]),
                    context.get_readable_name(features[4]),
                    context.get_readable_name(features[5])
                ];
                for (var i = 0; i < metadata_counts['items'].length; i++) {
                    var new_item = {};
                    for (var j = 0; j < features.length; j++) {
                        var item = metadata_counts['items'][i];
                        new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                    }
                    metadata_counts['items'][i] = new_item;
                }

                parsets_obj.draw_parsets(metadata_counts, plot_features);
            } else {
                console.warn("No 'items' found in metadata_counts: " + metadata_counts);
            }

            $('.clinical-trees .spinner').hide();
            $('.user-data-trees .spinner').hide();
            $('.parallel-sets .spinner').hide();
            $('.cohort-info .spinner').hide();
            $('.cohort-info .total-values').show();
        },

        update_counts_parsets: function(base_url_domain, endpoint, cohort_id, version, program_id){
            var context = this;
            var filters = this.format_filters(program_id);
            var api_url = this.generate_metadata_url(base_url_domain, endpoint, filters, cohort_id, undefined, version, program_id);

            // Get active panel
            var active_program_id = $('ul.nav-tabs-data li.active a').data('program-id');
            var active_panel = '' + active_program_id+'-data';

            if(api_url.length > MAX_URL_LEN) {
                $('#url-len-max-alert').show();
                // This method is expected to return a promise, so send back a pre-rejected one
                return $.Deferred().reject();
            } else {
                $('#url-len-max-alert').hide();
            }

            $('.clinical-trees .spinner').show();
            $('.user-data-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            $('button[data-target="#apply-filters-modal"]').prop('disabled',true);
            $('#apply-filters-form input[type="submit"]').prop('disabled',true);

            var startReq = new Date().getTime();
            return $.ajax({
                type: 'GET',
                url: api_url,

                // On success
                success: function (results, status, xhr) {
                    var stopReq = new Date().getTime();
                    console.debug("[BENCHMARKING] Time for response in update_counts_parsets: "+(stopReq-startReq)+ "ms");
                    attr_counts = results['count'];
                    $('#' + active_program_id + '-data-total-samples').html(results['total']);
                    $('#' + active_program_id + '-data-total-participants').html(results['cases']);
                    // $('#user-data-total-samples').html(results['user_data'] && results['user_data_total'] !== null ? results['user_data_total'] : "NA");
                    // $('#user-data-total-participants').html(results['user_data'] && results['user_data_participants'] !== null ? results['user_data_participants'] : "NA");
                    context.update_filter_counts(attr_counts);

                    var clin_tree_attr_counts = Object.keys(filters).length > 0 ? context.filter_data_for_clin_trees(attr_counts, clin_tree_attr) : attr_counts;
                    clin_tree_attr_counts.length > 0 && tree_graph_obj.draw_trees(clin_tree_attr_counts,clin_tree_attr,'#tree-graph-clinical-'+active_program_id);

                    if (results.hasOwnProperty('items')) {
                        var features = [
                            'cnvrPlatform',
                            'DNAseq_data',
                            'methPlatform',
                            'gexpPlatform',
                            'mirnPlatform',
                            'rppaPlatform'
                        ];
                        var plot_features = [
                            context.get_readable_name(features[0]),
                            context.get_readable_name(features[1]),
                            context.get_readable_name(features[2]),
                            context.get_readable_name(features[3]),
                            context.get_readable_name(features[4]),
                            context.get_readable_name(features[5])
                        ];
                        for (var i = 0; i < results['items'].length; i++) {
                            var new_item = {};
                            for (var j = 0; j < features.length; j++) {
                                var item = results['items'][i];
                                new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                            }
                            results['items'][i] = new_item;
                        }

                        parsets_obj.draw_parsets(results, plot_features);
                    } else {
                        console.debug(results);
                    }
                },
                error: function(req,status,err){
                    $('#' + active_program_id + '-data-total-samples').html("Error");
                    $('#' + active_program_id + '-data-total-participants').html("Error");
                    // $('#user-data-total-samples').html("Error");
                    // $('#user-data-total-participants').html("Error");
                },
                complete: function(xhr,status) {
                    $('.clinical-trees .spinner').hide();
                    $('.user-data-trees .spinner').hide();
                    $('.parallel-sets .spinner').hide();
                    $('.cohort-info .spinner').hide();
                    $('.cohort-info .total-values').show();
                }
            });
        },

        format_filters: function(program_id) {
            var list = {};
            var program_selector = '';
            if (program_id != '0') {
                program_selector = '#' + program_id + '-data ';
            }
            $(program_selector + '.selected-filters .panel-body span').each(function() {
                var $this = $(this),
                    key = $this.data('feature-name'),
                    val = $this.data('value-name');

                if ($this.data('feature-id'))
                    key = $this.data('feature-id');
                if ($this.data('value-id'))
                    val = $this.data('value-id');

                if(!list[key])
                    list[key] = [];
                list[key].push(val);
            });
            return list;
        },

        // TODO: We no longer use the endpoints for this; it can be simplified into just producing the filter set
        generate_metadata_url: function(base_url_domain, endpoint, filters, cohort_id, limit, version, program_id) {
            version = version || 'v1';
            var api_url = base_url_domain + '/cohorts/get_metadata_ajax/?version=' + version + '&endpoint=' + endpoint + '&program_id=' + program_id + '&';

            if (cohort_id) {
                api_url += 'cohort_id=' + cohort_id + '&';
            }
            if (limit != null && limit !== undefined) {
                api_url += 'limit=' + limit + '&';
            }

            if (filters) {
                api_url += 'filters=' + encodeURIComponent(JSON.stringify(filters)) + '&';
            }
            console.log(api_url)
            return api_url;
        },

        update_filter_counts: function(counts) {

            counts_by_name = {};

            // Convert the array into a map for easier searching
            counts.map(function(obj){
                counts_by_name[obj.name] = {
                    values: {},
                    total: obj.total
                }
                var values = counts_by_name[obj.name].values;
                obj.values.map(function(val){
                    values[val.value] = val.count;
                });
            });

            $('.filter-panel li.list-group-item div.cohort-feature-select-block').each(function() {
                var $this = $(this),
                    attr = $this.data('feature-name');
                if(attr && attr.length > 0 && attr !== 'specific-mutation' ) {
                    $('ul#' + attr + ' input').each(function () {

                        var $that = $(this),
                            value = $that.data('value-name'),
                            id = $that.data('value-id'),
                            displ_name = ($that.data('value-displ-name') == 'NA' ? 'None' : $that.data('value-displ-name')),
                            new_count = '';
                        if (counts_by_name[attr]) {
                            if (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name] || counts_by_name[attr].values[id]) {
                                new_count = '(' + (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name] || counts_by_name[attr].values[id]) + ')';
                            }
                        }
                        // All entries which were not returned are assumed to be zero
                        if (new_count == '') {
                            new_count = '(0)';
                        }
                        $that.siblings('span').html(new_count);
                    });
                }
            });
        },
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

        get_readable_name: function(csv_name) {
            var translation_dictionary = {
                'DNAseq_data':              'DNAseq',
                'Yes':                      'GA',
                'No':                       'N/A',
                'mirnPlatform':             'microRNA',
                'None':                     'N/A',
                'IlluminaHiSeq_miRNASeq':   'HiSeq',
                'IlluminaGA_miRNASeq':      'GA',
                'cnvrPlatform':             'SNP/CN',
                'Genome_Wide_SNP_6':        'SNP6',
                'methPlatform':             'DNAmeth',
                'HumanMethylation27':       '27k',
                'HumanMethylation450':      '450k',
                'gexpPlatform':             'mRNA',
                'IlluminaHiSeq_RNASeq':     'HiSeq/BCGSC', // actually this is bcgsc, broad, and unc
                'IlluminaHiSeq_RNASeqV2':   'HiSeq/UNC V2',
                'IlluminaGA_RNASeq':        'GA/BCGSC', // actually this is bcgsc and unc
                'IlluminaGA_RNASeqV2':      'GA/UNC V2',
                'rppaPlatform':             'Protein',
                'MDA_RPPA_Core':            'RPPA',
                'FEMALE':                   'Female',
                'MALE':                     'Male',
                '0':                        'Wild Type',
                '1':                        'Mutant',
                'age_at_initial_pathologic_diagnosis': 'Age at Diagnosis'
            };

            if (csv_name in translation_dictionary){
                return translation_dictionary[csv_name];
            } else{
                csv_name = csv_name.replace(/_/g, ' ');
                return csv_name.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
            }
        }
    }
});
<commit_msg>-> Fixed a bug where program IDs weren't being passed to the tree graph and count updating methods<commit_after>/**
 *
 * Copyright 2016, Institute for Systems Biology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

var MAX_URL_LEN = 2000;

define(['jquery', 'tree_graph', 'stack_bar_chart', 'draw_parsets'],
function($, tree_graph, stack_bar_chart, draw_parsets) {

    var tree_graph_obj = Object.create(tree_graph, {});
    var parsets_obj = Object.create(draw_parsets, {});

    var clin_tree_attr = {
        disease_code: 'Disease Code',
        vital_status: 'Vital Status',
        SampleTypeCode: 'Sample Type',
        tumor_tissue_site: 'Tumor Tissue Site',
        gender: 'Gender',
        age_at_initial_pathologic_diagnosis: 'Age at Initial Pathologic Diagnosis'
    };

    var user_data_attr = {
        user_project: 'Project',
        user_study: 'Study'
    };

    return  {

        filter_data_for_clin_trees: function(attr_counts, these_attr, program_id) {
            if(program_id == null || program_id == undefined) {
                program_id = $('ul.nav-tabs-data li.active a').data('program-id');
            }
            var filtered_clin_trees = {};
            var attr_counts_clin_trees = null;
            var filters = this.format_filters(program_id);
            var tree_attr_map = {};

            Object.keys(these_attr).map(function(attr){
                tree_attr_map[attr] = 1;
            });
            for(var i in filters) {
                if(filters.hasOwnProperty(i)) {
                    var fname = (i.indexOf(":") >= 0) ? i.split(/:/)[1] : i;
                    if (tree_attr_map[fname]) {
                        if (!filtered_clin_trees[fname]) {
                            filtered_clin_trees[fname] = {};
                        }
                        filters[i].map(function(val){
                            filtered_clin_trees[fname][val] = 1;
                        });
                    }
                }
            }
            if(Object.keys(filtered_clin_trees).length > 0) {
                attr_counts_clin_trees = JSON.parse(JSON.stringify(attr_counts));
                for(var i=0; i < attr_counts_clin_trees.length; i++) {
                    if(filtered_clin_trees[attr_counts_clin_trees[i].name]) {
                        attr_counts_clin_trees[i].total = 0;
                        var new_values = [];
                        for(var j=0; j < attr_counts_clin_trees[i].values.length; j++) {
                            if(filtered_clin_trees[attr_counts_clin_trees[i].name][attr_counts_clin_trees[i].values[j].value]) {
                                new_values.push(attr_counts_clin_trees[i].values[j]);
                                attr_counts_clin_trees[i].total += attr_counts_clin_trees[i].values[j].count;
                            }
                        }
                        attr_counts_clin_trees[i].values = new_values;
                    }
                }
            }
            return (attr_counts_clin_trees || attr_counts);
        },

        update_counts_parsets_direct: function(filters, program_id) {
            if(program_id == null || program_id == undefined) {
                program_id = $('ul.nav-tabs-data li.active a').data('program-id');
            }

            $('.clinical-trees .spinner').show();
            $('.user-data-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            var context = this;

            attr_counts = metadata_counts['count'];

            $('#isb-cgc-data-total-samples').html(metadata_counts['total']);
            $('#isb-cgc-data-total-participants').html(metadata_counts['cases']);
            $('#user-data-total-samples').html(user_data && metadata_counts['user_data_total'] !== null ? metadata_counts['user_data_total'] : "NA");
            $('#user-data-total-participants').html(user_data && metadata_counts['user_data_participants'] !== null ? metadata_counts['user_data_participants'] : "NA");

            this.update_filter_counts(attr_counts);
            // If there were filters, we need to adjust their counts so the barchart reflects what
            // was actually filtered
            var filters = this.format_filters(program_id);
            var clin_tree_attr_counts = Object.keys(filters).length > 0 ? this.filter_data_for_clin_trees(attr_counts, clin_tree_attr, program_id) : attr_counts;
            tree_graph_obj.draw_trees(clin_tree_attr_counts,clin_tree_attr,'#isb-cgc-tree-graph-clinical');

            if (metadata_counts.hasOwnProperty('items')) {
                var features = [
                    'cnvrPlatform',
                    'DNAseq_data',
                    'methPlatform',
                    'gexpPlatform',
                    'mirnPlatform',
                    'rppaPlatform'
                ];

                var plot_features = [
                    context.get_readable_name(features[0]),
                    context.get_readable_name(features[1]),
                    context.get_readable_name(features[2]),
                    context.get_readable_name(features[3]),
                    context.get_readable_name(features[4]),
                    context.get_readable_name(features[5])
                ];
                for (var i = 0; i < metadata_counts['items'].length; i++) {
                    var new_item = {};
                    for (var j = 0; j < features.length; j++) {
                        var item = metadata_counts['items'][i];
                        new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                    }
                    metadata_counts['items'][i] = new_item;
                }

                parsets_obj.draw_parsets(metadata_counts, plot_features);
            } else {
                console.warn("No 'items' found in metadata_counts: " + metadata_counts);
            }

            $('.clinical-trees .spinner').hide();
            $('.user-data-trees .spinner').hide();
            $('.parallel-sets .spinner').hide();
            $('.cohort-info .spinner').hide();
            $('.cohort-info .total-values').show();
        },

        update_counts_parsets: function(base_url_domain, endpoint, cohort_id, version, program_id){
            if(program_id == null || program_id == undefined) {
                program_id = $('ul.nav-tabs-data li.active a').data('program-id');
            }

            var context = this;
            var filters = this.format_filters(program_id);
            var api_url = this.generate_metadata_url(base_url_domain, endpoint, filters, cohort_id, undefined, version, program_id);

            // Get active panel
            var active_program_id = program_id || $('ul.nav-tabs-data li.active a').data('program-id');
            var active_panel = '' + active_program_id+'-data';

            if(api_url.length > MAX_URL_LEN) {
                $('#url-len-max-alert').show();
                // This method is expected to return a promise, so send back a pre-rejected one
                return $.Deferred().reject();
            } else {
                $('#url-len-max-alert').hide();
            }

            $('.clinical-trees .spinner').show();
            $('.user-data-trees .spinner').show();
            $('.parallel-sets .spinner').show();
            $('.cohort-info .total-values').hide();
            $('.cohort-info .spinner').show();

            $('button[data-target="#apply-filters-modal"]').prop('disabled',true);
            $('#apply-filters-form input[type="submit"]').prop('disabled',true);

            var startReq = new Date().getTime();
            return $.ajax({
                type: 'GET',
                url: api_url,

                // On success
                success: function (results, status, xhr) {
                    var stopReq = new Date().getTime();
                    console.debug("[BENCHMARKING] Time for response in update_counts_parsets: "+(stopReq-startReq)+ "ms");
                    attr_counts = results['count'];
                    $('#' + active_program_id + '-data-total-samples').html(results['total']);
                    $('#' + active_program_id + '-data-total-participants').html(results['cases']);
                    // $('#user-data-total-samples').html(results['user_data'] && results['user_data_total'] !== null ? results['user_data_total'] : "NA");
                    // $('#user-data-total-participants').html(results['user_data'] && results['user_data_participants'] !== null ? results['user_data_participants'] : "NA");
                    context.update_filter_counts(attr_counts);

                    var clin_tree_attr_counts = Object.keys(filters).length > 0 ? context.filter_data_for_clin_trees(attr_counts, clin_tree_attr) : attr_counts;
                    clin_tree_attr_counts.length > 0 && tree_graph_obj.draw_trees(clin_tree_attr_counts,clin_tree_attr,'#tree-graph-clinical-'+active_program_id);

                    if (results.hasOwnProperty('items')) {
                        var features = [
                            'cnvrPlatform',
                            'DNAseq_data',
                            'methPlatform',
                            'gexpPlatform',
                            'mirnPlatform',
                            'rppaPlatform'
                        ];
                        var plot_features = [
                            context.get_readable_name(features[0]),
                            context.get_readable_name(features[1]),
                            context.get_readable_name(features[2]),
                            context.get_readable_name(features[3]),
                            context.get_readable_name(features[4]),
                            context.get_readable_name(features[5])
                        ];
                        for (var i = 0; i < results['items'].length; i++) {
                            var new_item = {};
                            for (var j = 0; j < features.length; j++) {
                                var item = results['items'][i];
                                new_item[plot_features[j]] = context.get_readable_name(item[features[j]]);
                            }
                            results['items'][i] = new_item;
                        }

                        parsets_obj.draw_parsets(results, plot_features);
                    } else {
                        console.debug(results);
                    }
                },
                error: function(req,status,err){
                    $('#' + active_program_id + '-data-total-samples').html("Error");
                    $('#' + active_program_id + '-data-total-participants').html("Error");
                    // $('#user-data-total-samples').html("Error");
                    // $('#user-data-total-participants').html("Error");
                },
                complete: function(xhr,status) {
                    $('.clinical-trees .spinner').hide();
                    $('.user-data-trees .spinner').hide();
                    $('.parallel-sets .spinner').hide();
                    $('.cohort-info .spinner').hide();
                    $('.cohort-info .total-values').show();
                }
            });
        },

        format_filters: function(program_id) {
            var list = {};
            var program_selector = '';
            if (program_id != '0') {
                program_selector = '#' + program_id + '-data ';
            }
            $(program_selector + '.selected-filters .panel-body span').each(function() {
                var $this = $(this),
                    key = $this.data('feature-name'),
                    val = $this.data('value-name');

                if ($this.data('feature-id'))
                    key = $this.data('feature-id');
                if ($this.data('value-id'))
                    val = $this.data('value-id');

                if(!list[key])
                    list[key] = [];
                list[key].push(val);
            });
            return list;
        },

        // TODO: We no longer use the endpoints for this; it can be simplified into just producing the filter set
        generate_metadata_url: function(base_url_domain, endpoint, filters, cohort_id, limit, version, program_id) {
            version = version || 'v1';
            var api_url = base_url_domain + '/cohorts/get_metadata_ajax/?version=' + version + '&endpoint=' + endpoint + '&program_id=' + program_id + '&';

            if (cohort_id) {
                api_url += 'cohort_id=' + cohort_id + '&';
            }
            if (limit != null && limit !== undefined) {
                api_url += 'limit=' + limit + '&';
            }

            if (filters) {
                api_url += 'filters=' + encodeURIComponent(JSON.stringify(filters)) + '&';
            }
            console.log(api_url)
            return api_url;
        },

        update_filter_counts: function(counts) {

            counts_by_name = {};

            // Convert the array into a map for easier searching
            counts.map(function(obj){
                counts_by_name[obj.name] = {
                    values: {},
                    total: obj.total
                }
                var values = counts_by_name[obj.name].values;
                obj.values.map(function(val){
                    values[val.value] = val.count;
                });
            });

            $('.filter-panel li.list-group-item div.cohort-feature-select-block').each(function() {
                var $this = $(this),
                    attr = $this.data('feature-name');
                if(attr && attr.length > 0 && attr !== 'specific-mutation' ) {
                    $('ul#' + attr + ' input').each(function () {

                        var $that = $(this),
                            value = $that.data('value-name'),
                            id = $that.data('value-id'),
                            displ_name = ($that.data('value-displ-name') == 'NA' ? 'None' : $that.data('value-displ-name')),
                            new_count = '';
                        if (counts_by_name[attr]) {
                            if (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name] || counts_by_name[attr].values[id]) {
                                new_count = '(' + (counts_by_name[attr].values[value] || counts_by_name[attr].values[displ_name] || counts_by_name[attr].values[id]) + ')';
                            }
                        }
                        // All entries which were not returned are assumed to be zero
                        if (new_count == '') {
                            new_count = '(0)';
                        }
                        $that.siblings('span').html(new_count);
                    });
                }
            });
        },
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

        get_readable_name: function(csv_name) {
            var translation_dictionary = {
                'DNAseq_data':              'DNAseq',
                'Yes':                      'GA',
                'No':                       'N/A',
                'mirnPlatform':             'microRNA',
                'None':                     'N/A',
                'IlluminaHiSeq_miRNASeq':   'HiSeq',
                'IlluminaGA_miRNASeq':      'GA',
                'cnvrPlatform':             'SNP/CN',
                'Genome_Wide_SNP_6':        'SNP6',
                'methPlatform':             'DNAmeth',
                'HumanMethylation27':       '27k',
                'HumanMethylation450':      '450k',
                'gexpPlatform':             'mRNA',
                'IlluminaHiSeq_RNASeq':     'HiSeq/BCGSC', // actually this is bcgsc, broad, and unc
                'IlluminaHiSeq_RNASeqV2':   'HiSeq/UNC V2',
                'IlluminaGA_RNASeq':        'GA/BCGSC', // actually this is bcgsc and unc
                'IlluminaGA_RNASeqV2':      'GA/UNC V2',
                'rppaPlatform':             'Protein',
                'MDA_RPPA_Core':            'RPPA',
                'FEMALE':                   'Female',
                'MALE':                     'Male',
                '0':                        'Wild Type',
                '1':                        'Mutant',
                'age_at_initial_pathologic_diagnosis': 'Age at Diagnosis'
            };

            if (csv_name in translation_dictionary){
                return translation_dictionary[csv_name];
            } else{
                csv_name = csv_name.replace(/_/g, ' ');
                return csv_name.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
            }
        }
    }
});
<|endoftext|>


<commit_before>/*! taboverride.style v0.1.0-dev | https://github.com/wjbryant/taboverride.style
Copyright (c) 2013 Bill Bryant | http://opensource.org/licenses/mit */

/*global exports, require, define, tabOverride */

// use CommonJS or AMD if available
(function (factory) {
    'use strict';

    if (typeof exports === 'object' && typeof require === 'function') {
        // Node.js/CommonJS
        factory(require('taboverride'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD - register as an anonymous module
        // files must be concatenated using an AMD-aware tool such as r.js
        define(['taboverride'], factory);
    } else {
        // no module format - use global variable
        factory(tabOverride);
    }
}(function (tabOverride) {
    'use strict';

    var style = true,
        enabledClass = 'tabOverrideEnabled',
        activeClass = 'tabOverrideActive',
        hardTabSize = 4,
        styleElem,
        styleSheet,
        tabSizeRule,
        extraSelectors = [],
        // this is a live collection
        textareas = document.getElementsByTagName('textarea');

    // add a class to an element
    function addClass(elem, cssClass) {
        // check if the element has the specified CSS class before adding it
        if (!(new RegExp('(?:^|\\s)' + cssClass + '(?:\\s|$)')).test(elem.className)) {
            elem.className += (elem.className ? ' ' : '') + cssClass;
        }
    }

    // remove a class from an element
    function removeClass(elem, cssClass) {
        elem.className = elem.className.replace(
            new RegExp('(?:^|\\s)' + cssClass + '(?=\\s|$)', 'g'),
            ''
        );
    }

    // replace a class with a new one for the specified element
    function replaceClass(elem, oldClass, newClass) {
        elem.className = elem.className.replace(
            new RegExp('(^|\\s)' + oldClass + '(?=\\s|$)', 'g'),
            '$1' + newClass
        );
    }

    // add the enabled class
    function addEnabledClass(elem) {
        addClass(elem, enabledClass);
    }

    // add the active class
    function addActiveClass(elem) {
        addClass(elem, activeClass);
    }

    // remove the enabled class
    function removeEnabledClass(elem) {
        removeClass(elem, enabledClass);
    }

    // remove the active class
    function removeActiveClass(elem) {
        removeClass(elem, activeClass);
    }

    // loop through all textareas and update them to the new class
    // if no new class is specified, remove the old class
    function updateClassOnTextareas(oldClass, newClass) {
        var editClass = newClass ? replaceClass : removeClass,
            len = textareas.length,
            i;

        for (i = 0; i < len; i += 1) {
            editClass(textareas[i], oldClass, newClass);
        }
    }

    function updateEnabledClass(newClass) {
        updateClassOnTextareas(enabledClass, newClass);
    }

    function updateActiveClass(newClass) {
        updateClassOnTextareas(activeClass, newClass);
    }

    // change the tab-size CSS property value
    function updateTabSizeCSSValue(tabSize) {
        tabSizeRule.style.MozTabSize = tabSize;
        tabSizeRule.style.OTabSize = tabSize;
        tabSizeRule.style.tabSize = tabSize;
    }

    function updateTabSizeCSSRule() {
        var selector = 'textarea.' + enabledClass;

        if (extraSelectors.length) {
            selector += ',' + extraSelectors.join(',')
                .replace(/\.\(enabledClass\)/g, '.' +  enabledClass)
                .replace(/\.\(activeClass\)/g, '.' + activeClass);
        }

        if (styleSheet.deleteRule) {
            if (styleSheet.cssRules.length) {
                styleSheet.deleteRule(0);
            }
            styleSheet.insertRule(selector + '{}', 0);
        } else if (styleSheet.removeRule) {
            // IE
            if (styleSheet.rules.length) {
                styleSheet.removeRule(0);
            }
            styleSheet.addRule(selector, '', 0);
        }

        tabSizeRule = (styleSheet.cssRules || styleSheet.rules)[0];
        updateTabSizeCSSValue(hardTabSize);
    }

    function addTabSizeCSSSelector(newSelector) {
        extraSelectors.push(newSelector);
        updateTabSizeCSSRule();
    }

    function removeTabSizeCSSSelector(cssSelector) {
        var i,
            len = extraSelectors.length;

        for (i = 0; i < len; i += 1) {
            if (extraSelectors[i] === cssSelector) {
                extraSelectors.splice(i, 1);
                break;
            }
        }

        updateTabSizeCSSRule();
    }

    // provide a method to enable/disable the extension
    tabOverride.style = function (enable) {
        var len,
            i,
            editEnabledClass,
            editActiveClass,
            currTextarea;

        if (arguments.length) {

            tabOverride.utils.executeExtensions('setStyle', [enable]);

            if (enable) {
                editEnabledClass = addEnabledClass;
                editActiveClass = addActiveClass;
                style = true;
            } else {
                editEnabledClass = removeEnabledClass;
                editActiveClass = removeActiveClass;
                style = false;
            }

            len = textareas.length;

            for (i = 0; i < len; i += 1) {
                currTextarea = textareas[i];
                if (currTextarea.getAttribute('data-taboverride-enabled')) {
                    editEnabledClass(currTextarea);
                    editActiveClass(currTextarea);
                }
            }

            return this;
        }

        return style;
    };

    // get/set the "enabled" class name (default = tabOverrideEnabled)
    tabOverride.style.enabledClass = function (newClass) {
        if (arguments.length) {
            if (newClass && typeof newClass === 'string') {
                updateClassOnTextareas(enabledClass, newClass);
                enabledClass = newClass;
                updateTabSizeCSSRule();
            }
            return this;
        }
        return enabledClass;
    };

    // get/set the "active" class name (default = tabOverrideActive)
    tabOverride.style.activeClass = function (newClass) {
        if (arguments.length) {
            if (newClass && typeof newClass === 'string') {
                updateClassOnTextareas(activeClass, newClass);
                activeClass = newClass;
                updateTabSizeCSSRule();
            }
            return this;
        }
        return activeClass;
    };

    // get/set the hard tab size (default = 4)
    tabOverride.style.hardTabSize = function (size) {
        if (arguments.length) {
            if (typeof size === 'number' && size > 0) {
                updateTabSizeCSSValue(size);
                hardTabSize = size;
            }
            return this;
        }
        return hardTabSize;
    };

    // public util methods
    tabOverride.style.utils = {
        addEnabledClass: addEnabledClass,
        addActiveClass: addActiveClass,
        removeEnabledClass: removeEnabledClass,
        removeActiveClass: removeActiveClass,
        updateEnabledClass: updateEnabledClass,
        updateActiveClass: updateActiveClass,
        addTabSizeCSSSelector: addTabSizeCSSSelector,
        removeTabSizeCSSSelector: removeTabSizeCSSSelector
    };

    // create a new style sheet element
    if (document.createStyleSheet) {
        // IE
        styleSheet = document.createStyleSheet();
    } else {
        // add a new style element to the page
        styleElem = document.createElement('style');
        document.getElementsByTagName('head')[0].appendChild(styleElem);
        styleSheet = styleElem.sheet || document.styleSheets[document.styleSheets - 1];
    }

    // create the CSS rule
    updateTabSizeCSSRule();

    // add the extension to Tab Override (hook into the set method)
    tabOverride.addExtension('set', function (elem, enable) {
        if (style) {
            if (enable) {
                addEnabledClass(elem);
                addActiveClass(elem);
            } else {
                removeEnabledClass(elem);
                removeActiveClass(elem);
            }
        }
    });

    // whenever the listeners are added, add the active class
    tabOverride.addExtension('addListeners', function (elem) {
        if (style) {
            addActiveClass(elem);
        }
    });

    // whenever the listeners are removed, remove the active class
    tabOverride.addExtension('removeListeners', function (elem) {
        if (style) {
            removeActiveClass(elem);
        }
    });
}));
<commit_msg>add utils.hardTabSizeSupported property<commit_after>/*! taboverride.style v0.1.0-dev | https://github.com/wjbryant/taboverride.style
Copyright (c) 2013 Bill Bryant | http://opensource.org/licenses/mit */

/*global exports, require, define, tabOverride */

// use CommonJS or AMD if available
(function (factory) {
    'use strict';

    if (typeof exports === 'object' && typeof require === 'function') {
        // Node.js/CommonJS
        factory(require('taboverride'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD - register as an anonymous module
        // files must be concatenated using an AMD-aware tool such as r.js
        define(['taboverride'], factory);
    } else {
        // no module format - use global variable
        factory(tabOverride);
    }
}(function (tabOverride) {
    'use strict';

    var style = true,
        enabledClass = 'tabOverrideEnabled',
        activeClass = 'tabOverrideActive',
        hardTabSize = 4,
        styleElem,
        styleSheet,
        tabSizeRule,
        extraSelectors = [],
        // this is a live collection
        textareas = document.getElementsByTagName('textarea'),
        iElemStyle = document.createElement('i').style,
        hardTabSizeSupported = iElemStyle.tabSize === '' ||
            iElemStyle.MozTabSize === '' ||
            iElemStyle.OTabSize === '';

    // add a class to an element
    function addClass(elem, cssClass) {
        // check if the element has the specified CSS class before adding it
        if (!(new RegExp('(?:^|\\s)' + cssClass + '(?:\\s|$)')).test(elem.className)) {
            elem.className += (elem.className ? ' ' : '') + cssClass;
        }
    }

    // remove a class from an element
    function removeClass(elem, cssClass) {
        elem.className = elem.className.replace(
            new RegExp('(?:^|\\s)' + cssClass + '(?=\\s|$)', 'g'),
            ''
        );
    }

    // replace a class with a new one for the specified element
    function replaceClass(elem, oldClass, newClass) {
        elem.className = elem.className.replace(
            new RegExp('(^|\\s)' + oldClass + '(?=\\s|$)', 'g'),
            '$1' + newClass
        );
    }

    // add the enabled class
    function addEnabledClass(elem) {
        addClass(elem, enabledClass);
    }

    // add the active class
    function addActiveClass(elem) {
        addClass(elem, activeClass);
    }

    // remove the enabled class
    function removeEnabledClass(elem) {
        removeClass(elem, enabledClass);
    }

    // remove the active class
    function removeActiveClass(elem) {
        removeClass(elem, activeClass);
    }

    // loop through all textareas and update them to the new class
    // if no new class is specified, remove the old class
    function updateClassOnTextareas(oldClass, newClass) {
        var editClass = newClass ? replaceClass : removeClass,
            len = textareas.length,
            i;

        for (i = 0; i < len; i += 1) {
            editClass(textareas[i], oldClass, newClass);
        }
    }

    function updateEnabledClass(newClass) {
        updateClassOnTextareas(enabledClass, newClass);
    }

    function updateActiveClass(newClass) {
        updateClassOnTextareas(activeClass, newClass);
    }

    // change the tab-size CSS property value
    function updateTabSizeCSSValue(tabSize) {
        tabSizeRule.style.MozTabSize = tabSize;
        tabSizeRule.style.OTabSize = tabSize;
        tabSizeRule.style.tabSize = tabSize;
    }

    function updateTabSizeCSSRule() {
        var selector = 'textarea.' + enabledClass;

        if (extraSelectors.length) {
            selector += ',' + extraSelectors.join(',')
                .replace(/\.\(enabledClass\)/g, '.' +  enabledClass)
                .replace(/\.\(activeClass\)/g, '.' + activeClass);
        }

        if (styleSheet.deleteRule) {
            if (styleSheet.cssRules.length) {
                styleSheet.deleteRule(0);
            }
            styleSheet.insertRule(selector + '{}', 0);
        } else if (styleSheet.removeRule) {
            // IE
            if (styleSheet.rules.length) {
                styleSheet.removeRule(0);
            }
            styleSheet.addRule(selector, '', 0);
        }

        tabSizeRule = (styleSheet.cssRules || styleSheet.rules)[0];
        updateTabSizeCSSValue(hardTabSize);
    }

    function addTabSizeCSSSelector(newSelector) {
        extraSelectors.push(newSelector);
        updateTabSizeCSSRule();
    }

    function removeTabSizeCSSSelector(cssSelector) {
        var i,
            len = extraSelectors.length;

        for (i = 0; i < len; i += 1) {
            if (extraSelectors[i] === cssSelector) {
                extraSelectors.splice(i, 1);
                break;
            }
        }

        updateTabSizeCSSRule();
    }

    // provide a method to enable/disable the extension
    tabOverride.style = function (enable) {
        var len,
            i,
            editEnabledClass,
            editActiveClass,
            currTextarea;

        if (arguments.length) {

            tabOverride.utils.executeExtensions('setStyle', [enable]);

            if (enable) {
                editEnabledClass = addEnabledClass;
                editActiveClass = addActiveClass;
                style = true;
            } else {
                editEnabledClass = removeEnabledClass;
                editActiveClass = removeActiveClass;
                style = false;
            }

            len = textareas.length;

            for (i = 0; i < len; i += 1) {
                currTextarea = textareas[i];
                if (currTextarea.getAttribute('data-taboverride-enabled')) {
                    editEnabledClass(currTextarea);
                    editActiveClass(currTextarea);
                }
            }

            return this;
        }

        return style;
    };

    // get/set the "enabled" class name (default = tabOverrideEnabled)
    tabOverride.style.enabledClass = function (newClass) {
        if (arguments.length) {
            if (newClass && typeof newClass === 'string') {
                updateClassOnTextareas(enabledClass, newClass);
                enabledClass = newClass;
                updateTabSizeCSSRule();
            }
            return this;
        }
        return enabledClass;
    };

    // get/set the "active" class name (default = tabOverrideActive)
    tabOverride.style.activeClass = function (newClass) {
        if (arguments.length) {
            if (newClass && typeof newClass === 'string') {
                updateClassOnTextareas(activeClass, newClass);
                activeClass = newClass;
                updateTabSizeCSSRule();
            }
            return this;
        }
        return activeClass;
    };

    // get/set the hard tab size (default = 4)
    tabOverride.style.hardTabSize = function (size) {
        if (arguments.length) {
            if (typeof size === 'number' && size > 0) {
                updateTabSizeCSSValue(size);
                hardTabSize = size;
            }
            return this;
        }
        return hardTabSize;
    };

    // public utility properties and methods
    tabOverride.style.utils = {
        hardTabSizeSupported: hardTabSizeSupported,
        addEnabledClass: addEnabledClass,
        addActiveClass: addActiveClass,
        removeEnabledClass: removeEnabledClass,
        removeActiveClass: removeActiveClass,
        updateEnabledClass: updateEnabledClass,
        updateActiveClass: updateActiveClass,
        addTabSizeCSSSelector: addTabSizeCSSSelector,
        removeTabSizeCSSSelector: removeTabSizeCSSSelector
    };

    // this was used to determine hard tab size support and is no longer needed
    iElemStyle = null;

    // create a new style sheet element
    if (document.createStyleSheet) {
        // IE
        styleSheet = document.createStyleSheet();
    } else {
        // add a new style element to the page
        styleElem = document.createElement('style');
        document.getElementsByTagName('head')[0].appendChild(styleElem);
        styleSheet = styleElem.sheet || document.styleSheets[document.styleSheets - 1];
    }

    // create the CSS rule
    updateTabSizeCSSRule();

    // add the extension to Tab Override (hook into the set method)
    tabOverride.addExtension('set', function (elem, enable) {
        if (style) {
            if (enable) {
                addEnabledClass(elem);
                addActiveClass(elem);
            } else {
                removeEnabledClass(elem);
                removeActiveClass(elem);
            }
        }
    });

    // whenever the listeners are added, add the active class
    tabOverride.addExtension('addListeners', function (elem) {
        if (style) {
            addActiveClass(elem);
        }
    });

    // whenever the listeners are removed, remove the active class
    tabOverride.addExtension('removeListeners', function (elem) {
        if (style) {
            removeActiveClass(elem);
        }
    });
}));
<|endoftext|>