<commit_before>/*
 * Format for Selenium Remote Control Perl client.
 */

var subScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
subScriptLoader.loadSubScript('chrome://selenium-ide/content/formats/remoteControl.js', this);

this.name = "perl-rc";

// method name will not be used in this format
function testMethodName(testName) {
	return testName;
}

var originalFormatCommands = formatCommands;
formatCommands = function(commands) {
	this.tests = 0;
	var lines = originalFormatCommands(commands);
	if (this.tests == 0) {
		lines += addIndent("pass;\n");
	}
	return lines;
}

var formatter = this;

string = function(value) {
	if (value != null) {
		value = value.replace(/\\/g, '\\\\');
		value = value.replace(/\'/g, '\\\'');
		value = value.replace(/\r/g, '\\r');
		value = value.replace(/\n/g, '\\n');
		return "'" + value + "'";
	} else {
		return "'";
	}
}

variableName = function(value) {
	return "$" + value;
}

concatString = function(array) {
	return array.join(" . ");
}

function assertTrue(expression) {
	if (formatter.assertOrVerifyFailureOnNext) {
		return expression.toString() + " or die;";
	} else {
		formatter.tests++;
		if (expression.assertable) {
			expression.suffix = "_ok";
			return expression.toString() + ";";
		} else {
			return "ok(" + expression.toString() + ");";
		}
	}
}

function assertFalse(expression) {
	if (formatter.assertOrVerifyFailureOnNext) {
		return expression.toString() + " and die;";
	} else {
		formatter.tests++;
		return "ok(not " + expression.toString() + ");";
	}
}

var verifyTrue = assertTrue;
var verifyFalse = assertFalse;

function joinExpression(expression) {
    return "join(',', " + expression.toString() + ")";
}

function assignToVariable(type, variable, expression) {
	if (type == 'String[]') {
		return "my @" + variable + " = " + expression.toString();
	} else {
		return "my $" + variable + " = " + expression.toString();
	}
}

function waitFor(expression) {
	return "WAIT: {\n" +
		indents(1) + "for (1..60) {\n" +
		indents(2) + "if (eval { " + expression.toString() + " }) { pass; last WAIT }\n" +
		indents(2) + "sleep(1);\n" +
		indents(1) + "}\n" +
		indents(1) + 'fail("timeout");\n' +
		"}";
}

function assertOrVerifyFailure(line, isAssert) {
	return 'dies_ok { ' + line + ' };';
}

Equals.prototype.toString = function() {
	return this.e1.toString() + " eq " + this.e2.toString();
}

NotEquals.prototype.toString = function() {
	return this.e1.toString() + " ne " + this.e2.toString();
}

Equals.prototype.assert = function() {
	if (formatter.assertOrVerifyFailureOnNext) {
		return assertTrue(this);
	} else {
		formatter.tests++;
		if (!this.e2.args) {
			return "is(" + this.e1 + ", " + this.e2 + ");";
		} else {
			var expression = this.e2;
			expression.suffix = "_is";
			expression.noGet = true;
			expression.args.push(this.e1);
			return expression.toString() + ";";
		}
	}
}

Equals.prototype.verify = Equals.prototype.assert;

NotEquals.prototype.assert = function() {
	if (formatter.assertOrVerifyFailureOnNext) {
		return assertTrue(this);
	} else {
		if (!this.e2.args) {
			return "isnt(" + this.e1 + ", " + this.e2 + ");";
		} else {
			formatter.tests++;
			var expression = this.e2;
			expression.suffix = "_isnt";
			expression.noGet = true;
			expression.args.push(this.e1);
			return expression.toString() + ";";
		}
	}
}

NotEquals.prototype.verify = NotEquals.prototype.assert;

RegexpMatch.prototype.toString = function() {
	return this.expression + " =~ /" + this.pattern.replace(/\//g, "\\/") + "/";
}

RegexpNotMatch.prototype.toString = function() {
	return notOperator() + "(" + RegexpMatch.prototype.toString.call(this) + ")";
}

function ifCondition(expression, callback) {
    return "if (" + expression.toString() + ") {\n" + callback() + "}";
}

function pause(milliseconds) {
	return "sleep(" + (parseInt(milliseconds) / 1000) + ");";
}

function echo(message) {
	return "print(" + xlateArgument(message) + ' . "\\n");'
}

function statement(expression) {
	if (!formatter.assertOrVerifyFailureOnNext) {
		formatter.tests++;
		expression.suffix = "_ok";
	}
	return expression.toString() + ";";
}

function array(value) {
	var str = '(';
	for (var i = 0; i < value.length; i++) {
		str += string(value[i]);
		if (i < value.length - 1) str += ", ";
	}
	str += ')';
	return str;
}

function nonBreakingSpace() {
    return "\"\\x{00A0}\"";
}

CallSelenium.prototype.assertable = true;

CallSelenium.prototype.toString = function() {
	var result = '';
	if (this.negative) {
		result += '!';
	}
	if (options.receiver) {
		result += options.receiver + '->';
	}
	var command = underscore(this.message);
	if (this.noGet) {
		command = command.replace(/^get_/, '');
	}
	result += command;
	if (this.suffix) {
		result += this.suffix;
	}
	result += '(';
	for (var i = 0; i < this.args.length; i++) {
		result += this.args[i];
		if (i < this.args.length - 1) {
			result += ', ';
		}
	}
	result += ')';
	return result;
}

function formatComment(comment) {
	return comment.comment.replace(/.+/mg, function(str) {
			return "# " + str;
		});
}

this.options = {
	receiver: "$sel",
	rcHost: "localhost",
	rcPort: "4444",
	environment: "*chrome",
	header:
		'use strict;\n' +
		'use warnings;\n' +
		'use utf8;\n' +
		'BEGIN {\n' +
		'    binmode STDOUT, ":utf8";\n' +
		'    binmode STDERR, ":utf8";\n' +
		'}\n' +
		'use Time::HiRes qw(sleep);\n' +
		'use Test::WWW::Selenium;\n' +
		'use Test::More "no_plan";\n' +
		'use Test::Exception;\n' +
		'\n' +
		'my ${receiver} = Test::WWW::Selenium->new( host => "${rcHost}", \n' +
		'                                    port => ${rcPort}, \n' +
		'                                    browser => "${environment}", \n' +
		'                                    browser_url => "${baseURL}" );\n' +
		'\n',
	footer: "",
	indent: "4",
	initialIndents: '0'
};

this.configForm =
	'<description>Variable for Selenium instance</description>' +
	'<textbox id="options_receiver" />' +
	'<description>Selenium RC host</description>' +
	'<textbox id="options_rcHost" />' +
	'<description>Selenium RC port</description>' +
	'<textbox id="options_rcPort" />' +
	'<description>Environment</description>' +
	'<textbox id="options_environment" />' +
	'<description>Header</description>' +
	'<textbox id="options_header" multiline="true" flex="1" rows="4"/>' +
	'<description>Footer</description>' +
	'<textbox id="options_footer" multiline="true" flex="1" rows="4"/>' +
	'<description>Indent</description>' +
	'<menulist id="options_indent"><menupopup>' +
	'<menuitem label="Tab" value="tab"/>' +
	'<menuitem label="1 space" value="1"/>' +
	'<menuitem label="2 spaces" value="2"/>' +
	'<menuitem label="3 spaces" value="3"/>' +
	'<menuitem label="4 spaces" value="4"/>' +
	'<menuitem label="5 spaces" value="5"/>' +
	'<menuitem label="6 spaces" value="6"/>' +
	'<menuitem label="7 spaces" value="7"/>' +
	'<menuitem label="8 spaces" value="8"/>' +
	'</menupopup></menulist>';
<commit_msg>Fixing incorrect empty string for perl formatter<commit_after>/*
 * Format for Selenium Remote Control Perl client.
 */

var subScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
subScriptLoader.loadSubScript('chrome://selenium-ide/content/formats/remoteControl.js', this);

this.name = "perl-rc";

// method name will not be used in this format
function testMethodName(testName) {
	return testName;
}

var originalFormatCommands = formatCommands;
formatCommands = function(commands) {
	this.tests = 0;
	var lines = originalFormatCommands(commands);
	if (this.tests == 0) {
		lines += addIndent("pass;\n");
	}
	return lines;
}

var formatter = this;

string = function(value) {
	if (value != null) {
		value = value.replace(/\\/g, '\\\\');
		value = value.replace(/\'/g, '\\\'');
		value = value.replace(/\r/g, '\\r');
		value = value.replace(/\n/g, '\\n');
		return "'" + value + "'";
	} else {
		return "''";
	}
}

variableName = function(value) {
	return "$" + value;
}

concatString = function(array) {
	return array.join(" . ");
}

function assertTrue(expression) {
	if (formatter.assertOrVerifyFailureOnNext) {
		return expression.toString() + " or die;";
	} else {
		formatter.tests++;
		if (expression.assertable) {
			expression.suffix = "_ok";
			return expression.toString() + ";";
		} else {
			return "ok(" + expression.toString() + ");";
		}
	}
}

function assertFalse(expression) {
	if (formatter.assertOrVerifyFailureOnNext) {
		return expression.toString() + " and die;";
	} else {
		formatter.tests++;
		return "ok(not " + expression.toString() + ");";
	}
}

var verifyTrue = assertTrue;
var verifyFalse = assertFalse;

function joinExpression(expression) {
    return "join(',', " + expression.toString() + ")";
}

function assignToVariable(type, variable, expression) {
	if (type == 'String[]') {
		return "my @" + variable + " = " + expression.toString();
	} else {
		return "my $" + variable + " = " + expression.toString();
	}
}

function waitFor(expression) {
	return "WAIT: {\n" +
		indents(1) + "for (1..60) {\n" +
		indents(2) + "if (eval { " + expression.toString() + " }) { pass; last WAIT }\n" +
		indents(2) + "sleep(1);\n" +
		indents(1) + "}\n" +
		indents(1) + 'fail("timeout");\n' +
		"}";
}

function assertOrVerifyFailure(line, isAssert) {
	return 'dies_ok { ' + line + ' };';
}

Equals.prototype.toString = function() {
	return this.e1.toString() + " eq " + this.e2.toString();
}

NotEquals.prototype.toString = function() {
	return this.e1.toString() + " ne " + this.e2.toString();
}

Equals.prototype.assert = function() {
	if (formatter.assertOrVerifyFailureOnNext) {
		return assertTrue(this);
	} else {
		formatter.tests++;
		if (!this.e2.args) {
			return "is(" + this.e1 + ", " + this.e2 + ");";
		} else {
			var expression = this.e2;
			expression.suffix = "_is";
			expression.noGet = true;
			expression.args.push(this.e1);
			return expression.toString() + ";";
		}
	}
}

Equals.prototype.verify = Equals.prototype.assert;

NotEquals.prototype.assert = function() {
	if (formatter.assertOrVerifyFailureOnNext) {
		return assertTrue(this);
	} else {
		if (!this.e2.args) {
			return "isnt(" + this.e1 + ", " + this.e2 + ");";
		} else {
			formatter.tests++;
			var expression = this.e2;
			expression.suffix = "_isnt";
			expression.noGet = true;
			expression.args.push(this.e1);
			return expression.toString() + ";";
		}
	}
}

NotEquals.prototype.verify = NotEquals.prototype.assert;

RegexpMatch.prototype.toString = function() {
	return this.expression + " =~ /" + this.pattern.replace(/\//g, "\\/") + "/";
}

RegexpNotMatch.prototype.toString = function() {
	return notOperator() + "(" + RegexpMatch.prototype.toString.call(this) + ")";
}

function ifCondition(expression, callback) {
    return "if (" + expression.toString() + ") {\n" + callback() + "}";
}

function pause(milliseconds) {
	return "sleep(" + (parseInt(milliseconds) / 1000) + ");";
}

function echo(message) {
	return "print(" + xlateArgument(message) + ' . "\\n");'
}

function statement(expression) {
	if (!formatter.assertOrVerifyFailureOnNext) {
		formatter.tests++;
		expression.suffix = "_ok";
	}
	return expression.toString() + ";";
}

function array(value) {
	var str = '(';
	for (var i = 0; i < value.length; i++) {
		str += string(value[i]);
		if (i < value.length - 1) str += ", ";
	}
	str += ')';
	return str;
}

function nonBreakingSpace() {
    return "\"\\x{00A0}\"";
}

CallSelenium.prototype.assertable = true;

CallSelenium.prototype.toString = function() {
	var result = '';
	if (this.negative) {
		result += '!';
	}
	if (options.receiver) {
		result += options.receiver + '->';
	}
	var command = underscore(this.message);
	if (this.noGet) {
		command = command.replace(/^get_/, '');
	}
	result += command;
	if (this.suffix) {
		result += this.suffix;
	}
	result += '(';
	for (var i = 0; i < this.args.length; i++) {
		result += this.args[i];
		if (i < this.args.length - 1) {
			result += ', ';
		}
	}
	result += ')';
	return result;
}

function formatComment(comment) {
	return comment.comment.replace(/.+/mg, function(str) {
			return "# " + str;
		});
}

this.options = {
	receiver: "$sel",
	rcHost: "localhost",
	rcPort: "4444",
	environment: "*chrome",
	header:
		'use strict;\n' +
		'use warnings;\n' +
		'use utf8;\n' +
		'BEGIN {\n' +
		'    binmode STDOUT, ":utf8";\n' +
		'    binmode STDERR, ":utf8";\n' +
		'}\n' +
		'use Time::HiRes qw(sleep);\n' +
		'use Test::WWW::Selenium;\n' +
		'use Test::More "no_plan";\n' +
		'use Test::Exception;\n' +
		'\n' +
		'my ${receiver} = Test::WWW::Selenium->new( host => "${rcHost}", \n' +
		'                                    port => ${rcPort}, \n' +
		'                                    browser => "${environment}", \n' +
		'                                    browser_url => "${baseURL}" );\n' +
		'\n',
	footer: "",
	indent: "4",
	initialIndents: '0'
};

this.configForm =
	'<description>Variable for Selenium instance</description>' +
	'<textbox id="options_receiver" />' +
	'<description>Selenium RC host</description>' +
	'<textbox id="options_rcHost" />' +
	'<description>Selenium RC port</description>' +
	'<textbox id="options_rcPort" />' +
	'<description>Environment</description>' +
	'<textbox id="options_environment" />' +
	'<description>Header</description>' +
	'<textbox id="options_header" multiline="true" flex="1" rows="4"/>' +
	'<description>Footer</description>' +
	'<textbox id="options_footer" multiline="true" flex="1" rows="4"/>' +
	'<description>Indent</description>' +
	'<menulist id="options_indent"><menupopup>' +
	'<menuitem label="Tab" value="tab"/>' +
	'<menuitem label="1 space" value="1"/>' +
	'<menuitem label="2 spaces" value="2"/>' +
	'<menuitem label="3 spaces" value="3"/>' +
	'<menuitem label="4 spaces" value="4"/>' +
	'<menuitem label="5 spaces" value="5"/>' +
	'<menuitem label="6 spaces" value="6"/>' +
	'<menuitem label="7 spaces" value="7"/>' +
	'<menuitem label="8 spaces" value="8"/>' +
	'</menupopup></menulist>';
<|endoftext|>


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

var gles2 = null;
try { gles2 = gles2 || require('./build/Release/node-gles2.node'); } catch (err) {}
try { gles2 = gles2 || process._linkedBinding('node_gles2'); } catch (err) {}
try { gles2 = gles2 || process.binding('node_gles2'); } catch (err) {}
module.exports = gles2;
<commit_msg>add object exporter<commit_after>/**
 * Copyright (c) Flyover Games, LLC.  All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to
 * whom the Software is furnished to do so, subject to the
 * following conditions:
 *
 * The above copyright notice and this permission notice shall
 * be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var node_gles2 = null;
try { node_gles2 = node_gles2 || require('./build/Release/node-gles2.node'); } catch (err) {}
try { node_gles2 = node_gles2 || process._linkedBinding('node_gles2'); } catch (err) {}
try { node_gles2 = node_gles2 || process.binding('node_gles2'); } catch (err) {}
module.exports = node_gles2;

/// var node_gles2 = require('@flyover/node-gles2');
/// var gl = node_gles2.gl();
/// node_gles2.gl* -> gl.*
/// node_gles2.GL_* -> gl.*
node_gles2.gl = function (out) {
	out = out || {};
	var re = /^(gl|GL_)(.*)/;
	for (var key in node_gles2) {
		var match = key.match(re);
		if (match && match[2]) {
			//console.log(key, match[2]);
			out[match[2]] = node_gles2[key];
		} else {
			//console.log("!!!", key);
			out[key] = node_gles2[key];
		}
	}
	return out;
}

//node_gles2.gl();
<|endoftext|>


<commit_before>import axios from 'axios';
import { URLNames, PropertyNames, VariableNames } from 'data/enum/configNames';
import { getValue } from 'util/injector';
import { CONFIG_MANAGER } from 'data/Injectables';

const getLocaleConfig = () => {
	const configManager = getValue(CONFIG_MANAGER);

	const languages = configManager.getProperty(PropertyNames.AVAILABLE_LOCALES).map((locale) => {
		if (typeof locale === 'string')	{
			return {
				code: locale,
				urlPrefix: locale,
				translationKey: locale,
			};
		}
		return locale;
	});

	const config = {
		persistent: false,
		defaultCode: configManager.getProperty(PropertyNames.DEFAULT_LOCALE),
		languages,
	};

	return {
		localeEnabled: configManager.getVariable(VariableNames.LOCALE_ENABLED),
		localeRoutingEnabled: configManager.getVariable(VariableNames.LOCALE_ROUTING_ENABLED),
		config,
	};
};

export default getLocaleConfig;
<commit_msg>remove unused imports<commit_after>import { PropertyNames, VariableNames } from 'data/enum/configNames';
import { getValue } from 'util/injector';
import { CONFIG_MANAGER } from 'data/Injectables';

const getLocaleConfig = () => {
	const configManager = getValue(CONFIG_MANAGER);

	const languages = configManager.getProperty(PropertyNames.AVAILABLE_LOCALES).map((locale) => {
		if (typeof locale === 'string')	{
			return {
				code: locale,
				urlPrefix: locale,
				translationKey: locale,
			};
		}
		return locale;
	});

	const config = {
		persistent: false,
		defaultCode: configManager.getProperty(PropertyNames.DEFAULT_LOCALE),
		languages,
	};

	return {
		localeEnabled: configManager.getVariable(VariableNames.LOCALE_ENABLED),
		localeRoutingEnabled: configManager.getVariable(VariableNames.LOCALE_ROUTING_ENABLED),
		config,
	};
};

export default getLocaleConfig;
<|endoftext|>


<commit_before>imagespace.views.SearchBarView = imagespace.View.extend({
    events: {
        'click .im-nav-link': function (event) {
            var link = $(event.currentTarget);

            imagespace.router.navigate(link.attr('im-target'), {trigger: true});

            // Must call this after calling navigateTo, since that
            // deactivates all global nav links.
            link.addClass('active');
        },

        'click .im-search-image': function (event) {
            this.imageDetailWidget = new imagespace.views.ImageDetailWidget({
                el: $('#g-dialog-container'),
                image: this.image,
                parentView: this
            });
            this.imageDetailWidget.render();
        },

        'keypress .im-search': function (event) {
            var q = $(event.currentTarget).val();
            if (event.which === 13) {
                var query = encodeURIComponent(q);
                imagespace.router.navigate('search/' + query, {trigger: true});
            }
        },

        'input .im-search': function (event) {
            var q = $(event.currentTarget).val();
            if (q.length > 0) {
                $('.im-search-button').removeAttr('disabled');
            } else {
                $('.im-search-button').attr('disabled', 'disabled');
            }
        },

        'click .im-search-button': function (event) {
            var query = encodeURIComponent($('.im-search').val());
            imagespace.router.navigate('search/' + query, {trigger: true});
        },

        'click #advanced-search': function (event) {
            event.preventDefault();
            $(imagespace.templates.advancedSearchWidget()).girderModal(false);
        }
    },

    dropzoneEvents: {
        'change #im-files': function () {
            var files = $('#im-files')[0].files;
            _.each(files, function (file) {
                this.upload(file);
            }, this);
        },

        'click #im-upload .im-advanced-search-button': function () {
            $('#im-files').click();
        },

        'dragenter input.im-search': function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'copy';
            d3.select('input.im-search')
                .classed('btn-success', true)
                .classed('btn-primary', false);
        },

        'dragleave input.im-search': function (e) {
            e.stopPropagation();
            e.preventDefault();
            d3.select('input.im-search')
                .classed('btn-success', false)
                .classed('btn-primary', true);
        },

        'dragover input.im-search': function (e) {
            e.preventDefault();
        },

        'drop input.im-search': function (e) {
            var files = e.originalEvent.dataTransfer.files;
            e.stopPropagation();
            e.preventDefault();
            if (files.length === 0) {
                this.loadUrl(e.originalEvent.dataTransfer.getData('URL'));
            } else {
                _.each(files, function (file) {
                    this.upload(file);
                }, this);
            }
        }
    },

    initialize: function (settings) {
        this.settings = settings || {};
        this.settings.loggedIn = girder.currentUser;

        if (settings.dropzone) {
            _.extend(this.events, this.dropzoneEvents);
        }
    },

    render: function () {
        this.$el.html(imagespace.templates.searchBarWidget(this.settings));
        return this;
    },

    upload: function (file) {
        var reader = new FileReader();

        $('input.im-search')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        reader.onload = _.bind(function (e) {
            var data = new Uint8Array(e.target.result);
            girder.restRequest({
                path: 'imagefeatures',
                data: data,
                method: 'POST',
                processData: false,
                contentType: 'application/octet-stream'
            }).done(_.bind(function (image) {
                var dataURLReader = new FileReader();

                dataURLReader.onloadend = _.bind(function () {
                    image.imageUrl = dataURLReader.result;
                    imagespace.userData.images.unshift(image);
                    if (girder.currentUser) {
                        girder.restRequest({
                            path: 'folder?text=Private'
                        }).done(_.bind(function (folders) {
                            var privateFolder = null;
                            folders.forEach(function (folder) {
                                if (folder.parentId === girder.currentUser.id) {
                                    privateFolder = folder;
                                }
                            })
                            if (privateFolder) {
                                this.girderUpload(this.dataURLToBlob(dataURLReader.result), file.name, privateFolder._id, null, _.bind(function (fileObject) {
                                    var location = window.location, item;
                                    image.imageUrl = location.protocol + '//' + location.host + location.pathname + '/girder/api/v1/file/' + fileObject.id + '/download?token=' + girder.cookie.find('girderToken');

                                    console.log('fileObject');
                                    console.log(fileObject);

                                    item = new girder.models.ItemModel({_id: fileObject.attributes.itemId});
                                    image.item_id = fileObject.attributes.itemId;
                                    item._sendMetadata(image, _.bind(function () {
                                        this.render();
                                    }, this));
                                }, this));
                            }
                        }, this));
                    }
                }, this);

                dataURLReader.readAsDataURL(file);
                image.id = file.name;
            }, this));
        }, this);

        reader.readAsArrayBuffer(file);
    },

    loadUrl: function (url) {
        $('input.im-search')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        girder.restRequest({
            path: 'imagefeatures',
            data: {
                url: url
            },
            method: 'POST'
        }).done(_.bind(function (image) {
            image.imageUrl = url;
            image.id = url;

            this.addUserImage(image);
        }, this));
    },

    girderUpload: function (data, name, folderId, itemToOverwrite, success, error) {
        success = success || function () {};
        error = error || function () {};

        var file, bindEvents = function (file) {
            file.on('g:upload.complete', function () {
                success(file);
            }).on('g:upload.error', function () {
            }).on('g:upload.error g:upload.errorStarting', function () {
                error(file);
            });
            return file;
        };

        if (itemToOverwrite) {
            // We have the dataset's itemid, but we need its fileid.
            var files = new girder.collections.FileCollection();
            files.altUrl = 'item/' + itemToOverwrite + '/files';

            files.on('g:changed', function () {
                file = bindEvents(files.models[0]);
                file.updateContents(data);
            }).fetch();
        } else {
            var folder = new girder.models.FolderModel({_id: folderId});
            file = bindEvents(new girder.models.FileModel());
            file.uploadToFolder(folder, data, name);
        }

        return file;
    },

    dataURLToBlob: function (dataURL) {
        var BASE64_MARKER = ';base64,';
        if (dataURL.indexOf(BASE64_MARKER) == -1) {
            var parts = dataURL.split(','),
                contentType = parts[0].split(':')[1],
                raw = decodeURIComponent(parts[1]);

            return new Blob([raw], {type: contentType});
        }

        var parts = dataURL.split(BASE64_MARKER),
            contentType = parts[0].split(':')[1],
            raw = window.atob(parts[1]),
            rawLength = raw.length,
            uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], {type: contentType});
    },

    addUserImage: function (image) {
        image.source_query = window.location.href;

        girder.restRequest({
            path: 'folder?text=Private'
        }).done(_.bind(function (folders) {
            var privateFolder = null;
            folders.forEach(function (folder) {
                if (folder.parentId === girder.currentUser.id) {
                    privateFolder = folder;
                }
            })
            if (privateFolder) {
                var item = new girder.models.ItemModel({
                    name: image.id,
                    folderId: privateFolder._id
                });

                item.once('g:saved', _.bind(function () {
                    console.log(item);
                    image.item_id = item.attributes._id;
                    console.log(image);
                    item._sendMetadata(image, _.bind(function () {
                        this.render();
                    }, this), function (error) {
                        // TODO report error
                    })
                }, this)).once('g:error', function (error) {
                    console.log(error);
                }, this).save();
            }
        }, this));
    }
});
<commit_msg>Live update of user data after upload completion<commit_after>imagespace.views.SearchBarView = imagespace.View.extend({
    events: {
        'click .im-nav-link': function (event) {
            var link = $(event.currentTarget);

            imagespace.router.navigate(link.attr('im-target'), {trigger: true});

            // Must call this after calling navigateTo, since that
            // deactivates all global nav links.
            link.addClass('active');
        },

        'click .im-search-image': function (event) {
            this.imageDetailWidget = new imagespace.views.ImageDetailWidget({
                el: $('#g-dialog-container'),
                image: this.image,
                parentView: this
            });
            this.imageDetailWidget.render();
        },

        'keypress .im-search': function (event) {
            var q = $(event.currentTarget).val();
            if (event.which === 13) {
                var query = encodeURIComponent(q);
                imagespace.router.navigate('search/' + query, {trigger: true});
            }
        },

        'input .im-search': function (event) {
            var q = $(event.currentTarget).val();
            if (q.length > 0) {
                $('.im-search-button').removeAttr('disabled');
            } else {
                $('.im-search-button').attr('disabled', 'disabled');
            }
        },

        'click .im-search-button': function (event) {
            var query = encodeURIComponent($('.im-search').val());
            imagespace.router.navigate('search/' + query, {trigger: true});
        },

        'click #advanced-search': function (event) {
            event.preventDefault();
            $(imagespace.templates.advancedSearchWidget()).girderModal(false);
        }
    },

    dropzoneEvents: {
        'change #im-files': function () {
            var files = $('#im-files')[0].files;
            _.each(files, function (file) {
                this.upload(file);
            }, this);
        },

        'click #im-upload .im-advanced-search-button': function () {
            $('#im-files').click();
        },

        'dragenter input.im-search': function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'copy';
            d3.select('input.im-search')
                .classed('btn-success', true)
                .classed('btn-primary', false);
        },

        'dragleave input.im-search': function (e) {
            e.stopPropagation();
            e.preventDefault();
            d3.select('input.im-search')
                .classed('btn-success', false)
                .classed('btn-primary', true);
        },

        'dragover input.im-search': function (e) {
            e.preventDefault();
        },

        'drop input.im-search': function (e) {
            var files = e.originalEvent.dataTransfer.files;
            e.stopPropagation();
            e.preventDefault();
            if (files.length === 0) {
                this.loadUrl(e.originalEvent.dataTransfer.getData('URL'));
            } else {
                _.each(files, function (file) {
                    this.upload(file);
                }, this);
            }
        }
    },

    initialize: function (settings) {
        this.settings = settings || {};
        this.settings.loggedIn = girder.currentUser;

        if (settings.dropzone) {
            _.extend(this.events, this.dropzoneEvents);
        }
    },

    render: function () {
        this.$el.html(imagespace.templates.searchBarWidget(this.settings));
        return this;
    },

    upload: function (file) {
        var reader = new FileReader();

        $('input.im-search')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        reader.onload = _.bind(function (e) {
            var data = new Uint8Array(e.target.result);
            girder.restRequest({
                path: 'imagefeatures',
                data: data,
                method: 'POST',
                processData: false,
                contentType: 'application/octet-stream'
            }).done(_.bind(function (image) {
                var dataURLReader = new FileReader();

                dataURLReader.onloadend = _.bind(function () {
                    image.imageUrl = dataURLReader.result;
                    imagespace.userData.images.unshift(image);
                    if (girder.currentUser) {
                        girder.restRequest({
                            path: 'folder?text=Private'
                        }).done(_.bind(function (folders) {
                            var privateFolder = null;
                            folders.forEach(function (folder) {
                                if (folder.parentId === girder.currentUser.id) {
                                    privateFolder = folder;
                                }
                            })
                            if (privateFolder) {
                                this.girderUpload(this.dataURLToBlob(dataURLReader.result), file.name, privateFolder._id, null, _.bind(function (fileObject) {
                                    var location = window.location, item;
                                    image.imageUrl = location.protocol + '//' + location.host + location.pathname + '/girder/api/v1/file/' + fileObject.id + '/download?token=' + girder.cookie.find('girderToken');

                                    console.log('fileObject');
                                    console.log(fileObject);

                                    item = new girder.models.ItemModel({_id: fileObject.attributes.itemId});
                                    image.item_id = fileObject.attributes.itemId;
                                    item._sendMetadata(image, _.bind(function () {
                                        this.render();
                                        imagespace.userDataView.render();
                                    }, this));
                                }, this));
                            }
                        }, this));
                    }
                }, this);

                dataURLReader.readAsDataURL(file);
                image.id = file.name;
            }, this));
        }, this);

        reader.readAsArrayBuffer(file);
    },

    loadUrl: function (url) {
        $('input.im-search')
            .addClass('btn-info disabled')
            .removeClass('btn-default')
            .html(' Processing ...');

        girder.restRequest({
            path: 'imagefeatures',
            data: {
                url: url
            },
            method: 'POST'
        }).done(_.bind(function (image) {
            image.imageUrl = url;
            image.id = url;

            this.addUserImage(image);
        }, this));
    },

    girderUpload: function (data, name, folderId, itemToOverwrite, success, error) {
        success = success || function () {};
        error = error || function () {};

        var file, bindEvents = function (file) {
            file.on('g:upload.complete', function () {
                success(file);
            }).on('g:upload.error', function () {
            }).on('g:upload.error g:upload.errorStarting', function () {
                error(file);
            });
            return file;
        };

        if (itemToOverwrite) {
            // We have the dataset's itemid, but we need its fileid.
            var files = new girder.collections.FileCollection();
            files.altUrl = 'item/' + itemToOverwrite + '/files';

            files.on('g:changed', function () {
                file = bindEvents(files.models[0]);
                file.updateContents(data);
            }).fetch();
        } else {
            var folder = new girder.models.FolderModel({_id: folderId});
            file = bindEvents(new girder.models.FileModel());
            file.uploadToFolder(folder, data, name);
        }

        return file;
    },

    dataURLToBlob: function (dataURL) {
        var BASE64_MARKER = ';base64,';
        if (dataURL.indexOf(BASE64_MARKER) == -1) {
            var parts = dataURL.split(','),
                contentType = parts[0].split(':')[1],
                raw = decodeURIComponent(parts[1]);

            return new Blob([raw], {type: contentType});
        }

        var parts = dataURL.split(BASE64_MARKER),
            contentType = parts[0].split(':')[1],
            raw = window.atob(parts[1]),
            rawLength = raw.length,
            uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], {type: contentType});
    },

    addUserImage: function (image) {
        image.source_query = window.location.href;

        girder.restRequest({
            path: 'folder?text=Private'
        }).done(_.bind(function (folders) {
            var privateFolder = null;
            folders.forEach(function (folder) {
                if (folder.parentId === girder.currentUser.id) {
                    privateFolder = folder;
                }
            })
            if (privateFolder) {
                var item = new girder.models.ItemModel({
                    name: image.id,
                    folderId: privateFolder._id
                });

                item.once('g:saved', _.bind(function () {
                    console.log(item);
                    image.item_id = item.attributes._id;
                    console.log(image);
                    item._sendMetadata(image, _.bind(function () {
                        this.render();
                    }, this), function (error) {
                        // TODO report error
                    })
                }, this)).once('g:error', function (error) {
                    console.log(error);
                }, this).save();
            }
        }, this));
    }
});
<|endoftext|>


<commit_before>var fs = require("fs");
var util = require("util");

// Common dependencies to get LayoutManager running.
var Backbone = require("backbone");
var _ = require("underscore");

// Using Cheerio instead of jQuery, because Cheerio emulates a loosely
// compatible API that we further augment to ensure unit tests pass.  It is
// also much faster than jsdom.
var $ = require("cheerio");

// This is to avoid unwanted errors thrown when using
// `Backbone.View#setElement`.
$.prototype.unbind = $.prototype.off = function() { return this; };

// Since jQuery is not being used and LayoutManager depends on a Promise
// implementation close to jQuery, we use `underscore.deferred` here which
// matches jQuery's Deferred API exactly.
var def = require("underscore.deferred");

// Get Backbone and _ into the global scope.
_.defaults(global, { Backbone: Backbone, _: _ });

// Include the LayoutManager source, without eval.
require("../backbone.layoutmanager");

// Set the Backbone DOM library to be Cheerio.
Backbone.$ = $;

// Configure LayoutManager with some very useful defaults for Node.js
// environments.  This allows the end user to simply consume instead of
// fighting with the desirable configuration.
Backbone.Layout.configure({
  deferred: function() {
    return def.Deferred();
  },

  fetch: function(path) {
    var done = this.async();

    fs.readFile(path, function(err, contents) {
      if (err) {
        console.error("Unable to load file " + path + " : " + err);

        return done(null);
      }

      done(_.template(contents.toString()));
    });
  },

  // This is really the only way you will want to partially apply a view into
  // a layout.  Its entirely possible you'll want to do it differently, so
  // this method is available to change.
  partial: function($root, $el, rentManager, manager) {
    // If selector is specified, attempt to find it.
    if (manager.selector) {
      $root = $root[rentManager.noel ? "filter" : "find"](manager.selector);
    }

    // If no root found, return false.
    if (!$root.length) {
      return false;
    }

    // Use the insert method if `insert` argument is true.
    if (manager.insert) {
      this.insert($root, $el);
    } else {
      this.html($root, $el);
    }

    // If successfully added, return true.
    return true;
  },

  when: function(promises) {
    return def.when.apply(null, promises);
  },

  contains: function(parent, child) {
    var $child = $(child);

    // According to the jQuery API, an element does not "contain" itself.
    if (child === parent) {
      return false;
    }

    // Step up the descendents, stopping when the root element is reached
    // (signaled by `.parent()` returning a reference to the same object).
    while ($child !== $child.parent()) {
      $child = $child.parent();

      if ($child[0] === parent) {
        return true;
      }
    }

    return false;
  }
});

module.exports = Backbone.Layout;
<commit_msg>Correct implementation of "partial" in Node.js<commit_after>var fs = require("fs");
var util = require("util");

// Common dependencies to get LayoutManager running.
var Backbone = require("backbone");
var _ = require("underscore");

// Using Cheerio instead of jQuery, because Cheerio emulates a loosely
// compatible API that we further augment to ensure unit tests pass.  It is
// also much faster than jsdom.
var $ = require("cheerio");

// This is to avoid unwanted errors thrown when using
// `Backbone.View#setElement`.
$.prototype.unbind = $.prototype.off = function() { return this; };

// Since jQuery is not being used and LayoutManager depends on a Promise
// implementation close to jQuery, we use `underscore.deferred` here which
// matches jQuery's Deferred API exactly.
var def = require("underscore.deferred");

// Get Backbone and _ into the global scope.
_.defaults(global, { Backbone: Backbone, _: _ });

// Include the LayoutManager source, without eval.
require("../backbone.layoutmanager");

// Set the Backbone DOM library to be Cheerio.
Backbone.$ = $;

// Configure LayoutManager with some very useful defaults for Node.js
// environments.  This allows the end user to simply consume instead of
// fighting with the desirable configuration.
Backbone.Layout.configure({
  deferred: function() {
    return def.Deferred();
  },

  fetch: function(path) {
    var done = this.async();

    fs.readFile(path, function(err, contents) {
      if (err) {
        console.error("Unable to load file " + path + " : " + err);

        return done(null);
      }

      done(_.template(contents.toString()));
    });
  },

  // This is really the only way you will want to partially apply a view into
  // a layout.  Its entirely possible you'll want to do it differently, so
  // this method is available to change.
  partial: function($root, $el, rentManager, manager) {
    // If selector is specified, attempt to find it.
    if (manager.selector) {
			if (rentManager.noel) {
				var $filtered = $root.filter(manager.selector);
				$root = $filtered.length ? $filtered : $root.find(manager.selector);
			} else {
				$root = $root.find(manager.selector);
			}
    }

    // If no root found, return false.
    if (!$root.length) {
      return false;
    }

    // Use the insert method if `insert` argument is true.
    if (manager.insert) {
      this.insert($root, $el);
    } else {
      this.html($root, $el);
    }

    // If successfully added, return true.
    return true;
  },

  when: function(promises) {
    return def.when.apply(null, promises);
  },

  contains: function(parent, child) {
    var $child = $(child);

    // According to the jQuery API, an element does not "contain" itself.
    if (child === parent) {
      return false;
    }

    // Step up the descendents, stopping when the root element is reached
    // (signaled by `.parent()` returning a reference to the same object).
    while ($child !== $child.parent()) {
      $child = $child.parent();

      if ($child[0] === parent) {
        return true;
      }
    }

    return false;
  }
});

module.exports = Backbone.Layout;
<|endoftext|>


<commit_before>/* global window */
/* eslint-disable import/no-extraneous-dependencies */
import { addParameters } from '@storybook/web-components';
import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';
import { getCustomElements } from './customElements';

function mapData(data) {
  return data.map(item => ({
    name: item.name,
    type: { name: item.type },
    required: '',
    description: item.description,
    defaultValue: item.default,
  }));
}

function isEmpty(obj) {
  return Object.entries(obj).length === 0 && obj.constructor === Object;
}

function isValidComponent(tagName, customElements) {
  if (!tagName) {
    return false;
  }
  if (tagName && typeof tagName === 'string') {
    return true;
  }
  throw new Error('Provided component needs to be a string. e.g. component: "my-element"');
}

function isValidMetaData(customElements) {
  if (!customElements) {
    return false;
  }
  if (customElements && customElements.tags && Array.isArray(customElements.tags)) {
    return true;
  }
  throw new Error(`You need to setup valid meta data in your config.js via setCustomElements().
    See the readme of addon-docs for web components for more details.`);
}

addParameters({
  docs: {
    container: DocsContainer,
    page: DocsPage,
    extractProps: tagName => {
      const customElements = getCustomElements();
      if (isValidComponent(tagName) && isValidMetaData(customElements)) {
        const metaData = customElements.tags.find(
          tag => tag.name.toUpperCase() === tagName.toUpperCase()
        );
        const sections = {};
        if (metaData.properties) {
          sections.props = mapData(metaData.properties);
        }
        if (metaData.events) {
          sections.events = mapData(metaData.events);
        }
        if (metaData.slots) {
          sections.slots = mapData(metaData.slots);
        }
        if (metaData.cssProperties) {
          sections.css = mapData(metaData.cssProperties);
        }
        return isEmpty(sections) ? false : { sections };
      }
      return false;
    },
    extractComponentDescription: tagName => {
      const customElements = getCustomElements();
      if (isValidComponent(tagName) && isValidMetaData(customElements)) {
        const metaData = customElements.tags.find(
          tag => tag.name.toUpperCase() === tagName.toUpperCase()
        );
        if (metaData && metaData.description) {
          return metaData.description;
        }
      }
      return false;
    },
  },
});
<commit_msg>chore: small code improvements<commit_after>/* global window */
/* eslint-disable import/no-extraneous-dependencies */
import { addParameters } from '@storybook/web-components';
import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';
import { getCustomElements } from './customElements';

function mapData(data) {
  return data.map(item => ({
    name: item.name,
    type: { name: item.type },
    required: '',
    description: item.description,
    defaultValue: item.default,
  }));
}

function isEmpty(obj) {
  return Object.entries(obj).length === 0 && obj.constructor === Object;
}

function isValidComponent(tagName) {
  if (!tagName) {
    return false;
  }
  if (typeof tagName === 'string') {
    return true;
  }
  throw new Error('Provided component needs to be a string. e.g. component: "my-element"');
}

function isValidMetaData(customElements) {
  if (!customElements) {
    return false;
  }
  if (customElements.tags && Array.isArray(customElements.tags)) {
    return true;
  }
  throw new Error(`You need to setup valid meta data in your config.js via setCustomElements().
    See the readme of addon-docs for web components for more details.`);
}

addParameters({
  docs: {
    container: DocsContainer,
    page: DocsPage,
    extractProps: tagName => {
      const customElements = getCustomElements();
      if (isValidComponent(tagName) && isValidMetaData(customElements)) {
        const metaData = customElements.tags.find(
          tag => tag.name.toUpperCase() === tagName.toUpperCase()
        );
        const sections = {};
        if (metaData.properties) {
          sections.props = mapData(metaData.properties);
        }
        if (metaData.events) {
          sections.events = mapData(metaData.events);
        }
        if (metaData.slots) {
          sections.slots = mapData(metaData.slots);
        }
        if (metaData.cssProperties) {
          sections.css = mapData(metaData.cssProperties);
        }
        return isEmpty(sections) ? false : { sections };
      }
      return false;
    },
    extractComponentDescription: tagName => {
      const customElements = getCustomElements();
      if (isValidComponent(tagName) && isValidMetaData(customElements)) {
        const metaData = customElements.tags.find(
          tag => tag.name.toUpperCase() === tagName.toUpperCase()
        );
        if (metaData && metaData.description) {
          return metaData.description;
        }
      }
      return false;
    },
  },
});
<|endoftext|>


<commit_before>var express = require('express');
var monk = require('monk');
var bodyParser = require('body-parser');

var dbAPI = require('api/db.js');
var common = require('api/routing_common.js');

var User = require('api/models/User.js');
var Activity = require('api/models/Activity.js');

var router = express.Router();
router.use(bodyParser.json());

/*
 * Route: GET /activities -- Retrieve list of all activities.
 * Requires no parameters.
 */
router.get('/activities', common.asyncMiddleware(
    async (req, res) => {
        let activitiesList = await dbAPI.activities.find({}, {});
        let summaries = await Promise.all(activitiesList.map((doc) => {
            act = new Activity(doc._id);
            return act.summary();
        }));

        res.status(200).json(summaries);
    }
));

/*
 * Route: POST /activities -- create a new Activity.
 * Requires:
 * - 'title' [string]
 * - 'description' [string]
 * - 'startTime' [Date]
 * - 'endTime' [Date]
 * - 'maxHours' [double]
 */
router.post('/activities', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to create Activities.");

        var exists = (await dbAPI.activities.count( {title: req.body.title}) > 0);
        if(exists) return Promise.reject("Activity already exists.");

        await common.checkRequestParameters(req, 'title', 'description', 'startTime', 'endTime', 'maxHours');

        var newActivity = new Activity();
        newActivity.title(req.body.title);
        newActivity.description(req.body.description);

        await Promise.all([
            newActivity.startTime(new Date(req.body.startTime)),
            newActivity.endTime(new Date(req.body.endTime)),
            newActivity.maxHours(req.body.maxHours),
            newActivity.userHours([]),
        ]);

        await newActivity.save();
        res.status(201).json(await newActivity.summary());
    }
));

/* Middleware for getting the Activity object corresponding to :aid. */
router.use('/activities/:aid', common.asyncMiddleware(
    async (req, res, next) => {
        var activity = new Activity(monk.id(req.params.aid));
        if(!(await activity.exists())) return Promise.reject("Activity does not exist.");

        req.activity = activity;
        next();
    }
));

/*
 * Route: GET /activities/:aid -- get a specific Activity.
 * Requires no parameters.
 */
router.get('/activities/:aid', common.asyncMiddleware(
    async (req, res) => { res.status(200).json(await req.activity.summary()); }
));

/*
 * Route: PUT /activities/:aid -- update a specific Activity.
 * All parameters are optional: see POST /activities for a list of potential options / parameters
 */
router.put('/activities/:aid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to modify Activities.");

        if(req.body.title) req.activity.title(req.body.title);
        if(req.body.description) req.activity.description(req.body.description);
        if(req.body.maxHours) await req.activity.maxHours(req.body.maxHours);
        if(req.body.userHours) await req.activity.userHours(req.body.userHours);
        if(req.body.startTime) await req.activity.startTime(new Date(req.body.startTime));
        if(req.body.endTime) await req.activity.endTime(new Date(req.body.endTime));

        await req.activity.save();
        res.status(200).json(await req.activity.summary());
    }
));

/*
 * Route: DELETE /activities/:aid -- delete an Activity.
 * This route takes no parameters.
 */
router.delete('/activities/:aid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to modify Activities.");

        await req.activity.delete();
        res.status(204).end();
    }
));

/*
 * Route: GET /activities/:aid/checkin -- check the current user into an Activity.
 * This route takes no parameters.
 */
router.get('/activities/:aid/checkin', common.asyncMiddleware(
    async (req, res) => {
        var userHours = await req.activity.userHours();
        var idx = userHours.findIndex(doc => monk.id(doc.user) === monk.id(req.user.id()));

        if(idx !== -1) return Promise.reject("User "+req.user.id()+" has already checked into this Activity.");

        var maxHours = await req.activity.maxHours();
        var checkinObject = {
            user: req.user.id(),
            hours: maxHours,
            checkIn: new Date(),
        };
        userHours.push(checkinObject);

        await req.activity.userHours(userHours);
        await req.activity.save();

        res.status(201).json(checkinObject);
    }
));

/*
 * Collection: /activities/:aid/users[/:uid] -- Contains user sign-ins / hours for this Activity.
 */
router.use('/activities/:aid/users', common.asyncMiddleware(
    async (req, res, next) => {
        req.userHours = await req.activity.userHours();
        next();
    }
));

router.get('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => { res.status(200).json(req.userHours); }
));

router.put('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to modify Activities.");
        if(!(req.body instanceof Array)) return Promise.reject("Sent object is not an array.");

        await req.activity.userHours(req.body);
        await req.activity.save();
        res.status(200).json(await req.activity.userHours());
    }
));

router.post('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => {
        await common.checkRequestParameters(req, 'user', 'hours', 'checkIn');

        req.userHours.push({
            user: req.body.user,
            hours: req.body.hours,
            checkIn: req.body.checkIn
        });

        await req.activity.userHours(req.userHours);
        await req.activity.save();

        res.status(200).json(await req.activity.userHours());
    }
));

router.delete('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => {
        await req.activity.userHours([]);
        await req.activity.save();

        res.status(204).end();
    }
));

/* Begin collection element-specific stuff */
router.use('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res, next) => {
        var user = new User(monk.id(req.params.uid));
        if(!await user.exists()) return Promise.reject("User "+req.params.uid+" does not exist.");

        var targetIndex = req.userHours.findIndex(doc => monk.id(doc.user).toString() === monk.id(req.params.uid).toString() );
        if(targetIndex === -1) return Promise.reject("No hours entry found for user "+req.params.uid+".");

        req.targetUser = user;
        req.targetIndex = targetIndex;
        next();
    }
))

router.get('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res) => {
        res.status(200).json(req.userHours[req.targetIndex]);
    }
));

router.put('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not allowed to modify Activities.");

        if(req.body.hours) req.userHours[req.targetIndex].hours = req.body.hours;
        if(req.body.checkIn) req.userHours[req.targetIndex].checkIn = new Date(req.body.checkIn);

        await req.activity.userHours(req.userHours);
        await req.activity.save();

        res.status(200).json(req.userHours[req.targetIndex]);
    }
));

router.delete('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not allowed to modify Activities.");
        req.userHours.splice(req.targetIndex, 1);

        await req.activity.userHours(req.userHours);
        await req.activity.save();

        res.status(204).end();
    }
));

module.exports = router;
<commit_msg>Fix sequencing bug when creating new Activities<commit_after>var express = require('express');
var monk = require('monk');
var bodyParser = require('body-parser');

var dbAPI = require('api/db.js');
var common = require('api/routing_common.js');

var User = require('api/models/User.js');
var Activity = require('api/models/Activity.js');

var router = express.Router();
router.use(bodyParser.json());

/*
 * Route: GET /activities -- Retrieve list of all activities.
 * Requires no parameters.
 */
router.get('/activities', common.asyncMiddleware(
    async (req, res) => {
        let activitiesList = await dbAPI.activities.find({}, {});
        let summaries = await Promise.all(activitiesList.map((doc) => {
            act = new Activity(doc._id);
            return act.summary();
        }));

        res.status(200).json(summaries);
    }
));

/*
 * Route: POST /activities -- create a new Activity.
 * Requires:
 * - 'title' [string]
 * - 'description' [string]
 * - 'startTime' [Date]
 * - 'endTime' [Date]
 * - 'maxHours' [double]
 */
router.post('/activities', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to create Activities.");

        var exists = (await dbAPI.activities.count( {title: req.body.title}) > 0);
        if(exists) return Promise.reject("Activity already exists.");

        await common.checkRequestParameters(req, 'title', 'description', 'startTime', 'endTime', 'maxHours');

        var newActivity = new Activity();
        newActivity.title(req.body.title);
        newActivity.description(req.body.description);

        await newActivity.userHours([]); // must be set before maxHours to prevent a bug
        await Promise.all([
            newActivity.startTime(new Date(req.body.startTime)),
            newActivity.endTime(new Date(req.body.endTime)),
            newActivity.maxHours(req.body.maxHours),
        ]);

        await newActivity.save();
        res.status(201).json(await newActivity.summary());
    }
));

/* Middleware for getting the Activity object corresponding to :aid. */
router.use('/activities/:aid', common.asyncMiddleware(
    async (req, res, next) => {
        var activity = new Activity(monk.id(req.params.aid));
        if(!(await activity.exists())) return Promise.reject("Activity does not exist.");

        req.activity = activity;
        next();
    }
));

/*
 * Route: GET /activities/:aid -- get a specific Activity.
 * Requires no parameters.
 */
router.get('/activities/:aid', common.asyncMiddleware(
    async (req, res) => { res.status(200).json(await req.activity.summary()); }
));

/*
 * Route: PUT /activities/:aid -- update a specific Activity.
 * All parameters are optional: see POST /activities for a list of potential options / parameters
 */
router.put('/activities/:aid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to modify Activities.");

        if(req.body.title) req.activity.title(req.body.title);
        if(req.body.description) req.activity.description(req.body.description);
        if(req.body.maxHours) await req.activity.maxHours(req.body.maxHours);
        if(req.body.userHours) await req.activity.userHours(req.body.userHours);
        if(req.body.startTime) await req.activity.startTime(new Date(req.body.startTime));
        if(req.body.endTime) await req.activity.endTime(new Date(req.body.endTime));

        await req.activity.save();
        res.status(200).json(await req.activity.summary());
    }
));

/*
 * Route: DELETE /activities/:aid -- delete an Activity.
 * This route takes no parameters.
 */
router.delete('/activities/:aid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to modify Activities.");

        await req.activity.delete();
        res.status(204).end();
    }
));

/*
 * Route: GET /activities/:aid/checkin -- check the current user into an Activity.
 * This route takes no parameters.
 */
router.get('/activities/:aid/checkin', common.asyncMiddleware(
    async (req, res) => {
        var userHours = await req.activity.userHours();
        var idx = userHours.findIndex(doc => monk.id(doc.user) === monk.id(req.user.id()));

        if(idx !== -1) return Promise.reject("User "+req.user.id()+" has already checked into this Activity.");

        var maxHours = await req.activity.maxHours();
        var checkinObject = {
            user: req.user.id(),
            hours: maxHours,
            checkIn: new Date(),
        };
        userHours.push(checkinObject);

        await req.activity.userHours(userHours);
        await req.activity.save();

        res.status(201).json(checkinObject);
    }
));

/*
 * Collection: /activities/:aid/users[/:uid] -- Contains user sign-ins / hours for this Activity.
 */
router.use('/activities/:aid/users', common.asyncMiddleware(
    async (req, res, next) => {
        req.userHours = await req.activity.userHours();
        next();
    }
));

router.get('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => { res.status(200).json(req.userHours); }
));

router.put('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not authorized to modify Activities.");
        if(!(req.body instanceof Array)) return Promise.reject("Sent object is not an array.");

        await req.activity.userHours(req.body);
        await req.activity.save();
        res.status(200).json(await req.activity.userHours());
    }
));

router.post('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => {
        await common.checkRequestParameters(req, 'user', 'hours', 'checkIn');

        req.userHours.push({
            user: req.body.user,
            hours: req.body.hours,
            checkIn: req.body.checkIn
        });

        await req.activity.userHours(req.userHours);
        await req.activity.save();

        res.status(200).json(await req.activity.userHours());
    }
));

router.delete('/activities/:aid/users', common.asyncMiddleware(
    async (req, res) => {
        await req.activity.userHours([]);
        await req.activity.save();

        res.status(204).end();
    }
));

/* Begin collection element-specific stuff */
router.use('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res, next) => {
        var user = new User(monk.id(req.params.uid));
        if(!await user.exists()) return Promise.reject("User "+req.params.uid+" does not exist.");

        var targetIndex = req.userHours.findIndex(doc => monk.id(doc.user).toString() === monk.id(req.params.uid).toString() );
        if(targetIndex === -1) return Promise.reject("No hours entry found for user "+req.params.uid+".");

        req.targetUser = user;
        req.targetIndex = targetIndex;
        next();
    }
))

router.get('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res) => {
        res.status(200).json(req.userHours[req.targetIndex]);
    }
));

router.put('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not allowed to modify Activities.");

        if(req.body.hours) req.userHours[req.targetIndex].hours = req.body.hours;
        if(req.body.checkIn) req.userHours[req.targetIndex].checkIn = new Date(req.body.checkIn);

        await req.activity.userHours(req.userHours);
        await req.activity.save();

        res.status(200).json(req.userHours[req.targetIndex]);
    }
));

router.delete('/activities/:aid/users/:uid', common.asyncMiddleware(
    async (req, res) => {
        if(!await req.user.activityCreator()) return Promise.reject("User is not allowed to modify Activities.");
        req.userHours.splice(req.targetIndex, 1);

        await req.activity.userHours(req.userHours);
        await req.activity.save();

        res.status(204).end();
    }
));

module.exports = router;
<|endoftext|>


<commit_before>var assert = require('assert');
var child_process = require('child_process');
var fs = require('fs');
var path = require('path');

var compiler = require('../../src/compiler/compiler');
var parser = require('../../src/parser');
var lexer = require('../../src/lexer');

function globEach(path_, ext, callback, doneCallback) {
    var wildcard = ext === '*';
    if (!doneCallback) {
        doneCallback = function() {};
    }

    var list = fs.readdirSync(path_);
    var pending = list.length;
    if (!pending) return doneCallback(null);
    list.forEach(function(file) {
        file = path_ + '/' + file;
        var stat = fs.statSync(file);
        if (stat && stat.isDirectory()) {
            globEach(file, ext, callback, function(err) {
                if (!--pending) doneCallback(err);
            });
        } else {
            // If it's got the right extension, add it to the list.
            if(wildcard || file.substr(file.length - ext.length) === ext)
                callback(path.normalize(file));
            if (!--pending) doneCallback(null);
        }
    });
}

function compile(code, format) {
    var parsed = parser(lexer(code));
    var compiled = compiler({
        filename: 'test',
        tree: parsed,
        format: format,
    });

    return compiled;
}

describe('Parity tests', function() {

    function run(code, format, expectation) {
        var compiled = compile(code, format);

        var mod;
        try {
            mod = (new Function('return ' + compiled))();
        } catch (e) {
            assert.fail('Error during initialization: ' + e.toString());
        }

        var result;
        try {
            result = mod.main();
        } catch (e) {
            console.error(compiled);
            throw e;
        }
        assert.equal(result, expectation);
    }

    var succeededLLI = 0;
    var failedLLI = 0;

    globEach(
        path.resolve(__dirname, 'tests'),
        '.bt',
        function globEachReader(btPath) {
            var read = fs.readFileSync(btPath).toString();
            var readExpectation = fs.readFileSync(btPath + '.txt').toString().trim();

            describe(btPath, function() {

                it('formats with debug-tree', function jsFunctionalTestBody() {
                    var output = compile(read, 'debug-tree');
                    assert.ok(output);
                });

                it('in JS', function jsFunctionalTestBody() {
                    run(read, 'js', readExpectation);
                });

                it('in Asm.js', function asmjsFunctionalTestBody() {
                    run(read, 'asmjs', readExpectation);
                });

                it('in LLVM IR', function llvmirFunctionalTestBody(done) {
                    this.slow(500);

                    var parsed;
                    var compiled;
                    try {
                        parsed = parser(lexer(read));
                        compiled = compiler({
                            filename: 'test',
                            tree: parsed,
                            format: 'llvmir'
                        });
                    } catch (e) {
                        done(e);
                        return;
                    }

                    child_process.exec(
                        path.resolve(process.cwd(), 'bin', 'btype') + ' ' + btPath + ' --target=llvmir | opt -S',
                        function(err, stdout, stderr) {
                            if (err) {
                                done(err);
                            } else if (stderr) {
                                done(new Error(stderr.toString()));
                            } else {
                                runLLI();
                            }
                        }
                    );

                    function runLLI() {
                        var cp = child_process.exec(
                            path.resolve(process.cwd(), 'bin', 'btype') + ' --target=llvmir --runtime --runtime-entry=testmain | opt -S | lli',
                            function(err, stdout, stderr) {
                                if (err) {
                                    failedLLI++;
                                    done(err);
                                } else if (stderr) {
                                    failedLLI++;
                                    done(stderr);
                                } else {
                                    succeededLLI++;
                                    assert.ok(JSON.parse(stdout) == JSON.parse(readExpectation), stdout + ' != ' + readExpectation);
                                    done();
                                }
                            }
                        );

                        var parsed = parser(lexer(read));
                        var env = compiler.buildEnv({filename: 'test', tree: parsed});
                        var mainFunc = env.requested.exports.main;
                        var mainFuncDef = env.requested.functionDeclarations[mainFunc];

                        var raw = 'import debug;\n';
                        raw += read + '\n';
                        switch (mainFuncDef.getType(env.requested).getReturnType().typeName) {
                            case 'int':
                                raw += 'func testmain() {\n    debug.printint(main());\n}\nexport testmain;';
                                break;
                            case 'float':
                                raw += 'func testmain() {\n    debug.printfloat(main());\n}\nexport testmain;';
                                break;
                            case 'bool':
                                raw += 'func testmain() {\n    debug.printbool(main());\n}\nexport testmain;';
                                break;
                        }

                        cp.stdin.write(raw);
                        cp.stdin.end();

                    }

                });

            });

        }

    );

});

describe('Compile tests', function() {

    globEach(
        path.resolve(__dirname, 'compiletests'),
        '.bt',
        function(btPath) {
            var read = fs.readFileSync(btPath).toString();

            describe(btPath, function() {
                it('compiles to JS', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'js'
                    });
                    assert.ok(compiled);
                });
                it('compiles to Asm.js', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'asmjs'
                    });
                    assert.ok(compiled);
                });
                it('compiles to LLVM IR', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'llvmir'
                    });
                    assert.ok(compiled);
                });
                it('formats with debug-tree', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'debug-tree'
                    });
                    assert.ok(compiled);
                });

            });
        }
    );

});

describe('Failure tests', function() {

    globEach(
        path.resolve(__dirname, 'failtests'),
        '.bt',
        function(btPath) {
            var read = fs.readFileSync(btPath).toString();

            var expectedExceptionPath = path.dirname(btPath);
            expectedExceptionPath += path.sep;
            expectedExceptionPath += path.basename(btPath, '.bt') + '.txt';

            it(btPath, function failTestBody() {
                assert.throws(
                    function() {
                        compiler({
                            filename: 'test',
                            tree: parser(lexer(read)),
                            format: 'debug-tree',
                        });
                    },
                    function(err) {
                        if (fs.existsSync(expectedExceptionPath)) {
                            var exceptionText = fs.readFileSync(expectedExceptionPath).toString();
                            return exceptionText === err.toString();
                        } else {
                            fs.writeFileSync(expectedExceptionPath, err.toString());
                            return true;
                        }
                    }
                );

            });

        }
    );

});

describe('String tests', function() {

    function run(code, format, expectation) {
        var compiled = compile(code, format);

        var mod;
        try {
            mod = (new Function('return ' + compiled))();
        } catch (e) {
            assert.fail('Error during initialization: ' + e.toString());
        }

        var result;
        try {
            result = mod.main();
        } catch (e) {
            console.error(compiled);
            throw e;
        }

        var converted = mod.$strings.read(result);
        assert.equal(converted, expectation);
    }

    globEach(
        path.resolve(__dirname, 'strings'),
        '.bt',
        function(btPath) {
            var read = fs.readFileSync(btPath).toString();
            var readExpectation = fs.readFileSync(btPath + '.txt').toString().trim();

            describe(btPath, function() {

                it('runs in JS', function jsStringTestBody() {
                    run(read, 'js', readExpectation);
                });

                it('runs in Asm.js', function asmjsStringTestBody() {
                    run(read, 'asmjs', readExpectation);
                });

                it('formats in debug-tree', function debugTreeStringTestBody() {
                    assert.ok(compile(read, 'debug-tree'));
                });

            });

        }
    );

});
<commit_msg>Clean up globEach in functional tests<commit_after>var assert = require('assert');
var child_process = require('child_process');
var fs = require('fs');
var path = require('path');

var compiler = require('../../src/compiler/compiler');
var parser = require('../../src/parser');
var lexer = require('../../src/lexer');

function globEach(path_, ext, callback) {
    ext = '.' + ext; // for path.extname

    fs.readdirSync(path_).forEach(function(file) {
        file = path.resolve(path_, file);
        var stat = fs.statSync(file);
        if (stat && stat.isDirectory()) {
            globEach(file, ext, callback);
        } else {
            // If it's got the right extension, add it to the list.
            if (path.extname(file) === ext) {
                callback(path.normalize(file));
            }
        }
    });
}

function compile(code, format) {
    var parsed = parser(lexer(code));
    var compiled = compiler({
        filename: 'test',
        tree: parsed,
        format: format,
    });

    return compiled;
}

describe('Parity tests', function() {

    function run(code, format, expectation) {
        var compiled = compile(code, format);

        var mod;
        try {
            mod = (new Function('return ' + compiled))();
        } catch (e) {
            assert.fail('Error during initialization: ' + e.toString());
        }

        var result;
        try {
            result = mod.main();
        } catch (e) {
            console.error(compiled);
            throw e;
        }
        assert.equal(result, expectation);
    }

    var succeededLLI = 0;
    var failedLLI = 0;

    globEach(
        path.resolve(__dirname, 'tests'),
        '.bt',
        function globEachReader(btPath) {
            var read = fs.readFileSync(btPath).toString();
            var readExpectation = fs.readFileSync(btPath + '.txt').toString().trim();

            describe(btPath, function() {

                it('formats with debug-tree', function jsFunctionalTestBody() {
                    var output = compile(read, 'debug-tree');
                    assert.ok(output);
                });

                it('in JS', function jsFunctionalTestBody() {
                    run(read, 'js', readExpectation);
                });

                it('in Asm.js', function asmjsFunctionalTestBody() {
                    run(read, 'asmjs', readExpectation);
                });

                it('in LLVM IR', function llvmirFunctionalTestBody(done) {
                    this.slow(500);

                    var parsed;
                    var compiled;
                    try {
                        parsed = parser(lexer(read));
                        compiled = compiler({
                            filename: 'test',
                            tree: parsed,
                            format: 'llvmir'
                        });
                    } catch (e) {
                        done(e);
                        return;
                    }

                    child_process.exec(
                        path.resolve(process.cwd(), 'bin', 'btype') + ' ' + btPath + ' --target=llvmir | opt -S',
                        function(err, stdout, stderr) {
                            if (err) {
                                done(err);
                            } else if (stderr) {
                                done(new Error(stderr.toString()));
                            } else {
                                runLLI();
                            }
                        }
                    );

                    function runLLI() {
                        var cp = child_process.exec(
                            path.resolve(process.cwd(), 'bin', 'btype') + ' --target=llvmir --runtime --runtime-entry=testmain | opt -S | lli',
                            function(err, stdout, stderr) {
                                if (err) {
                                    failedLLI++;
                                    done(err);
                                } else if (stderr) {
                                    failedLLI++;
                                    done(stderr);
                                } else {
                                    succeededLLI++;
                                    assert.ok(JSON.parse(stdout) == JSON.parse(readExpectation), stdout + ' != ' + readExpectation);
                                    done();
                                }
                            }
                        );

                        var parsed = parser(lexer(read));
                        var env = compiler.buildEnv({filename: 'test', tree: parsed});
                        var mainFunc = env.requested.exports.main;
                        var mainFuncDef = env.requested.functionDeclarations[mainFunc];

                        var raw = 'import debug;\n';
                        raw += read + '\n';
                        switch (mainFuncDef.getType(env.requested).getReturnType().typeName) {
                            case 'int':
                                raw += 'func testmain() {\n    debug.printint(main());\n}\nexport testmain;';
                                break;
                            case 'float':
                                raw += 'func testmain() {\n    debug.printfloat(main());\n}\nexport testmain;';
                                break;
                            case 'bool':
                                raw += 'func testmain() {\n    debug.printbool(main());\n}\nexport testmain;';
                                break;
                        }

                        cp.stdin.write(raw);
                        cp.stdin.end();

                    }

                });

            });

        }

    );

});

describe('Compile tests', function() {

    globEach(
        path.resolve(__dirname, 'compiletests'),
        '.bt',
        function(btPath) {
            var read = fs.readFileSync(btPath).toString();

            describe(btPath, function() {
                it('compiles to JS', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'js'
                    });
                    assert.ok(compiled);
                });
                it('compiles to Asm.js', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'asmjs'
                    });
                    assert.ok(compiled);
                });
                it('compiles to LLVM IR', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'llvmir'
                    });
                    assert.ok(compiled);
                });
                it('formats with debug-tree', function compileTestBody() {
                    var parsed = parser(lexer(read));
                    var compiled = compiler({
                        filename: 'test',
                        tree: parsed,
                        format: 'debug-tree'
                    });
                    assert.ok(compiled);
                });

            });
        }
    );

});

describe('Failure tests', function() {

    globEach(
        path.resolve(__dirname, 'failtests'),
        '.bt',
        function(btPath) {
            var read = fs.readFileSync(btPath).toString();

            var expectedExceptionPath = path.dirname(btPath);
            expectedExceptionPath += path.sep;
            expectedExceptionPath += path.basename(btPath, '.bt') + '.txt';

            it(btPath, function failTestBody() {
                assert.throws(
                    function() {
                        compiler({
                            filename: 'test',
                            tree: parser(lexer(read)),
                            format: 'debug-tree',
                        });
                    },
                    function(err) {
                        if (fs.existsSync(expectedExceptionPath)) {
                            var exceptionText = fs.readFileSync(expectedExceptionPath).toString();
                            return exceptionText === err.toString();
                        } else {
                            fs.writeFileSync(expectedExceptionPath, err.toString());
                            return true;
                        }
                    }
                );

            });

        }
    );

});

describe('String tests', function() {

    function run(code, format, expectation) {
        var compiled = compile(code, format);

        var mod;
        try {
            mod = (new Function('return ' + compiled))();
        } catch (e) {
            assert.fail('Error during initialization: ' + e.toString());
        }

        var result;
        try {
            result = mod.main();
        } catch (e) {
            console.error(compiled);
            throw e;
        }

        var converted = mod.$strings.read(result);
        assert.equal(converted, expectation);
    }

    globEach(
        path.resolve(__dirname, 'strings'),
        '.bt',
        function(btPath) {
            var read = fs.readFileSync(btPath).toString();
            var readExpectation = fs.readFileSync(btPath + '.txt').toString().trim();

            describe(btPath, function() {

                it('runs in JS', function jsStringTestBody() {
                    run(read, 'js', readExpectation);
                });

                it('runs in Asm.js', function asmjsStringTestBody() {
                    run(read, 'asmjs', readExpectation);
                });

                it('formats in debug-tree', function debugTreeStringTestBody() {
                    assert.ok(compile(read, 'debug-tree'));
                });

            });

        }
    );

});
<|endoftext|>


<commit_before>/**
 * Created by epotignano on 15/4/16.
 */

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Formsy from 'formsy-react';
import MenuItem from 'material-ui/lib/menus/menu-item';
import { FormsyText, FormsySelect } from 'formsy-material-ui';
import { ConfirmAppointment } from '../actions/Appointments';
import { getPatientByEmail, selectPatient, patientSelectModal, fillPatientData} from '../actions/PatientsActions';
import PatientsModal from '../components/PatientsModal';
import PatientCard from '../components/PatientCard';

Formsy.addValidationRule('isRequiredIfNotValue', function (values, value, otherField) {
  if(value || values[otherField]) {
    return true;
  }
});

class Checkout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      openPatientModal : false
    }
  }

  openModal() {
    const { dispatch } = this.props;
    dispatch(patientSelectModal())
  }

  submitAppointment(data) {
    const { dispatch, appointment } = this.props;
    const { keep } = appointment;
    //TODO Transformations for adapt the object to the DTO for Appointments
    dispatch(ConfirmAppointment({
      solicitante : data,
      turno: keep.appointment,
      location: keep.appointment.location,
      doctor: keep.appointment.doctor
    }));
  }

  enableButton() {
    this.setState({
      canSubmit: true
    });
  }

  disableButton() {
    this.setState({
      canSubmit: false
    });
  }

  checkUser(userEmail) {
    const { dispatch } = this.props;
    dispatch(getPatientByEmail(userEmail));
  }

  reOpenPatientsModal(){
    const { dispatch } = this.props;
    dispatch(patientSelectModal())
  }

  reRenderForm() {
    const { dispatch } = this.props;
    dispatch(fillPatientData())
  }

  render() {

    const { appointment, patients } = this.props;
    const { keep } = appointment;
    let _modal = (this.state.openPatientModal) ? <PatientsModal patientsList={patients.patient}/> : null;
    let _form = (
      <Formsy.Form ref="appointmentForm" className="ui large form"
                   onValid={this.enableButton.bind(this)}
                   onInvalid={this.disableButton.bind(this)}
                   onValidSubmit={this.submitAppointment.bind(this)}
      >

              <FormsyText
                name='email_particular'
                hintText="Email"
                required
                value=""
                onChange={(e, value) => this.checkUser(value)}
              />

              <FormsyText
                name='nombre'
                hintText="Nombre"
                required
                value=""
              />

              <FormsyText
                name='apellido'
                hintText="Apellido"
                required
                value=""
              />

              <FormsySelect
                name="sexo"
                required
                floatingLabelText="Sexo"
                menuItems={this.selectFieldItems}
              >
                <MenuItem value={'M'} primaryText="Masculino" />
                <MenuItem value={'F'} primaryText="Femenino" />
              </FormsySelect>

              <FormsyText
                name='numero_tel_celular'
                hintText="Número de teléfono celular"
                validations="isRequiredIfNotValue:numero_tel_particular"
                value=""
              />

              <FormsyText
                name='numero_tel_particular'
                hintText="Número de teléfono particular"
                validations="isRequiredIfNotValue:numero_tel_celular"
              />

              <FormsyText
                name='note'
                hintText="Notas"
                value=""
              />

            <button type="submit" className="ui button fluid blue">
              Solicitar cita
            </button>

      </Formsy.Form>);

    let _changePatientButton = (patients.patient && patients.patient.length > 1) ? (<button onClick={this.reOpenPatientsModal.bind(this)}>
        Cambiar paciente
    </button>) : null;

    let _selectedPatientCard = (

            <PatientCard patient={patients.selectedPatient}/>

            {_changePatientButton}
            <button onClick={this.reRenderForm.bind(this)}>
              Cambiar email
            </button>

          <button onClick={() => this.submitAppointment(patients.selectedPatient)} className="ui button fluid blue">
            Solicitar cita
          </button>

    );

    var _render = (patients.selectedPatient) ? _selectedPatientCard : _form;

    return (

              Fecha: {keep.appointment.fecha_hora_inicio.format("dddd DD MMMM YYYY")}

              Horario: {keep.appointment.fecha_hora_inicio.format("HH:mm")}

              Duración: { keep.appointment.duracion_en_minutos} minutos

          { _render }
          <PatientsModal patientsList={patients.patient}/>

    )
  }

}

function mapStateToProps(state) {
  const { appointment, patients } = state;
  return {
    appointment,
    patients
  }
}

Checkout.propTypes = {
  dispatch : PropTypes.any
}

Checkout.contextTypes = {
  store: PropTypes.any
};

Checkout.stateTypes = {
  keep: PropTypes.any,
  doctor: PropTypes.any
};

export default connect(mapStateToProps)(Checkout);
<commit_msg>Added birthdate<commit_after>/**
 * Created by epotignano on 15/4/16.
 */

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Formsy from 'formsy-react';
import MenuItem from 'material-ui/lib/menus/menu-item';
import { FormsyText, FormsySelect, FormsyDate } from 'formsy-material-ui';
import { ConfirmAppointment } from '../actions/Appointments';
import { getPatientByEmail, selectPatient, patientSelectModal, fillPatientData} from '../actions/PatientsActions';
import PatientsModal from '../components/PatientsModal';
import PatientCard from '../components/PatientCard';

Formsy.addValidationRule('isRequiredIfNotValue', function (values, value, otherField) {
  if(value || values[otherField]) {
    return true;
  }
});

class Checkout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      openPatientModal : false
    }
  }

  openModal() {
    const { dispatch } = this.props;
    dispatch(patientSelectModal())
  }

  submitAppointment(data) {
    const { dispatch, appointment } = this.props;
    const { keep } = appointment;
    //TODO Transformations for adapt the object to the DTO for Appointments
    dispatch(ConfirmAppointment({
      solicitante : data,
      turno: keep.appointment,
      location: keep.appointment.location,
      doctor: keep.appointment.doctor
    }));
  }

  enableButton() {
    this.setState({
      canSubmit: true
    });
  }

  disableButton() {
    this.setState({
      canSubmit: false
    });
  }

  checkUser(userEmail) {
    const { dispatch } = this.props;
    dispatch(getPatientByEmail(userEmail));
  }

  reOpenPatientsModal(){
    const { dispatch } = this.props;
    dispatch(patientSelectModal())
  }

  reRenderForm() {
    const { dispatch } = this.props;
    dispatch(fillPatientData())
  }

  render() {

    const { appointment, patients } = this.props;
    const { keep } = appointment;
    let _modal = (this.state.openPatientModal) ? <PatientsModal patientsList={patients.patient}/> : null;
    let _form = (
      <Formsy.Form ref="appointmentForm" className="ui large form"
                   onValid={this.enableButton.bind(this)}
                   onInvalid={this.disableButton.bind(this)}
                   onValidSubmit={this.submitAppointment.bind(this)}
      >

              <FormsyText
                name='email_particular'
                hintText="Email"
                required
                value=""
                onChange={(e, value) => this.checkUser(value)}
              />

              <FormsyText
                name='nombre'
                hintText="Nombre"
                required
                value=""
              />

              <FormsyText
                name='apellido'
                hintText="Apellido"
                required
                value=""
              />

              <FormsyDate
               name="fecha_nacimiento"
               floatingLabelText="Fecha"
             />

              <FormsySelect
                name="sexo"
                required
                floatingLabelText="Sexo"
                menuItems={this.selectFieldItems}
              >
                <MenuItem value={'M'} primaryText="Masculino" />
                <MenuItem value={'F'} primaryText="Femenino" />
              </FormsySelect>

              <FormsyText
                name='numero_tel_celular'
                hintText="Número de teléfono celular"
                validations="isRequiredIfNotValue:numero_tel_particular"
                value=""
              />

              <FormsyText
                name='numero_tel_particular'
                hintText="Número de teléfono particular"
                validations="isRequiredIfNotValue:numero_tel_celular"
              />

              <FormsyText
                name='note'
                hintText="Notas"
                value=""
              />

            <button type="submit" className="ui button fluid blue">
              Solicitar cita
            </button>

      </Formsy.Form>);

    let _changePatientButton = (patients.patient && patients.patient.length > 1) ? (<button onClick={this.reOpenPatientsModal.bind(this)}>
        Cambiar paciente
    </button>) : null;

    let _selectedPatientCard = (

            <PatientCard patient={patients.selectedPatient}/>

            {_changePatientButton}
            <button onClick={this.reRenderForm.bind(this)}>
              Cambiar email
            </button>

          <button onClick={() => this.submitAppointment(patients.selectedPatient)} className="ui button fluid blue">
            Solicitar cita
          </button>

    );

    var _render = (patients.selectedPatient) ? _selectedPatientCard : _form;

    return (

              Fecha: {keep.appointment.fecha_hora_inicio.format("dddd DD MMMM YYYY")}

              Horario: {keep.appointment.fecha_hora_inicio.format("HH:mm")}

              Duración: { keep.appointment.duracion_en_minutos} minutos

          { _render }
          <PatientsModal patientsList={patients.patient}/>

    )
  }

}

function mapStateToProps(state) {
  const { appointment, patients } = state;
  return {
    appointment,
    patients
  }
}

Checkout.propTypes = {
  dispatch : PropTypes.any
}

Checkout.contextTypes = {
  store: PropTypes.any
};

Checkout.stateTypes = {
  keep: PropTypes.any,
  doctor: PropTypes.any
};

export default connect(mapStateToProps)(Checkout);
<|endoftext|>