<commit_before>/**
 * Hold the needed data to create the UI Projet -> Edit. Actually it's used in :
 * "ProjectProperties.js", "PhonegapUIRows.js" & "Build.js".
 * In this kind, the data are defined in the statics attribute and are structured this way :
 * * Array of drawers : a drawer contain the following attributs  :
 * - id : define the name of the drawer's component that will be created
 * - name: define the name of the drawer's label
 * - rows: define the content of the drawer, a drawer contains an array of rows and each row contain the following attributs :
 * -- name: used to create the UI widget that hold the name of the row, this name is exactely the name of the xml tag of the file
 *          config.xml that will be generated (except for splashScreen row)
 * -- label : the content of the label of the row
 * -- content: the content of the row, the format of this content can change depending on the type of the UI widget used (picker, input, ...)
 * -- defaultValue: the default value displayed in the widget
 * -- defaultHeight: the default icon/splash screen height
 * -- defaultWidth: the default icon/splash screen Width
 * -- type: contain the last part of the name of the kind that will be used to define a row, these kinds are defined in
 *          the "PhonegapUIRows.js"
 * -- jsonSection: a subsection of "providers.phonegap" in the file "project.json"
 * @type {String}
 */
enyo.kind({
	name: "Phonegap.UIConfiguration",
	statics: {
		androidSdkVersions: {"19": ["Android 4.4"], "18": ["Android 4.3"], "17": ["Android 4.2, 4.2.2"], "16": ["Android 4.1, 4.1.1"],
		"15": ["Android 4.0.3, 4.0.4"], "14": ["Android 4.0, 4.0.1, 4.0.2"], "13": ["Android 3.2"],
		"12": ["Android 3.1.x"], "11": ["Android 3.0.x"], "10": ["Android 2.3.4, 2.3.3"], "9": ["Android 2.3.2, 2.3.1, 2.3"],
		"8": ["Android 2.2.x"], "7": ["Android 2.1.x"]},

		commonDrawersContent: [
			{
				id: "buildOption",
				name: "Build Options",
				type: "Drawer",
				rows: [
					{name: "autoGenerateXML", label: "Generate config.xml file when building", content: "", defaultValue: "true", type: "BuildOption"},
					{name: "minification", label:"Activate the build minification", content:"", defaultValue: "true", type: "BuildOption"}
				]
			},
			{
				id: "applicationPermissions",
				name: "Application permissions",
				type: "PanelInDrawer",
				rows: [
					{name: "battery", label: "Battery",	content: "",defaultValue: "",  type: "CheckBoxRow", jsonSection: "features"},
					{name: "camera", label: "Camera", content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "contact", label: "Contact",	content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "file", label: "File", content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "media",	label: "Media", content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "geolocation", label: "Geolocation", content: "", defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "network", label: "Network", content: "",defaultValue: "",  type: "CheckBoxRow", jsonSection: "features"},
					{name: "notification", label: "Notification", content: "", defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "device", label: "Device", content: "", defaultValue: "",  type: "CheckBoxRow", jsonSection: "features"}
				]
			},
			{
				id: "sharedConfiguration",
				name: "Shared configuration",
				type: "Drawer",
				rows: [
					{
						name: "phonegap-version",
						label:"Phonegap version",
						content:["3.1.0", "2.9.0", "2.7.0", "2.5.0"],
						defaultValue: "3.1.0", // As recommended by PGB [doc|https://build.phonegap.com/docs/config-xml] see Multi-platform
						type: "PickerRow",
						jsonSection: "preferences"
					},
					{name: "orientation", label:"Orientation",content:["both", "landscape", "portrait"], defaultValue: "both", type: "PickerRow", jsonSection: "preferences"},
					{name: "target-device",	label: "Target device", content: ["universal", "handset", "tablet"], defaultValue: "universal", type: "PickerRow", jsonSection: "preferences"},
					{name: "fullscreen", label: "Fullscreen mode", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "access", label: "Access origin", content: "", defaultValue: "http://127.0.0.1", type: "AccessRow", jsonSection: "preferences"},
					{name: "icon", label: "Icon", content: "icon.png", defaultValue: "/icon.png", defaultWidth: "32", defaultHeight: "32", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "SplashScreen", content: "", defaultValue: "", defaultWidth: "60", defaultHeight: "60", type: "ImgRow", description: "(px)"}
				]
			}
		],

		platformDrawersContent: [
			{
				id: "android",
				name: "Google Android",
				type: "Target",
				rows: [
					{name: "android-installLocation", label: "Install Location", content: ["internalOnly", "preferExternal", "auto"], defaultValue: "internalOnly", type: "PickerRow", jsonSection: "preferences"},
					{name: "android-minSdkVersion", label: "Min. API Level/Android Version ", content: [], defaultValue: "7", type: "SDKVersionRow", jsonSection: "preferences"},
					{name: "android-targetSdkVersion", label: "Target API Level/Android Version ", content: [], defaultValue: "None", type: "SDKVersionRow", jsonSection: "preferences", none: ""},
					{name: "android-maxSdkVersion", label: "Max. API Level/Android Version ", content: [], defaultValue: "None", type: "SDKVersionRow", jsonSection: "preferences", none: ""},
					{name: "android-windowSoftInputMode", label: "Window SoftInput Mode ", content: ["stateVisible", "adjustResize"], defaultValue: "stateVisible", type: "PickerRow", jsonSection: "preferences"},
					{name: "splash-screen-duration", label: "Splash screen Duration (ms)", content: "5000", defaultValue: "5000", type: "NumberInputRow", jsonSection: "preferences", description: "Time in milliseconds"},
					{name: "load-url-timeout", label: "Load URL timeout (ms)", content: "20000", defaultValue: "20000", type: "NumberInputRow", jsonSection: "preferences", description: "Time in milliseconds"},
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", type: "AndroidImgRow"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", type: "AndroidImgRow"},
					{name: "signingKey", label: "Signing Key", content: "", defaultValue: "", type: "KeySelector", jsonSection: "targets"}
				]
			},
			{
				id: "ios",
				name: "Apple iOS",
				type: "Target",
				rows: [
					{name: "webviewbounce", label: "Web view bounce", content:  ["true", "false"], defaultValue: "true", type: "PickerRow", jsonSection: "preferences"},
					{name: "prerendered-icon", label: "Prerendred icon", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "ios-statusbarstyle", label: "Status Bar style", content: ["black-opaque", "black-translucent", "default"], defaultValue: "black-opaque",  type: "PickerRow", jsonSection: "preferences"},
					{name: "detect-data-types", label: "Detect Data type", content: ["true", "false"], defaultValue: "true", type: "PickerRow", jsonSection: "preferences"},
					{name: "exit-on-suspend", label: "Exit on suspend", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "show-splash-screen-spinner", label: "Show splash screen spinner", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "auto-hide-splash-screen", label: "Auto-hide splash screen", content: ["true", "false"], defaultValue: "true", type: "PickerRow", jsonSection: "preferences"},
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"},
					{name: "signingKey", label: "Signing Key", content: "", defaultValue: "", type: "KeySelector", jsonSection: "targets"}
				]
			},
			{
				id: "winphone",
				name: "Microsoft Windows Phone 7",
				type: "Target",
				rows: [
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"}
				]
			},
			{
				id: "blackberry",
				name: "RIM Blackberry",
				type: "Target",
				rows: [
					{name: "disable-cursor", label: "Disable Cursor", content:  ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"},
					{name: "signingKey", label: "Signing Key", content: "", defaultValue: "", type: "KeySelector", jsonSection: "targets"}
				]
			},
			{
				id: "webos",
				name: "HP webOS 2",
				type: "Target",
				rows: [
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"}
				]
			}

		]
	}
});
<commit_msg>ENYO-3765: add back "3.0.0" as a supported Phonegap version<commit_after>/**
 * Hold the needed data to create the UI Projet -> Edit. Actually it's used in :
 * "ProjectProperties.js", "PhonegapUIRows.js" & "Build.js".
 * In this kind, the data are defined in the statics attribute and are structured this way :
 * * Array of drawers : a drawer contain the following attributs  :
 * - id : define the name of the drawer's component that will be created
 * - name: define the name of the drawer's label
 * - rows: define the content of the drawer, a drawer contains an array of rows and each row contain the following attributs :
 * -- name: used to create the UI widget that hold the name of the row, this name is exactely the name of the xml tag of the file
 *          config.xml that will be generated (except for splashScreen row)
 * -- label : the content of the label of the row
 * -- content: the content of the row, the format of this content can change depending on the type of the UI widget used (picker, input, ...)
 * -- defaultValue: the default value displayed in the widget
 * -- defaultHeight: the default icon/splash screen height
 * -- defaultWidth: the default icon/splash screen Width
 * -- type: contain the last part of the name of the kind that will be used to define a row, these kinds are defined in
 *          the "PhonegapUIRows.js"
 * -- jsonSection: a subsection of "providers.phonegap" in the file "project.json"
 * @type {String}
 */
enyo.kind({
	name: "Phonegap.UIConfiguration",
	statics: {
		androidSdkVersions: {"19": ["Android 4.4"], "18": ["Android 4.3"], "17": ["Android 4.2, 4.2.2"], "16": ["Android 4.1, 4.1.1"],
		"15": ["Android 4.0.3, 4.0.4"], "14": ["Android 4.0, 4.0.1, 4.0.2"], "13": ["Android 3.2"],
		"12": ["Android 3.1.x"], "11": ["Android 3.0.x"], "10": ["Android 2.3.4, 2.3.3"], "9": ["Android 2.3.2, 2.3.1, 2.3"],
		"8": ["Android 2.2.x"], "7": ["Android 2.1.x"]},

		commonDrawersContent: [
			{
				id: "buildOption",
				name: "Build Options",
				type: "Drawer",
				rows: [
					{name: "autoGenerateXML", label: "Generate config.xml file when building", content: "", defaultValue: "true", type: "BuildOption"},
					{name: "minification", label:"Activate the build minification", content:"", defaultValue: "true", type: "BuildOption"}
				]
			},
			{
				id: "applicationPermissions",
				name: "Application permissions",
				type: "PanelInDrawer",
				rows: [
					{name: "battery", label: "Battery",	content: "",defaultValue: "",  type: "CheckBoxRow", jsonSection: "features"},
					{name: "camera", label: "Camera", content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "contact", label: "Contact",	content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "file", label: "File", content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "media",	label: "Media", content: "",defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "geolocation", label: "Geolocation", content: "", defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "network", label: "Network", content: "",defaultValue: "",  type: "CheckBoxRow", jsonSection: "features"},
					{name: "notification", label: "Notification", content: "", defaultValue: "", type: "CheckBoxRow", jsonSection: "features"},
					{name: "device", label: "Device", content: "", defaultValue: "",  type: "CheckBoxRow", jsonSection: "features"}
				]
			},
			{
				id: "sharedConfiguration",
				name: "Shared configuration",
				type: "Drawer",
				rows: [
					{
						name: "phonegap-version",
						label:"Phonegap version",
						content:["3.1.0", "3.0.0", "2.9.0", "2.7.0", "2.5.0"],
						defaultValue: "3.1.0", // As recommended by PGB [doc|https://build.phonegap.com/docs/config-xml] see Multi-platform
						type: "PickerRow",
						jsonSection: "preferences"
					},
					{name: "orientation", label:"Orientation",content:["both", "landscape", "portrait"], defaultValue: "both", type: "PickerRow", jsonSection: "preferences"},
					{name: "target-device",	label: "Target device", content: ["universal", "handset", "tablet"], defaultValue: "universal", type: "PickerRow", jsonSection: "preferences"},
					{name: "fullscreen", label: "Fullscreen mode", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "access", label: "Access origin", content: "", defaultValue: "http://127.0.0.1", type: "AccessRow", jsonSection: "preferences"},
					{name: "icon", label: "Icon", content: "icon.png", defaultValue: "/icon.png", defaultWidth: "32", defaultHeight: "32", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "SplashScreen", content: "", defaultValue: "", defaultWidth: "60", defaultHeight: "60", type: "ImgRow", description: "(px)"}
				]
			}
		],

		platformDrawersContent: [
			{
				id: "android",
				name: "Google Android",
				type: "Target",
				rows: [
					{name: "android-installLocation", label: "Install Location", content: ["internalOnly", "preferExternal", "auto"], defaultValue: "internalOnly", type: "PickerRow", jsonSection: "preferences"},
					{name: "android-minSdkVersion", label: "Min. API Level/Android Version ", content: [], defaultValue: "7", type: "SDKVersionRow", jsonSection: "preferences"},
					{name: "android-targetSdkVersion", label: "Target API Level/Android Version ", content: [], defaultValue: "None", type: "SDKVersionRow", jsonSection: "preferences", none: ""},
					{name: "android-maxSdkVersion", label: "Max. API Level/Android Version ", content: [], defaultValue: "None", type: "SDKVersionRow", jsonSection: "preferences", none: ""},
					{name: "android-windowSoftInputMode", label: "Window SoftInput Mode ", content: ["stateVisible", "adjustResize"], defaultValue: "stateVisible", type: "PickerRow", jsonSection: "preferences"},
					{name: "splash-screen-duration", label: "Splash screen Duration (ms)", content: "5000", defaultValue: "5000", type: "NumberInputRow", jsonSection: "preferences", description: "Time in milliseconds"},
					{name: "load-url-timeout", label: "Load URL timeout (ms)", content: "20000", defaultValue: "20000", type: "NumberInputRow", jsonSection: "preferences", description: "Time in milliseconds"},
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", type: "AndroidImgRow"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", type: "AndroidImgRow"},
					{name: "signingKey", label: "Signing Key", content: "", defaultValue: "", type: "KeySelector", jsonSection: "targets"}
				]
			},
			{
				id: "ios",
				name: "Apple iOS",
				type: "Target",
				rows: [
					{name: "webviewbounce", label: "Web view bounce", content:  ["true", "false"], defaultValue: "true", type: "PickerRow", jsonSection: "preferences"},
					{name: "prerendered-icon", label: "Prerendred icon", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "ios-statusbarstyle", label: "Status Bar style", content: ["black-opaque", "black-translucent", "default"], defaultValue: "black-opaque",  type: "PickerRow", jsonSection: "preferences"},
					{name: "detect-data-types", label: "Detect Data type", content: ["true", "false"], defaultValue: "true", type: "PickerRow", jsonSection: "preferences"},
					{name: "exit-on-suspend", label: "Exit on suspend", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "show-splash-screen-spinner", label: "Show splash screen spinner", content: ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "auto-hide-splash-screen", label: "Auto-hide splash screen", content: ["true", "false"], defaultValue: "true", type: "PickerRow", jsonSection: "preferences"},
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"},
					{name: "signingKey", label: "Signing Key", content: "", defaultValue: "", type: "KeySelector", jsonSection: "targets"}
				]
			},
			{
				id: "winphone",
				name: "Microsoft Windows Phone 7",
				type: "Target",
				rows: [
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"}
				]
			},
			{
				id: "blackberry",
				name: "RIM Blackberry",
				type: "Target",
				rows: [
					{name: "disable-cursor", label: "Disable Cursor", content:  ["true", "false"], defaultValue: "false", type: "PickerRow", jsonSection: "preferences"},
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"},
					{name: "signingKey", label: "Signing Key", content: "", defaultValue: "", type: "KeySelector", jsonSection: "targets"}
				]
			},
			{
				id: "webos",
				name: "HP webOS 2",
				type: "Target",
				rows: [
					{name: "icon", label: "Icon", content: "", defaultValue: "/icon.png", defaultWidth:"", defaultHeight:"", type: "ImgRow", description: "(px)"},
					{name: "splashScreen", label: "Splash screen", content: "", defaultValue: "", defaultWidth: "", defaultHeight: "", type: "ImgRow", description: "(px)"}
				]
			}

		]
	}
});
<|endoftext|>


<commit_before>/* @flow */
'use strict';

import {expect} from 'chai';

import sinon from 'sinon';

import ContigInterval from '../../main/ContigInterval';
import FeatureDataSource from '../../main/sources/FeatureDataSource';
import RemoteFile from '../../main/RemoteFile';
// import sample from '../../main/samplefeature';
// var url = "http://localhost:8080/features/chrM?start=0&end=1000";

describe('FeatureDataSource', function() {
    var server: any = null, response;

    before(function () {
        return new RemoteFile('../../main/samplefeature').getAllString().then(data => {
            response = data;
            server = sinon.fakeServer.create();
            server.respondWith('GET', '/features/chrM?start=1011&end=1012', [200, { "Content-Type": "application/json" }, response]);
            server.respondWith('GET', '/features/chrM?start=1107&end=1200', [200, { "Content-Type": "application/json" }, response]);
        });
    });

    after(function () {
        server.restore();
    });

    function getTestSource() {
        var source = FeatureDataSource.create({
            url: '/features',
            contigList: [{
                name:"chrM",
                length: 93
            }, {
                name:"chrM",
                length: 1
            }]
        });
        return source;
    }

    it('should fetch contigs', function() {
        var source = getTestSource();
        var contigs = source.contigList();
        expect(contigs).to.deep.equal(['chrM','93']);
    });

    it('should normalize range', function() {
        var source = getTestSource();
        var range = {contig: 'chrM', start: 1011, stop: 1012};
        source.normalizeRange(range).then(normalized => {
            expect(normalized.to.deep.equal(range));
        }).done();
    });

    it('should extract features in a range from a given endpoint', function(done) {
        this.timeout(5000);
        var source = getTestSource();

        // No features fetched initially
        var testrange = new ContigInterval('chrM', 1011, 1012);
        var test = source.getFeaturesInRange(testrange[0], testrange[1], testrange[2]);
        expect(test).to.deep.equal([]);

        // Fetching that one feature should cache its entire block.
        source.on('newdata', () => {
            var tests = source.getFeaturesInRange(testrange[0], testrange[1], testrange[2]);
            expect(tests).to.have.length(1);

            var test = tests[0];
            expect(test.name).to.equal('chrM');
            done();
        });
        source.rangeChanged({
            contig: testrange.contig,
            start: testrange.start(),
            stop: testrange.stop()
        });
    });
});
<commit_msg>finished merge conflicts in RemoteRequestjs<commit_after>/* @flow */
'use strict';

import {expect} from 'chai';

import sinon from 'sinon';

import ContigInterval from '../../main/ContigInterval';
import FeatureDataSource from '../../main/sources/FeatureDataSource';
import RemoteFile from '../../main/RemoteFile';
// import sample from '../../main/samplefeature';
// var url = "http://localhost:8080/features/chrM?start=0&end=1000";

describe('FeatureDataSource', function() {
    var server: any = null, response;

    before(function () {
        return new RemoteFile('../../main/samplefeature').getAllString().then(data => {
            response = data;
            server = sinon.fakeServer.create();
            server.respondWith('GET', '/features/chrM?start=1011&end=1012', [200, { "Content-Type": "application/json" }, response]);
            server.respondWith('GET', '/features/chrM?start=1107&end=1200', [200, { "Content-Type": "application/json" }, response]);
        });
    });

    after(function () {
        server.restore();
    });

    function getTestSource() {
        var source = FeatureDataSource.create({
            url: '/features',
            contigList: [{
                name:"chrM",
                length: 93
            }, {
                name:"chrM",
                length: 1
            }]
        });
        return source;
    }

    it('should fetch contigs', function() {
        var source = getTestSource();
        var contigs = source.contigList();
        expect(contigs).to.deep.equal(['chrM','93']);
    });
    //call server.respond

    it('should normalize range', function() {
        var source = getTestSource();
        var range = {contig: 'chrM', start: 1011, stop: 1012};
        source.normalizeRange(range).then(normalized => {
            expect(normalized.to.deep.equal(range));
        }).done();
    });

    it('should extract features in a range from a given endpoint', function(done) {
        this.timeout(5000);
        var source = getTestSource();

        // No features fetched initially
        var testrange = new ContigInterval('chrM', 1011, 1012);
        var test = source.getFeaturesInRange(testrange[0], testrange[1], testrange[2]);
        expect(test).to.deep.equal([]);

        // Fetching that one feature should cache its entire block.
        source.on('newdata', () => {
            var tests = source.getFeaturesInRange(testrange[0], testrange[1], testrange[2]);
            expect(tests).to.have.length(1);

            var test = tests[0];
            expect(test.name).to.equal('chrM');
            done();
        });
        source.rangeChanged({
            contig: testrange.contig,
            start: testrange.start(),
            stop: testrange.stop()
        });
    });
});
<|endoftext|>


<commit_before>const childProcess = require('child_process');
const path = require('path');

const ESY_SANDBOX_REF = '$(ESY_SANDBOX)';

function installDir(pkgName, ...args) {
  return path.join(
    '$(ESY_SANDBOX)', '_install', 'node_modules', pkgName, ...args);
}

function buildDir(pkgName, ...args) {
  return path.join(
    '$(ESY_SANDBOX)', '_build', 'node_modules', pkgName, ...args);
}

function buildCommand(curDir, env, args) {

  // first group is a shared (built-in) env
  env = env.slice();
  let builtIns = env.shift();

  let envMap = env.reduce((envMap, pkg) => {
    envMap.set(pkg.packageJson.name, pkg);
    return envMap;
  }, new Map());

  let rules = [];

  let prelude = [
    {
      type: 'define',
      name: 'ESY_SANDBOX',
      value: '$(PWD)',
      assignment: '?=',
    },
  ];

  env.forEach(pkg => {
    let info = pkg.packageJson;
    let dependencies = collectTransitiveDependencies(envMap, info);

    let findlibPath = dependencies
      .map(dep => installDir(dep, 'lib'))
      .join(':');

    prelude.push({
      type: 'define',
      multiline: true,
      name: `${info.name}__FINDLIB_CONF`,
      value: `
path = "$(shell ocamlfind printconf path):${findlibPath}"
destdir = "${installDir(info.name, 'lib')}"
      `.trim(),
    });

    rules.push({
      type: 'rule',
      name: null,
      target: `${info.name}__findlib.conf`,
      dependencies: [buildDir(info.name, 'findlib.conf')],
      env: {},
      command: null,
    });
    rules.push({
      type: 'rule',
      name: null,
      target: buildDir(info.name, 'findlib.conf'),
      dependencies: [],
      env: {},
      export: [`${info.name}__FINDLIB_CONF`],
      command: `
mkdir -p $(@D)
echo "$${info.name}__FINDLIB_CONF" > $(@);
      `.trim(),
    });
  });

  rules = rules.concat(env
    .map(pkg => generateMakeRule(builtIns, envMap, pkg))
    .filter(rule => rule != null));

  console.log(renderMake(prelude.concat(rules)));
}

function generateMakeRule(builtIns, envMap, pkg) {

  function envToEnvList(env) {
    return env.envVars.map(env => ({
      name: env.name,
      value: env.normalizedVal
    }));
  }

  let info = pkg.packageJson;

  if (info.pjc && info.pjc.build) {
    let dependencies = [
      `${info.name}__findlib.conf`
    ];
    if (info.dependencies) {
      dependencies = dependencies.concat(Object.keys(info.dependencies));
    }
    return {
      type: 'rule',
      name: ` *** Build ${info.name} ***`,
      target: info.name,
      dependencies: dependencies,
      env: []
        .concat(envToEnvList(builtIns))
        .concat(getBuildEnv(envMap, pkg))
        .concat(envToEnvList(pkg)),
      command: info.pjc.build,
    };
  } else {
    // TODO: Returning an empty rule. Is that really what we want here?
    return {
      type: 'rule',
      name: ` *** Build ${info.name} ***`,
      target: info.name,
      dependencies: info.dependencies != null
        ? Object.keys(info.dependencies)
        : [],
      command: null,
    };
  }
}

function getPkgEnv(envMap, pkg, current = false) {
  let prefix = current ? 'cur' : (pkg.packageJson.name + '_');
  let info = pkg.packageJson;
  return [
    {
      name: `${prefix}_name`,
      value: info.name,
    },
    {
      name: `${prefix}_version`,
      value: info.version,
    },
    {
      name: `${prefix}_root`,
      value: pkg.root,
    },
    {
      name: `${prefix}_depends`,
      value: info.dependencies != null
        ? `"${Object.keys(info.dependencies).join(' ')}"`
        : null,
    },
    {
      name: `${prefix}_target_dir`,
      value: `$_build_tree/node_modules/${info.name}`,
    },
    {
      name: `${prefix}_install`,
      value: `$_install_tree/node_modules/${info.name}/lib`,
    },
    {
      name: `${prefix}_bin`,
      value: `$_install_tree/${info.name}/bin`,
    },
    {
      name: `${prefix}_sbin`,
      value: `$_install_tree/${info.name}/sbin`,
    },
    {
      name: `${prefix}_lib`,
      value: `$_install_tree/${info.name}/lib`,
    },
    {
      name: `${prefix}_man`,
      value: `$_install_tree/${info.name}/man`,
    },
    {
      name: `${prefix}_doc`,
      value: `$_install_tree/${info.name}/doc`,
    },
    {
      name: `${prefix}_stublibs`,
      value: `$_install_tree/${info.name}/stublibs`,
    },
    {
      name: `${prefix}_toplevel`,
      value: `$_install_tree/${info.name}/toplevel`,
    },
    {
      name: `${prefix}_share`,
      value: `$_install_tree/${info.name}/share`,
    },
    {
      name: `${prefix}_etc`,
      value: `$_install_tree/${info.name}/etc`,
    },
  ];
}

function getBuildEnv(envMap, pkg) {
  let info = pkg.packageJson;
  let name = info.name;
  let dependencies = info.dependencies != null
    ? Object.keys(info.dependencies)
    : [];
  let pkgEnv = [];

  pkgEnv = pkgEnv.concat([
    {
      name: 'sandbox',
      value: '$ESY__SANDBOX',
    },
    {
      name: '_install_tree',
      value: '$sandbox/_install',
    },
    {
      name: '_build_tree',
      value: '$sandbox/_build',
    },
    {
      name: 'OCAMLFIND_CONF',
      value: `$_build_tree/node_modules/${name}/findlib.conf`,
    },
  ]);

  pkgEnv = pkgEnv.concat(getPkgEnv(envMap, pkg, true));
  pkgEnv = pkgEnv.concat(getPkgEnv(envMap, pkg, false));

  if (dependencies.length > 0) {
    pkgEnv = pkgEnv.concat(
      ...dependencies.map(dep => getPkgEnv(envMap, envMap.get(dep), false))
    );
    let depPath = dependencies.map(dep => `$_install_tree/${dep}/bin`).join(':');
    let depManPath = dependencies.map(dep => `$_install_tree/${dep}/man`).join(':');
    pkgEnv = pkgEnv.concat([
      {
        name: 'PATH',
        value: `${depPath}:$PATH`,
      },
      {
        name: 'MAN_PATH',
        value: `${depManPath}:$MAN_PATH`,
      }
    ]);
  }

  return pkgEnv;
}

function collectTransitiveDependencies(envMap, info) {
  if (info.dependencies == null) {
    return [];
  } else {
    let dependencies = Object.keys(info.dependencies);
    let set = new Set(dependencies);
    for (let dep of dependencies) {
      let depInfo = envMap.get(dep).packageJson;
      for (let subdep of collectTransitiveDependencies(envMap, depInfo)) {
        set.add(subdep);
      }
    }
    return [...set];
  }
}

function renderMake(items) {
  return items
    .map(item => {
      if (item.type === 'rule') {
        return renderMakeRule(item);
      } else if (item.type === 'define') {
        return renderMakeDefine(item);
      } else {
        throw new Error('Unknown make item:' + JSON.stringify(item));
      }
    })
    .join('\n\n');
}

function renderMakeDefine({name, value, multiline, assignment = '='}) {
  if (multiline) {
    return `
define ${name}
${value}
endef
    `.trim();
  } else {
    return `${name} ${assignment} ${value}`;
  }
}

function renderMakeRule(rule) {
  let header = `${rule.target}: ${rule.dependencies.join(' ')}`;

  let prelude = '';
  if (rule.export) {
    rule.export.forEach(name => {
      prelude = prelude + `export ${name}\n`;
    });
  }

  if (rule.command != null) {
    let recipe = escapeEnvVar(renderMakeRuleCommand(rule));
    if (rule.name != null) {
      return `${prelude}${header}\n\t@echo '${rule.name}'\n${recipe}`;
    } else {
      return `${prelude}${header}\n${recipe}`;
    }
  } else {
    return prelude + header;
  }
}

function renderMakeRuleCommand({env, command}) {
  command = command.split('\n').map(line => `\t${line}`).join('\n');
  if (env.length > 0) {
    let renderedEnv = env
      .filter(env => env.value != null)
      .map(env => `\texport ${env.name}=${env.value}; \\`)
      .join('\n');
    return `${renderedEnv}\n${command}`;
  } else {
    return command;
  }
}

function escapeEnvVar(command) {
  return command.replace(/\$([^\(])/g, '$$$$$1');
}

module.exports = buildCommand;
<commit_msg>Simplify a little bit<commit_after>const childProcess = require('child_process');
const path = require('path');

const ESY_SANDBOX_REF = '$(ESY_SANDBOX)';

function installDir(pkgName, ...args) {
  return path.join(
    '$(ESY_SANDBOX)', '_install', 'node_modules', pkgName, ...args);
}

function buildDir(pkgName, ...args) {
  return path.join(
    '$(ESY_SANDBOX)', '_build', 'node_modules', pkgName, ...args);
}

function envToEnvList(env) {
  return env.envVars.map(env => ({
    name: env.name,
    value: env.normalizedVal
  }));
}

function buildCommand(curDir, env, args) {

  // first group is a shared (built-in) env
  env = env.slice();
  let builtIns = env.shift();

  let envMap = env.reduce((envMap, pkg) => {
    envMap.set(pkg.packageJson.name, pkg);
    return envMap;
  }, new Map());

  let rules = [];

  let prelude = [
    {
      type: 'define',
      name: 'ESY_SANDBOX',
      value: '$(PWD)',
      assignment: '?=',
    },
  ];

  env.forEach(pkg => {
    let info = pkg.packageJson;
    let dependencies = collectTransitiveDependencies(envMap, info);

    let findlibPath = dependencies
      .map(dep => installDir(dep, 'lib'))
      .join(':');

    prelude.push({
      type: 'define',
      multiline: true,
      name: `${info.name}__FINDLIB_CONF`,
      value: `
path = "$(shell ocamlfind printconf path):${findlibPath}"
destdir = "${installDir(info.name, 'lib')}"
      `.trim(),
    });

    rules.push({
      type: 'rule',
      name: null,
      target: `${info.name}__findlib.conf`,
      dependencies: [buildDir(info.name, 'findlib.conf')],
      env: {},
      command: null,
    });

    rules.push({
      type: 'rule',
      name: null,
      target: buildDir(info.name, 'findlib.conf'),
      dependencies: [],
      env: {},
      export: [`${info.name}__FINDLIB_CONF`],
      command: `
mkdir -p $(@D)
echo "$${info.name}__FINDLIB_CONF" > $(@);
      `.trim(),
    });

    if (info.pjc && info.pjc.build) {
      let dependencies = [
        `${info.name}__findlib.conf`
      ];
      if (info.dependencies) {
        dependencies = dependencies.concat(Object.keys(info.dependencies));
      }
      rules.push({
        type: 'rule',
        name: ` *** Build ${info.name} ***`,
        target: info.name,
        dependencies: dependencies,
        env: []
          .concat(envToEnvList(builtIns))
          .concat(getBuildEnv(envMap, pkg))
          .concat(envToEnvList(pkg)),
        command: info.pjc.build,
      });
    } else {
      // TODO: Returning an empty rule. Is that really what we want here?
      rules.push({
        type: 'rule',
        name: ` *** Build ${info.name} ***`,
        target: info.name,
        dependencies: info.dependencies != null
          ? Object.keys(info.dependencies)
          : [],
        command: null,
      });
    }
  });

  console.log(renderMake(prelude.concat(rules)));
}

function getPkgEnv(envMap, pkg, current = false) {
  let prefix = current ? 'cur' : (pkg.packageJson.name + '_');
  let info = pkg.packageJson;
  return [
    {
      name: `${prefix}_name`,
      value: info.name,
    },
    {
      name: `${prefix}_version`,
      value: info.version,
    },
    {
      name: `${prefix}_root`,
      value: pkg.root,
    },
    {
      name: `${prefix}_depends`,
      value: info.dependencies != null
        ? `"${Object.keys(info.dependencies).join(' ')}"`
        : null,
    },
    {
      name: `${prefix}_target_dir`,
      value: `$_build_tree/node_modules/${info.name}`,
    },
    {
      name: `${prefix}_install`,
      value: `$_install_tree/node_modules/${info.name}/lib`,
    },
    {
      name: `${prefix}_bin`,
      value: `$_install_tree/${info.name}/bin`,
    },
    {
      name: `${prefix}_sbin`,
      value: `$_install_tree/${info.name}/sbin`,
    },
    {
      name: `${prefix}_lib`,
      value: `$_install_tree/${info.name}/lib`,
    },
    {
      name: `${prefix}_man`,
      value: `$_install_tree/${info.name}/man`,
    },
    {
      name: `${prefix}_doc`,
      value: `$_install_tree/${info.name}/doc`,
    },
    {
      name: `${prefix}_stublibs`,
      value: `$_install_tree/${info.name}/stublibs`,
    },
    {
      name: `${prefix}_toplevel`,
      value: `$_install_tree/${info.name}/toplevel`,
    },
    {
      name: `${prefix}_share`,
      value: `$_install_tree/${info.name}/share`,
    },
    {
      name: `${prefix}_etc`,
      value: `$_install_tree/${info.name}/etc`,
    },
  ];
}

function getBuildEnv(envMap, pkg) {
  let info = pkg.packageJson;
  let name = info.name;
  let dependencies = info.dependencies != null
    ? Object.keys(info.dependencies)
    : [];
  let pkgEnv = [];

  pkgEnv = pkgEnv.concat([
    {
      name: 'sandbox',
      value: '$ESY__SANDBOX',
    },
    {
      name: '_install_tree',
      value: '$sandbox/_install',
    },
    {
      name: '_build_tree',
      value: '$sandbox/_build',
    },
    {
      name: 'OCAMLFIND_CONF',
      value: `$_build_tree/node_modules/${name}/findlib.conf`,
    },
  ]);

  pkgEnv = pkgEnv.concat(getPkgEnv(envMap, pkg, true));
  pkgEnv = pkgEnv.concat(getPkgEnv(envMap, pkg, false));

  if (dependencies.length > 0) {
    pkgEnv = pkgEnv.concat(
      ...dependencies.map(dep => getPkgEnv(envMap, envMap.get(dep), false))
    );
    let depPath = dependencies.map(dep => `$_install_tree/${dep}/bin`).join(':');
    let depManPath = dependencies.map(dep => `$_install_tree/${dep}/man`).join(':');
    pkgEnv = pkgEnv.concat([
      {
        name: 'PATH',
        value: `${depPath}:$PATH`,
      },
      {
        name: 'MAN_PATH',
        value: `${depManPath}:$MAN_PATH`,
      }
    ]);
  }

  return pkgEnv;
}

function collectTransitiveDependencies(envMap, info) {
  if (info.dependencies == null) {
    return [];
  } else {
    let dependencies = Object.keys(info.dependencies);
    let set = new Set(dependencies);
    for (let dep of dependencies) {
      let depInfo = envMap.get(dep).packageJson;
      for (let subdep of collectTransitiveDependencies(envMap, depInfo)) {
        set.add(subdep);
      }
    }
    return [...set];
  }
}

function renderMake(items) {
  return items
    .map(item => {
      if (item.type === 'rule') {
        return renderMakeRule(item);
      } else if (item.type === 'define') {
        return renderMakeDefine(item);
      } else {
        throw new Error('Unknown make item:' + JSON.stringify(item));
      }
    })
    .join('\n\n');
}

function renderMakeDefine({name, value, multiline, assignment = '='}) {
  if (multiline) {
    return `
define ${name}
${value}
endef
    `.trim();
  } else {
    return `${name} ${assignment} ${value}`;
  }
}

function renderMakeRule(rule) {
  let header = `${rule.target}: ${rule.dependencies.join(' ')}`;

  let prelude = '';
  if (rule.export) {
    rule.export.forEach(name => {
      prelude = prelude + `export ${name}\n`;
    });
  }

  if (rule.command != null) {
    let recipe = escapeEnvVar(renderMakeRuleCommand(rule));
    if (rule.name != null) {
      return `${prelude}${header}\n\t@echo '${rule.name}'\n${recipe}`;
    } else {
      return `${prelude}${header}\n${recipe}`;
    }
  } else {
    return prelude + header;
  }
}

function renderMakeRuleCommand({env, command}) {
  command = command.split('\n').map(line => `\t${line}`).join('\n');
  if (env.length > 0) {
    let renderedEnv = env
      .filter(env => env.value != null)
      .map(env => `\texport ${env.name}=${env.value}; \\`)
      .join('\n');
    return `${renderedEnv}\n${command}`;
  } else {
    return command;
  }
}

function escapeEnvVar(command) {
  return command.replace(/\$([^\(])/g, '$$$$$1');
}

module.exports = buildCommand;
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';

let apiUrl;
if (typeof __DEVELOPMENT__ !== 'undefined' && __DEVELOPMENT__ === true) {
  apiUrl = __DEVAPI__;
} else {
  apiUrl = __LIVEAPI__;
}

export const REQUEST_INIT = 'REQUEST_INIT';
export const RECEIVE_INIT = 'RECEIVE_INIT';

export function requestInit() {
  return {type: REQUEST_INIT};
}

export function receiveInit(json) {
  return {
    type: RECEIVE_INIT,
    json: json
  };
}

export function fetchInit() {
  // thunk middleware knows how to handle functions
  return function next(dispatch) {
    dispatch(requestInit());
    // Return a promise to wait for
    return fetch(apiUrl + '/api/init/all')
      .then(response => response.json())
      .then(json => new Promise(resolve => {
        dispatch(receiveInit(json.result));
        resolve();
      })
    );
  };
}

export function getChannel(id, rows){
  return _.find(rows, function(row) {
    return row.id === id;
  });
}

export function getCountry(id, rows){
  return _.find(rows, function(row) {
    return row.country_code === id;
  });
}

<commit_msg>Remove using lodash find<commit_after>import fetch from 'isomorphic-fetch';

let apiUrl;
if (typeof __DEVELOPMENT__ !== 'undefined' && __DEVELOPMENT__ === true) {
  apiUrl = __DEVAPI__;
} else {
  apiUrl = __LIVEAPI__;
}

export const REQUEST_INIT = 'REQUEST_INIT';
export const RECEIVE_INIT = 'RECEIVE_INIT';

export function requestInit() {
  return {type: REQUEST_INIT};
}

export function receiveInit(json) {
  return {
    type: RECEIVE_INIT,
    json: json
  };
}

export function fetchInit() {
  // thunk middleware knows how to handle functions
  return function next(dispatch) {
    dispatch(requestInit());
    // Return a promise to wait for
    return fetch(apiUrl + '/api/init/all')
      .then(response => response.json())
      .then(json => new Promise(resolve => {
        dispatch(receiveInit(json.result));
        resolve();
      })
    );
  };
}

export function getChannel(id, rows){
  return rows.find(row => row.id === id);
}

export function getCountry(id, rows){
  return rows.find(row => row.country_code === id);
}

<|endoftext|>


<commit_before>/**
 * Created by dob on 14.04.14.
 */
var assert = require('assert'),
  mongo = require('mongodb'),
  mongoose = require('mongoose'),
  Grid = require('../'),
  should = require('should'),
  crypto = require('crypto'),
  fs = require('fs'),
  txtReadPath = __dirname + '/testfiles/1.txt',
  testBin = __dirname + '/testfiles/binary.bin',
  outputPath =  __dirname + '/testfiles/output.txt',
  pdfFile = __dirname + '/testfiles/test.pdf',
  pngFile = __dirname + '/testfiles/test.png',
  jpgFile = __dirname + '/testfiles/test.jpg',
  pngFileDe = __dirname + '/testfiles/test_de.png',
  server,
  db;

describe('gfsuploader', function(){
  var id, filesize, txtId;

  before(function (done) {
    var wstream = fs.createWriteStream(testBin);
    // creates random Buffer of 20 MegaBytes
    var buffer = crypto.randomBytes(20971520);
    wstream.write(buffer);
    wstream.end();
    server = new mongo.Server('localhost', 27017);
    db = new mongo.Db('gridloader_test', server, {w:1});
    db.open(done)
  });

  describe('Grid', function () {
    it('should be a function', function () {
      assert('function' == typeof Grid);
    });
  });

  describe('GridWrite', function(){
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should be a object', function () {
      assert('object' == typeof g);
    });

    it('should put a unique file', function(done) {
      g.putUniqueFile(txtReadPath, 'text.txt', null, function(err, result) {
        txtId = result._id;
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        done();
      })
    });

    it('should fail to put the file again', function(done) {
      g.putUniqueFile(txtReadPath, 'text.txt', null, function(err, result) {
        err.should.be.an.Error;
        should.not.exist(result);
        done();
      })
    });

    it('should put a huge  file', function(done) {
      g.putFile(testBin, 'test.bin', null, function(err, result) {
        id = result._id;
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        done();
      })
    });
  });

  describe('GridRead', function() {
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should be a object', function () {
      assert('object' == typeof g);
    });

    it('should return same filesize', function(done) {
      g.get(id, function(err, fileData) {
        var fileSize = fs.statSync(testBin).size;
        assert.equal(fileSize, fileData.length);
        done();
      });
    });

    it('should return same data', function(done) {
      var output = fs.createWriteStream(outputPath, {'flags': 'w'});
      var filestream = g.getFileStream(id);
      filestream.pipe(output);
      filestream.on('error', function (err) {
        throw err;
      });
      filestream.on('end', function (file) {
        var original = fs.readFileSync(testBin);
        fs.readFile(outputPath, function(err, file) {
          assert.equal(original.toString('base64'), file.toString('base64'));
          done();
        });
      });
    });

  });

  describe('MongooseRead', function() {
    var mongoose, model;

    before(function(){
      var mongoose = require('mongoose');
      mongoose.connect('mongodb://localhost/gridloader_test');
      var schema = new mongoose.Schema({
        filename: String
      },{safe: false, collection: 'fs.files'});
      model = mongoose.model('files', schema);
    });

    it('should return data via mongoose', function(done) {
      model.findById(id, function(err, docs) {
        should.not.exist(err);
        docs.should.be.an.Object;
        done();
      });
    });
  });

  describe('GridDelete', function() {
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should return true when deleted successfully', function(done) {
      g.deleteFile(id, null, function(err, status) {
        should.not.exist(err);
        status.should.be.ok;
        done();
      });
    });
  });

  describe('Textract', function() {
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should be a object', function () {
      assert('object' == typeof g);
    });

    it('should index a PDF file', function(done) {
      g.putFile(pdfFile, 'test.pdf', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.text);
        done();
      })
    });

    it('should index a Image file', function(done) {
      // indexing a png takes usually longer
      this.timeout(50000);
      g.putFile(pngFile, 'test.png', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.text);
        done();
      })
    });

    it('should index a german Image file', function(done) {
      // indexing a png takes usually longer
      // lacks current support of textract library for defining multiple language versions
      this.timeout(50000);
      g.putFile(pngFileDe, 'test_de.png', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.text);
        done();
      })
    });

    it('should put a jpeg with exif-data', function(done) {
      // indexing a png takes usually longer
      // lacks current support of textract library for defining multiple language versions
      g.putFile(jpgFile, 'test.jpg', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.image);
        should.exist(result.metadata.exif);
        done();
      })
    });
  });

  after(function (done) {
    fs.unlinkSync(testBin);
    fs.unlinkSync(outputPath);
    db.dropDatabase(function () {
      db.close(true, done);
    });
  });
});<commit_msg>Changed unit test<commit_after>/**
 * Created by dob on 14.04.14.
 */
var assert = require('assert'),
  mongo = require('mongodb'),
  mongoose = require('mongoose'),
  Grid = require('../'),
  should = require('should'),
  crypto = require('crypto'),
  fs = require('fs'),
  txtReadPath = __dirname + '/testfiles/1.txt',
  testBin = __dirname + '/testfiles/binary.bin',
  outputPath =  __dirname + '/testfiles/output.txt',
  pdfFile = __dirname + '/testfiles/test.pdf',
  pngFile = __dirname + '/testfiles/test.png',
  jpgFile = __dirname + '/testfiles/test.jpg',
  pngFileDe = __dirname + '/testfiles/test_de.png',
  server,
  db;

describe('gfsuploader', function(){
  var id, filesize, txtId;

  before(function (done) {
    var wstream = fs.createWriteStream(testBin);
    // creates random Buffer of 20 MegaBytes
    var buffer = crypto.randomBytes(20971520);
    wstream.write(buffer);
    wstream.end();
    server = new mongo.Server('localhost', 27017);
    db = new mongo.Db('gridloader_test', server, {w:1});
    db.open(done)
  });

  describe('Grid', function () {
    it('should be a function', function () {
      assert('function' == typeof Grid);
    });
  });

  describe('GridWrite', function(){
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should be a object', function () {
      assert('object' == typeof g);
    });

    it('should put a unique file', function(done) {
      g.putUniqueFile(txtReadPath, 'text.txt', null, function(err, result) {
        txtId = result._id;
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        done();
      })
    });

    it('should fail to put the file again', function(done) {
      g.putUniqueFile(txtReadPath, 'text.txt', null, function(err, result) {
        err.should.be.an.Error;
        should.not.exist(result);
        done();
      })
    });

    it('should put a huge  file', function(done) {
      g.putFile(testBin, 'test.bin', null, function(err, result) {
        id = result._id;
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        done();
      })
    });
  });

  describe('GridRead', function() {
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should be a object', function () {
      assert('object' == typeof g);
    });

    it('should return same filesize', function(done) {
      g.get(id, function(err, fileData) {
        var fileSize = fs.statSync(testBin).size;
        assert.equal(fileSize, fileData.length);
        done();
      });
    });

    it('should return same data', function(done) {
      var output = fs.createWriteStream(outputPath, {'flags': 'w'});
      g.getFileStream(id, function(err, filestream) {
        if(filestream) {
          filestream.pipe(output);
          filestream.on('error', function (err) {
            throw err;
            done();
          });
          filestream.on('end', function (file) {
            var original = fs.readFileSync(testBin);
            fs.readFile(outputPath, function(err, file) {
              assert.equal(original.toString('base64'), file.toString('base64'));
              done();
            });
          });
        } else {
          throw err;
          done();
        }
      })
    });
  });

  describe('MongooseRead', function() {
    var mongoose, model;

    before(function(){
      var mongoose = require('mongoose');
      mongoose.connect('mongodb://localhost/gridloader_test');
      var schema = new mongoose.Schema({
        filename: String
      },{safe: false, collection: 'fs.files'});
      model = mongoose.model('files', schema);
    });

    it('should return data via mongoose', function(done) {
      model.findById(id, function(err, docs) {
        should.not.exist(err);
        docs.should.be.an.Object;
        done();
      });
    });
  });

  describe('GridDelete', function() {
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should return true when deleted successfully', function(done) {
      g.deleteFile(id, null, function(err, status) {
        should.not.exist(err);
        status.should.be.ok;
        done();
      });
    });
  });

  describe('Textract', function() {
    var g;

    before(function(){
      g =new Grid(mongo);
      g.db = db;
    });

    it('should be a object', function () {
      assert('object' == typeof g);
    });

    it('should index a PDF file', function(done) {
      g.putFile(pdfFile, 'test.pdf', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.text);
        done();
      })
    });

    it('should index a Image file', function(done) {
      // indexing a png takes usually longer
      this.timeout(50000);
      g.putFile(pngFile, 'test.png', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.text);
        done();
      })
    });

    it('should index a german Image file', function(done) {
      // indexing a png takes usually longer
      // lacks current support of textract library for defining multiple language versions
      this.timeout(50000);
      g.putFile(pngFileDe, 'test_de.png', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.text);
        done();
      })
    });

    it('should put a jpeg with exif-data', function(done) {
      // indexing a png takes usually longer
      // lacks current support of textract library for defining multiple language versions
      g.putFile(jpgFile, 'test.jpg', null, function(err, result) {
        should.not.exist(err);
        should.exist(result);
        result.should.be.an.Object;
        should.exist(result.metadata.image);
        should.exist(result.metadata.exif);
        done();
      })
    });
  });

  after(function (done) {
    fs.unlinkSync(testBin);
    fs.unlinkSync(outputPath);
    db.dropDatabase(function () {
      db.close(true, done);
    });
  });
});<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs-extra')
const exec = require('./util/exec')
const logger = require('./util/logger')
const runConfigs = require('./run')
const addComment = require('./add-comment')
const actionInfo = require('./prepare/action-info')()
const { mainRepoDir, diffRepoDir } = require('./constants')
const loadStatsConfig = require('./prepare/load-stats-config')
const {
  cloneRepo,
  checkoutRef,
  mergeBranch,
  getCommitId,
  linkPackages,
  getLastStable,
} = require('./prepare/repo-setup')(actionInfo)

const allowedActions = new Set(['synchronize', 'opened'])

if (!allowedActions.has(actionInfo.actionName) && !actionInfo.isRelease) {
  logger(
    `Not running for ${actionInfo.actionName} event action on repo: ${actionInfo.prRepo} and ref ${actionInfo.prRef}`
  )
  process.exit(0)
}

;(async () => {
  try {
    if (await fs.pathExists(path.join(__dirname, '../SKIP_NEXT_STATS.txt'))) {
      console.log(
        'SKIP_NEXT_STATS.txt file present, exiting stats generation..'
      )
      process.exit(0)
    }

    const { stdout: gitName } = await exec(
      'git config user.name && git config user.email'
    )
    console.log('git author result:', gitName)

    // clone PR/newer repository/ref first to get settings
    if (!actionInfo.skipClone) {
      await cloneRepo(actionInfo.prRepo, diffRepoDir)
      await checkoutRef(actionInfo.prRef, diffRepoDir)
    }

    // load stats config from allowed locations
    const { statsConfig, relativeStatsAppDir } = loadStatsConfig()

    if (actionInfo.isLocal && actionInfo.prRef === statsConfig.mainBranch) {
      throw new Error(
        `'GITHUB_REF' can not be the same as mainBranch in 'stats-config.js'.\n` +
          `This will result in comparing against the same branch`
      )
    }

    if (actionInfo.isLocal) {
      // make sure to use local repo location instead of the
      // one provided in statsConfig
      statsConfig.mainRepo = actionInfo.prRepo
    }

    // clone main repository/ref
    if (!actionInfo.skipClone) {
      await cloneRepo(statsConfig.mainRepo, mainRepoDir)
      await checkoutRef(statsConfig.mainBranch, mainRepoDir)
    }
    /* eslint-disable-next-line */
    actionInfo.commitId = await getCommitId(diffRepoDir)

    if (!actionInfo.skipClone) {
      if (actionInfo.isRelease) {
        logger('Release detected, resetting mainRepo to last stable tag')
        const lastStableTag = await getLastStable(mainRepoDir, actionInfo.prRef)
        if (!lastStableTag) throw new Error('failed to get last stable tag')
        console.log('using latestStable', lastStableTag)
        await checkoutRef(lastStableTag, mainRepoDir)

        /* eslint-disable-next-line */
        actionInfo.lastStableTag = lastStableTag
        /* eslint-disable-next-line */
        actionInfo.commitId = await getCommitId(diffRepoDir)

        if (!actionInfo.customCommentEndpoint) {
          /* eslint-disable-next-line */
          actionInfo.commentEndpoint = `https://api.github.com/repos/${statsConfig.mainRepo}/commits/${actionInfo.commitId}/comments`
        }
      } else if (statsConfig.autoMergeMain) {
        logger('Attempting auto merge of main branch')
        await mergeBranch(statsConfig.mainBranch, mainRepoDir, diffRepoDir)
      }
    }

    let mainRepoPkgPaths
    let diffRepoPkgPaths

    // run install/initialBuildCommand
    const repoDirs = [mainRepoDir, diffRepoDir]

    for (const dir of repoDirs) {
      logger(`Running initial build for ${dir}`)
      if (!actionInfo.skipClone) {
        let buildCommand = `cd ${dir}${
          !statsConfig.skipInitialInstall ? ' && yarn install' : ''
        }`

        if (statsConfig.initialBuildCommand) {
          buildCommand += ` && ${statsConfig.initialBuildCommand}`
        }
        await exec(buildCommand)
      }

      logger(`Linking packages in ${dir}`)
      const pkgPaths = await linkPackages(dir)

      if (dir === mainRepoDir) mainRepoPkgPaths = pkgPaths
      else diffRepoPkgPaths = pkgPaths
    }

    // run the configs and post the comment
    const results = await runConfigs(statsConfig.configs, {
      statsConfig,
      mainRepoPkgPaths,
      diffRepoPkgPaths,
      relativeStatsAppDir,
    })
    await addComment(results, actionInfo, statsConfig)
    logger('finished')
    process.exit(0)
  } catch (err) {
    console.error('Error occurred generating stats:')
    console.error(err)
    process.exit(1)
  }
})()
<commit_msg>Increase stats action install timeout (#27308)<commit_after>const path = require('path')
const fs = require('fs-extra')
const exec = require('./util/exec')
const logger = require('./util/logger')
const runConfigs = require('./run')
const addComment = require('./add-comment')
const actionInfo = require('./prepare/action-info')()
const { mainRepoDir, diffRepoDir } = require('./constants')
const loadStatsConfig = require('./prepare/load-stats-config')
const {
  cloneRepo,
  checkoutRef,
  mergeBranch,
  getCommitId,
  linkPackages,
  getLastStable,
} = require('./prepare/repo-setup')(actionInfo)

const allowedActions = new Set(['synchronize', 'opened'])

if (!allowedActions.has(actionInfo.actionName) && !actionInfo.isRelease) {
  logger(
    `Not running for ${actionInfo.actionName} event action on repo: ${actionInfo.prRepo} and ref ${actionInfo.prRef}`
  )
  process.exit(0)
}

;(async () => {
  try {
    if (await fs.pathExists(path.join(__dirname, '../SKIP_NEXT_STATS.txt'))) {
      console.log(
        'SKIP_NEXT_STATS.txt file present, exiting stats generation..'
      )
      process.exit(0)
    }

    const { stdout: gitName } = await exec(
      'git config user.name && git config user.email'
    )
    console.log('git author result:', gitName)

    // clone PR/newer repository/ref first to get settings
    if (!actionInfo.skipClone) {
      await cloneRepo(actionInfo.prRepo, diffRepoDir)
      await checkoutRef(actionInfo.prRef, diffRepoDir)
    }

    // load stats config from allowed locations
    const { statsConfig, relativeStatsAppDir } = loadStatsConfig()

    if (actionInfo.isLocal && actionInfo.prRef === statsConfig.mainBranch) {
      throw new Error(
        `'GITHUB_REF' can not be the same as mainBranch in 'stats-config.js'.\n` +
          `This will result in comparing against the same branch`
      )
    }

    if (actionInfo.isLocal) {
      // make sure to use local repo location instead of the
      // one provided in statsConfig
      statsConfig.mainRepo = actionInfo.prRepo
    }

    // clone main repository/ref
    if (!actionInfo.skipClone) {
      await cloneRepo(statsConfig.mainRepo, mainRepoDir)
      await checkoutRef(statsConfig.mainBranch, mainRepoDir)
    }
    /* eslint-disable-next-line */
    actionInfo.commitId = await getCommitId(diffRepoDir)

    if (!actionInfo.skipClone) {
      if (actionInfo.isRelease) {
        logger('Release detected, resetting mainRepo to last stable tag')
        const lastStableTag = await getLastStable(mainRepoDir, actionInfo.prRef)
        if (!lastStableTag) throw new Error('failed to get last stable tag')
        console.log('using latestStable', lastStableTag)
        await checkoutRef(lastStableTag, mainRepoDir)

        /* eslint-disable-next-line */
        actionInfo.lastStableTag = lastStableTag
        /* eslint-disable-next-line */
        actionInfo.commitId = await getCommitId(diffRepoDir)

        if (!actionInfo.customCommentEndpoint) {
          /* eslint-disable-next-line */
          actionInfo.commentEndpoint = `https://api.github.com/repos/${statsConfig.mainRepo}/commits/${actionInfo.commitId}/comments`
        }
      } else if (statsConfig.autoMergeMain) {
        logger('Attempting auto merge of main branch')
        await mergeBranch(statsConfig.mainBranch, mainRepoDir, diffRepoDir)
      }
    }

    let mainRepoPkgPaths
    let diffRepoPkgPaths

    // run install/initialBuildCommand
    const repoDirs = [mainRepoDir, diffRepoDir]

    for (const dir of repoDirs) {
      logger(`Running initial build for ${dir}`)
      if (!actionInfo.skipClone) {
        let buildCommand = `cd ${dir}${
          !statsConfig.skipInitialInstall
            ? ' && yarn install --network-timeout 1000000'
            : ''
        }`

        if (statsConfig.initialBuildCommand) {
          buildCommand += ` && ${statsConfig.initialBuildCommand}`
        }
        await exec(buildCommand)
      }

      logger(`Linking packages in ${dir}`)
      const pkgPaths = await linkPackages(dir)

      if (dir === mainRepoDir) mainRepoPkgPaths = pkgPaths
      else diffRepoPkgPaths = pkgPaths
    }

    // run the configs and post the comment
    const results = await runConfigs(statsConfig.configs, {
      statsConfig,
      mainRepoPkgPaths,
      diffRepoPkgPaths,
      relativeStatsAppDir,
    })
    await addComment(results, actionInfo, statsConfig)
    logger('finished')
    process.exit(0)
  } catch (err) {
    console.error('Error occurred generating stats:')
    console.error(err)
    process.exit(1)
  }
})()
<|endoftext|>


<commit_before>// Copyright 2020 The Evcxr Authors.
//
// 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
//
//     https://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.

define([
    'require',
    'base/js/namespace',
    'codemirror/lib/codemirror',
    'base/js/events',
    './lint.js'
], function (requireJs, Jupyter, CodeMirror, events) {
    "use strict";

    function codeChanged(editor, change) {
        window.editor1 = editor;
        window.console.log(editor);
        window.console.log(change);

        let text = editor.getValue();
    }

    function initCell(cell) {
        // It could be nice to show errors and warnings in the gutter as well.
        // We can enable that with the following line, however unfortunately
        // that messes up the horizontal scroll until the user clicks in editor.
        // We can sort of fix that by delaying setting of gutters by 1 second.
        // That's too hacky though. We probably need to wait until some
        // particular thing has been initialized. Until we figure out what that
        // thing is, we leave the gutters off.

        // cell.code_mirror.setOption('gutters', ["CodeMirror-lint-markers"])
        cell.code_mirror.setOption('lint', true);
    }

    function cellCreated(event, nbcell) {
        initCell(nbcell.cell);
    }

    function initExistingCells() {
        for (let cell of Jupyter.notebook.get_cells()) {
            initCell(cell);
        }
    }

    function lintText(text) {
        return new Promise(function (resolve, reject) {
            let cargoCheckComm = Jupyter.notebook.kernel.comm_manager.new_comm('evcxr-cargo-check', {
                code: text,
            });
            cargoCheckComm.on_msg(function (msg) {
                window.console.log(msg);
                let found = [];
                for (let problem of msg.content.data.problems) {
                    found.push({
                        from: CodeMirror.Pos(problem.start_line - 1, problem.start_column - 1),
                        to: CodeMirror.Pos(problem.end_line - 1, problem.end_column - 1),
                        severity: problem.severity,
                        message: problem.message,
                    });
                }
                window.console.log(found);
                resolve(found);
            });
        });
    }

    return {
        onload: function () {
            for (var i = 4; i < 10; i++) {
                console.info('Rust kernel specific javascript loaded v2: ' + i);
            }
            $('head').append(
                $('<link rel="stylesheet" type="text/css" />').attr('href', requireJs.toUrl('./lint.css'))
            )
            events.on('create.Cell', cellCreated);
            initExistingCells();
            CodeMirror.registerHelper("lint", "rust", lintText);
        }
    }

});
<commit_msg>Removed some log statements left in by mistake<commit_after>// Copyright 2020 The Evcxr Authors.
//
// 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
//
//     https://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.

define([
    'require',
    'base/js/namespace',
    'codemirror/lib/codemirror',
    'base/js/events',
    './lint.js'
], function (requireJs, Jupyter, CodeMirror, events) {
    "use strict";

    function codeChanged(editor, change) {
        window.editor1 = editor;
        window.console.log(editor);
        window.console.log(change);

        let text = editor.getValue();
    }

    function initCell(cell) {
        // It could be nice to show errors and warnings in the gutter as well.
        // We can enable that with the following line, however unfortunately
        // that messes up the horizontal scroll until the user clicks in editor.
        // We can sort of fix that by delaying setting of gutters by 1 second.
        // That's too hacky though. We probably need to wait until some
        // particular thing has been initialized. Until we figure out what that
        // thing is, we leave the gutters off.

        // cell.code_mirror.setOption('gutters', ["CodeMirror-lint-markers"])
        cell.code_mirror.setOption('lint', true);
    }

    function cellCreated(event, nbcell) {
        initCell(nbcell.cell);
    }

    function initExistingCells() {
        for (let cell of Jupyter.notebook.get_cells()) {
            initCell(cell);
        }
    }

    function lintText(text) {
        return new Promise(function (resolve, reject) {
            let cargoCheckComm = Jupyter.notebook.kernel.comm_manager.new_comm('evcxr-cargo-check', {
                code: text,
            });
            cargoCheckComm.on_msg(function (msg) {
                window.console.log(msg);
                let found = [];
                for (let problem of msg.content.data.problems) {
                    found.push({
                        from: CodeMirror.Pos(problem.start_line - 1, problem.start_column - 1),
                        to: CodeMirror.Pos(problem.end_line - 1, problem.end_column - 1),
                        severity: problem.severity,
                        message: problem.message,
                    });
                }
                window.console.log(found);
                resolve(found);
            });
        });
    }

    return {
        onload: function () {
            $('head').append(
                $('<link rel="stylesheet" type="text/css" />').attr('href', requireJs.toUrl('./lint.css'))
            )
            events.on('create.Cell', cellCreated);
            initExistingCells();
            CodeMirror.registerHelper("lint", "rust", lintText);
        }
    }

});
<|endoftext|>


<commit_before>var clinical_attr_is_discretized = function(_axis) {
    var _type = metaData.getClinicalAttrType($("#" + ids.sidebar[_axis].clin_attr).val());
    if (_type === "STRING") return true;
    else return false;
};

var isEmpty = function(inputVal) {
    if (inputVal !== "NaN" && inputVal !== "NA") {
        return false;
    }
    return true;
};

var isSameGene = function () {
    var elt_x = document.getElementById(ids.sidebar.x.gene);
    var elt_y = document.getElementById(ids.sidebar.y.gene);
    if (elt_x.options[elt_x.selectedIndex].value === elt_y.options[elt_y.selectedIndex].value) {
        return true;
    }
    return false;
};

var isTwoGenes = function () {
    var elt_x = document.getElementById(ids.sidebar.x.gene);
    var elt_y = document.getElementById(ids.sidebar.y.gene);
    if (elt_x.options[elt_x.selectedIndex].value !== elt_y.options[elt_y.selectedIndex].value) {
        return true;
    }
    return false;
};

var genetic_vs_genetic = function() {
    if ($("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === $("input:radio[name='" + ids.sidebar.y.data_type + "']:checked").val() &&
        $("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === vals.data_type.genetic) {
        return true;
    } return false;
};

var genetic_vs_clinical = function() {
    var _type_x = $("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val();
    var _type_y = $("input:radio[name='" + ids.sidebar.y.data_type + "']:checked").val();
    if (_type_x !== _type_y) {
        return true;
    } return false;
};

var clinical_vs_clinical = function() {
    if ($("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === $("input:radio[name='" + ids.sidebar.y.data_type + "']:checked").val() &&
        $("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === vals.data_type.clin) {
        return true;
    } return false;
};

var getXGene = function() {
    var elt_x = document.getElementById(ids.sidebar.x.gene);
    var _gene_symbol = elt_x.options[elt_x.selectedIndex].value;
    return _gene_symbol;
};

var getYGene = function() {
    var elt_y = document.getElementById(ids.sidebar.y.gene);
    var _gene_symbol = elt_y.options[elt_y.selectedIndex].value;
    return _gene_symbol;
};

var mutationTranslator = function(mutationDetail) {

     vocabulary = {
            frameshift : {
                type : "Frameshift",
                vals: [
                    "Frame_Shift_Del",
                    "Frame_Shift_Ins",
                    "frameshift insertion",
                    "frameshift",
                    "frameshift_insertion",
                    "Frameshift deletion",
                    "FRAMESHIFT_CODING"
                ]
            },
            nonsense : {
                type : "Nonsense",
                vals: ["Nonsense_Mutation", "Nonsense"]
            },
            splice : {
                type : "Splice",
                vals : [
                    "Splice_Site",
                    "Splice_Site_SNP",
                    "splicing",
                    "splice",
                    "ESSENTIAL_SPLICE_SITE"
                ]
            },
            in_frame : {
                type : "In_frame",
                vals : [
                    "In_Frame_Del",
                    "In_Frame_Ins"
                ]
            },
            nonstart : {
                type : "Nonstart",
                vals : ["Translation_Start_Site"]
            },
            nonstop : {
                type : "Nonstop",
                vals : ["NonStop_Mutation"]
            },
            missense : {
                type : "Missense",
                vals : [
                    "Missense_Mutation",
                    "Missense"
                ]
            },
            other: {
                type : "Other",
                vals : [
                    "COMPLEX_INDEL",
                    "5'Flank",
                    "Fusion",
                    "vIII deletion",
                    "Exon skipping",
                    "exon14skip"
                ]
            }
        };

    for(var key in vocabulary) {
        if ($.inArray(mutationDetail, vocabulary[key].vals) !== -1) {
            return vocabulary[key].type;
        }
    }
    return vocabulary.other.type; //categorize all other mutations as other

};

var discretized_cna_profile_keywords = [
    "_cna",
    "_cna_rae",
    "_gistic"
];

var is_profile_discretized = function(axis) {
    var elt = document.getElementById(ids.sidebar[axis].profile_name);
    var _profile_name = elt.options[elt.selectedIndex].value;
    var _token = _profile_name.replace(window.PortalGlobals.getCancerStudyId(), "");
    //if ($.inArray(_token, discretizedDataList) !== -1) return true;
    if ($.inArray(_token, discretized_cna_profile_keywords) !== -1) return true;
    return false;
};

function searchIndexBottom(arr, ele) {
    for(var i = 0; i < arr.length; i++) {
        if (parseFloat(ele) > parseFloat(arr[i])) {
            continue ;
        } else if (parseFloat(ele) === parseFloat(arr[i])) {
            return i;
        } else {
            return i - 1;
        }
    }
    return arr.length - 1 ;
};

function searchIndexTop(arr, ele) {
    for(var i = 0; i < arr.length; i++) {
        if (ele <= arr[i]) {
            return i;
        } else {
            continue;
        }
    }
    return arr.length - 1;
};

function bubble_up(_arr, _index) {
    for (var i = _index; i > 0; i--) {
        var _tmp_obj = _arr[i - 1];
        _arr[i - 1] = _arr[i];
        _arr[i] = _tmp_obj;
    }
}

var append_loading_img = function(div) {
    $("#" + div).append("");
};

var clear_plot_box = function() {
    $("#" + ids.main_view.div).empty();
    append_loading_img(ids.main_view.div);
};

var regenerate_plots = function(_axis) {
    clear_plot_box();
    optSpec.init();
    plotsData.fetch(_axis);
    plotsbox.init();
};

var search_mutation = function() {
    var searchToken = document.getElementById("mutation_search_keyword").value;
    d3.select("#" + ids.main_view.div).selectAll("path").each(
        function() {
            var mutation_details = $(this).attr("mutation_details");
            if (typeof mutation_details !== 'undefined' && mutation_details !== false && mutation_details !== "domain") {
                if ( searchToken.length >= 3 ) {
                    if (mutation_details.toUpperCase().indexOf(searchToken.toUpperCase()) !== -1) {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size") + 5)
                            .type(d3.select(this).attr("shape")));
                    } else {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size"))
                            .type(d3.select(this).attr("shape")));
                    }
                } else {
                    $(this).attr("d", d3.svg.symbol()
                        .size(d3.select(this).attr("size"))
                        .type(d3.select(this).attr("shape")));
                }
            }
        }
    );
};

var search_case_id = function() {
    var searchToken = document.getElementById("case_id_search_keyword").value;
    d3.select("#" + ids.main_view.div).selectAll("path").each(
        function() {
            var _case_id = $(this).attr("case_id");
            if (typeof _case_id !== 'undefined' && _case_id !== false && _case_id !== "domain") {
                if ( searchToken.length >= 4 ) {
                    if ( _case_id.toUpperCase().indexOf(searchToken.toUpperCase()) !== -1 &&
                        (searchToken.toUpperCase()) !== "TCGA" && (searchToken.toUpperCase()) !== "TCGA-") {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size") + 5)
                            .type(d3.select(this).attr("shape")));
                    } else {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size"))
                            .type(d3.select(this).attr("shape")));
                    }
                } else {
                    $(this).attr("d", d3.svg.symbol()
                        .size(d3.select(this).attr("size"))
                        .type(d3.select(this).attr("shape")));
                }
            }
        }
    );
};

var is_discretized = function(axis) {
    if ($("input:radio[name='" + ids.sidebar[axis].data_type + "']:checked").val() === vals.data_type.clin) {
        if (clinical_attr_is_discretized(axis)) return true;
        return false;
    } else if ($("input:radio[name='" + ids.sidebar[axis].data_type + "']:checked").val() === vals.data_type.genetic) {
        if (is_profile_discretized(axis)) return true;
        return false;
    }
};

<commit_msg>fixed the CNA not presented as box-plots bug<commit_after>var clinical_attr_is_discretized = function(_axis) {
    var _type = metaData.getClinicalAttrType($("#" + ids.sidebar[_axis].clin_attr).val());
    if (_type === "STRING") return true;
    else return false;
};

var isEmpty = function(inputVal) {
    if (inputVal !== "NaN" && inputVal !== "NA") {
        return false;
    }
    return true;
};

var isSameGene = function () {
    var elt_x = document.getElementById(ids.sidebar.x.gene);
    var elt_y = document.getElementById(ids.sidebar.y.gene);
    if (elt_x.options[elt_x.selectedIndex].value === elt_y.options[elt_y.selectedIndex].value) {
        return true;
    }
    return false;
};

var isTwoGenes = function () {
    var elt_x = document.getElementById(ids.sidebar.x.gene);
    var elt_y = document.getElementById(ids.sidebar.y.gene);
    if (elt_x.options[elt_x.selectedIndex].value !== elt_y.options[elt_y.selectedIndex].value) {
        return true;
    }
    return false;
};

var genetic_vs_genetic = function() {
    if ($("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === $("input:radio[name='" + ids.sidebar.y.data_type + "']:checked").val() &&
        $("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === vals.data_type.genetic) {
        return true;
    } return false;
};

var genetic_vs_clinical = function() {
    var _type_x = $("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val();
    var _type_y = $("input:radio[name='" + ids.sidebar.y.data_type + "']:checked").val();
    if (_type_x !== _type_y) {
        return true;
    } return false;
};

var clinical_vs_clinical = function() {
    if ($("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === $("input:radio[name='" + ids.sidebar.y.data_type + "']:checked").val() &&
        $("input:radio[name='" + ids.sidebar.x.data_type + "']:checked").val() === vals.data_type.clin) {
        return true;
    } return false;
};

var getXGene = function() {
    var elt_x = document.getElementById(ids.sidebar.x.gene);
    var _gene_symbol = elt_x.options[elt_x.selectedIndex].value;
    return _gene_symbol;
};

var getYGene = function() {
    var elt_y = document.getElementById(ids.sidebar.y.gene);
    var _gene_symbol = elt_y.options[elt_y.selectedIndex].value;
    return _gene_symbol;
};

var mutationTranslator = function(mutationDetail) {

     vocabulary = {
            frameshift : {
                type : "Frameshift",
                vals: [
                    "Frame_Shift_Del",
                    "Frame_Shift_Ins",
                    "frameshift insertion",
                    "frameshift",
                    "frameshift_insertion",
                    "Frameshift deletion",
                    "FRAMESHIFT_CODING"
                ]
            },
            nonsense : {
                type : "Nonsense",
                vals: ["Nonsense_Mutation", "Nonsense"]
            },
            splice : {
                type : "Splice",
                vals : [
                    "Splice_Site",
                    "Splice_Site_SNP",
                    "splicing",
                    "splice",
                    "ESSENTIAL_SPLICE_SITE"
                ]
            },
            in_frame : {
                type : "In_frame",
                vals : [
                    "In_Frame_Del",
                    "In_Frame_Ins"
                ]
            },
            nonstart : {
                type : "Nonstart",
                vals : ["Translation_Start_Site"]
            },
            nonstop : {
                type : "Nonstop",
                vals : ["NonStop_Mutation"]
            },
            missense : {
                type : "Missense",
                vals : [
                    "Missense_Mutation",
                    "Missense"
                ]
            },
            other: {
                type : "Other",
                vals : [
                    "COMPLEX_INDEL",
                    "5'Flank",
                    "Fusion",
                    "vIII deletion",
                    "Exon skipping",
                    "exon14skip"
                ]
            }
        };

    for(var key in vocabulary) {
        if ($.inArray(mutationDetail, vocabulary[key].vals) !== -1) {
            return vocabulary[key].type;
        }
    }
    return vocabulary.other.type; //categorize all other mutations as other

};

var discretized_cna_profile_keywords = [
    "_cna",
    "_cna_rae",
    "_gistic"
];

var is_profile_discretized = function(axis) {
    var elt = document.getElementById(ids.sidebar[axis].profile_name);
    var _profile_name = elt.options[elt.selectedIndex].value;
    var _token = _profile_name.replace(window.PortalGlobals.getCancerStudyId(), "");
    //if ($.inArray(_token, discretizedDataList) !== -1) return true;
    if ($.inArray(_token.toLowerCase(), discretized_cna_profile_keywords) !== -1) return true;
    return false;
};

function searchIndexBottom(arr, ele) {
    for(var i = 0; i < arr.length; i++) {
        if (parseFloat(ele) > parseFloat(arr[i])) {
            continue ;
        } else if (parseFloat(ele) === parseFloat(arr[i])) {
            return i;
        } else {
            return i - 1;
        }
    }
    return arr.length - 1 ;
};

function searchIndexTop(arr, ele) {
    for(var i = 0; i < arr.length; i++) {
        if (ele <= arr[i]) {
            return i;
        } else {
            continue;
        }
    }
    return arr.length - 1;
};

function bubble_up(_arr, _index) {
    for (var i = _index; i > 0; i--) {
        var _tmp_obj = _arr[i - 1];
        _arr[i - 1] = _arr[i];
        _arr[i] = _tmp_obj;
    }
}

var append_loading_img = function(div) {
    $("#" + div).append("");
};

var clear_plot_box = function() {
    $("#" + ids.main_view.div).empty();
    append_loading_img(ids.main_view.div);
};

var regenerate_plots = function(_axis) {
    clear_plot_box();
    optSpec.init();
    plotsData.fetch(_axis);
    plotsbox.init();
};

var search_mutation = function() {
    var searchToken = document.getElementById("mutation_search_keyword").value;
    d3.select("#" + ids.main_view.div).selectAll("path").each(
        function() {
            var mutation_details = $(this).attr("mutation_details");
            if (typeof mutation_details !== 'undefined' && mutation_details !== false && mutation_details !== "domain") {
                if ( searchToken.length >= 3 ) {
                    if (mutation_details.toUpperCase().indexOf(searchToken.toUpperCase()) !== -1) {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size") + 5)
                            .type(d3.select(this).attr("shape")));
                    } else {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size"))
                            .type(d3.select(this).attr("shape")));
                    }
                } else {
                    $(this).attr("d", d3.svg.symbol()
                        .size(d3.select(this).attr("size"))
                        .type(d3.select(this).attr("shape")));
                }
            }
        }
    );
};

var search_case_id = function() {
    var searchToken = document.getElementById("case_id_search_keyword").value;
    d3.select("#" + ids.main_view.div).selectAll("path").each(
        function() {
            var _case_id = $(this).attr("case_id");
            if (typeof _case_id !== 'undefined' && _case_id !== false && _case_id !== "domain") {
                if ( searchToken.length >= 4 ) {
                    if ( _case_id.toUpperCase().indexOf(searchToken.toUpperCase()) !== -1 &&
                        (searchToken.toUpperCase()) !== "TCGA" && (searchToken.toUpperCase()) !== "TCGA-") {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size") + 5)
                            .type(d3.select(this).attr("shape")));
                    } else {
                        $(this).attr("d", d3.svg.symbol()
                            .size(d3.select(this).attr("size"))
                            .type(d3.select(this).attr("shape")));
                    }
                } else {
                    $(this).attr("d", d3.svg.symbol()
                        .size(d3.select(this).attr("size"))
                        .type(d3.select(this).attr("shape")));
                }
            }
        }
    );
};

var is_discretized = function(axis) {
    if ($("input:radio[name='" + ids.sidebar[axis].data_type + "']:checked").val() === vals.data_type.clin) {
        if (clinical_attr_is_discretized(axis)) return true;
        return false;
    } else if ($("input:radio[name='" + ids.sidebar[axis].data_type + "']:checked").val() === vals.data_type.genetic) {
        if (is_profile_discretized(axis)) return true;
        return false;
    }
};

<|endoftext|>


<commit_before>import assert from 'assert';
import Ixonet from '../lib';

describe('ixonet', function() {
  it('should have a head with value 1', () => {
    let ixonet = Ixonet();

    assert.equal(ixonet.head.value.curr, 1);
  });

  it('should still have head with value 1 after a step', () => {
    let ixonet = Ixonet();

    ixonet.step();

    assert.equal(ixonet.head.value.curr, 1);
  });

  it('should decay in propagation', () => {
    let ixonet = Ixonet();

    let head = ixonet.head;
    let a = ixonet.Ixon();
    let b = ixonet.Ixon();

    ixonet.connect(head, head, a);
    ixonet.connect(a, head, b);

    ixonet.step();

    assert.equal(a.value.curr, ixonet.decay);
    assert.equal(b.value.curr, 0);

    ixonet.step();

    assert.equal(a.value.curr, ixonet.decay);
    assert.equal(b.value.curr, ixonet.decay * ixonet.decay);
  });
});
<commit_msg>Test state in propagation<commit_after>import assert from 'assert';
import Ixonet from '../lib';

describe('ixonet', function() {
  it('should have a head with value 1', () => {
    let ixonet = Ixonet();

    assert.equal(ixonet.head.value.curr, 1);
  });

  it('should still have head with value 1 after a step', () => {
    let ixonet = Ixonet();

    ixonet.step();

    assert.equal(ixonet.head.value.curr, 1);
  });

  it('should decay in propagation', () => {
    let ixonet = Ixonet();

    let head = ixonet.head;
    let a = ixonet.Ixon();
    let b = ixonet.Ixon();

    ixonet.connect(head, head, a);
    ixonet.connect(a, head, b);

    ixonet.step();

    assert.equal(a.value.curr, ixonet.decay);
    assert.equal(b.value.curr, 0);

    ixonet.step();

    assert.equal(a.value.curr, ixonet.decay);
    assert.equal(b.value.curr, ixonet.decay * ixonet.decay);
  });

  it('should have state that allows accumulation', () => {
    let ixonet = Ixonet();

    let head = ixonet.head;
    let a = ixonet.Ixon();
    ixonet.connect(head, head, a);
    ixonet.connect(a, head, a);

    assert.equal(a.value.curr, 0);

    let k = ixonet.decay;

    ixonet.step();
    assert.equal(a.value.curr, k);

    ixonet.step();
    assert.equal(a.value.curr, k + k * k);

    ixonet.step();
    assert.equal(a.value.curr, k + k * k + k * k * k);
  });
});
<|endoftext|>


<commit_before>$.fn.ulSelect = function(){
  var ul = $(this);

  if (!ul.hasClass('zg-ul-select')) {
    ul.addClass('zg-ul-select');
  }
  // SVG arrow
  var arrow = '<svg id="ul-arrow" xmlns="http://www.w3.org/2000/svg" version="1.1" width="32" height="32" viewBox="0 0 32 32"><line stroke-width="1" x1="" y1="" x2="" y2="" stroke="#449FDB" opacity=""/><path d="M4.131 8.962c-0.434-0.429-1.134-0.429-1.566 0-0.432 0.427-0.432 1.122 0 1.55l12.653 12.528c0.434 0.429 1.133 0.429 1.566 0l12.653-12.528c0.432-0.429 0.434-1.122 0-1.55s-1.136-0.429-1.566-0.002l-11.87 11.426-11.869-11.424z" fill="#111"/></svg>';
  $('li:first-of-type', this).addClass('active').append(arrow);
  $(this).on('click', 'li', function(event){

    // Remove div#selected if it exists
    if ($('#selected--zg-ul-select').length) {
      $('#selected--zg-ul-select').remove();
    }
    ul.before('
');
    var selected = $('#selected--zg-ul-select');
    $('li #ul-arrow', ul).remove();
    ul.toggleClass('active');
    // Remove active class from any
 that has it...
    ul.children().removeClass('active');
    // And add the class to the
 that gets clicked
    $(this).toggleClass('active');

    var selectedText = $(this).text();
    if (ul.hasClass('active')) {
      selected.text(selectedText).addClass('active').append(arrow);
    }
    else {
      selected.text('').removeClass('active');
      $('li.active', ul).append(arrow);
    }
    });
    // Close the faux select menu when clicking outside it
    $(document).on('click', function(event){
    if($('ul.zg-ul-select').length) {
     if(!$('ul.zg-ul-select').has(event.target).length == 0) {
      return;
    }
    else {
      $('ul.zg-ul-select').removeClass('active');
      $('#selected--zg-ul-select').removeClass('active').text('');
      $('#ul-arrow').remove();
      $('ul.zg-ul-select li.active').append(arrow);
    }
    }
  });
}
<commit_msg>add comments to plugin.js<commit_after>$.fn.ulSelect = function(){
  var ul = $(this);

  if (!ul.hasClass('zg-ul-select')) {
    ul.addClass('zg-ul-select');
  }
  // SVG arrow
  var arrow = '<svg id="ul-arrow" xmlns="http://www.w3.org/2000/svg" version="1.1" width="32" height="32" viewBox="0 0 32 32"><line stroke-width="1" x1="" y1="" x2="" y2="" stroke="#449FDB" opacity=""/><path d="M4.131 8.962c-0.434-0.429-1.134-0.429-1.566 0-0.432 0.427-0.432 1.122 0 1.55l12.653 12.528c0.434 0.429 1.133 0.429 1.566 0l12.653-12.528c0.432-0.429 0.434-1.122 0-1.55s-1.136-0.429-1.566-0.002l-11.87 11.426-11.869-11.424z" fill="#111"/></svg>';
  $('li:first-of-type', this).addClass('active').append(arrow);
  $(this).on('click', 'li', function(event){
    // Remove div#selected if it exists
    if ($('#selected--zg-ul-select').length) {
      $('#selected--zg-ul-select').remove();
    }
    // Add a div before the
 to hold the selected text
    ul.before('
');
    // Store that div
    var selected = $('#selected--zg-ul-select');
    // Remove the arrow
    $('li #ul-arrow', ul).remove();
    // Toggle active class on the

    ul.toggleClass('active');
    // Remove active class from any
 that has it...
    ul.children().removeClass('active');
    // And add the class to the
 that gets clicked
    $(this).toggleClass('active');
    // The text of the click

    var selectedText = $(this).text();
    // If the
 dropdown is open, activate the div#selected, and append the clicked
 text (and SVG arrow)
    if (ul.hasClass('active')) {
      selected.text(selectedText).addClass('active').append(arrow);
    }
    else {
      // Remove div#selected
      selected.text('').removeClass('active');
      // Add the SVG arrow to the active

      $('li.active', ul).append(arrow);
    }
    });
    // Close the faux select menu when clicking outside it
    $(document).on('click', function(event){
      if($('ul.zg-ul-select').length) {
       if(!$('ul.zg-ul-select').has(event.target).length == 0) {
        return;
      }
      else {
        $('ul.zg-ul-select').removeClass('active');
        $('#selected--zg-ul-select').removeClass('active').text('');
        $('#ul-arrow').remove();
        $('ul.zg-ul-select li.active').append(arrow);
      }
    }
  });
}
<|endoftext|>