<commit_before>var async = require('async');
var chalk = require('chalk');
var chai = require("chai");
var expect = chai.expect;
var inspect = require("util").inspect;

var Cluster = require('../cluster');
var cluster;

var ERROR_THRESHOLD = 10;

function SIGN_COLOR(value, threshold, inverse) {
    var scavenge = value, color = "black";
    // If value is string account for single character pre/postfix (very specific/awful implementation)
    if(typeof value === 'string') {
        // Ignore First & Last Chars
        if(typeof value[0] === 'string') value = value.substring(1);
        if(typeof value[value.length - 1] === 'string') value = value.substr(0, scavenge.length - 2);
        // Ends with MS
        if(value.slice(-2) === 'ms') value = value.substr(0, scavenge.length - 3);
        value = parseFloat(value);
    }
    if(!threshold) threshold = 0;
    if(inverse) color = (value > threshold)?'red':((value < threshold)?'green':'yellow');
    else color = (value > threshold)?'green':((value < threshold)?'red':'yellow');

    return chalk[color](scavenge);
}

function NANO_TO_MS(val, decimals) {
    var m = Math.pow(10, (decimals || 3));
    return Math.round((val/1e+6) * m)/m;
}

function REDUCE_STATS(array) {
    var MIN = Math.min.apply(Math, array), MAX = Math.max.apply(Math, array);
    var SUM = array.reduce(function(a, b) { return a + b; });
    var AVG = SUM / array.length;
    for(var i=0; i<array.length; i++) {

    }
    return {
        min: MIN,
        max: MAX,
        average: AVG,
        error: Math.round((Math.abs(AVG - MIN)/Math.abs(MIN) + Math.abs(AVG - MAX)/Math.abs(MAX))/2 * 100000)/1000,
        sum: SUM
    };
}

function MAKE_BENCHMARK(func, iterations, callback) {
    var count = 0;
    var stats = [];
    async.doWhilst(function BENCHMARK_WRAPPER(callback){
        count++;
        var started = process.hrtime();
        func(function BENCHMARK_CALLBACK(error){
            var finished = process.hrtime(started);
            // Calculate Time Difference
            var diff = finished[0] * 1e9 + finished[1];
            stats.push(diff);
            callback(error, stats);
        });
    }, function BENCHMARK_ITERATOR(){
        return count < (iterations || 10);
    }, function BENCHMARK_RESULTS(error){
        callback(error, REDUCE_STATS(stats));
    });
}

function OUTPUT_BENCHMARK(func, iterations, threshold, callback) {
    MAKE_BENCHMARK(func, iterations, function(error, stats) {
        console.log("--------------------------\nBENCHMARK RESULTS FOR", chalk.cyan(func.name || 'Unknown'));
        if(error) {
            console.log(chalk.red("> BENCHMARK FAILED <"));
            console.trace(error);
        }else{
            console.log(">  Averaged at", NANO_TO_MS(stats.average) + 'ms', SIGN_COLOR("±" + stats.error + '%', threshold || ERROR_THRESHOLD, true));
            console.log(">  Worst Case:", NANO_TO_MS(stats.max) + 'ms', "Best Case:", NANO_TO_MS(stats.min) + 'ms');
            console.log(">  Total time:", NANO_TO_MS(stats.sum) + 'ms', "for", iterations, "rounds");
        }
        console.log("--------------------------");
        if(callback) callback(error, stats);
    });
}

// Finish the compare method
/*function COMPARE_BENCHMARK(funcs, iterations, callback) {
    async.series(funcs, function BENCHMARK_COMPARER(error, results) {

    });
}*/

describe("Init Test Suite", function() {
    this.timeout(20000);
    it('should construct an instance', function() {
        cluster = new Cluster();
        cluster.deploy();
    });
    it('should run tasks on the cluster with arguments', function(done) {
        cluster.addShared('multiply', 'module.exports = function m(a, b, callback){ callback(null, a*b); }', function(error, task) {
            if(error) throw error;
            task.distribute(function(error, success) {
                if(error) throw error;
                expect(success[0]).to.be.gt(0);
                OUTPUT_BENCHMARK(function Basic_Parallel_Test(callback){
                    // Parallelize on all cores
                    async.each(new Array(require('os').cpus().length), function(i, callback) {
                        cluster.do('multiply', 4, 8, function(error, r) {
                            if(!error && (r !== 4*8)) error = new Error("Wrong output");
                            callback(error);
                        });
                    }, callback);
                }, 1000, 15, function(){
                    console.log("Finished running", 1000 * require('os').cpus().length, "tests");
                    done();
                });
            });
        });
    });
});<commit_msg>Implemented Automatic benchmark parallelization<commit_after>var async = require('async');
var chalk = require('chalk');
var chai = require("chai");
var expect = chai.expect;
var inspect = require("util").inspect;

var Cluster = require('../cluster');
var cluster;

var ERROR_THRESHOLD = 10;

function SIGN_COLOR(value, threshold, inverse) {
    var scavenge = value, color = "black";
    // If value is string account for single character pre/postfix (very specific/awful implementation)
    if(typeof value === 'string') {
        // Ignore First & Last Chars
        if(typeof value[0] === 'string') value = value.substring(1);
        if(typeof value[value.length - 1] === 'string') value = value.substr(0, scavenge.length - 2);
        // Ends with MS
        if(value.slice(-2) === 'ms') value = value.substr(0, scavenge.length - 3);
        value = parseFloat(value);
    }
    if(!threshold) threshold = 0;
    if(inverse) color = (value > threshold)?'red':((value < threshold)?'green':'yellow');
    else color = (value > threshold)?'green':((value < threshold)?'red':'yellow');

    return chalk[color](scavenge);
}

function NANO_TO_MS(val, decimals) {
    var m = Math.pow(10, (decimals || 3));
    return Math.round((val/1e+6) * m)/m;
}

function REDUCE_STATS(array) {
    var MIN = Math.min.apply(Math, array), MAX = Math.max.apply(Math, array);
    var SUM = array.reduce(function(a, b) { return a + b; });
    var AVG = SUM / array.length;
    for(var i=0; i<array.length; i++) {

    }
    return {
        min: MIN,
        max: MAX,
        average: AVG,
        error: Math.round((Math.abs(AVG - MIN)/Math.abs(MIN) + Math.abs(AVG - MAX)/Math.abs(MAX))/2 * 100000)/1000,
        sum: SUM,
        total: array.length
    };
}

function MAKE_BENCHMARK(func, options, callback) {
    var count = 0;
    var stats = [];
    var Total_Started = process.hrtime();
    async.doWhilst(function BENCHMARK_WRAPPER(callback){
        count++;
        function BENCHMARK_CALLBACK(unique_callback){
            var started = process.hrtime();
            return function BENCHMARK_CALLBACK__FUNC(error) {
                var finished = process.hrtime(started);
                // Calculate Time Difference
                var diff = finished[0] * 1e9 + finished[1];
                // Push difference to stats
                stats.push(diff);
                unique_callback(error, stats);
            };
        }
        if(options.parallel) {
            // Parallelize on all cores
            async.times(options.parallel, function(n, parallel_callback){
                func(BENCHMARK_CALLBACK(parallel_callback));
            }, callback);
        }else{
            func(BENCHMARK_CALLBACK(callback));
        }
    }, function BENCHMARK_ITERATOR(){
        return count < (options.iterations || 10);
    }, function BENCHMARK_RESULTS(error){
        var Reduced = REDUCE_STATS(stats);
        var Total_Finished = process.hrtime(Total_Started);
        // Calculate Time Difference
        Reduced.overall = Total_Finished[0] * 1e9 + Total_Finished[1];
        callback(error, Reduced);
    });
}

function OUTPUT_BENCHMARK(func, options, callback) {
    function LOG() {
        // Mocha ident
        var prepend = "    ";
        var args = Array.prototype.slice.call(arguments);
        args.unshift(prepend);
        args = args.map(function(v){
            // Add prepend after all new lines created with \n\r ...
            if(typeof v === 'string') v = v.replace(/(?:\r\n|\r|\n)/g, "\n" + prepend);
            return chalk.gray(v);
        });
        console.log.apply(console, args);
    }
    MAKE_BENCHMARK(func, options, function(error, stats) {
        LOG("\n" + chalk.green('√'), chalk.white("BENCHMARK RESULTS FOR"), chalk.cyan(func.name || 'Unknown'));
        if(error) {
            LOG(chalk.red("> BENCHMARK FAILED <"));
            console.trace(error);
        }else{
            LOG("\tAveraged at", NANO_TO_MS(stats.average) + 'ms', SIGN_COLOR("±" + stats.error + '%', options.threshold || ERROR_THRESHOLD, true));
            LOG("\tWorst Case:", NANO_TO_MS(stats.max) + 'ms', "Best Case:", NANO_TO_MS(stats.min) + 'ms');
            LOG("\tTotal time:", NANO_TO_MS(stats.overall) + 'ms', "for", stats.total, "rounds");
        }
        LOG();
        if(callback) callback(error, stats);
    });
}

// Finish the compare method
/*function COMPARE_BENCHMARK(funcs, iterations, callback) {
    async.series(funcs, function BENCHMARK_COMPARER(error, results) {

    });
}*/

describe("Init Test Suite", function() {
    this.timeout(20000);
    it('should construct an instance', function() {
        cluster = new Cluster();
        cluster.deploy();
    });
    it('should run tasks on the cluster with arguments', function(done) {
        cluster.addShared('multiply', 'module.exports = function m(a, b, callback){ callback(null, a*b); }', function(error, task) {
            if(error) throw error;
            task.distribute(function(error, success) {
                if(error) throw error;
                expect(success[0]).to.be.gt(0);
                OUTPUT_BENCHMARK(function Basic_Parallel_Test(callback){
                    cluster.do('multiply', 4, 8, function(error, r) {
                        if(!error && (r !== 4*8)) error = new Error("Wrong output");
                        callback(error);
                    });
                }, { iterations: 100, threshold: 15, parallel: require('os').cpus().length }, function(){
                    done();
                });
            });
        });
    });
});<|endoftext|>


<commit_before>/*global config*/
import React from 'react';
import { render } from 'react-dom';
import { createHistory } from 'history';
import { Router, useRouterHistory } from 'react-router';
import routes from './routes';
import Cookies from 'js-cookie';

if (!config.apiRoot) {
  console.warn('You need to set your apiRoot via localStorage');
  console.warn('e.g. localStorage["apiRootOverride"] = "https://path.to-api.com/v1/api"');
}

if (config.fullstoryToken && Cookies.get(config.usernameCookie)) {
  FS.identify(Cookies.get(config.usernameCookie), {
    app: 'blazar'
  });
}

const browserHistory = useRouterHistory(createHistory) ({
  basename: config.appRoot
});

render(
  <Router history={browserHistory}>
    {routes}
  </Router>,
  document.getElementById('app')
);
<commit_msg>temporary testing<commit_after>/*global config*/
import React from 'react';
import { render } from 'react-dom';
import { createHistory } from 'history';
import { Router, useRouterHistory } from 'react-router';
import routes from './routes';
import Cookies from 'js-cookie';

if (!config.apiRoot) {
  console.warn('You need to set your apiRoot via localStorage');
  console.warn('e.g. localStorage["apiRootOverride"] = "https://path.to-api.com/v1/api"');
}

if (config.fullstoryToken && Cookies.get(config.usernameCookie)) {
  console.log("Got in the if");
  FS.identify(Cookies.get(config.usernameCookie), {
    app: 'blazar'
  });
} else {
  console.log("Did not get in the if");
}

console.log("Fullstory token: ", config.fullstoryToken);
console.log("Cookie key: ", config.usernameCookie);
console.log("Cookie val: ", Cookies.get(config.usernameCookie));

const browserHistory = useRouterHistory(createHistory) ({
  basename: config.appRoot
});

render(
  <Router history={browserHistory}>
    {routes}
  </Router>,
  document.getElementById('app')
);
<|endoftext|>


<commit_before>var cdb = require('cartodb.js-v3');
cdb.admin = require('cdb.admin');
var $ = require('jquery-cdb-v3');
var navigateThroughRouter = require('../../../view_helpers/navigate_through_router');

/**
 * The content of the dropdown menu opened by the link at the end of the breadcrumbs menu, e.g.
 *   username > [Maps]
 *          ______/\____
 *         |            |
 *         |    this    |
 *         |____________|
 */
module.exports = cdb.admin.DropdownMenu.extend({
  className: 'Dropdown BreadcrumbsDropdown',

  events: {
    'click a':  '_navigateToLinksHref'
  },

  initialize: function() {
    this.elder('initialize');
    if (!this.options.viewModel) {
      throw new Error('viewModel must be provided');
    }
    this.viewModel = this.options.viewModel;
    // Optional
    this.router = this.options.router;
  },

  render: function() {
    var dashboardUrl = this.model.viewUrl().dashboard();
    var datasetsUrl = dashboardUrl.datasets();
    var deepInsightsUrl = dashboardUrl.deepInsights();
    var mapsUrl = dashboardUrl.maps();

    this.$el.html(this.template_base({
      avatarUrl: this.model.get('avatar_url'),
      userName: this.model.get('username'),
      mapsUrl: mapsUrl,
      datasetsUrl: datasetsUrl,
      deepInsightsUrl: deepInsightsUrl,
      lockedDatasetsUrl: datasetsUrl.lockedItems(),
      lockedMapsUrl: mapsUrl.lockedItems(),
      isDeepInsightsEnabled: this.model.featureEnabled('cartod1b'),
      isDeepInsights: this.viewModel.isDisplayingDeepInsights(),
      isDatasets: this.viewModel.isDisplayingDatasets(),
      isMaps: this.viewModel.isDisplayingMaps(),
      isLocked: this.viewModel.isDisplayingLockedItems()
    }));

    // Necessary to hide dialog on click outside popup, for example.
    cdb.god.bind('closeDialogs', this.hide, this);

    // TODO: taken from existing code, how should dropdowns really be added to the DOM?
    $('body').append(this.el);

    return this;
  },

  _navigateToLinksHref: function() {
    this.hide(); //hide must be called before routing for proper deconstruct of dropdown
    if (this.options.router) {
      navigateThroughRouter.apply(this, arguments);
    }
  },

  clean: function() {
    // Until https://github.com/CartoDB/cartodb.js/issues/238 is resolved:
    $(this.options.target).unbind("click", this._handleClick);
    this.constructor.__super__.clean.apply(this);
  }
});
<commit_msg>remove variable load for cartod1b ff from dropdown view<commit_after>var cdb = require('cartodb.js-v3');
cdb.admin = require('cdb.admin');
var $ = require('jquery-cdb-v3');
var navigateThroughRouter = require('../../../view_helpers/navigate_through_router');

/**
 * The content of the dropdown menu opened by the link at the end of the breadcrumbs menu, e.g.
 *   username > [Maps]
 *          ______/\____
 *         |            |
 *         |    this    |
 *         |____________|
 */
module.exports = cdb.admin.DropdownMenu.extend({
  className: 'Dropdown BreadcrumbsDropdown',

  events: {
    'click a':  '_navigateToLinksHref'
  },

  initialize: function() {
    this.elder('initialize');
    if (!this.options.viewModel) {
      throw new Error('viewModel must be provided');
    }
    this.viewModel = this.options.viewModel;
    // Optional
    this.router = this.options.router;
  },

  render: function() {
    var dashboardUrl = this.model.viewUrl().dashboard();
    var datasetsUrl = dashboardUrl.datasets();
    var deepInsightsUrl = dashboardUrl.deepInsights();
    var mapsUrl = dashboardUrl.maps();

    this.$el.html(this.template_base({
      avatarUrl: this.model.get('avatar_url'),
      userName: this.model.get('username'),
      mapsUrl: mapsUrl,
      datasetsUrl: datasetsUrl,
      deepInsightsUrl: deepInsightsUrl,
      lockedDatasetsUrl: datasetsUrl.lockedItems(),
      lockedMapsUrl: mapsUrl.lockedItems(),
      isDeepInsights: this.viewModel.isDisplayingDeepInsights(),
      isDatasets: this.viewModel.isDisplayingDatasets(),
      isMaps: this.viewModel.isDisplayingMaps(),
      isLocked: this.viewModel.isDisplayingLockedItems()
    }));

    // Necessary to hide dialog on click outside popup, for example.
    cdb.god.bind('closeDialogs', this.hide, this);

    // TODO: taken from existing code, how should dropdowns really be added to the DOM?
    $('body').append(this.el);

    return this;
  },

  _navigateToLinksHref: function() {
    this.hide(); //hide must be called before routing for proper deconstruct of dropdown
    if (this.options.router) {
      navigateThroughRouter.apply(this, arguments);
    }
  },

  clean: function() {
    // Until https://github.com/CartoDB/cartodb.js/issues/238 is resolved:
    $(this.options.target).unbind("click", this._handleClick);
    this.constructor.__super__.clean.apply(this);
  }
});
<|endoftext|>


<commit_before>define([ "lodash",
         "dojo/_base/declare",
         "dojo/_base/array",
         "dojo/Deferred",
         "dojo/dom-construct",
         "dojo/on",
         "dojo/request",
         "codemirror",
         "dijit/Toolbar",
         "dijit/form/Button",
         "../traffic",
         "../util/sampleFlow",
         "../util/requestAuthenticator",
         "../util/_DynamicTemplatedWidget",
         "dijit/_WidgetsInTemplateMixin",
         "dojo/text!./templates/ReportEditor.ejs" ], function(_, declare, array, Deferred, domConstruct, on, request,
	CodeMirror, Toolbar, Button, traffic, sampleFlow, requestAuthenticator, _DynamicTemplatedWidget, _WidgetsInTemplateMixin, template) {

	return declare([ _DynamicTemplatedWidget, _WidgetsInTemplateMixin ], {
		templateString: template,
		_onShow: function() {
			if (this.codeMirror)
				this.codeMirror.refresh();
		},
		postCreate: function() {
			this.inherited(arguments);

			var self = this;

				CodeMirror.commands.autocomplete = function(cm) {
					CodeMirror.simpleHint(cm, CodeMirror.javascriptHint, {
						completeSingle: false,
						additionalContext: {
							//Only expose the important attributes of flow. Most attrs are confusing and for internal use only.
							"flow": {
								"request": sampleFlow.request,
								"response": sampleFlow,
								"id": sampleFlow.id,
								"getSimilarFlows": sampleFlow.getSimilarFlows
							},
							"traffic": traffic,
							"detailView": self.detailViewObj,
							"_": _
						}
					});
				};
				CodeMirror.commands.autoformat = function(cm) {
					var range = {
						from: cm.getCursor(true),
						to: cm.getCursor(false)
					};
					if(range.from.ch == range.to.ch && range.from.line == range.to.line)
						range = {"from": {"ch": 0, "line": 0}, "to": {"ch": 0, "line": cm.lineCount()}};
					cm.autoIndentRange(range.from, range.to);
				};

				//breaks if -n > options.length
				function increaseSelectedOptionIndex(n){
					var node = self.scriptSelectionNode;
					node.selectedIndex = (n + node.selectedIndex + node.options.length) % node.options.length;

					on.emit(self.scriptSelectionNode, "change", {
						bubbles: true,
						cancelable: true
					});
				}

				self.codeMirror = CodeMirror.fromTextArea(self.reportCodeNode, {
					lineNumbers: true,
					mode: "javascript",
					tabSize: 2,
					matchBrackets: true,
					extraKeys: {
						"Enter": "newlineAndIndentContinueComment",
						"Ctrl-Enter": function(){ self.startButton.onClick(); },
						"Alt-PageDown": function(){ increaseSelectedOptionIndex(1); },
						"Alt-PageUp" : function(){ increaseSelectedOptionIndex(-1); },
						"Ctrl-Space": "autocomplete",
						"Shift-Ctrl-F": "autoformat"
					}
				});
				self.codeMirror.on("cursorActivity", function() {
					self.codeMirror.matchHighlight("CodeMirror-matchhighlight");
				});

				//Editor Synchronization
				var API_PATH = "/api/fs/report_scripts/";

				var saveReq, lastState, files = {};

				//Load all available scripts
				request(API_PATH+"?recursive=true",{handleAs:"json"}).then(function(dirs){

					var optionsFragment = document.createDocumentFragment();
					array.forEach(dirs,function(dir){
						array.forEach(dir[2],function(file){
							var filename = (dir[0].replace("\\","/") + "/" + file).substr(1);
							var option = domConstruct.create("option", {value: filename, selected: filename=="=intro.js" ? true : false}, optionsFragment);
							option.textContent = filename;
							files[filename] = option;
						});
					});
					domConstruct.place(optionsFragment, self.scriptSelectionNode);

				});
				function isSaved(){
					return lastState === self.getCode() || self.get("currentFilename") === undefined;
				}
				function isReadOnly(){
					return self.get("currentFilename").indexOf("=") === 0;
				}

				function save(newfile){

					if(isSaved() || isReadOnly())
						return (new Deferred()).resolve();
					if(saveReq)
						saveReq.cancel();

					var def = new Deferred();

					requestAuthenticator.active.then(function(writable){
						if(!writable){
							self.statusNode.textContent = "read only mode: unsaved";
							def.resolve(false);
						}
						else {

							self.statusNode.textContent = "saving...";
							self.set("currentFilename",self.get("currentFilename").replace(/[^ \w\.\-\/\\]/g,""));
							var method = newfile ? request.post : request.put;
							var code = self.getCode();
							saveReq = method(API_PATH + self.get("currentFilename"),
								{data:JSON.stringify({"content":code})});
							saveReq.then(function(){
									self.statusNode.textContent = "saved.";
									lastState = code;
									saveReq = null;
									def.resolve(arguments);
							});

						}
					});
					return def;
				}
				function newfile(filename){
					if(filename in files)
						return load(filename);
					var option = domConstruct.create("option", {value: filename, selected: true}, self.scriptSelectionNode);
					option.textContent = filename;
					self.set("currentFilename",filename);
					self.codeMirror.setValue("\n\n\n\n\n\n\n\n");
					save(true);
				}
				function delfile(filename){
					if(!(filename in files))
						return;
					if(filename == self.get("currentFilename"))
						increaseSelectedOptionIndex(1);
					domConstruct.destroy(files[filename]);
					delete files[filename];
					return request.del(API_PATH+filename);
				}
				function load(filename){
					save().then(function(){
						request.get(API_PATH+filename).then(function(script){
							self.set("currentFilename",filename);
							lastState = (self.get("currentFilename").indexOf("=") < 0 ? script : undefined);
							self.codeMirror.setValue(script);
							self.statusNode.textContent = "";
						});

					});
				}

				on(self.newScriptButton,"click",function(){
					var filename = window.prompt("New file name:");
					if(filename !== null)
						newfile(filename);
				});

				on(self.deleteScriptButton,"click",function(){
					var del = window.prompt("Do you really want to delete "+self.get("currentFilename")+"?\nEnter DELETE to continue.");
					if(del === "DELETE")
						delfile(self.get("currentFilename"));
				});

				var saveTimeout;
				self.codeMirror.on("change",function(){
					window.clearTimeout(saveTimeout);
					if(isReadOnly()){
						self.statusNode.textContent = "read only";
					}
					else if(isSaved()){
						self.statusNode.textContent = "saved.";
					} else {
						self.statusNode.textContent = "";
						saveTimeout = window.setTimeout(function(){
							save();
						}, 300);
					}
				});

				on(self.scriptSelectionNode,"change",function(){
					load(this.options[this.selectedIndex].value);
				});
				load("=intro.js");

			this.startButton = new Button({
				iconClass: "dijitIcon dijitIconFunction"
			}, this.startButtonNode);
		},
		getCode: function() {
			return this.codeMirror ? this.codeMirror.getValue() : "";
		}
	});

});<commit_msg>fix flow.response auto completion<commit_after>define([ "lodash",
         "dojo/_base/declare",
         "dojo/_base/array",
         "dojo/Deferred",
         "dojo/dom-construct",
         "dojo/on",
         "dojo/request",
         "codemirror",
         "dijit/Toolbar",
         "dijit/form/Button",
         "../traffic",
         "../util/sampleFlow",
         "../util/requestAuthenticator",
         "../util/_DynamicTemplatedWidget",
         "dijit/_WidgetsInTemplateMixin",
         "dojo/text!./templates/ReportEditor.ejs" ], function(_, declare, array, Deferred, domConstruct, on, request,
	CodeMirror, Toolbar, Button, traffic, sampleFlow, requestAuthenticator, _DynamicTemplatedWidget, _WidgetsInTemplateMixin, template) {

	return declare([ _DynamicTemplatedWidget, _WidgetsInTemplateMixin ], {
		templateString: template,
		_onShow: function() {
			if (this.codeMirror)
				this.codeMirror.refresh();
		},
		postCreate: function() {
			this.inherited(arguments);

			var self = this;

				CodeMirror.commands.autocomplete = function(cm) {
					CodeMirror.simpleHint(cm, CodeMirror.javascriptHint, {
						completeSingle: false,
						additionalContext: {
							//Only expose the important attributes of flow. Most attrs are confusing and for internal use only.
							"flow": {
								"request": sampleFlow.request,
								"response": sampleFlow.response,
								"id": sampleFlow.id,
								"getSimilarFlows": sampleFlow.getSimilarFlows
							},
							"traffic": traffic,
							"detailView": self.detailViewObj,
							"_": _
						}
					});
				};
				CodeMirror.commands.autoformat = function(cm) {
					var range = {
						from: cm.getCursor(true),
						to: cm.getCursor(false)
					};
					if(range.from.ch == range.to.ch && range.from.line == range.to.line)
						range = {"from": {"ch": 0, "line": 0}, "to": {"ch": 0, "line": cm.lineCount()}};
					cm.autoIndentRange(range.from, range.to);
				};

				//breaks if -n > options.length
				function increaseSelectedOptionIndex(n){
					var node = self.scriptSelectionNode;
					node.selectedIndex = (n + node.selectedIndex + node.options.length) % node.options.length;

					on.emit(self.scriptSelectionNode, "change", {
						bubbles: true,
						cancelable: true
					});
				}

				self.codeMirror = CodeMirror.fromTextArea(self.reportCodeNode, {
					lineNumbers: true,
					mode: "javascript",
					tabSize: 2,
					matchBrackets: true,
					extraKeys: {
						"Enter": "newlineAndIndentContinueComment",
						"Ctrl-Enter": function(){ self.startButton.onClick(); },
						"Alt-PageDown": function(){ increaseSelectedOptionIndex(1); },
						"Alt-PageUp" : function(){ increaseSelectedOptionIndex(-1); },
						"Ctrl-Space": "autocomplete",
						"Shift-Ctrl-F": "autoformat"
					}
				});
				self.codeMirror.on("cursorActivity", function() {
					self.codeMirror.matchHighlight("CodeMirror-matchhighlight");
				});

				//Editor Synchronization
				var API_PATH = "/api/fs/report_scripts/";

				var saveReq, lastState, files = {};

				//Load all available scripts
				request(API_PATH+"?recursive=true",{handleAs:"json"}).then(function(dirs){

					var optionsFragment = document.createDocumentFragment();
					array.forEach(dirs,function(dir){
						array.forEach(dir[2],function(file){
							var filename = (dir[0].replace("\\","/") + "/" + file).substr(1);
							var option = domConstruct.create("option", {value: filename, selected: filename=="=intro.js" ? true : false}, optionsFragment);
							option.textContent = filename;
							files[filename] = option;
						});
					});
					domConstruct.place(optionsFragment, self.scriptSelectionNode);

				});
				function isSaved(){
					return lastState === self.getCode() || self.get("currentFilename") === undefined;
				}
				function isReadOnly(){
					return self.get("currentFilename").indexOf("=") === 0;
				}

				function save(newfile){

					if(isSaved() || isReadOnly())
						return (new Deferred()).resolve();
					if(saveReq)
						saveReq.cancel();

					var def = new Deferred();

					requestAuthenticator.active.then(function(writable){
						if(!writable){
							self.statusNode.textContent = "read only mode: unsaved";
							def.resolve(false);
						}
						else {

							self.statusNode.textContent = "saving...";
							self.set("currentFilename",self.get("currentFilename").replace(/[^ \w\.\-\/\\]/g,""));
							var method = newfile ? request.post : request.put;
							var code = self.getCode();
							saveReq = method(API_PATH + self.get("currentFilename"),
								{data:JSON.stringify({"content":code})});
							saveReq.then(function(){
									self.statusNode.textContent = "saved.";
									lastState = code;
									saveReq = null;
									def.resolve(arguments);
							});

						}
					});
					return def;
				}
				function newfile(filename){
					if(filename in files)
						return load(filename);
					var option = domConstruct.create("option", {value: filename, selected: true}, self.scriptSelectionNode);
					option.textContent = filename;
					self.set("currentFilename",filename);
					self.codeMirror.setValue("\n\n\n\n\n\n\n\n");
					save(true);
				}
				function delfile(filename){
					if(!(filename in files))
						return;
					if(filename == self.get("currentFilename"))
						increaseSelectedOptionIndex(1);
					domConstruct.destroy(files[filename]);
					delete files[filename];
					return request.del(API_PATH+filename);
				}
				function load(filename){
					save().then(function(){
						request.get(API_PATH+filename).then(function(script){
							self.set("currentFilename",filename);
							lastState = (self.get("currentFilename").indexOf("=") < 0 ? script : undefined);
							self.codeMirror.setValue(script);
							self.statusNode.textContent = "";
						});

					});
				}

				on(self.newScriptButton,"click",function(){
					var filename = window.prompt("New file name:");
					if(filename !== null)
						newfile(filename);
				});

				on(self.deleteScriptButton,"click",function(){
					var del = window.prompt("Do you really want to delete "+self.get("currentFilename")+"?\nEnter DELETE to continue.");
					if(del === "DELETE")
						delfile(self.get("currentFilename"));
				});

				var saveTimeout;
				self.codeMirror.on("change",function(){
					window.clearTimeout(saveTimeout);
					if(isReadOnly()){
						self.statusNode.textContent = "read only";
					}
					else if(isSaved()){
						self.statusNode.textContent = "saved.";
					} else {
						self.statusNode.textContent = "";
						saveTimeout = window.setTimeout(function(){
							save();
						}, 300);
					}
				});

				on(self.scriptSelectionNode,"change",function(){
					load(this.options[this.selectedIndex].value);
				});
				load("=intro.js");

			this.startButton = new Button({
				iconClass: "dijitIcon dijitIconFunction"
			}, this.startButtonNode);
		},
		getCode: function() {
			return this.codeMirror ? this.codeMirror.getValue() : "";
		}
	});

});<|endoftext|>


<commit_before>describe("MagicCarpet", function() {
  var subject;

  beforeEach(function() {
    subject = MagicCarpet;
  });

  afterEach(function() {
    $("#magic-carpet").remove();
  });

  it("has its async property set to false by default", function(){
    expect(subject.async).toBeFalse();
  });

  it("has its asyncComplete property set to true by default", function(){
    expect(subject.asyncComplete).toBeTrue();
  });

  it("has an object for caching request results", function(){
    expect(subject.cache).toBeObject();
  });

  describe("initialize", function() {
    beforeEach(function() {
      spyOn(subject, "cacheElements");
      spyOn(subject, "appendSandbox");
      spyOn(subject, "bindAll");
      subject.initialize();
    });

    it("caches the necessary elements", function() {
      expect(subject.cacheElements).toHaveBeenCalled();
    });

    it("appends the sandbox", function(){
      expect(subject.appendSandbox).toHaveBeenCalled();
    });

    it("binds all of its functions", function(){
      expect(subject.bindAll).toHaveBeenCalled();
    });
  });

  describe("bindAll", function(){
    var dummyFunction;
    beforeEach(function() {
      subject.dummyOption = false;
      dummyFunction = function() { this.dummyOption = true; };
      subject.dummy = dummyFunction;
      subject.bindAll();
    });

    afterEach(function() {
      delete subject.dummy;
      delete subject.dummyOption;
    });

    it("binds all methods", function(){
      expect(subject.dummy).not.toEqual(dummyFunction);
      subject.dummy();
      expect(subject.dummyOption).toBeTrue();
    });
  });

  describe("bind", function(){
    it("binds the function to the context", function(){
      var obj = {};
      obj.func = function(arg) { this.funcArg = arg; };
      subject.bind(obj, "func");
      var func = obj.func;
      func("arg");
      expect(obj.funcArg).toEqual("arg");
    });
  });

  describe("cacheElements", function() {
    beforeEach(function() {
      spyOn(subject, "createSandbox").and.returnValue("sandbox");
      subject.cacheElements();
    });

    it("caches a sandbox", function() {
      expect(subject.sandbox).toEqual("sandbox");
    });
  });

  describe("createSandbox", function() {
    it("returns a div", function() {
      expect(subject.createSandbox().tagName).toEqual("DIV");
    });

    it("returns a div with an ID of #magic-carpet", function() {
      expect(subject.createSandbox().getAttribute("id")).toEqual("magic-carpet");
    });
  });

  describe("appendSandbox", function() {
    beforeEach(function() {
      subject.cacheElements();
      subject.appendSandbox();
    });

    it("appends the sandbox to the body", function() {
      expect(subject.sandbox).toBeDefined();
      expect(subject.sandbox).toEqual($("body #magic-carpet")[0]);
    });
  });

  describe("emptySandbox", function(){
    beforeEach(function() {
      subject.cacheElements();
      subject.sandbox.innerHTML = '

';
      subject.emptySandbox();
    });

    it("empties the sandbox", function(){
      expect($("#dummy")[0]).toBeUndefined();
      expect(subject.sandbox.innerHTML).toEqual("");
    });
  });

  describe("request", function(){
    var requestData;
    beforeEach(function() {
      subject.cacheElements();
      spyOn(subject, "fetch");
      requestData = { some: "template" };
    });

    it("fetches the markup if the request isn't cached", function(){
      subject.cache = {};
      subject.request(requestData);
      expect(subject.fetch).toHaveBeenCalledWith(requestData);
      expect(subject.sandbox.innerHTML).toEqual("");
    });

    it("puts the markup on the page when it's already cached", function(){
      subject.cache[$.param(requestData)] = "markup";
      subject.request(requestData);
      expect(subject.fetch).not.toHaveBeenCalled();
      expect(subject.sandbox.innerHTML).toEqual("markup");
    });
  });

  describe("fetch", function(){
    var arg;
    beforeEach(function() {
      subject.asyncComplete = true;
      subject.lastRequest = undefined;
      spyOn($, "ajax").and.returnValue(promiseStub);
      subject.async = "default async setting";
      subject.fetch("data");
      arg = $.ajax.calls.argsFor(0)[0];
    });

    it("makes a get request to /magic_carpet", function(){
      expect(arg.url).toEqual("/magic_carpet");
      expect(arg.method).toEqual("get");
    });

    it("uses the global magic carpet async setting", function(){
      expect(arg.async).toEqual("default async setting");
    });

    it("passes its argument as data", function(){
      expect(arg.data).toEqual("data");
    });

    it("sets asyncComplete to false", function(){
      expect(subject.asyncComplete).toBeFalse();
    });

    it("handles success", function(){
      expect(promiseStub.done).toHaveBeenCalledWith(subject.handleSuccess);
    });

    it("handles failure", function(){
      expect(promiseStub.fail).toHaveBeenCalledWith(subject.handleFailure);
    });

    it("cleans up after itself", function(){
      expect(promiseStub.always).toHaveBeenCalledWith(subject.afterRequest);
    });

    it("caches the request object", function(){
      expect(subject.lastRequest).toEqual("data");
    });
  });

  describe("handleSuccess", function(){
    var lastRequest;
    var markup;
    beforeEach(function() {
      subject.appendSandbox();
      lastRequest = { some: "template" };
      subject.lastRequest = lastRequest;
      subject.cache = {};
      markup = '

';
      subject.handleSuccess(markup);
    });

    it("puts the markup in the sandbox", function(){
      expect($("#magic-carpet #fresh-markup")[0]).toBeDefined();
    });

    it("caches the markup", function(){
      expect(subject.cache[$.param(lastRequest)]).toEqual(markup);
    });
  });

  describe("handleFailure", function(){
    it("throws an error with a message", function(){
      var errorObj = { error: "There was a problem" };
      var response = { responseJSON: errorObj };
      expect(function() {
        subject.handleFailure(response);
      }).toThrow(new Error(errorObj.error));
    });
  });

  describe("afterRequest", function(){
    beforeEach(function() {
      subject.asyncComplete = false;
      subject.afterRequest();
    });

    it("sets asyncComplete to true", function(){
      expect(subject.asyncComplete).toBeTrue();
    });
  });
});
<commit_msg>added a couple integration specs<commit_after>describe("MagicCarpet", function() {
  var subject;

  beforeEach(function() {
    subject = MagicCarpet;
  });

  afterEach(function() {
    $("#magic-carpet").remove();
  });

  it("has its async property set to false by default", function(){
    expect(subject.async).toBeFalse();
  });

  it("has its asyncComplete property set to true by default", function(){
    expect(subject.asyncComplete).toBeTrue();
  });

  it("has an object for caching request results", function(){
    expect(subject.cache).toBeObject();
  });

  describe("initialize", function() {
    beforeEach(function() {
      spyOn(subject, "cacheElements");
      spyOn(subject, "appendSandbox");
      spyOn(subject, "bindAll");
      subject.initialize();
    });

    it("caches the necessary elements", function() {
      expect(subject.cacheElements).toHaveBeenCalled();
    });

    it("appends the sandbox", function(){
      expect(subject.appendSandbox).toHaveBeenCalled();
    });

    it("binds all of its functions", function(){
      expect(subject.bindAll).toHaveBeenCalled();
    });
  });

  describe("bindAll", function(){
    var dummyFunction;
    beforeEach(function() {
      subject.dummyOption = false;
      dummyFunction = function() { this.dummyOption = true; };
      subject.dummy = dummyFunction;
      subject.bindAll();
    });

    afterEach(function() {
      delete subject.dummy;
      delete subject.dummyOption;
    });

    it("binds all methods", function(){
      expect(subject.dummy).not.toEqual(dummyFunction);
      subject.dummy();
      expect(subject.dummyOption).toBeTrue();
    });
  });

  describe("bind", function(){
    it("binds the function to the context", function(){
      var obj = {};
      obj.func = function(arg) { this.funcArg = arg; };
      subject.bind(obj, "func");
      var func = obj.func;
      func("arg");
      expect(obj.funcArg).toEqual("arg");
    });
  });

  describe("cacheElements", function() {
    beforeEach(function() {
      spyOn(subject, "createSandbox").and.returnValue("sandbox");
      subject.cacheElements();
    });

    it("caches a sandbox", function() {
      expect(subject.sandbox).toEqual("sandbox");
    });
  });

  describe("createSandbox", function() {
    it("returns a div", function() {
      expect(subject.createSandbox().tagName).toEqual("DIV");
    });

    it("returns a div with an ID of #magic-carpet", function() {
      expect(subject.createSandbox().getAttribute("id")).toEqual("magic-carpet");
    });
  });

  describe("appendSandbox", function() {
    beforeEach(function() {
      subject.cacheElements();
      subject.appendSandbox();
    });

    it("appends the sandbox to the body", function() {
      expect(subject.sandbox).toBeDefined();
      expect(subject.sandbox).toEqual($("body #magic-carpet")[0]);
    });
  });

  describe("emptySandbox", function(){
    beforeEach(function() {
      subject.cacheElements();
      subject.sandbox.innerHTML = '

';
      subject.emptySandbox();
    });

    it("empties the sandbox", function(){
      expect($("#dummy")[0]).toBeUndefined();
      expect(subject.sandbox.innerHTML).toEqual("");
    });
  });

  describe("request", function(){
    var requestData;
    beforeEach(function() {
      subject.cacheElements();
      spyOn(subject, "fetch");
      requestData = { some: "template" };
    });

    it("fetches the markup if the request isn't cached", function(){
      subject.cache = {};
      subject.request(requestData);
      expect(subject.fetch).toHaveBeenCalledWith(requestData);
      expect(subject.sandbox.innerHTML).toEqual("");
    });

    it("puts the markup on the page when it's already cached", function(){
      subject.cache[$.param(requestData)] = "markup";
      subject.request(requestData);
      expect(subject.fetch).not.toHaveBeenCalled();
      expect(subject.sandbox.innerHTML).toEqual("markup");
    });
  });

  describe("fetch", function(){
    var arg;
    beforeEach(function() {
      subject.asyncComplete = true;
      subject.lastRequest = undefined;
      spyOn($, "ajax").and.returnValue(promiseStub);
      subject.async = "default async setting";
      subject.fetch("data");
      arg = $.ajax.calls.argsFor(0)[0];
    });

    it("makes a get request to /magic_carpet", function(){
      expect(arg.url).toEqual("/magic_carpet");
      expect(arg.method).toEqual("get");
    });

    it("uses the global magic carpet async setting", function(){
      expect(arg.async).toEqual("default async setting");
    });

    it("passes its argument as data", function(){
      expect(arg.data).toEqual("data");
    });

    it("sets asyncComplete to false", function(){
      expect(subject.asyncComplete).toBeFalse();
    });

    it("handles success", function(){
      expect(promiseStub.done).toHaveBeenCalledWith(subject.handleSuccess);
    });

    it("handles failure", function(){
      expect(promiseStub.fail).toHaveBeenCalledWith(subject.handleFailure);
    });

    it("cleans up after itself", function(){
      expect(promiseStub.always).toHaveBeenCalledWith(subject.afterRequest);
    });

    it("caches the request object", function(){
      expect(subject.lastRequest).toEqual("data");
    });
  });

  describe("handleSuccess", function(){
    var lastRequest;
    var markup;
    beforeEach(function() {
      subject.appendSandbox();
      lastRequest = { some: "template" };
      subject.lastRequest = lastRequest;
      subject.cache = {};
      markup = '

';
      subject.handleSuccess(markup);
    });

    it("puts the markup in the sandbox", function(){
      expect($("#magic-carpet #fresh-markup")[0]).toBeDefined();
    });

    it("caches the markup", function(){
      expect(subject.cache[$.param(lastRequest)]).toEqual(markup);
    });
  });

  describe("handleFailure", function(){
    it("throws an error with a message", function(){
      var errorObj = { error: "There was a problem" };
      var response = { responseJSON: errorObj };
      expect(function() {
        subject.handleFailure(response);
      }).toThrow(new Error(errorObj.error));
    });
  });

  describe("afterRequest", function(){
    beforeEach(function() {
      subject.asyncComplete = false;
      subject.afterRequest();
    });

    it("sets asyncComplete to true", function(){
      expect(subject.asyncComplete).toBeTrue();
    });
  });

  describe("integration specs", function(){
    beforeEach(function() {
      subject.async = false;
      subject.initialize();
    });

    describe("templates", function(){
      it("renders templates with instance variables", function(){
        subject.request({
          controller_name: "Wishes",
          template: "new",
          instance_variables: {
            wish: {
              model: "Wish"
            }
          }
        });
        expect($("#magic-carpet #new_wish")[0]).toBeDefined();
      });

      describe("errors", function(){
        it("renders missing controller errors", function(){
          expect(function() {
            subject.request({
              controller_name: "blort",
              action_name: "new"
            });
          }).toThrow(new Error("wrong constant name blortController for 'new' template."));
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>
var x
var y
var width
var height
var balls = []

function setup() {
  createCanvas(windowWidth, windowHeight)
  x = windowWidth / 2
  y = windowHeight / 2
  width = 10
  height = 10
   for (var i=0; i<100; i++) {
    balls.push(new Ball());
  }
  // ball = new Ball()
  // ball1 = new Ball()
}

function draw() {
  background('white')
  // ellipse(x, y, width, height)
  // ellipse(y,x,width,height)
  // ellipse(x,x,width,height)
  // ball.display()
  // ball.move()
  // ball1.display()
  // ball1.move()
  textSize(64)
  text("☂",mouseX-100,mouseY+100)
  for (var i=0; i<balls.length; i++) {
    balls[i].move();
    balls[i].display();
  }
  // this.speed = this.speed * 9.81
}

function Ball() {
  this.x = random(0,windowWidth);
  this.y = random(0,windowHeight);
  this.diameter = width;
  this.speed = 20;

  this.move = function() {
    // this.x += random(-this.speed, this.speed);
    // this.y += random(-this.speed, this.speed);

    if (this.y < windowHeight) {
    this.y = this.y + 1*this.speed
    this.x = this.x + random(-3,3)
    this.diameter = this.diameter+1
  } else {
    this.y = 0
    this.diameter = 10
  }
  };

  this.display = function() {
    textSize(32)
    text("💧",this.x,this.y)
  };
}<commit_msg>updated umbrella location<commit_after>
var x
var y
var width
var height
var balls = []

function setup() {
  createCanvas(windowWidth, windowHeight)
  x = windowWidth / 2
  y = windowHeight / 2
  width = 10
  height = 10
   for (var i=0; i<100; i++) {
    balls.push(new Ball());
  }
  // ball = new Ball()
  // ball1 = new Ball()
}

function draw() {
  background('white')
  // ellipse(x, y, width, height)
  // ellipse(y,x,width,height)
  // ellipse(x,x,width,height)
  // ball.display()
  // ball.move()
  // ball1.display()
  // ball1.move()
  textSize(64)
  text("☂",mouseX-30,mouseY)
  for (var i=0; i<balls.length; i++) {
    balls[i].move();
    balls[i].display();
  }
  // this.speed = this.speed * 9.81
}

function Ball() {
  this.x = random(0,windowWidth);
  this.y = random(0,windowHeight);
  this.diameter = width;
  this.speed = 20;

  this.move = function() {
    // this.x += random(-this.speed, this.speed);
    // this.y += random(-this.speed, this.speed);

    if (this.y < windowHeight) {
    this.y = this.y + 1*this.speed
    this.x = this.x + random(-3,3)
    this.diameter = this.diameter+1
  } else {
    this.y = 0
    this.diameter = 10
  }
  };

  this.display = function() {
    textSize(32)
    text("💧",this.x,this.y)
  };
}<|endoftext|>


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

import React from 'react';
import { Platform} from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
import Button from './Button';
import View from './View';
import Title from './Title';
import InputGroup from './InputGroup';
import Subtitle from './Subtitle';
import _ from 'lodash';

export default class Header extends NativeBaseComponent {

    propTypes: {
        searchBar : React.PropTypes.bool,
        rounded : React.PropTypes.bool,
        style : React.PropTypes.object,
        iconRight: React.PropTypes.bool
    }

    getInitialStyle() {
        return {
            navbar: {
                backgroundColor: this.getTheme().toolbarDefaultBg,
                justifyContent: (!Array.isArray(this.props.children)) ? 'center' : 'space-between',
                flexDirection: 'row',
                alignItems: 'center',
                paddingHorizontal: 15,
                paddingTop: (Platform.OS === 'ios' ) ? 15 : 0,
                shadowColor: '#000',
                shadowOffset: {width: 0, height: 2},
                shadowOpacity: 0.1,
                shadowRadius: 1.5,
                height: this.getTheme().toolbarHeight,
                elevation: 3,
                position: 'relative'
            },
            iosToolbarSearch: {
                backgroundColor: this.getTheme().toolbarInputColor,
                borderRadius: this.props.rounded ? 25 : 2,
                height: 30,
                borderColor: 'transparent',
                flex:1
            },
            androidToolbarSearch: {
                backgroundColor: '#fff',
                borderRadius: 2,
                borderColor: 'transparent',
                elevation: 2,
                flex:1
            },
            toolbarButton: {
                paddingHorizontal: 15
            }
        }
    }

    prepareRootProps() {

        var defaultProps = {
            style: this.getInitialStyle().navbar
        };

        return computeProps(this.props, defaultProps);

    }
    renderChildren() {
        if(!Array.isArray(this.props.children)) {
            return this.props.children;
        }

        else if (Array.isArray(this.props.children)) {
            var newChildren = [];
            var childrenArray = React.Children.toArray(this.props.children);

            var buttons = [];
            buttons = _.remove(childrenArray, function(item) {
                if(item.type == Button) {
                    return true;
                }
            });

            var title = [];
            title = _.remove(childrenArray, function(item) {
                if(item.type == Title) {
                    return true;
                }
            });

            var subtitle = [];
            subtitle = _.remove(childrenArray, function(item) {
                if(item.type == Subtitle) {
                    return true;
                }
            });

            var input = [];
            input = _.remove(childrenArray, function(item) {
                if(item.type == InputGroup) {
                    return true;
                }
            });

            if (buttons.length == 1 && this.props.iconRight) {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='title' style={{position: 'absolute', left: 0, right: 0, top: 13, bottom: 0, alignSelf: 'center', justifyContent: 'center'}}>
                    {[title[0],subtitle[0]]}
                    </View>)
                    newChildren.push(<View key='title2' style={{flex: 3, alignSelf: 'stretch'}} />)
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -14}}>
                    {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                    </View>)
                }
                else {
                    newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'stretch', justifyContent: 'center'}}>
                    {[title[0]]}
                    </View>)
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -10, marginRight: 12}}>
                    {React.cloneElement(buttons[0], {style: this.getInitialStyle().toolbarButton, header : true, textStyle: {color: this.getTheme().toolbarTextColor}})}
                    </View>)
                }
            }

            else if (this.props.searchBar) {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='search' style={{flex: 1, alignSelf: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -7}}>
                        {React.cloneElement(input[0],{style: this.getInitialStyle().iosToolbarSearch, toolbar : true, key : 'inp'})}
                        </View>)
                        newChildren.push(<View key='searchBtn' style={{alignItems: 'center', justifyContent: 'center', flexDirection: 'row', marginRight: -14}}>
                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                        </View>)
                    } else {
                        newChildren.push(<View key='search' style={{flex: 1,alignSelf: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -8, marginRight: -8}}>
                        {React.cloneElement(input[0],{style: this.getInitialStyle().androidToolbarSearch, atoolbar : true})}
                        </View>)
                    }
                }
                else {
                    if (Platform.OS === 'ios') {
                        newChildren.push(<View key='title' style={{position: 'absolute', left: 0, right: 0, top: 13, bottom: 0, alignSelf: 'center', justifyContent: 'center'}}>
                        {[title[0],subtitle[0]]}
                        </View>)
                        newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -14}}>
                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                        </View>)
                        newChildren.push(<View key='title2' style={{flex: 3, alignSelf: 'stretch'}} />)
                        if (buttons.length>1) {
                            for (let i = 1; i < buttons.length; i++) {
                                newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -14}}>
                                {React.cloneElement(buttons[i], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                                </View>)
                            }
                        }
                    }
                    else {
                        newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -10, marginRight: 12}}>
                        {React.cloneElement(buttons[0], {style: this.getInitialStyle().toolbarButton, header : true, textStyle: {color: this.getTheme().toolbarTextColor}})}
                        </View>)
                        newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'stretch', justifyContent: 'center'}}>
                        {[title[0]]}
                        </View>)
                        for (let i = 1; i < buttons.length; i++) {
                            newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -7}}>
                            {React.cloneElement(buttons[i], {style: this.getInitialStyle().toolbarButton, header : true, textStyle: {color: this.getTheme().toolbarTextColor}})}
                            </View>)
                        }
                    }

                }
                return newChildren;
            }
        }

        render() {
            return(
            <View {...this.prepareRootProps()} >
            {this.renderChildren()}
            </View>
        );
    }
}
<commit_msg>Header button right alignment<commit_after>/* @flow */
'use strict';

import React from 'react';
import { Platform} from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
import Button from './Button';
import View from './View';
import Title from './Title';
import InputGroup from './InputGroup';
import Subtitle from './Subtitle';
import _ from 'lodash';

export default class Header extends NativeBaseComponent {

    propTypes: {
        searchBar : React.PropTypes.bool,
        rounded : React.PropTypes.bool,
        style : React.PropTypes.object,
        iconRight: React.PropTypes.bool
    }

    getInitialStyle() {
        return {
            navbar: {
                backgroundColor: this.getTheme().toolbarDefaultBg,
                justifyContent: (!Array.isArray(this.props.children)) ? 'center' : 'space-between',
                flexDirection: 'row',
                alignItems: 'center',
                paddingHorizontal: 15,
                paddingTop: (Platform.OS === 'ios' ) ? 15 : 0,
                shadowColor: '#000',
                shadowOffset: {width: 0, height: 2},
                shadowOpacity: 0.1,
                shadowRadius: 1.5,
                height: this.getTheme().toolbarHeight,
                elevation: 3,
                position: 'relative'
            },
            iosToolbarSearch: {
                backgroundColor: this.getTheme().toolbarInputColor,
                borderRadius: this.props.rounded ? 25 : 2,
                height: 30,
                borderColor: 'transparent',
                flex:1
            },
            androidToolbarSearch: {
                backgroundColor: '#fff',
                borderRadius: 2,
                borderColor: 'transparent',
                elevation: 2,
                flex:1
            },
            toolbarButton: {
                paddingHorizontal: 15
            }
        }
    }

    prepareRootProps() {

        var defaultProps = {
            style: this.getInitialStyle().navbar
        };

        return computeProps(this.props, defaultProps);

    }
    renderChildren() {
        if(!Array.isArray(this.props.children)) {
            return this.props.children;
        }

        else if (Array.isArray(this.props.children)) {
            var newChildren = [];
            var childrenArray = React.Children.toArray(this.props.children);

            var buttons = [];
            buttons = _.remove(childrenArray, function(item) {
                if(item.type == Button) {
                    return true;
                }
            });

            var title = [];
            title = _.remove(childrenArray, function(item) {
                if(item.type == Title) {
                    return true;
                }
            });

            var subtitle = [];
            subtitle = _.remove(childrenArray, function(item) {
                if(item.type == Subtitle) {
                    return true;
                }
            });

            var input = [];
            input = _.remove(childrenArray, function(item) {
                if(item.type == InputGroup) {
                    return true;
                }
            });

            if (buttons.length == 1 && this.props.iconRight) {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='title' style={{position: 'absolute', left: 0, right: 0, top: 13, bottom: 0, alignSelf: 'center', justifyContent: 'center'}}>
                    {[title[0],subtitle[0]]}
                    </View>)
                    newChildren.push(<View key='title2' style={{flex: 3, alignSelf: 'stretch'}} />)
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -14}}>
                    {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                    </View>)
                }
                else {
                    newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'stretch', justifyContent: 'center'}}>
                    {[title[0]]}
                    </View>)
                    newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -10, marginRight: 12}}>
                    {React.cloneElement(buttons[0], {style: this.getInitialStyle().toolbarButton, header : true, textStyle: {color: this.getTheme().toolbarTextColor}})}
                    </View>)
                }
            }

            else if (this.props.searchBar) {
                if (Platform.OS === 'ios') {
                    newChildren.push(<View key='search' style={{flex: 1, alignSelf: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -7}}>
                        {React.cloneElement(input[0],{style: this.getInitialStyle().iosToolbarSearch, toolbar : true, key : 'inp'})}
                        </View>)
                        newChildren.push(<View key='searchBtn' style={{alignItems: 'center', justifyContent: 'center', flexDirection: 'row', marginRight: -14}}>
                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                        </View>)
                    } else {
                        newChildren.push(<View key='search' style={{flex: 1,alignSelf: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -8, marginRight: -8}}>
                        {React.cloneElement(input[0],{style: this.getInitialStyle().androidToolbarSearch, atoolbar : true})}
                        </View>)
                    }
                }
                else {
                    if (Platform.OS === 'ios') {
                        newChildren.push(<View key='title' style={{position: 'absolute', left: 0, right: 0, top: 13, bottom: 0, alignSelf: 'center', justifyContent: 'center'}}>
                        {[title[0],subtitle[0]]}
                        </View>)
                        newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -14}}>
                        {React.cloneElement(buttons[0], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                        </View>)
                        newChildren.push(<View key='title2' style={{flex: 3, alignSelf: 'stretch'}} />)
                        if (buttons.length>1) {
                            for (let i = 1; i < buttons.length; i++) {
                                newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -14}}>
                                {React.cloneElement(buttons[i], {color: this.getTheme().iosToolbarBtnColor, style: this.getInitialStyle().toolbarButton})}
                                </View>)
                            }
                        }
                    }
                    else {
                        newChildren.push(<View key='btn1' style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginLeft: -10, marginRight: 12}}>
                        {React.cloneElement(buttons[0], {style: this.getInitialStyle().toolbarButton, header : true, textStyle: {color: this.getTheme().toolbarTextColor}})}
                        </View>)
                        newChildren.push(<View key='title' style={{flex: 3, alignSelf: 'stretch', justifyContent: 'center'}}>
                        {[title[0]]}
                        </View>)
                        for (let i = 1; i < buttons.length; i++) {
                            newChildren.push(<View key={'btn' + (i+1)} style={{alignItems: 'center', justifyContent: 'flex-start', flexDirection: 'row', marginRight: -7}}>
                            {React.cloneElement(buttons[i], {style: this.getInitialStyle().toolbarButton, header : true, textStyle: {color: this.getTheme().toolbarTextColor}})}
                            </View>)
                        }
                    }

                }
                return newChildren;
            }
        }

        render() {
            return(
            <View {...this.prepareRootProps()} >
            {this.renderChildren()}
            </View>
        );
    }
}
<|endoftext|>


<commit_before>// @flow
import React from 'react'
import {get} from 'lodash'
import {Item as DefaultItem, List as DefaultList} from 'part:@sanity/components/lists/default'
import {Item as SortableItem, List as SortableList} from 'part:@sanity/components/lists/sortable'
import ArrayFunctions from 'part:@sanity/form-builder/input/array/functions'
import Fieldset from 'part:@sanity/components/fieldsets/default'
import {PatchEvent, set, unset} from '../../PatchEvent'
import {startsWith} from '../../utils/pathUtils'
import {resolveTypeName} from '../../utils/resolveTypeName'
import type {Path} from '../../typedefs/path'
import type {Type, Marker} from '../../typedefs'
import type {ItemValue} from '../ArrayInput/typedefs'
import InvalidValue from '../InvalidValueInput'
import styles from './styles/ArrayOfPrimitivesInput.css'
import getEmptyValue from './getEmptyValue'
import Item from './Item'

function move(arr, from, to) {
  const copy = arr.slice()
  const val = copy[from]
  copy.splice(from, 1)
  copy.splice(to, 0, val)
  return copy
}

function insertAt(arr, index, item) {
  const copy = arr.slice()
  copy.splice(index + 1, 0, item)
  return copy
}

type Props = {
  type: Type,
  value: Array<ItemValue>,
  level: number,
  onChange: (event: PatchEvent) => void,
  onFocus: Path => void,
  onBlur: () => void,
  focusPath: Path,
  readOnly: ?boolean,
  markers: Array<Marker>
}

export default class ArrayOfPrimitivesInput extends React.PureComponent<Props> {
  _element: ?Fieldset
  _lastAddedIndex = -1

  set(nextValue: any[]) {
    this._lastAddedIndex = -1
    const patch = nextValue.length === 0 ? unset() : set(nextValue)
    this.props.onChange(PatchEvent.from(patch))
  }

  removeAt(index: number) {
    const {value = []} = this.props
    this.set(value.filter((_, i) => i !== index))
    this.props.onFocus([Math.max(0, index - 1)])
  }

  handleAppend = itemValue => {
    const {value = [], onFocus} = this.props
    this.set(value.concat(itemValue))
    onFocus([value.length])
  }

  handlePrepend = itemValue => {
    const {value = [], onFocus} = this.props
    this.set([itemValue].concat(value))
    onFocus([value.length])
  }

  insertAt(index, type) {
    const {value = [], onFocus} = this.props
    this.set(insertAt(value, index, getEmptyValue(type)))
    onFocus([index + 1])
  }

  handleRemoveItem = (index: number) => {
    this.removeAt(index)
  }

  handleItemChange = event => {
    this._lastAddedIndex = -1
    this.props.onChange(event)
  }

  handleItemEnterKey = index => {
    this.insertAt(index, this.props.type.of[0])
    this._lastAddedIndex = index + 1
  }

  handleItemEscapeKey = index => {
    const {value} = this.props
    if (index === this._lastAddedIndex && value[index] === '') {
      this.removeAt(index)
    }
  }

  handleSortEnd = event => {
    const {value} = this.props
    const {oldIndex, newIndex} = event
    this.set(move(value, oldIndex, newIndex))
  }

  getMemberType(typeName) {
    const {type} = this.props
    return type.of.find(
      memberType => memberType.name === typeName || memberType.jsonType === typeName
    )
  }

  renderItem = (item, index) => {
    const {type, level, markers, value, focusPath, onChange, onFocus, readOnly, onBlur} = this.props

    const typeName = resolveTypeName(item)
    const itemMemberType = this.getMemberType(typeName)

    if (!itemMemberType) {
      return (
        <InvalidValue
          key={index}
          actualType={typeName}
          validTypes={type.of.map(memberType => memberType.name)}
          onChange={ev => onChange(ev.prefixAll(index))}
          value={value}
        />
      )
    }

    const isSortable = get(type, 'options.sortable') !== false
    const ListItem = isSortable ? SortableItem : DefaultItem
    const filteredMarkers = markers.filter(marker => startsWith([index], marker.path))

    return (
      <ListItem key={index} index={index} className={styles.item}>
        <Item
          level={level + 1}
          index={index}
          value={item}
          readOnly={readOnly}
          markers={filteredMarkers}
          isSortable={isSortable}
          type={itemMemberType}
          focusPath={focusPath}
          onFocus={onFocus}
          onBlur={onBlur}
          onEnterKey={this.handleItemEnterKey}
          onEscapeKey={this.handleItemEscapeKey}
          onChange={this.handleItemChange}
          onRemove={this.handleRemoveItem}
        />
      </ListItem>
    )
  }

  renderList(value) {
    const {type} = this.props
    const isSortable = get(type, 'options.sortable') !== false
    return isSortable ? (
      <SortableList
        className={styles.list}
        onSortEnd={this.handleSortEnd}
        movingItemClass={styles.movingItem}
        useDragHandle
      >
        {value.map(this.renderItem)}
      </SortableList>
    ) : (
      <DefaultList decoration="divider">{value.map(this.renderItem)}</DefaultList>
    )
  }

  setElement = (el: ?Fieldset) => {
    this._element = el
  }

  focus() {
    if (this._element) {
      this._element.focus()
    }
  }

  handleFocusItem = index => {
    this.props.onFocus([index])
  }

  render() {
    const {type, value, level, markers, readOnly, onChange, onFocus} = this.props
    return (
      <Fieldset
        legend={type.title}
        description={type.description}
        level={level}
        tabIndex={0}
        onFocus={onFocus}
        ref={this.setElement}
        markers={markers}
      >

{value && value.length > 0 && this.renderList(value)}

            <ArrayFunctions
              type={type}
              value={value}
              readOnly={readOnly}
              onAppendItem={this.handleAppend}
              onPrependItem={this.handlePrepend}
              onFocusItem={this.handleFocusItem}
              onCreateValue={getEmptyValue}
              onChange={onChange}
            />

      </Fieldset>
    )
  }
}
<commit_msg>[form-builder] Remove gap in arrayOfPrimitiveInput<commit_after>// @flow
import React from 'react'
import {get} from 'lodash'
import {Item as DefaultItem, List as DefaultList} from 'part:@sanity/components/lists/default'
import {Item as SortableItem, List as SortableList} from 'part:@sanity/components/lists/sortable'
import ArrayFunctions from 'part:@sanity/form-builder/input/array/functions'
import Fieldset from 'part:@sanity/components/fieldsets/default'
import {PatchEvent, set, unset} from '../../PatchEvent'
import {startsWith} from '../../utils/pathUtils'
import {resolveTypeName} from '../../utils/resolveTypeName'
import type {Path} from '../../typedefs/path'
import type {Type, Marker} from '../../typedefs'
import type {ItemValue} from '../ArrayInput/typedefs'
import InvalidValue from '../InvalidValueInput'
import styles from './styles/ArrayOfPrimitivesInput.css'
import getEmptyValue from './getEmptyValue'
import Item from './Item'

function move(arr, from, to) {
  const copy = arr.slice()
  const val = copy[from]
  copy.splice(from, 1)
  copy.splice(to, 0, val)
  return copy
}

function insertAt(arr, index, item) {
  const copy = arr.slice()
  copy.splice(index + 1, 0, item)
  return copy
}

type Props = {
  type: Type,
  value: Array<ItemValue>,
  level: number,
  onChange: (event: PatchEvent) => void,
  onFocus: Path => void,
  onBlur: () => void,
  focusPath: Path,
  readOnly: ?boolean,
  markers: Array<Marker>
}

export default class ArrayOfPrimitivesInput extends React.PureComponent<Props> {
  _element: ?Fieldset
  _lastAddedIndex = -1

  set(nextValue: any[]) {
    this._lastAddedIndex = -1
    const patch = nextValue.length === 0 ? unset() : set(nextValue)
    this.props.onChange(PatchEvent.from(patch))
  }

  removeAt(index: number) {
    const {value = []} = this.props
    this.set(value.filter((_, i) => i !== index))
    this.props.onFocus([Math.max(0, index - 1)])
  }

  handleAppend = itemValue => {
    const {value = [], onFocus} = this.props
    this.set(value.concat(itemValue))
    onFocus([value.length])
  }

  handlePrepend = itemValue => {
    const {value = [], onFocus} = this.props
    this.set([itemValue].concat(value))
    onFocus([value.length])
  }

  insertAt(index, type) {
    const {value = [], onFocus} = this.props
    this.set(insertAt(value, index, getEmptyValue(type)))
    onFocus([index + 1])
  }

  handleRemoveItem = (index: number) => {
    this.removeAt(index)
  }

  handleItemChange = event => {
    this._lastAddedIndex = -1
    this.props.onChange(event)
  }

  handleItemEnterKey = index => {
    this.insertAt(index, this.props.type.of[0])
    this._lastAddedIndex = index + 1
  }

  handleItemEscapeKey = index => {
    const {value} = this.props
    if (index === this._lastAddedIndex && value[index] === '') {
      this.removeAt(index)
    }
  }

  handleSortEnd = event => {
    const {value} = this.props
    const {oldIndex, newIndex} = event
    this.set(move(value, oldIndex, newIndex))
  }

  getMemberType(typeName) {
    const {type} = this.props
    return type.of.find(
      memberType => memberType.name === typeName || memberType.jsonType === typeName
    )
  }

  renderItem = (item, index) => {
    const {type, level, markers, value, focusPath, onChange, onFocus, readOnly, onBlur} = this.props

    const typeName = resolveTypeName(item)
    const itemMemberType = this.getMemberType(typeName)

    if (!itemMemberType) {
      return (
        <InvalidValue
          key={index}
          actualType={typeName}
          validTypes={type.of.map(memberType => memberType.name)}
          onChange={ev => onChange(ev.prefixAll(index))}
          value={value}
        />
      )
    }

    const isSortable = get(type, 'options.sortable') !== false
    const ListItem = isSortable ? SortableItem : DefaultItem
    const filteredMarkers = markers.filter(marker => startsWith([index], marker.path))

    return (
      <ListItem key={index} index={index} className={styles.item}>
        <Item
          level={level + 1}
          index={index}
          value={item}
          readOnly={readOnly}
          markers={filteredMarkers}
          isSortable={isSortable}
          type={itemMemberType}
          focusPath={focusPath}
          onFocus={onFocus}
          onBlur={onBlur}
          onEnterKey={this.handleItemEnterKey}
          onEscapeKey={this.handleItemEscapeKey}
          onChange={this.handleItemChange}
          onRemove={this.handleRemoveItem}
        />
      </ListItem>
    )
  }

  renderList(value) {
    const {type} = this.props
    const isSortable = get(type, 'options.sortable') !== false
    return isSortable ? (
      <SortableList
        className={styles.list}
        onSortEnd={this.handleSortEnd}
        movingItemClass={styles.movingItem}
        useDragHandle
      >
        {value.map(this.renderItem)}
      </SortableList>
    ) : (
      <DefaultList decoration="divider">{value.map(this.renderItem)}</DefaultList>
    )
  }

  setElement = (el: ?Fieldset) => {
    this._element = el
  }

  focus() {
    if (this._element) {
      this._element.focus()
    }
  }

  handleFocusItem = index => {
    this.props.onFocus([index])
  }

  render() {
    const {type, value, level, markers, readOnly, onChange, onFocus} = this.props
    return (
      <Fieldset
        legend={type.title}
        description={type.description}
        level={level}
        tabIndex={0}
        onFocus={onFocus}
        ref={this.setElement}
        markers={markers}
      >

          {value && value.length > 0 &&
{this.renderList(value)}
}

            <ArrayFunctions
              type={type}
              value={value}
              readOnly={readOnly}
              onAppendItem={this.handleAppend}
              onPrependItem={this.handlePrepend}
              onFocusItem={this.handleFocusItem}
              onCreateValue={getEmptyValue}
              onChange={onChange}
            />

      </Fieldset>
    )
  }
}
<|endoftext|>


<commit_before>Jsonix.Model.AbstractElementsPropertyInfo = Jsonix.Class(Jsonix.Model.PropertyInfo, {
	wrapperElementName : null,
	initialize : function(options) {
		Jsonix.Util.Ensure.ensureObject(options);
		Jsonix.Model.PropertyInfo.prototype.initialize.apply(this, [ options ]);
		var wen = options.wrapperElementName||options.wen||null;
		if (Jsonix.Util.Type.isObject(wen)) {
			Jsonix.Util.Ensure.ensureString(wen.localPart, 'Wrapper element name must contain a string property [localPart].');
			this.wrapperElementName = Jsonix.XML.QName.fromObject(wen);
		} else if (Jsonix.Util.Type.isString(wen)) {
			this.wrapperElementName = new Jsonix.XML.QName(this.defaultElementNamespaceURI, wen);
		} else {
			this.wrapperElementName = null;
		}
	},
	unmarshal : function(context, input, scope) {
		var result = null;
		var that = this;
		var callback = function(value) {
			if (that.collection) {
				if (result === null) {
					result = [];
				}
				result.push(value);

			} else {
				if (result === null) {
					result = value;
				} else {
					// TODO Report validation error
					throw new Error("Value already set.");
				}
			}
		};

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			this.unmarshalWrapperElement(context, input, scope, callback);
		} else {
			this.unmarshalElement(context, input, scope, callback);
		}
		return result;
	},
	unmarshalWrapperElement : function(context, input, scope, callback) {
		var et = input.next();
		while (et !== Jsonix.XML.Input.END_ELEMENT) {
			// New sub-element starts
			if (et === Jsonix.XML.Input.START_ELEMENT) {
				this.unmarshalElement(context, input, scope, callback);
			} else if (et === Jsonix.XML.Input.SPACE || et === Jsonix.XML.Input.COMMENT || et === Jsonix.XML.Input.PROCESSING_INSTRUCTION) {
				// Skip whitespace
			} else {
				// TODO ignore comments, processing
				// instructions
				throw new Error("Illegal state: unexpected event type [" + et + "].");
			}
			et = input.next();
		}
	},
	unmarshalElement : function(context, input, scope, callback) {
		throw new Error("Abstract method [unmarshalElement].");
	},
	marshal : function(value, context, output, scope) {

		if (!Jsonix.Util.Type.exists(value)) {
			// Do nothing
			return;
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			output.writeStartElement(this.wrapperElementName);
		}

		if (!this.collection) {
			this.marshalElement(value, context, output, scope);
		} else {
			Jsonix.Util.Ensure.ensureArray(value);
			// TODO Exception if not array
			for ( var index = 0; index < value.length; index++) {
				var item = value[index];
				// TODO Exception if item does not exist
				this.marshalElement(item, context, output, scope);
			}
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			output.writeEndElement();
		}
	},
	marshalElement : function(value, context, output, scope) {
		throw new Error("Abstract method [marshalElement].");
	},
	marshalElementTypeInfo : function(elementName, typeInfo,  value, context, output, scope) {
		output.writeStartElement(elementName);
		typeInfo.marshal(value, context, output, scope);
		output.writeEndElement();
	},
	buildStructure : function(context, structure) {
		Jsonix.Util.Ensure.ensureObject(structure);
		if (Jsonix.Util.Type.exists(structure.value)) {
			// TODO better exception
			throw new Error("The structure already defines a value property.");
		} else if (!Jsonix.Util.Type.exists(structure.elements)) {
			structure.elements = {};
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			structure.elements[this.wrapperElementName.key] = this;
		} else {
			this.buildStructureElements(context, structure);
		}
	},
	buildStructureElements : function(context, structure) {
		throw new Error("Abstract method [buildStructureElements].");
	},
	CLASS_NAME : 'Jsonix.Model.AbstractElementsPropertyInfo'
});
<commit_msg>Compact naming.<commit_after>Jsonix.Model.AbstractElementsPropertyInfo = Jsonix.Class(Jsonix.Model.PropertyInfo, {
	wrapperElementName : null,
	initialize : function(mapping) {
		Jsonix.Util.Ensure.ensureObject(mapping);
		Jsonix.Model.PropertyInfo.prototype.initialize.apply(this, [ mapping ]);
		var wen = mapping.wrapperElementName||mapping.wen||null;
		if (Jsonix.Util.Type.isObject(wen)) {
			Jsonix.Util.Ensure.ensureString(wen.localPart, 'Wrapper element name must contain a string property [localPart].');
			this.wrapperElementName = Jsonix.XML.QName.fromObject(wen);
		} else if (Jsonix.Util.Type.isString(wen)) {
			this.wrapperElementName = new Jsonix.XML.QName(this.defaultElementNamespaceURI, wen);
		} else {
			this.wrapperElementName = null;
		}
	},
	unmarshal : function(context, input, scope) {
		var result = null;
		var that = this;
		var callback = function(value) {
			if (that.collection) {
				if (result === null) {
					result = [];
				}
				result.push(value);

			} else {
				if (result === null) {
					result = value;
				} else {
					// TODO Report validation error
					throw new Error("Value already set.");
				}
			}
		};

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			this.unmarshalWrapperElement(context, input, scope, callback);
		} else {
			this.unmarshalElement(context, input, scope, callback);
		}
		return result;
	},
	unmarshalWrapperElement : function(context, input, scope, callback) {
		var et = input.next();
		while (et !== Jsonix.XML.Input.END_ELEMENT) {
			// New sub-element starts
			if (et === Jsonix.XML.Input.START_ELEMENT) {
				this.unmarshalElement(context, input, scope, callback);
			} else if (et === Jsonix.XML.Input.SPACE || et === Jsonix.XML.Input.COMMENT || et === Jsonix.XML.Input.PROCESSING_INSTRUCTION) {
				// Skip whitespace
			} else {
				// TODO ignore comments, processing
				// instructions
				throw new Error("Illegal state: unexpected event type [" + et + "].");
			}
			et = input.next();
		}
	},
	unmarshalElement : function(context, input, scope, callback) {
		throw new Error("Abstract method [unmarshalElement].");
	},
	marshal : function(value, context, output, scope) {

		if (!Jsonix.Util.Type.exists(value)) {
			// Do nothing
			return;
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			output.writeStartElement(this.wrapperElementName);
		}

		if (!this.collection) {
			this.marshalElement(value, context, output, scope);
		} else {
			Jsonix.Util.Ensure.ensureArray(value);
			// TODO Exception if not array
			for ( var index = 0; index < value.length; index++) {
				var item = value[index];
				// TODO Exception if item does not exist
				this.marshalElement(item, context, output, scope);
			}
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			output.writeEndElement();
		}
	},
	marshalElement : function(value, context, output, scope) {
		throw new Error("Abstract method [marshalElement].");
	},
	marshalElementTypeInfo : function(elementName, typeInfo,  value, context, output, scope) {
		output.writeStartElement(elementName);
		typeInfo.marshal(value, context, output, scope);
		output.writeEndElement();
	},
	buildStructure : function(context, structure) {
		Jsonix.Util.Ensure.ensureObject(structure);
		if (Jsonix.Util.Type.exists(structure.value)) {
			// TODO better exception
			throw new Error("The structure already defines a value property.");
		} else if (!Jsonix.Util.Type.exists(structure.elements)) {
			structure.elements = {};
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			structure.elements[this.wrapperElementName.key] = this;
		} else {
			this.buildStructureElements(context, structure);
		}
	},
	buildStructureElements : function(context, structure) {
		throw new Error("Abstract method [buildStructureElements].");
	},
	CLASS_NAME : 'Jsonix.Model.AbstractElementsPropertyInfo'
});
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Dropdown from '../Dropdown'
import { Modal } from '../../../components'
/**
 * TODO add a concise description of this component
 */
const toggleDropdown = () => {}
const RejectTranslationModal = ({
  show,
  key,
  className,
  onHide,
  isOpen
}) => {
  return (
    <Modal show={show}
      onHide={close}
      key="reject-translation-modal"
      className="suggestions-modal">
      <Modal.Header>
        <Modal.Title>
        Reject translation</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        Reason:
        <Dropdown enabled isOpen
          onToggle={toggleDropdown()}
          className="Dropdown--right u-sMV-1-2">
          <Dropdown.Button>

              Dropdown button

          </Dropdown.Button>
          <Dropdown.Content>

Cat

Dog

Honey Badger

Walrus

          </Dropdown.Content>
        </Dropdown>
      </Modal.Body>
    </Modal>
  )
}

RejectTranslationModal.propTypes = {
  show: PropTypes.bool,
  className: PropTypes.string,
  key: PropTypes.string,
  onHide: PropTypes.func,
  toggleDropdown: PropTypes.func.isRequired,
  isOpen: PropTypes.bool.isRequired
}

export default RejectTranslationModal
<commit_msg>feat(ZNTA-2156): make dropdown open and close<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Dropdown from '../Dropdown'
import { Modal } from '../../../components'
/**
 * TODO add a concise description of this component
 */
export class RejectTranslationModal extends Component {
  static propTypes = {
    show: PropTypes.bool,
    className: PropTypes.string,
    key: PropTypes.string,
    onHide: PropTypes.func,
    toggleDropdown: PropTypes.func.isRequired,
    isOpen: PropTypes.bool.isRequired
  }

  constructor (props) {
    super(props)
    this.state = {
      dropdownOpen: false
    }
  }

  toggleDropdown = () => {
    this.setState(prevState => ({
      dropdownOpen: !prevState.dropdownOpen
    }))
  }

  render () {
    const {
      show,
      key,
      className,
      onHide,
      isOpen
    } = this.props
    return (
      <Modal show={show}
        onHide={close}
        key="reject-translation-modal"
        className="suggestions-modal">
        <Modal.Header>
          <Modal.Title>
          Reject translation</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Reason:
          <Dropdown enabled isOpen={this.state.dropdownOpen}
            onToggle={this.toggleDropdown}
            className="Dropdown--right u-sMV-1-2">
            <Dropdown.Button>

                Dropdown button

            </Dropdown.Button>
            <Dropdown.Content>

Cat

Dog

Honey Badger

Walrus

            </Dropdown.Content>
          </Dropdown>
        </Modal.Body>
      </Modal>
    )
  }
}

export default RejectTranslationModal
<|endoftext|>


<commit_before>function renderCell (params) {
  // return React.DOM.span(null, `column:${params.columnIndex}, row:${params.rowIndex}`)
  return React.DOM.input({
    className: 'input',
    onChange: function () {},
    value: `column:${params.columnIndex}, row:${params.rowIndex}`
  })
}

/*
function measurePerformance () {
  console.log('measurePerformance()')
  var measurements = React.addons.Perf.getLastMeasurements()
  if (measurements.length > 0) {
    console.group('printDOM')
    React.addons.Perf.printDOM(measurements)
    console.groupEnd()

    console.group('printWasted')
    React.addons.Perf.printWasted(measurements)
    console.groupEnd()

    React.addons.Perf.start()
  }
}
*/

var App = React.createClass({
  componentDidMount: function () {
    // React.addons.Perf.start()
    // window.Perf = React.addons.Perf
  },

  render: function() {
    return React.createElement(
      ReactVirtualized.AutoSizer,
      null,
      function (params) {
        return React.createElement(
          ReactVirtualized.Grid,
          {
            columnsCount: 1000,
            columnWidth: 200,
            height: params.height,
            overscanRowsCount: 0,
            renderCell: renderCell,
            rowHeight: 40,
            rowsCount: 1000,
            width: params.width
          }
        )
      }
    )
  }
})

ReactDOM.render(
  React.createElement(App),
  document.querySelector('#mount')
)
<commit_msg>Tweaked playground<commit_after>function renderCell (params) {
  // return React.DOM.span(null, `column:${params.columnIndex}, row:${params.rowIndex}`)
  return React.DOM.input({
    className: 'input',
    onChange: function () {},
    defaultValue: `column:${params.columnIndex}, row:${params.rowIndex}`
  })
}

/*
function measurePerformance () {
  console.log('measurePerformance()')
  var measurements = React.addons.Perf.getLastMeasurements()
  if (measurements.length > 0) {
    console.group('printDOM')
    React.addons.Perf.printDOM(measurements)
    console.groupEnd()

    console.group('printWasted')
    React.addons.Perf.printWasted(measurements)
    console.groupEnd()

    React.addons.Perf.start()
  }
}
*/

var App = React.createClass({
  componentDidMount: function () {
    // React.addons.Perf.start()
    // window.Perf = React.addons.Perf
  },

  render: function() {
    return React.createElement(
      ReactVirtualized.AutoSizer,
      null,
      function (params) {
        return React.createElement(
          ReactVirtualized.Grid,
          {
            columnsCount: 1000,
            columnWidth: 200,
            height: params.height,
            overscanRowsCount: 0,
            renderCell: renderCell,
            rowHeight: 40,
            rowsCount: 1000,
            width: params.width
          }
        )
      }
    )
  }
})

ReactDOM.render(
  React.createElement(App),
  document.querySelector('#mount')
)
<|endoftext|>


<commit_before>function Filter() {

};

function FilterColorThreshold() {
  Filter.call(this);

};

FilterColorThreshold.prototype = new Filter;

FilterColorThreshold.prototype.destructor=function() {
    // Get rid of the buffers?

}

FilterColorThreshold.prototype.Start = function() {
    // Create a div
    var dialogDiv = $('
')
        .attr('id', 'scar_ratio_dialog')
        .attr('title', 'Color thresholding filter');

    // Add graphs
    var selectors = [ { name: 'hue', max: 360}, { name: 'saturation', max: 256} , {name: 'value', max: 256}];

    for(var i = 0; i < selectors.length; i ++) {
        $('
' + selectors[i].name  + '
').appendTo(dialogDiv);

        $('')
            .attr('src', '/webgl-viewer/static/temp/' + selectors[i].name + ".png")
            .attr('width','100%')
            .appendTo(dialogDiv);

        $('
').appendTo(dialogDiv);
        selectors[i].sliderDiv = $('
').appendTo(dialogDiv);
        selectors[i].sliderDiv.slider({
            range:true,
            min: 0,
            max: selectors[i].max,
            values: [ 0, selectors[i].max ],
        });

    }

    $('<button>').appendTo(dialogDiv)
        .text('Update')
        .attr('id', 'updateButton');

    $('
').appendTo(dialogDiv);

    var dialog = dialogDiv.dialog({width: 500, height: 'auto'});

    $('#updateButton').click(function() {
        alert("Ready to update !!");
    });

}
<commit_msg>HSV and color histograms<commit_after>function Filter() {

};

function FilterColorThreshold() {
  Filter.call(this);
  this.Init()
};

FilterColorThreshold.prototype = new Filter;

FilterColorThreshold.prototype.destructor=function() {
    // Get rid of the buffers?

}

FilterColorThreshold.prototype.Init = function() {
  // Gets the graphs and constructs the dialog
  $.post('/webgl-viewer/get_image_histograms', {
            img : canvas.toDataURL('image/jpeg')
        },
        function(data) {
            this.Start()
        });
}

FilterColorThreshold.prototype.Start = function() {
    // Create a div
    var dialogDiv = $('
')
        .attr('id', 'scar_ratio_dialog')
        .attr('title', 'Color thresholding filter');

    // Add graphs
    var selectors = [ { name: 'hue', max: 360}, { name: 'saturation', max: 256} , {name: 'value', max: 256}];

    for(var i = 0; i < selectors.length; i ++) {
        $('
' + selectors[i].name  + '
').appendTo(dialogDiv);

        $('')
            .attr('src', '/webgl-viewer/static/temp/' + selectors[i].name + ".png")
            .attr('width','100%')
            .appendTo(dialogDiv);

        $('
').appendTo(dialogDiv);
        selectors[i].sliderDiv = $('
').appendTo(dialogDiv);
        selectors[i].sliderDiv.slider({
            range:true,
            min: 0,
            max: selectors[i].max,
            values: [ 0, selectors[i].max ],
        });

    }

    $('<button>').appendTo(dialogDiv)
        .text('Update')
        .attr('id', 'updateButton');

    $('
').appendTo(dialogDiv);

    var dialog = dialogDiv.dialog({width: 500, height: 'auto'});

    $('#updateButton').click(function() {
        alert("Ready to update !!");
    });

}
<|endoftext|>


<commit_before>var exec = require("child_process").exec;

function FortunePlugin(bot) {
	var self = this;
	self.name = "fortune";
	self.help = "Fortune teller plugin";
	self.depend = ["cmd"];

	self.events = {
		"cmd#fortune" : function(nick, to, args, message) {
			exec("fortune -s", function (error, stdout, stderr) {
				stdout.split("\n").forEach(function (line) {
					bot.say(to, line);
				});
			});
		}
	}
}

module.exports = FortunePlugin;
<commit_msg>Nicer formatting of fortunes<commit_after>var exec = require("child_process").exec;

function FortunePlugin(bot) {
	var self = this;
	self.name = "fortune";
	self.help = "Fortune teller plugin";
	self.depend = ["cmd"];

	self.events = {
		"cmd#fortune" : function(nick, to, args, message) {
			exec("fortune -s", function (error, stdout, stderr) {
				stdout.split("\n").forEach(function (line) {
					if (line != "")
						bot.say(to, "  " + line);
				});
			});
		}
	}
}

module.exports = FortunePlugin;
<|endoftext|>


<commit_before>'use strict';

module.exports = {

  plugins: [
    'jasmine',
  ],

  extends: [
    'plugin:jasmine/recommended',
  ],

  env: {
    jasmine: true,
  },

  rules: {
    'arrow-body-style': 0,
  },

};
<commit_msg>allow branch duplicates<commit_after>'use strict';

module.exports = {

  plugins: [
    'jasmine',
  ],

  extends: [
    'plugin:jasmine/recommended',
  ],

  env: {
    jasmine: true,
  },

  rules: {
    'arrow-body-style': 0,
    'jasmine/no-spec-dupes': [1, 'branch'],
    'jasmine/no-suite-dupes': [1, 'branch'],
  },

};
<|endoftext|>


<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'redgifs.com',
    version:'0.2',
    prepareImgLinks:function (callback) {
        var res = [];

        $('a[href^="https://redgifs.com/"]').one('mouseenter', function() {
            var link = $(this),
                gfyId = this.href.replace(/.*redgifs.com\/(..\/)?(watch\/)?(detail\/)?(\w+).*/, '$4');

            $.get('https://api.redgifs.com/v1/gfycats/' + gfyId, function (data) {
                if (data && data.gfyItem) {
                    link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.mp4Url : data.gfyItem.gifUrl]
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        });

        // sample:   https://thumbs2.redgifs.com/StickySereneMoray-small.jpg
        // fullsize: https://thumbs2.redgifs.com/StickySereneMoray-large.jpg
        hoverZoom.urlReplace(res,
            'img[src]',
            /-(small|medium)/,
            '-large'
        );

        // mobile version:   https://thumbs2.redgifs.com/CookedUprightAfricanparadiseflycatcher-mobile.mp4
        // best quality version: https://thumbs2.redgifs.com/CookedUprightAfricanparadiseflycatcher.mp4
        $('video:not(.hoverZoomMouseover)').addClass('hoverZoomMouseover').one('mouseover', function() {
            let link = $(this);
            let srcs = $(this).find('source[src]');
            if (srcs.length != 1) return;
            let videoUrlMobile = srcs[0].src;
            let videoUrlBestQuality = videoUrlMobile.replace('-mobile', '');
            let videoUrl = videoUrlMobile + '.video';
            if (link.data().hoverZoomSrc == undefined) { link.data().hoverZoomSrc = [] }
            if (link.data().hoverZoomSrc.indexOf(videoUrl) == -1) {
                link.data().hoverZoomSrc.unshift(videoUrl);
            }
            videoUrl = videoUrlBestQuality + '.video';
            if (link.data().hoverZoomSrc == undefined) { link.data().hoverZoomSrc = [] }
            if (link.data().hoverZoomSrc.indexOf(videoUrl) == -1) {
                link.data().hoverZoomSrc.unshift(videoUrl);
            }
            callback(link, name);
            hoverZoom.displayPicFromElement(link);
        });

        if (res.length) {
            callback($(res), this.name);
        }
    }
});
<commit_msg>Fix redgifs plugin to also support www-prefixed urls<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'redgifs.com',
    version:'0.2',
    prepareImgLinks:function (callback) {
        var res = [];

        $('a[href^="https://redgifs.com/"],a[href^="https://www.redgifs.com/"]').one('mouseenter', function() {
            var link = $(this),
                gfyId = this.href.replace(/.*redgifs.com\/(..\/)?(watch\/)?(detail\/)?(\w+).*/, '$4');

            $.get('https://api.redgifs.com/v1/gfycats/' + gfyId, function (data) {
                if (data && data.gfyItem) {
                    link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.mp4Url : data.gfyItem.gifUrl]
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        });

        // sample:   https://thumbs2.redgifs.com/StickySereneMoray-small.jpg
        // fullsize: https://thumbs2.redgifs.com/StickySereneMoray-large.jpg
        hoverZoom.urlReplace(res,
            'img[src]',
            /-(small|medium)/,
            '-large'
        );

        // mobile version:   https://thumbs2.redgifs.com/CookedUprightAfricanparadiseflycatcher-mobile.mp4
        // best quality version: https://thumbs2.redgifs.com/CookedUprightAfricanparadiseflycatcher.mp4
        $('video:not(.hoverZoomMouseover)').addClass('hoverZoomMouseover').one('mouseover', function() {
            let link = $(this);
            let srcs = $(this).find('source[src]');
            if (srcs.length != 1) return;
            let videoUrlMobile = srcs[0].src;
            let videoUrlBestQuality = videoUrlMobile.replace('-mobile', '');
            let videoUrl = videoUrlMobile + '.video';
            if (link.data().hoverZoomSrc == undefined) { link.data().hoverZoomSrc = [] }
            if (link.data().hoverZoomSrc.indexOf(videoUrl) == -1) {
                link.data().hoverZoomSrc.unshift(videoUrl);
            }
            videoUrl = videoUrlBestQuality + '.video';
            if (link.data().hoverZoomSrc == undefined) { link.data().hoverZoomSrc = [] }
            if (link.data().hoverZoomSrc.indexOf(videoUrl) == -1) {
                link.data().hoverZoomSrc.unshift(videoUrl);
            }
            callback(link, name);
            hoverZoom.displayPicFromElement(link);
        });

        if (res.length) {
            callback($(res), this.name);
        }
    }
});
<|endoftext|>