<commit_before>'use strict';

define(function () {
  // Create the Audio Context
  var audiocontext = new window.AudioContext();

  /**
   *
Returns the Audio Context for this sketch. Useful for users
   * who would like to dig deeper into the Web Audio API
   * .

   *
   * @method getAudioContext
   * @return {Object}    AudioContext for this sketch
   */
  p5.prototype.getAudioContext = function() {
    return audiocontext;
  };

  // if it is iOS, we have to have a user interaction to start Web Audio
  // http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
  var iOS =  navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false ;
  if (iOS) {
    var iosStarted = false;
    var startIOS = function() {
      if (iosStarted) return;

      // create empty buffer
      var buffer = audiocontext.createBuffer(1, 1, 22050);
      var source = audiocontext.createBufferSource();
      source.buffer = buffer;

      // connect to output (your speakers)
      source.connect(audiocontext.destination);
      // play the file
      source.start(0);
      console.log('start ios!');

      if (audiocontext.state === 'running') {
        iosStarted = true;
      }
    };
    document.addEventListener('touchend', startIOS, false);
    document.addEventListener('touchstart', startIOS, false);

    // TO DO: fake touch event so that audio will just start
  }

  return audiocontext;
});
<commit_msg>add getAudioContext example<commit_after>'use strict';

define(function () {
  // Create the Audio Context
  var audiocontext = new window.AudioContext();

  /**
   *
Returns the Audio Context for this sketch. Useful for users
   * who would like to dig deeper into the Web Audio API
   * .

   *
   *
Some browsers require users to startAudioContext
   * with a user gesture, such as touchStarted in the example below.

   *
   * @method getAudioContext
   * @return {Object}    AudioContext for this sketch
   * @example
   *

   *  function draw() {
   *    background(255);
   *    textAlign(CENTER);
   *
   *    if (getAudioContext().state !== 'running') {
   *      text('click to start audio', width/2, height/2);
   *    } else {
   *      text('audio is enabled', width/2, height/2);
   *    }
   *  }
   *
   *  function touchStarted() {
   *    if (getAudioContext().state !== 'running') {
   *      getAudioContext().resume();
   *    }
   *    var synth = new p5.MonoSynth();
   *    synth.play('A4', 0.5, 0, 0.2);
   *  }
   *
   *

   */
  p5.prototype.getAudioContext = function() {
    return audiocontext;
  };

  // if it is iOS, we have to have a user interaction to start Web Audio
  // http://paulbakaus.com/tutorials/html5/web-audio-on-ios/
  var iOS =  navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false ;
  if (iOS) {
    var iosStarted = false;
    var startIOS = function() {
      if (iosStarted) return;

      // create empty buffer
      var buffer = audiocontext.createBuffer(1, 1, 22050);
      var source = audiocontext.createBufferSource();
      source.buffer = buffer;

      // connect to output (your speakers)
      source.connect(audiocontext.destination);
      // play the file
      source.start(0);
      console.log('start ios!');

      if (audiocontext.state === 'running') {
        iosStarted = true;
      }
    };
    document.addEventListener('touchend', startIOS, false);
    document.addEventListener('touchstart', startIOS, false);

    // TO DO: fake touch event so that audio will just start
  }

  return audiocontext;
});
<|endoftext|>


<commit_before>Template.viewer.rendered = function() {
    presentationData = this.data;
    var page = presentationData.page;

    viewer = Crocodoc.createViewer('.viewer', {
        url: 'https://view-api.box.com/1/sessions/'+ presentationData.sessionId + '/assets',
        layout: Crocodoc.LAYOUT_PRESENTATION,
        page: page
    });
    viewer.load();

    viewer.on('ready', function() {
        _.delay(function() {
            $('.viewer').addClass('fade-in');
        }, 500);
    });

    Deps.autorun(function() {
        var presentationCursor = Presentations.find({_id: presentationData._id});
        currentPage = presentationCursor.fetch()[0].page;
        // Must use try/catch block because of bug in Deps.afterFlush
        try {
            viewer.scrollTo(currentPage);
        } catch (e) {
            var dumbErrorArray = [
                "Cannot call method 'scrollTo' of undefined",
                "Cannot read property 'scrollTo' of undefined"
            ]
            // Use underscore method instead
            if ($.inArray(e.message, dumbErrorArray) === -1) {
                throw(e);
            }
        }
    });
};
<commit_msg>refactor viewer Deps.autorun to only query for page field<commit_after>Template.viewer.rendered = function() {
    presentationData = this.data;
    var page = presentationData.page;

    viewer = Crocodoc.createViewer('.viewer', {
        url: 'https://view-api.box.com/1/sessions/'+ presentationData.sessionId + '/assets',
        layout: Crocodoc.LAYOUT_PRESENTATION,
        page: page
    });
    viewer.load();

    viewer.on('ready', function() {
        _.delay(function() {
            $('.viewer').addClass('fade-in');
        }, 500);
    });

    Deps.autorun(function() {
        var presentationCursor = Presentations.find(
            {_id: presentationData._id},
            {fields: {page: 1} }
        );
        currentPage = presentationCursor.fetch()[0].page;
        // Must use try/catch block because of bug in Deps.afterFlush
        try {
            viewer.scrollTo(currentPage);
        } catch (e) {
            var dumbErrorArray = [
                "Cannot call method 'scrollTo' of undefined",
                "Cannot read property 'scrollTo' of undefined"
            ]
            // Use underscore method instead
            if ($.inArray(e.message, dumbErrorArray) === -1) {
                throw(e);
            }
        }
    });
};
<|endoftext|>


<commit_before>'use strict';

const webpack = require('webpack');
const path = require('path');

const babel = {
  "plugins": [
    "transform-regenerator",
    "syntax-async-functions",
    "syntax-async-generators",
    "transform-async-to-generator",
    "syntax-flow",
    "transform-flow-strip-types"
  ].map((p) => require.resolve('babel-plugin-' + p)),
  "presets": ["es2015", "stage-0", "stage-3", "react"].map((p) => require.resolve('babel-preset-' + p))
}

module.exports = {
  output: {
    publicPath: '/assets/',
    path: 'dist/assets/',
    filename: 'main.js'
  },
  debug: false,
  devtool: false,
  entry: [
    './src/components/App.js'
  ],
  node: {
    console: false,
    process: 'mock',
    Buffer: 'buffer'
  },
  stats: {
    colors: true,
    reasons: false
  },
  plugins: [
    // new webpack.optimize.DedupePlugin(),
    // new webpack.optimize.UglifyJsPlugin(),
    // new webpack.optimize.AggressiveMergingPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  },
  resolve: {
    modulesDirectories: [
      path.join(__dirname, 'node_modules')
    ],
    alias: {
      'node_modules': path.join(__dirname + '/node_modules'),
      'fs': path.join(__dirname + '/node_modules', 'html5-fs'),
      'app': __dirname + '/src/app/',
      'styles': __dirname + '/src/styles',
      'mixins': __dirname + '/src/mixins',
      'components': __dirname + '/src/components/',
      'stores': __dirname + '/src/stores/',
      'actions': __dirname + '/src/actions/',
      'utils': __dirname + '/src/utils/'
    }
  },
  module: {
    loaders: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: babel
    }, {
      test: /\.js$/,
      include: /node_modules\/(hoek|qs|wreck|boom|logplease|ipfs-.+|orbit.*|crdts)/,
      loader: 'babel',
      query: babel
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader'
    }, {
      test: /\.scss/,
      loader: 'style-loader!css-loader!sass-loader?outputStyle=expanded'
    }, {
      test: /\.(png|jpg|woff|woff2)$/,
      loader: 'url-loader?limit=8192'
    }, {
      test: /\.json$/,
      loader: 'json'
    }]
  },
  externals: {
    du: '{}',
    net: '{}',
    tls: '{}',
    console: '{}',
    'require-dir': '{}',
    mkdirp: '{}'
  }
};
<commit_msg>Tweak dist build script<commit_after>'use strict';

const webpack = require('webpack');
const path = require('path');

const babel = {
  "plugins": [
    "transform-regenerator",
    "syntax-async-functions",
    "syntax-async-generators",
    "transform-async-to-generator",
    "syntax-flow",
    "transform-flow-strip-types"
  ].map((p) => require.resolve('babel-plugin-' + p)),
  "presets": ["es2015", "stage-0", "stage-3", "react"].map((p) => require.resolve('babel-preset-' + p))
}

module.exports = {
  output: {
    publicPath: '/assets/',
    path: 'dist/assets/',
    filename: 'main.js'
  },
  debug: false,
  devtool: false,
  entry: [
    './src/components/App.js'
  ],
  node: {
    console: false,
    process: 'mock',
    Buffer: 'buffer'
  },
  stats: {
    colors: true,
    reasons: false
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  },
  resolve: {
    modulesDirectories: [
      path.join(__dirname, 'node_modules')
    ],
    alias: {
      'node_modules': path.join(__dirname + '/node_modules'),
      'fs': path.join(__dirname + '/node_modules', 'html5-fs'),
      'app': __dirname + '/src/app/',
      'styles': __dirname + '/src/styles',
      'mixins': __dirname + '/src/mixins',
      'components': __dirname + '/src/components/',
      'stores': __dirname + '/src/stores/',
      'actions': __dirname + '/src/actions/',
      'utils': __dirname + '/src/utils/'
    }
  },
  module: {
    loaders: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: babel
    }, {
      test: /\.js$/,
      include: /node_modules\/(hoek|qs|wreck|boom|logplease|ipfs-.+|orbit.*|crdts)/,
      loader: 'babel',
      query: babel
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader'
    }, {
      test: /\.scss/,
      loader: 'style-loader!css-loader!sass-loader?outputStyle=expanded'
    }, {
      test: /\.(png|jpg|woff|woff2)$/,
      loader: 'url-loader?limit=8192'
    }, {
      test: /\.json$/,
      loader: 'json'
    }]
  },
  externals: {
    du: '{}',
    net: '{}',
    tls: '{}',
    console: '{}',
    'require-dir': '{}',
    mkdirp: '{}'
  }
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name GEFS-Online Spoilers Arming
// @description This extension (by Harry Xue) allows the user to arm the spoilers before landing.
// @namespace GEFS-Plugins
// @match http://www.gefs-online.com/gefs.php*
// @match http://gefs-online.com/gefs.php*
// @run-at document-end
// @version 0.1.3
// @grant none
// ==/UserScript==
/*
	Copyright (c) 2015 Harry Xue

	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.
*/
function S(){var e=ges.aircraft.setup.instruments||void 0,a=e&&void 0!==e.spoilers,s=ges.aircraft.animationValue.altitude-ges.groundElevation*metersToFeet||0;a?(T(),q&&ges.aircraft.groundContact&&0===ges.aircraft.animationValue.airbrakesPosition&&(controls.setters.setAirbrakes.set(),q=!1,T())):L(),clearInterval(x),x=gg>=s?setInterval(S,1500):setInterval(S,3e4)}function T(){p?q?$("#spoilers-arming").removeClass("btn-default").addClass("btn-success"):$("#spoilers-arming").removeClass("btn-success").addClass("btn-default"):(p=!0,$("#spoilers-arming").removeClass("btn-danger").addClass("btn-default"))}function L(){p=!1,q||$("#spoilers-arming").removeClass("btn-default").addClass("btn-danger"),q&&$("#spoilers-arming").removeClass("btn-success").addClass("btn-danger"),q=!1}var q=!1,p=!0,gg=4e3,x=setInterval(S,1500),w=$("<div>").addClass("setup-section").css("padding-bottom","0px").append($("<div>").addClass("input-prepend input-append").css("margin-bottom","4px").append($("<span>").addClass("add-on").text("Spoilers"),$("<button>").addClass("btn btn-default").attr("type","button").css("height","30px").css("width","30px").attr("id","spoilers-arming"))).appendTo(".gefs-f-standard");$("#spoilers-arming").click(function(){p&&(q=ges.aircraft.groundContact?!1:q?!1:!0,T())}),$(document).keydown(function(e){(220===e.which||220===e.keyCode)&&$("#spoilers-arming").click()});var A=Aircraft.prototype.load;Aircraft.prototype.load=function(e,a,s){var r=ges.aircraft.object3d._children;A.call(this,e,a,s);var t=setInterval(function(){r!==ges.aircraft.object3d._children&&(clearInterval(t),S())},16)};<commit_msg>Bug fixes<commit_after>// ==UserScript==
// @name GEFS-Online Spoilers Arming
// @description This extension (by Harry Xue) allows the user to arm the spoilers before landing.
// @namespace GEFS-Plugins
// @match http://www.gefs-online.com/gefs.php*
// @match http://gefs-online.com/gefs.php*
// @run-at document-end
// @version 0.1.3
// @grant none
// ==/UserScript==
/*
	Copyright (c) 2015 Harry Xue

	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.
*/
function S(){if(window.ges&&ges.aircraft&&ges.aircraft.setup&&ges.aircraft.setup.instruments){var e=void 0!==ges.aircraft.setup.instruments.spoilers,a=(ges.aircraft.animationValue.altitude||0)-(ges.groundElevation||0)*metersToFeet;e?(u(),I&&ges.aircraft.groundContact&&0===(ges.aircraft.animationValue.airbrakesPosition||0)&&(controls.setters.setAirbrakes.set(),I=!1,u()),clearInterval(Y),Y=G>=a?setInterval(S,1500):setInterval(S,3e4)):(l(),clearInterval(Y))}}function u(){M?I?$("#spoilers-arming").removeClass("btn-default").addClass("btn-success"):$("#spoilers-arming").removeClass("btn-success").addClass("btn-default"):(M=!0,$("#spoilers-arming").removeClass("btn-danger").addClass("btn-default"))}function l(){M=!1,I||$("#spoilers-arming").removeClass("btn-default").addClass("btn-danger"),I&&$("#spoilers-arming").removeClass("btn-success").addClass("btn-danger"),I=!1}var I=!1,M=!0,G=4e3,Y=setInterval(S,1500),h=$("<div>").addClass("setup-section").css("padding-bottom","0px").append($("<div>").addClass("input-prepend input-append").css("margin-bottom","4px").append($("<span>").addClass("add-on").text("Spoilers"),$("<button>").addClass("btn btn-default").attr("type","button").css("height","30px").css("width","30px").attr("id","spoilers-arming"))).appendTo(".gefs-f-standard");$("#spoilers-arming").click(function(){M&&(I=ges.aircraft.groundContact?!1:I?!1:!0,u())}),$(document).keydown(function(e){(220===e.which||220===e.keyCode)&&$("#spoilers-arming").click()});var T=setInterval(function(){if(ges.aircraft.object3d){clearInterval(T);var e=Aircraft.prototype.load;Aircraft.prototype.load=function(a,r,g){var t=ges.aircraft.object3d._children;e.call(this,a,r,g);var i=setInterval(function(){t!==ges.aircraft.object3d._children&&(clearInterval(i),S())},16)}}},16);<|endoftext|>


<commit_before>define(["sprd/data/SprdModel", "sprd/entity/Size", "sprd/entity/PrintTypeColor", "js/data/Entity", 'js/type/Color', 'sprd/entity/Price'], function (SprdModel, Size, PrintTypeColor, Entity, Color, Price) {

    var SCALEABILITY = {
        ENLARGEABLE: "enlargeable",
        SHRINKABLE: "shrinkable",
        UNUSABLE: "unusable",
        UNSCALABLE: "unscalable"
    };

    var COLOR_SPACE = {
        PrintColors: "print_colors",
        CMYK: "cmyk",
        RGB: "rgb"
    };

    var PrintType = SprdModel.inherit("sprd.model.PrintType", {

        defaults: {
            dpi: null,
            price: Price
        },

        schema: {
            dpi: String,
            size: Size,
            colors: [PrintTypeColor],
            price: Price
        },

        printColorCache: {},

        getClosestPrintColor: function (color) {
            color = Color.parse(color);

            if (this.isPrintColorColorSpace()) {

                var minDistance = null,
                    ret = null;

                this.$.colors.each(function (printColor) {
                    var distance = color.distanceTo(printColor.color());
                    if (minDistance === null || distance < minDistance) {
                        minDistance = distance;
                        ret = printColor;
                    }
                });

                return ret;
            } else {
                // digital colors
                var cacheId = this.$.id + "_" + color.toRGB().toString();

                if (!this.printColorCache[cacheId]) {
                    var printTypeColor = new PrintTypeColor({
                        fill: color,
                        price: this._getDigitalPrintColorPrice()
                    });
                    printTypeColor.$parent = this;

                    this.printColorCache[cacheId] = printTypeColor;
                }

                return this.printColorCache[cacheId];
            }
        },

        getPrintColorById: function (id) {

            if (this.$.colors) {
                for (var i = 0; i < this.$.colors.$items.length; i++) {
                    var printColor = this.$.colors.$items[i];
                    if (printColor.$.id == id) {
                        return printColor;
                    }
                }
            }

            return null;
        },

        isPrintColorColorSpace: function () {
            return this.get("restrictions.colorSpace") === COLOR_SPACE.PrintColors;
        },

        _getDigitalPrintColorPrice: function () {

            if (!this.$digitalPrintColorPrice) {
                this.$digitalPrintColorPrice = new Price();
            }

            return this.$digitalPrintColorPrice;
        },

        isScalable: function () {
            var scaleability = this.get("restrictions.scaleability");
            return scaleability !== SCALEABILITY.UNUSABLE && scaleability !== SCALEABILITY.UNSCALABLE;

        },

        isEnlargeable: function () {
            return this.get("restrictions.scaleability") === SCALEABILITY.ENLARGEABLE;
        },

        isShrinkable: function () {
            return this.get("restrictions.scaleability") === SCALEABILITY.SHRINKABLE;
        },

        containsPrintTypeColor: function (printTypeColor) {

            if (!printTypeColor) {
                return false;
            }

            if (this.isPrintColorColorSpace()) {
                var includes = false;
                this.$.colors.each(function (color) {
                    if (color.$.id == printTypeColor.$.id && color.$.name == printTypeColor.$.name) {
                        includes = true;
                    }

                });
                return includes;
            } else {
                return true;
            }
        }
    });

    PrintType.Restrictions = Entity.inherit("sprd.model.PrintType.Restrictions", {

        defaults: {
            colorSpace: COLOR_SPACE.PrintColors,
            whiteSupported: true,
            transparencySupported: true,
            scaleability: SCALEABILITY.ENLARGEABLE,
            maxPrintColorLayers: 3
        },

        schema: {
            colorSpace: String,
            whiteSupported: Boolean,
            transparencySupported: Boolean,
            scaleability: String,
            maxPrintColorLayers: Number,

            printableAlongWithPrintTypes: [PrintType],
            printableAbovePrintTypes: [PrintType]
        }

    });

    PrintType.Mapping = {
        DigitalTransfer: "1",
        Flock: "2",
        OffsetTransfer: "3",
        ScreenPrintTransfer: "4",
        ScreenPrint: "5",
        NylonFlex: "6",
        Sticker: "7",
        ThermalSublimation: "10",
        ColdTransfer: "11",
        Flex: "14",
        SpecialFlex: "16",
        DigitalDirect: "17",
        LaserPrinter: "20",
        ButtonPrint: "21"
    };

    // extend schema, because circular dependency between PrintType and Restriction
    PrintType.prototype.schema.restrictions = PrintType.Restrictions;

    PrintType.Restrictions.SCALEABILITY = SCALEABILITY;

    PrintType.Restrictions.COLOR_SPACE = COLOR_SPACE;

    return PrintType;
});
<commit_msg>DEV-123723 can not go to digital after selecting flex<commit_after>define(["sprd/data/SprdModel", "sprd/entity/Size", "sprd/entity/PrintTypeColor", "js/data/Entity", 'js/type/Color', 'sprd/entity/Price'], function (SprdModel, Size, PrintTypeColor, Entity, Color, Price) {

    var SCALEABILITY = {
        ENLARGEABLE: "enlargeable",
        SHRINKABLE: "shrinkable",
        UNUSABLE: "unusable",
        UNSCALABLE: "unscalable"
    };

    var COLOR_SPACE = {
        PrintColors: "print_colors",
        CMYK: "cmyk",
        RGB: "rgb"
    };

    var PrintType = SprdModel.inherit("sprd.model.PrintType", {

        defaults: {
            dpi: null,
            price: Price
        },

        schema: {
            dpi: String,
            size: Size,
            colors: [PrintTypeColor],
            price: Price
        },

        printColorCache: {},

        getClosestPrintColor: function (color) {
            color = Color.parse(color);

            if (this.isPrintColorColorSpace()) {

                var minDistance = null,
                    ret = null;

                this.$.colors.each(function (printColor) {
                    var distance = color.distanceTo(printColor.color());
                    if (minDistance === null || distance < minDistance) {
                        minDistance = distance;
                        ret = printColor;
                    }
                });

                return ret;
            } else {
                // digital colors
                var cacheId = this.$.id + "_" + color.toRGB().toString();

                if (!this.printColorCache[cacheId]) {
                    var printTypeColor = new PrintTypeColor({
                        fill: color,
                        price: this._getDigitalPrintColorPrice()
                    });
                    printTypeColor.$parent = this;

                    this.printColorCache[cacheId] = printTypeColor;
                }

                return this.printColorCache[cacheId];
            }
        },

        getPrintColorById: function (id) {

            if (this.$.colors) {
                for (var i = 0; i < this.$.colors.$items.length; i++) {
                    var printColor = this.$.colors.$items[i];
                    if (printColor.$.id == id) {
                        return printColor;
                    }
                }
            }

            return null;
        },

        isPrintColorColorSpace: function () {
            return this.get("restrictions.colorSpace") === COLOR_SPACE.PrintColors;
        },

        isDigital: function () {
            return !this.isPrintColorColorSpace();
        },

        _getDigitalPrintColorPrice: function () {

            if (!this.$digitalPrintColorPrice) {
                this.$digitalPrintColorPrice = new Price();
            }

            return this.$digitalPrintColorPrice;
        },

        isScalable: function () {
            var scaleability = this.get("restrictions.scaleability");
            return scaleability !== SCALEABILITY.UNUSABLE && scaleability !== SCALEABILITY.UNSCALABLE;

        },

        isEnlargeable: function () {
            return this.get("restrictions.scaleability") === SCALEABILITY.ENLARGEABLE;
        },

        isShrinkable: function () {
            return this.get("restrictions.scaleability") === SCALEABILITY.SHRINKABLE;
        },

        containsPrintTypeColor: function (printTypeColor) {

            if (!printTypeColor) {
                return false;
            }

            if (this.isPrintColorColorSpace()) {
                var includes = false;
                this.$.colors.each(function (color) {
                    if (color.$.id == printTypeColor.$.id && color.$.name == printTypeColor.$.name) {
                        includes = true;
                    }

                });
                return includes;
            } else {
                return true;
            }
        }
    });

    PrintType.Restrictions = Entity.inherit("sprd.model.PrintType.Restrictions", {

        defaults: {
            colorSpace: COLOR_SPACE.PrintColors,
            whiteSupported: true,
            transparencySupported: true,
            scaleability: SCALEABILITY.ENLARGEABLE,
            maxPrintColorLayers: 3
        },

        schema: {
            colorSpace: String,
            whiteSupported: Boolean,
            transparencySupported: Boolean,
            scaleability: String,
            maxPrintColorLayers: Number,

            printableAlongWithPrintTypes: [PrintType],
            printableAbovePrintTypes: [PrintType]
        }

    });

    PrintType.Mapping = {
        DigitalTransfer: "1",
        Flock: "2",
        OffsetTransfer: "3",
        ScreenPrintTransfer: "4",
        ScreenPrint: "5",
        NylonFlex: "6",
        Sticker: "7",
        ThermalSublimation: "10",
        ColdTransfer: "11",
        Flex: "14",
        SpecialFlex: "16",
        DigitalDirect: "17",
        LaserPrinter: "20",
        ButtonPrint: "21"
    };

    // extend schema, because circular dependency between PrintType and Restriction
    PrintType.prototype.schema.restrictions = PrintType.Restrictions;

    PrintType.Restrictions.SCALEABILITY = SCALEABILITY;

    PrintType.Restrictions.COLOR_SPACE = COLOR_SPACE;

    return PrintType;
});
<|endoftext|>


<commit_before>import React, { Component } from "react";
import PropTypes from "prop-types";

import { connectStyle } from "native-base-shoutem-theme";

import Ionicons from "react-native-vector-icons/Ionicons";
import Entypo from "react-native-vector-icons/Entypo";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import Foundation from "react-native-vector-icons/Foundation";
import MaterialIcons from "react-native-vector-icons/MaterialIcons";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import Octicons from "react-native-vector-icons/Octicons";
import Zocial from "react-native-vector-icons/Zocial";
import SimpleLineIcons from "react-native-vector-icons/SimpleLineIcons";

import mapPropsToStyleNames from "../Utils/mapPropsToStyleNames";

class IconNB extends Component {
	static contextTypes = {
		theme: PropTypes.object,
	};

	componentWillMount() {
		if (this.context.theme) {
			let iconType = this.props.type != undefined ? this.props.type : this.context.theme["@@shoutem.theme/themeStyle"].variables.iconFamily;
			switch (iconType) {
				case "Ionicons":
					this.Icon = Ionicons;
					break;
				case "Entypo":
					this.Icon = Entypo;
					break;
				case "FontAwesome":
					this.Icon = FontAwesome;
					break;
				case "Foundation":
					this.Icon = Foundation;
					break;
				case "MaterialIcons":
					this.Icon = MaterialIcons;
					break;
				case "MaterialCommunityIcons":
					this.Icon = MaterialCommunityIcons;
					break;
				case "Octicons":
					this.Icon = Octicons;
					break;
				case "Zocial":
					this.Icon = Zocial;
					break;
				case "SimpleLineIcons":
					this.Icon = SimpleLineIcons;
					break;
				default:
					this.Icon = Ionicons;
			}
		} else {
			this.Icon = Ionicons;
		}
	}

	render() {
		return <this.Icon ref={c => (this._root = c)} {...this.props} />;
	}
}

IconNB.propTypes = {
	style: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]),
	type: PropTypes.oneOf(["Ionicons", "Entypo", "FontAwesome", "Foundation", "MaterialIcons", "MaterialCommunityIcons", "Octicons", "Zocial", "SimpleLineIcons"]),
};

const StyledIconNB = connectStyle("NativeBase.IconNB", {}, mapPropsToStyleNames)(IconNB);

export { StyledIconNB as IconNB };
<commit_msg>Update IconNB.js<commit_after>import React, { Component } from "react";
import PropTypes from "prop-types";

import { connectStyle } from "native-base-shoutem-theme";

import Ionicons from "react-native-vector-icons/Ionicons";
import Entypo from "react-native-vector-icons/Entypo";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import Foundation from "react-native-vector-icons/Foundation";
import MaterialIcons from "react-native-vector-icons/MaterialIcons";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import Octicons from "react-native-vector-icons/Octicons";
import Zocial from "react-native-vector-icons/Zocial";
import SimpleLineIcons from "react-native-vector-icons/SimpleLineIcons";

import mapPropsToStyleNames from "../Utils/mapPropsToStyleNames";

class IconNB extends Component {
	static contextTypes = {
		theme: PropTypes.object,
	};

	setIcon(iconType) {
		if (iconType == undefined && this.context.theme) {
			iconType = this.context.theme["@@shoutem.theme/themeStyle"].variables.iconFamily;
		}
		switch (iconType) {
			case "Ionicons":
				this.Icon = Ionicons;
				break;
			case "Entypo":
				this.Icon = Entypo;
				break;
			case "FontAwesome":
				this.Icon = FontAwesome;
				break;
			case "Foundation":
				this.Icon = Foundation;
				break;
			case "MaterialIcons":
				this.Icon = MaterialIcons;
				break;
			case "MaterialCommunityIcons":
				this.Icon = MaterialCommunityIcons;
				break;
			case "Octicons":
				this.Icon = Octicons;
				break;
			case "Zocial":
				this.Icon = Zocial;
				break;
			case "SimpleLineIcons":
				this.Icon = SimpleLineIcons;
				break;
			default:
				this.Icon = Ionicons;
		}
	}

	componentWillMount() {
		setIcon(this.props.type);
	}

	componentWillUpdate(nextProps, nextState) {
    		if (nextProps.type && this.props.type != nextProps.type) {
      			setIcon(nextProps.type);
    		}
  	}

	render() {
		return <this.Icon ref={c => (this._root = c)} {...this.props} />;
	}
}

IconNB.propTypes = {
	style: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.array]),
	type: PropTypes.oneOf(["Ionicons", "Entypo", "FontAwesome", "Foundation", "MaterialIcons", "MaterialCommunityIcons", "Octicons", "Zocial", "SimpleLineIcons"]),
};

const StyledIconNB = connectStyle("NativeBase.IconNB", {}, mapPropsToStyleNames)(IconNB);

export { StyledIconNB as IconNB };
<|endoftext|>


<commit_before>
 /**
  * @namespace basis.router
  */

  var namespace = this.path;

  //
  // main part
  //

  var location = global.location;
  var document = global.document;
  var eventUtils = require('basis.dom.event');

  // documentMode logic from YUI to filter out IE8 Compat Mode which false positives
  var docMode = document.documentMode;
  var eventSupport = 'onhashchange' in global && (docMode === undefined || docMode > 7);

  var CHECK_INTERVAL = 50;

  var arrayFrom = basis.array.from;
  var routes = {};
  var matched = {};
  var started = false;
  var currentPath;
  var timer;

 /**
  * @class
  */
  var Route = basis.Class(basis.Token, {
    className: namespace + '.Route',

    matched: null,
    params_: null,
    names_: null,

    init: function(names){
      basis.Token.prototype.init.call(this, null);

      this.matched = this.as(Boolean);
      this.names_ = Array.isArray(names) ? names : [];
      this.params_ = {};
    },
    param: function(nameOrIdx){
      var idx = typeof nameOrIdx == 'number' ? nameOrIdx : this.names_.indexOf(nameOrIdx);
      if (idx in this.params_ == false)
        this.params_[idx] = this.as(function(value){
          return value && value[idx];
        });
      return this.params_[idx];
    }
  });

 /**
  * Convert string to regexp
  */
  function pathToRegExp(route){
    var value = String(route || '');
    var params = [];

    function findWord(offset){
      return value.substr(offset).match(/^\w+/);
    }

    function parse(offset, stopChar){
      var result = '';
      var res;

      for (var i = offset; i < value.length; i++)
      {
        var c = value.charAt(i);
        switch (c)
        {
          case stopChar:
            return {
              result: result,
              offset: i
            };

          case '\\':
            result += '\\' + value.charAt(++i);
            break;

          case '|':  // allow | inside braces
            result += stopChar != ')' ? '\\|' : '|';
            break;

          case '(':  // optional: (something) -> (?:something)?
            if (res = parse(i + 1, ')'))
            {
              i = res.offset;
              result += '(?:' + res.result + ')?';
            }
            else
            {
              result += '\\(';
            }

            break;

          case ':':  // named:   :name -> ([^/]+)
            if (res = findWord(i + 1))
            {
              i += res[0].length;
              result += '([^\/]+)';
              params.push(res[0]);
            }
            else
            {
              result += ':';
            }

            break;

          case '*':  // splat:   *name -> (.*?)
            if (res = findWord(i + 1))
            {
              i += res[0].length;
              result += '(.*?)';
              params.push(res[0]);
            }
            else
            {
              result += '\\*';
            }

            break;

          default:
            result += basis.string.forRegExp(c);
        }
      }

      return stopChar ? null : result;
    }

    var regexp = new RegExp('^' + parse(0) + '$', 'i');
    regexp.params = params;
    return regexp;
  }

  function startWatch(){
    if (eventSupport)
      eventUtils.addHandler(global, 'hashchange', checkUrl);
    else
      timer = setInterval(checkUrl, CHECK_INTERVAL);
  }
  function stopWatch(){
    if (eventSupport)
      eventUtils.removeHandler(global, 'hashchange', checkUrl);
    else
      clearInterval(timer);
  }

 /**
  * Start router
  */
  function start(){
    if (!started)
    {
      startWatch();
      started = true;

      /** @cut */ if (module.exports.debug)
      /** @cut */   basis.dev.log(namespace + ' started');

      checkUrl();
    }
  }

 /**
  * Stop router
  */
  function stop(){
    if (started)
    {
      stopWatch();
      started = false;

      /** @cut */ if (module.exports.debug)
      /** @cut */   basis.dev.log(namespace + ' stopped');
    }
  }

 /**
  * Process current location
  */
  function checkUrl(){
    var newPath = location.hash.substr(1) || '';

    if (newPath != currentPath)
    {
      var inserted = [];
      var deleted = [];
      /** @cut */ var log = [];

      currentPath = newPath;

      for (var path in routes)
      {
        var route = routes[path];
        var match = newPath.match(route.regexp);

        if (match)
        {
          if (!matched[path])
            inserted.push(route);

          match = arrayFrom(match, 1);
          matched[path] = match;
        }
        else
        {
          if (matched[path])
          {
            deleted.push(route);
            delete matched[path];
            route.token.set(null);
          }
        }
      }

      // callback off for previous matched
      for (var i = 0, route; route = deleted[i]; i++)
      {
        var callbacks = arrayFrom(route.callbacks);
        for (var j = 0, item; item = callbacks[j]; j++)
          if (item.callback.leave)
          {
            item.callback.leave.call(item.context);
            /** @cut */ log.push('\n', { type: 'leave', path: route.id, cb: item, route: route });
          }
      }

      // callback off for previous matched
      for (var i = 0, route; route = inserted[i]; i++)
      {
        var callbacks = arrayFrom(route.callbacks);
        for (var j = 0, item; item = callbacks[j]; j++)
          if (item.callback.enter)
          {
            item.callback.enter.call(item.context);
            /** @cut */ log.push('\n', { type: 'enter', path: route.id, cb: item, route: route });
          }
      }

      // callback for matched
      for (var path in matched)
      {
        var route = routes[path];
        var args = matched[path];
        var callbacks = arrayFrom(route.callbacks);

        for (var i = 0, item; item = callbacks[i]; i++)
          if (item.callback.match)
          {
            item.callback.match.apply(item.context, args);
            /** @cut */ log.push('\n', { type: 'match', path: route.id, cb: item, route: route, args: args });
          }

        route.token.set(args);
      }

      /** @cut */ if (module.exports.debug)
      /** @cut */   basis.dev.info.apply(basis.dev, [namespace + ': hash changed to "' + newPath + '"'].concat(log.length ? log : '\n<no matches>'));
    }
  }

 /**
  * Returns route
  */
  function get(path, autocreate){
    var route = path instanceof Route ? path : routes[path];

    if (!route && autocreate)
    {
      var regexp = Object.prototype.toString.call(path) == '[object RegExp]'
        ? path
        : pathToRegExp(path);

      route = routes[path] = {
        id: path,
        callbacks: [],
        token: new Route(regexp.params),
        regexp: regexp
      };

      if (typeof currentPath == 'string')
      {
        var match = currentPath.match(route.regexp);
        if (match)
        {
          match = arrayFrom(match, 1);
          matched[path] = match;
          route.token.set(match);
        }
      }
    }

    return route;
  }

 /**
  * Add path to be handled
  */
  function add(path, callback, context){
    var route = get(path, true);
    var config;
    /** @cut */ var log = [];

    config = {
      cb_: callback,
      context: context,
      callback: typeof callback != 'function' ? callback || {} : {
        match: callback
      }
    };

    route.callbacks.push(config);

    if (route.id in matched)
    {
      if (config.callback.enter)
      {
        config.callback.enter.call(context);
        /** @cut */ log.push('\n', { type: 'enter', path: route.id, cb: config, route: route });
      }

      if (config.callback.match)
      {
        config.callback.match.apply(context, matched[path]);
        /** @cut */ log.push('\n', { type: 'match', path: route.id, cb: config, route: route, args: matched[path] });
      }
    }

    /** @cut */ if (module.exports.debug)
    /** @cut */   basis.dev.info.apply(basis.dev, [namespace + ': add handler for route `' + path + '`'].concat(log.length ? log : '\n<no matches>'));

    return route.token;
  }

 /**
  * Remove handler for path
  */
  function remove(path, callback, context){
    var route = get(path);

    if (route)
    {
      for (var i = 0, cb; cb = route.callbacks[i]; i++)
        if (cb.cb_ === callback && cb.context === context)
        {
          var token = route.token;

          route.callbacks.splice(i, 1);

          if (!route.callbacks.length)
          {
            // check no attaches to route token
            if ((!token.handler || !token.handler.handler) && !token.matched.handler)
            {
              delete routes[route.id];
              delete matched[route.id];
            }
          }

          break;
        }
    }
  }

 /**
  * Navigate to specified path
  */
  function navigate(path, replace){
    if (replace)
      location.replace(location.pathname + '#' + path);
    else
      location.hash = path;

    if (started)
      checkUrl();
  }

  //
  // export names
  //

  module.exports = {
    debug: false,

    start: start,
    stop: stop,
    checkUrl: checkUrl,
    navigate: navigate,

    add: add,
    remove: remove,
    route: function(path){
      return get(path, true).token;
    }
  };
<commit_msg>basis.router: add named values to route match<commit_after>
 /**
  * @namespace basis.router
  */

  var namespace = this.path;

  //
  // main part
  //

  var location = global.location;
  var document = global.document;
  var eventUtils = require('basis.dom.event');

  // documentMode logic from YUI to filter out IE8 Compat Mode which false positives
  var docMode = document.documentMode;
  var eventSupport = 'onhashchange' in global && (docMode === undefined || docMode > 7);

  var CHECK_INTERVAL = 50;

  var arrayFrom = basis.array.from;
  var routes = {};
  var matched = {};
  var started = false;
  var currentPath;
  var timer;

 /**
  * @class
  */
  var Route = basis.Token.subclass({
    className: namespace + '.Route',

    matched: null,
    params_: null,
    names_: null,

    init: function(names){
      basis.Token.prototype.init.call(this, null);

      this.matched = this.as(Boolean);
      this.names_ = Array.isArray(names) ? names : [];
      this.params_ = {};
    },
    param: function(nameOrIdx){
      var idx = typeof nameOrIdx == 'number' ? nameOrIdx : this.names_.indexOf(nameOrIdx);

      if (idx in this.params_ == false)
        this.params_[idx] = this.as(function(value){
          return value && value[idx];
        });

      return this.params_[idx];
    },
    set: function(value){
      if (value)
      {
        // make a copy of value, it also converts value to object (as value is array of matches)
        value = basis.object.slice(value);

        // extend object with named values
        for (var key in value)
          if (key in this.names_)
            value[this.names_[key]] = value[key];
      }

      basis.Token.prototype.set.call(this, value);
    }
  });

 /**
  * Convert string to regexp
  */
  function pathToRegExp(route){
    var value = String(route || '');
    var params = [];

    function findWord(offset){
      return value.substr(offset).match(/^\w+/);
    }

    function parse(offset, stopChar){
      var result = '';
      var res;

      for (var i = offset; i < value.length; i++)
      {
        var c = value.charAt(i);
        switch (c)
        {
          case stopChar:
            return {
              result: result,
              offset: i
            };

          case '\\':
            result += '\\' + value.charAt(++i);
            break;

          case '|':  // allow | inside braces
            result += stopChar != ')' ? '\\|' : '|';
            break;

          case '(':  // optional: (something) -> (?:something)?
            if (res = parse(i + 1, ')'))
            {
              i = res.offset;
              result += '(?:' + res.result + ')?';
            }
            else
            {
              result += '\\(';
            }

            break;

          case ':':  // named:   :name -> ([^/]+)
            if (res = findWord(i + 1))
            {
              i += res[0].length;
              result += '([^\/]+)';
              params.push(res[0]);
            }
            else
            {
              result += ':';
            }

            break;

          case '*':  // splat:   *name -> (.*?)
            if (res = findWord(i + 1))
            {
              i += res[0].length;
              result += '(.*?)';
              params.push(res[0]);
            }
            else
            {
              result += '\\*';
            }

            break;

          default:
            result += basis.string.forRegExp(c);
        }
      }

      return stopChar ? null : result;
    }

    var regexp = new RegExp('^' + parse(0) + '$', 'i');
    regexp.params = params;
    return regexp;
  }

  function startWatch(){
    if (eventSupport)
      eventUtils.addHandler(global, 'hashchange', checkUrl);
    else
      timer = setInterval(checkUrl, CHECK_INTERVAL);
  }
  function stopWatch(){
    if (eventSupport)
      eventUtils.removeHandler(global, 'hashchange', checkUrl);
    else
      clearInterval(timer);
  }

 /**
  * Start router
  */
  function start(){
    if (!started)
    {
      startWatch();
      started = true;

      /** @cut */ if (module.exports.debug)
      /** @cut */   basis.dev.log(namespace + ' started');

      checkUrl();
    }
  }

 /**
  * Stop router
  */
  function stop(){
    if (started)
    {
      stopWatch();
      started = false;

      /** @cut */ if (module.exports.debug)
      /** @cut */   basis.dev.log(namespace + ' stopped');
    }
  }

 /**
  * Process current location
  */
  function checkUrl(){
    var newPath = location.hash.substr(1) || '';

    if (newPath != currentPath)
    {
      var inserted = [];
      var deleted = [];
      /** @cut */ var log = [];

      currentPath = newPath;

      for (var path in routes)
      {
        var route = routes[path];
        var match = newPath.match(route.regexp);

        if (match)
        {
          if (!matched[path])
            inserted.push(route);

          match = arrayFrom(match, 1);
          matched[path] = match;
        }
        else
        {
          if (matched[path])
          {
            deleted.push(route);
            delete matched[path];
            route.token.set(null);
          }
        }
      }

      // callback off for previous matched
      for (var i = 0, route; route = deleted[i]; i++)
      {
        var callbacks = arrayFrom(route.callbacks);
        for (var j = 0, item; item = callbacks[j]; j++)
          if (item.callback.leave)
          {
            item.callback.leave.call(item.context);
            /** @cut */ log.push('\n', { type: 'leave', path: route.id, cb: item, route: route });
          }
      }

      // callback off for previous matched
      for (var i = 0, route; route = inserted[i]; i++)
      {
        var callbacks = arrayFrom(route.callbacks);
        for (var j = 0, item; item = callbacks[j]; j++)
          if (item.callback.enter)
          {
            item.callback.enter.call(item.context);
            /** @cut */ log.push('\n', { type: 'enter', path: route.id, cb: item, route: route });
          }
      }

      // callback for matched
      for (var path in matched)
      {
        var route = routes[path];
        var args = matched[path];
        var callbacks = arrayFrom(route.callbacks);

        for (var i = 0, item; item = callbacks[i]; i++)
          if (item.callback.match)
          {
            item.callback.match.apply(item.context, args);
            /** @cut */ log.push('\n', { type: 'match', path: route.id, cb: item, route: route, args: args });
          }

        route.token.set(args);
      }

      /** @cut */ if (module.exports.debug)
      /** @cut */   basis.dev.info.apply(basis.dev, [namespace + ': hash changed to "' + newPath + '"'].concat(log.length ? log : '\n<no matches>'));
    }
  }

 /**
  * Returns route
  */
  function get(path, autocreate){
    var route = path instanceof Route ? path : routes[path];

    if (!route && autocreate)
    {
      var regexp = Object.prototype.toString.call(path) == '[object RegExp]'
        ? path
        : pathToRegExp(path);

      route = routes[path] = {
        id: path,
        callbacks: [],
        token: new Route(regexp.params),
        regexp: regexp
      };

      if (typeof currentPath == 'string')
      {
        var match = currentPath.match(route.regexp);
        if (match)
        {
          match = arrayFrom(match, 1);
          matched[path] = match;
          route.token.set(match);
        }
      }
    }

    return route;
  }

 /**
  * Add path to be handled
  */
  function add(path, callback, context){
    var route = get(path, true);
    var config;
    /** @cut */ var log = [];

    config = {
      cb_: callback,
      context: context,
      callback: typeof callback != 'function' ? callback || {} : {
        match: callback
      }
    };

    route.callbacks.push(config);

    if (route.id in matched)
    {
      if (config.callback.enter)
      {
        config.callback.enter.call(context);
        /** @cut */ log.push('\n', { type: 'enter', path: route.id, cb: config, route: route });
      }

      if (config.callback.match)
      {
        config.callback.match.apply(context, matched[path]);
        /** @cut */ log.push('\n', { type: 'match', path: route.id, cb: config, route: route, args: matched[path] });
      }
    }

    /** @cut */ if (module.exports.debug)
    /** @cut */   basis.dev.info.apply(basis.dev, [namespace + ': add handler for route `' + path + '`'].concat(log.length ? log : '\n<no matches>'));

    return route.token;
  }

 /**
  * Remove handler for path
  */
  function remove(path, callback, context){
    var route = get(path);

    if (route)
    {
      for (var i = 0, cb; cb = route.callbacks[i]; i++)
        if (cb.cb_ === callback && cb.context === context)
        {
          var token = route.token;

          route.callbacks.splice(i, 1);

          if (!route.callbacks.length)
          {
            // check no attaches to route token
            if ((!token.handler || !token.handler.handler) && !token.matched.handler)
            {
              delete routes[route.id];
              delete matched[route.id];
            }
          }

          break;
        }
    }
  }

 /**
  * Navigate to specified path
  */
  function navigate(path, replace){
    if (replace)
      location.replace(location.pathname + '#' + path);
    else
      location.hash = path;

    if (started)
      checkUrl();
  }

  //
  // export names
  //

  module.exports = {
    debug: false,

    start: start,
    stop: stop,
    checkUrl: checkUrl,
    navigate: navigate,

    add: add,
    remove: remove,
    route: function(path){
      return get(path, true).token;
    }
  };
<|endoftext|>


<commit_before>const request = require('request-promise');
const co = require('co');
const csv = require('csv');
const messages = require('elasticio-node').messages;
const client = require('elasticio-rest-node')();

let stringifier;
let signedUrl;
let timeout;
let rowCount = 0;

exports.init = init;
exports.process = processAction;

function init() {
    return co(function* gen() {

        stringifier = csv.stringify({
            header: true
        });

        signedUrl = yield client.resources.storage.createSignedUrl();

        console.log(signedUrl);

        let putUrl = signedUrl.put_url;
        console.log('CSV file to be uploaded file to uri=%s', putUrl);

        stringifier.pipe(request.put(putUrl));
    });
}

function processAction(msg) {
    const self = this;

    if (timeout) {
        clearTimeout(timeout);
    }

    timeout = setTimeout(()=> {
        console.log('Closing the stream due to inactivity');
        co(function* gen() {
            console.log('The resulting CSV file contains %s rows', rowCount);
            stringifier.end();

            const messageToEmit = messages.newMessageWithBody({
                rowCount
            });
            const fileName = messageToEmit.id + '.csv';
            messageToEmit.attachments[fileName] = signedUrl.get_url;
            console.log('%j', messageToEmit);
            signedUrl = null;
            rowCount = 0;

            console.log('Emitting message');
            self.emit('data', messageToEmit);

            yield init();
        });
    }, 5000);

    console.log('Writing to stream', msg.body);

    stringifier.write(msg.body);
    rowCount++;
}

/**

co(function* proc() {
    yield init();

    for (let i = 0; i <= 100; i++) {

        processAction({
            body: {
                run: i,
                timestamp: Date.now()
            }
        });
    }

    setTimeout(()=> {

        console.log('Next round');

        for (let i = 100; i <= 200; i++) {

            processAction({
                body: {
                    run: i,
                    timestamp: Date.now()
                }
            });
        }
    }, 10000);
});
 **/
<commit_msg>Proper attachment structure<commit_after>const request = require('request-promise');
const co = require('co');
const csv = require('csv');
const messages = require('elasticio-node').messages;
const client = require('elasticio-rest-node')();

let stringifier;
let signedUrl;
let timeout;
let rowCount = 0;

exports.init = init;
exports.process = processAction;

function init() {
    return co(function* gen() {

        stringifier = csv.stringify({
            header: true
        });

        signedUrl = yield client.resources.storage.createSignedUrl();

        console.log(signedUrl);

        let putUrl = signedUrl.put_url;
        console.log('CSV file to be uploaded file to uri=%s', putUrl);

        stringifier.pipe(request.put(putUrl));
    });
}

function processAction(msg) {
    const self = this;

    if (timeout) {
        clearTimeout(timeout);
    }

    timeout = setTimeout(()=> {
        console.log('Closing the stream due to inactivity');
        co(function* gen() {
            console.log('The resulting CSV file contains %s rows', rowCount);
            stringifier.end();

            const messageToEmit = messages.newMessageWithBody({
                rowCount
            });
            const fileName = messageToEmit.id + '.csv';
            messageToEmit.attachments[fileName] = {
                "content-type": "text/csv",
                url: signedUrl.get_url
            };
            console.log('%j', messageToEmit);
            signedUrl = null;
            rowCount = 0;

            console.log('Emitting message');
            self.emit('data', messageToEmit);

            yield init();
        });
    }, 5000);

    console.log('Writing to stream', msg.body);

    stringifier.write(msg.body);
    rowCount++;
}

/**

co(function* proc() {
    yield init();

    for (let i = 0; i <= 100; i++) {

        processAction({
            body: {
                run: i,
                timestamp: Date.now()
            }
        });
    }

    setTimeout(()=> {

        console.log('Next round');

        for (let i = 100; i <= 200; i++) {

            processAction({
                body: {
                    run: i,
                    timestamp: Date.now()
                }
            });
        }
    }, 10000);
});
 **/
<|endoftext|>


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

(function ($) {
    "use strict";

    const randomParam = `_=${$.now()}`;
    $('.carousel').each(function (carouselIndex, carousel) {
        const testCase = $(carousel).attr('id').substring(9);

        projectAction.getDashboardConfiguration(testCase, function (data) {
            const json = JSON.parse(data.responseObject());
            $.each(json, function (index) {
                if (json[index].show) {
                    if (json[index].id === 'unittest_overview') {
                        $('.carousel-inner', carousel).append('
' +
                            '' + '
');
                    } else {
                        $('.carousel-inner', carousel).append('
' +
                            '' + '
');
                    }
                }
            });
            $('.carousel-inner div:first-child', carousel).addClass('active');
        });
    });
})(jQuery3);
<commit_msg>remove zooming of images<commit_after>/*
 * Copyright (c) 2014-2018 T-Systems Multimedia Solutions GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function ($) {
    "use strict";

    const randomParam = `_=${$.now()}`;
    $('.carousel').each(function (carouselIndex, carousel) {
        const testCase = $(carousel).attr('id').substring(9);

        projectAction.getDashboardConfiguration(testCase, function (data) {
            const json = JSON.parse(data.responseObject());
            $.each(json, function (index) {
                if (json[index].show) {
                    if (json[index].id === 'unittest_overview') {
                        $('.carousel-inner', carousel).append('
' +
                            '' + '
');
                    } else {
                        $('.carousel-inner', carousel).append('
' +
                            '' + '
');
                    }
                }
            });
            $('.carousel-inner div:first-child', carousel).addClass('active');
        });
    });
})(jQuery3);
<|endoftext|>


<commit_before>(function () {

    angular.module('foodGenerator')
        .service('recipeStorageService', recipeStorageService);

    function recipeStorageService($window, recipeService) {

        this.addMarkedRecipe = addMarkedRecipe;
        this.removeMarkedRecipe = removeMarkedRecipe;
        this.getMarkedRecipes = getMarkedRecipes;
        this.clearMarkedRecipes = clearMarkedRecipes;

        this.addRecentlyViewedRecipe = addRecentlyViewedRecipe;
        this.getRecentlyViewedRecipes = getRecentlyViewedRecipes;
        this.clearRecentlyViewedRecipes = clearRecentlyViewedRecipes;

        this.addToShoppingList = addToShoppingList;
        this.removeFromShoppingList = removeFromShoppingList;
        this.getShoppingListRecipes = getShoppingListRecipes;
        this.clearShoppingList = clearShoppingList;

        ////////////////

        // Marked Recipes

        function addMarkedRecipe(recipe) {
            console.log("Adding recipe '" + recipe.title + "' to marked recipes.");
            addRecipeToStorage(recipe, 'foodgenerator.recipes.marked');
        }

        function removeMarkedRecipe(recipe) {
            if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.marked')) {
                console.log("Removed recipe '" + recipe.title + "' from marked recipes.");
            } else {
                console.error("Could not remove recipe '" + recipe.title + "': not contained in marked recipe list.");
            }
        }

        function getMarkedRecipes() {
            return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.marked'));
        }

        function clearMarkedRecipes() {
            clearRecipeStorage('foodgenerator.recipes.marked');
        }

        // Recently Viewed Recipes

        function addRecentlyViewedRecipe(recipe) {
            console.log("Registering new view for recipe '" + recipe.title + "'.");
            addRecipeToStorage(recipe, 'foodgenerator.recipes.recent');
        }

        function getRecentlyViewedRecipes() {
            return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.recent'));
        }

        function clearRecentlyViewedRecipes() {
            clearRecipeStorage('foodgenerator.recipes.marked');
        }

        // Shopping List

        function addToShoppingList(recipe) {
            console.log("Adding recipe '" + recipe.title + "' to shopping list.");
            addRecipeToStorage(recipe, 'foodgenerator.recipes.shopping');
        }

        function removeFromShoppingList(recipe) {
            if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.shopping')) {
                console.log("Removed recipe '" + recipe.title + "' from shopping list.");
            } else {
                console.error("Could not remove recipe '" + recipe.title + "': not contained in shopping list.");
            }
        }

        function getShoppingListRecipes() {
            return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.shopping'));
        }

        function clearShoppingList() {
            clearRecipeStorage('foodgenerator.recipes.shopping');
        }

        // Generic Functions

        function addRecipeToStorage(recipe, storageName) {
            // in case it is contained, remove element from current position
            removeRecipeFromStorage(recipe, storageName);

            // create a new list with the new recipe as only item
            var reorderedStorage = [recipe._id];

            // append other recipes if defined
            var recipeStorage = getRecipeStorage(storageName);
            if (recipeStorage) {
                reorderedStorage.push.apply(reorderedStorage, recipeStorage);
            }

            // save back to local storage
            setRecipeStorage(storageName, reorderedStorage);
        }

        function removeRecipeFromStorage(recipe, storageName) {
            var recipeStorage = getRecipeStorage(storageName);
            if (recipeStorage && recipeStorage.length) {
                var recipeIndex = recipeStorage.indexOf(recipe._id);

                if (recipeIndex > 0) {
                    // remove if list not empty and not a single element
                    recipeStorage.splice(recipeIndex, 1);
                    setRecipeStorage(storageName, recipeStorage);
                    return true;
                } else if (recipeIndex == 0) {
                    // clear if it the only element
                    clearRecipeStorage(storageName);
                }
            }
            return false;
        }

        function getRecipeStorage(storageName) {
            var recipeStorage = $window.localStorage[storageName];
            if (recipeStorage == undefined) {
                return [];
            }
            return recipeStorage.split(",");
        }

        function setRecipeStorage(storageName, recipeStorage) {
            var storageString = "";
            for (var index in recipeStorage) {
                //noinspection JSUnfilteredForInLoop
                storageString += recipeStorage[index];
            }
            $window.localStorage[storageName] = storageString;
        }

        function clearRecipeStorage(storageName) {
            $window.localStorage.removeItem(storageName);
        }

        function getRecipesFromIdList(recipeIds) {
            var recipes = [];
            for (var index in recipeIds) {
                //noinspection JSUnfilteredForInLoop
                recipeService.get(recipeIds[index]).then(function (response) {
                    recipes.push(response.data);
                })
            }
            return recipes;
        }

    }

})();
<commit_msg>Added missing return-Statement in recipe-storage service.<commit_after>(function () {

    angular.module('foodGenerator')
        .service('recipeStorageService', recipeStorageService);

    function recipeStorageService($window, recipeService) {

        this.addMarkedRecipe = addMarkedRecipe;
        this.removeMarkedRecipe = removeMarkedRecipe;
        this.getMarkedRecipes = getMarkedRecipes;
        this.clearMarkedRecipes = clearMarkedRecipes;

        this.addRecentlyViewedRecipe = addRecentlyViewedRecipe;
        this.getRecentlyViewedRecipes = getRecentlyViewedRecipes;
        this.clearRecentlyViewedRecipes = clearRecentlyViewedRecipes;

        this.addToShoppingList = addToShoppingList;
        this.removeFromShoppingList = removeFromShoppingList;
        this.getShoppingListRecipes = getShoppingListRecipes;
        this.clearShoppingList = clearShoppingList;

        ////////////////

        // Marked Recipes

        function addMarkedRecipe(recipe) {
            console.log("Adding recipe '" + recipe.title + "' to marked recipes.");
            addRecipeToStorage(recipe, 'foodgenerator.recipes.marked');
        }

        function removeMarkedRecipe(recipe) {
            if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.marked')) {
                console.log("Removed recipe '" + recipe.title + "' from marked recipes.");
            } else {
                console.error("Could not remove recipe '" + recipe.title + "': not contained in marked recipe list.");
            }
        }

        function getMarkedRecipes() {
            return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.marked'));
        }

        function clearMarkedRecipes() {
            clearRecipeStorage('foodgenerator.recipes.marked');
        }

        // Recently Viewed Recipes

        function addRecentlyViewedRecipe(recipe) {
            console.log("Registering new view for recipe '" + recipe.title + "'.");
            addRecipeToStorage(recipe, 'foodgenerator.recipes.recent');
        }

        function getRecentlyViewedRecipes() {
            return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.recent'));
        }

        function clearRecentlyViewedRecipes() {
            clearRecipeStorage('foodgenerator.recipes.marked');
        }

        // Shopping List

        function addToShoppingList(recipe) {
            console.log("Adding recipe '" + recipe.title + "' to shopping list.");
            addRecipeToStorage(recipe, 'foodgenerator.recipes.shopping');
        }

        function removeFromShoppingList(recipe) {
            if (removeRecipeFromStorage(recipe, 'foodgenerator.recipes.shopping')) {
                console.log("Removed recipe '" + recipe.title + "' from shopping list.");
            } else {
                console.error("Could not remove recipe '" + recipe.title + "': not contained in shopping list.");
            }
        }

        function getShoppingListRecipes() {
            return getRecipesFromIdList(getRecipeStorage('foodgenerator.recipes.shopping'));
        }

        function clearShoppingList() {
            clearRecipeStorage('foodgenerator.recipes.shopping');
        }

        // Generic Functions

        function addRecipeToStorage(recipe, storageName) {
            // in case it is contained, remove element from current position
            removeRecipeFromStorage(recipe, storageName);

            // create a new list with the new recipe as only item
            var reorderedStorage = [recipe._id];

            // append other recipes if defined
            var recipeStorage = getRecipeStorage(storageName);
            if (recipeStorage) {
                reorderedStorage.push.apply(reorderedStorage, recipeStorage);
            }

            // save back to local storage
            setRecipeStorage(storageName, reorderedStorage);
        }

        function removeRecipeFromStorage(recipe, storageName) {
            var recipeStorage = getRecipeStorage(storageName);
            if (recipeStorage && recipeStorage.length) {
                var recipeIndex = recipeStorage.indexOf(recipe._id);

                if (recipeIndex > 0) {
                    // remove if list not empty and not a single element
                    recipeStorage.splice(recipeIndex, 1);
                    setRecipeStorage(storageName, recipeStorage);
                    return true;
                } else if (recipeIndex == 0) {
                    // clear if it the only element
                    clearRecipeStorage(storageName);
                    return true;
                }
            }
            return false;
        }

        function getRecipeStorage(storageName) {
            var recipeStorage = $window.localStorage[storageName];
            if (recipeStorage == undefined) {
                return [];
            }
            return recipeStorage.split(",");
        }

        function setRecipeStorage(storageName, recipeStorage) {
            var storageString = "";
            for (var index in recipeStorage) {
                //noinspection JSUnfilteredForInLoop
                storageString += recipeStorage[index];
            }
            $window.localStorage[storageName] = storageString;
        }

        function clearRecipeStorage(storageName) {
            $window.localStorage.removeItem(storageName);
        }

        function getRecipesFromIdList(recipeIds) {
            var recipes = [];
            for (var index in recipeIds) {
                //noinspection JSUnfilteredForInLoop
                recipeService.get(recipeIds[index]).then(function (response) {
                    recipes.push(response.data);
                })
            }
            return recipes;
        }

    }

})();
<|endoftext|>


<commit_before>angular.module('foodGenerator')
    .controller("RegisterCtrl", function ($scope, $uibModalInstance) {
        $scope.errorText = '';

        $scope.register = register;
        $scope.cancel = cancel;

        function register() {
            console.log("Performing registration with email '" + $scope.email + "' and password '" + $scope.password + "'.");
            // var currUser = {};
            // currUser.register($scope.username, $scope.password).then(function () {
            //     $uibModalInstance.close();
            // }, function (response) {
            //     debugger;
            //     if (response.status == 400 || response.status == 401) {
            //         $scope.errorText = "An unknown error occured. Please try again later.";
            //     }
            // });
        }

        function cancel() {
            $uibModalInstance.dismiss('cancel');
        }
    });
<commit_msg>finished implementation of register controller<commit_after>angular.module('foodGenerator')
    .controller("RegisterCtrl", function ($scope, currentUser, $uibModalInstance) {
        $scope.errorText = '';

        $scope.register = register;
        $scope.cancel = cancel;

        function register() {
            currentUser.register($scope.email, $scope.password, $scope.firstName, $scope.lastName)
                .then(function () {
                    $uibModalInstance.close();
                    // returned token is automatically saved by auth-interceptor
                }, function (error) {
                    if (error.status == 400 || error.status == 401) {
                        $scope.errorText = "An unknown error occured. Please try again later.";
                    }
                });
        }

        function cancel() {
            $uibModalInstance.dismiss('cancel');
        }
    });
<|endoftext|>


<commit_before>'use strict';

let Chance = require('chance'),
    chance = new Chance();

const TABLE_NAME = 'users';

exports.seed = (knex, Promise) => {
  return Promise.join(
    // Deletes ALL existing entries
    knex(TABLE_NAME).del(),

    // Inserts seed entries
    generateTestData(knex)

    //outputData(knex)
  );
};

function outputData(knex) {
  return knex(TABLE_NAME).select().then(results => console.log(results));
}

function generateTestData(knex) {
  let promises = [];
  for (let i = 0; i < 100; i++) {
    promises.push(createRandomUser(knex));
  }
  return Promise.all(promises);
}

function createRandomUser(knex) {
  let datetime = chance.date().toISOString();

  let user = {
    external_id: chance.natural(),
    username: chance.word(),
    firstname: chance.first(),
    lastname: chance.last(),
    email: chance.email(),
    created_at: datetime,
    modified_at: datetime
  }

  return knex(TABLE_NAME).insert(user).then();
}<commit_msg>removed wrong then()<commit_after>'use strict';

let Chance = require('chance'),
    chance = new Chance();

const TABLE_NAME = 'users';

exports.seed = (knex, Promise) => {
  return Promise.join(
    // Deletes ALL existing entries
    knex(TABLE_NAME).del(),

    // Inserts seed entries
    generateTestData(knex)

    // outputData(knex)
  );
};

function outputData(knex) {
  return knex(TABLE_NAME).select().then(results => console.log(results));
}

function generateTestData(knex) {
  let promises = [];
  for (let i = 0; i < 100; i++) {
    promises.push(createRandomUser(knex));
  }
  return Promise.all(promises);
}

function createRandomUser(knex) {
  let datetime = chance.date().toISOString();

  let user = {
    external_id: chance.natural(),
    username: chance.word(),
    firstname: chance.first(),
    lastname: chance.last(),
    email: chance.email(),
    created_at: datetime,
    modified_at: datetime
  }

  return knex(TABLE_NAME).insert(user);
}<|endoftext|>


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

/**
 * Creates a node.js Javascript context to contain an instance of Aria Templates, and loads Aria Templates in it.
 * @param {String} ariaBootstrapFileName name of the file containing the Aria Templates bootstrap.
 * @param {Function} readLogicalPathSync synchronous function which will be used to read files on the disk (it is given
 * the logical path to read as its only parameter, and it should return the content of the file as a string or throw an
 * exception).
 * @param {Object} console object to be available as console in the context.
 * @return {Object} node.js context, suitable to be used with vm.runInContext. If there was no error during the
 * execution of this method, it should contain the Aria and aria properties giving access to the embedded Aria Templates
 * instance. An execTimeouts method is also available to call all currently registered timeouts in this javascript
 * context (which is useful to make calls to an Aria Templates asynchronous method synchronous in node).
 */
exports.createContext = function (ariaBootstrapFileName, readLogicalPathSync, console) {

    var vm = require('vm');

    var timeouts = [];
    var timeoutId = 0;

    var atContext = vm.createContext({
        console : console,
        setTimeout : function (fn, delay) {
            timeoutId++;
            var id = "" + timeoutId;
            timeouts.push({
                id : id,
                fn : fn,
                delay : delay
            });
            return id;
        },
        clearTimeout : function (id) {
            for (var i = 0, l = timeouts.length; i < l; i++) {
                var item = timeouts[i];
                if (item.id === id) {
                    timeouts.splice(i, 1);
                    return;
                }
            }
        },
        setInterval : function () {
            console.error('setInterval not implemented.');
        },
        clearInterval : function () {
            // not implemented
        },
        execTimeouts : function () {
            var l = timeouts.length;
            while (l > 0) {
                var minIndex = 0;
                for (var i = 1; i < l; i++) {
                    if (timeouts[i].delay < timeouts[minIndex].delay) {
                        minIndex = i;
                    }
                }
                var minItem = timeouts[minIndex];
                timeouts.splice(minIndex, 1);
                minItem.fn.call(atContext);
                // The function called at the previous line can add or remove items from timeouts, so it's necessary to
                // check again the length:
                l = timeouts.length;
            }
        },
        load : function (filePath) {
            try {
                var fileContent = readLogicalPathSync(filePath);
                vm.runInContext(fileContent, atContext, filePath);
            } catch (err) {
                console.error("Error while trying to execute " + filePath, err);
            }
        },
        Aria : {
            rootFolderPath : './'
        }
    });

    atContext.load(ariaBootstrapFileName);

    atContext.Aria.classDefinition({
        $classpath : "aria.node.Transport",
        $implements : ["aria.core.transport.ITransports"],
        $singleton : true,
        $prototype : {
            isReady : true,
            init : atContext.Aria.empty,
            request : function (request, callback) {
                atContext.setTimeout(function () {
                    var data;
                    try {
                        data = readLogicalPathSync(request.url);
                    } catch (err) {
                        callback.fn.call(callback.scope, err, callback.args);
                        return;
                    }
                    callback.fn.call(callback.scope, false, callback.args, {
                        status : 200,
                        responseText : data
                    });
                }, 0);
            }
        }
    });

    atContext.aria.core.IO.updateTransports({
        "sameDomain" : "aria.node.Transport"
    });

    return atContext;
};<commit_msg>AT in node.js: emulating XMLHttpRequest instead of adding a transport<commit_after>/*
 * Copyright 2013 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var createXMLHttpRequest = function () {};
var XMLHttpRequestProto = createXMLHttpRequest.prototype = {};

XMLHttpRequestProto.UNSENT = 0;
XMLHttpRequestProto.OPENED = 1;
XMLHttpRequestProto.HEADERS_RECEIVED = 2;
XMLHttpRequestProto.LOADING = 3;
XMLHttpRequestProto.DONE = 4;

XMLHttpRequestProto.abort = XMLHttpRequestProto.setRequestHeader = function () {};
XMLHttpRequestProto.getResponseHeader = function () {
    return null;
};
XMLHttpRequestProto.getAllResponseHeaders = function () {
    return "";
};
XMLHttpRequestProto._changeReadyState = function (state) {
    this.readyState = state;
    if (this.onreadystatechange) {
        this.onreadystatechange();
    }
};
XMLHttpRequestProto.open = function (method, url, async) {
    this.method = method;
    this.url = url;
    this.async = async;
    this._changeReadyState(this.OPENED);
};

XMLHttpRequestProto.send = function () {
    var responseText, status;
    var self = this;
    try {
        responseText = self._readLogicalPathSync.call(null, self.url);
        status = 200;
    } catch (err) {
        responseText = err + "";
        status = 404;
    }
    var loadResult = function () {
        self.status = status;
        self.statusText = status === 200 ? "OK" : "NOT FOUND";
        self.responseText = responseText;
        self._changeReadyState(self.DONE);
        self = responseText = loadResult = null;
    };
    if (this.async) {
        this._setTimeout(loadResult, 0);
    } else {
        loadResult();
    }
};

/**
 * Creates a node.js Javascript context to contain an instance of Aria Templates, and loads Aria Templates in it.
 * @param {String} ariaBootstrapFileName name of the file containing the Aria Templates bootstrap.
 * @param {Function} readLogicalPathSync synchronous function which will be used to read files on the disk (it is given
 * the logical path to read as its only parameter, and it should return the content of the file as a string or throw an
 * exception).
 * @param {Object} console object to be available as console in the context.
 * @return {Object} node.js context, suitable to be used with vm.runInContext. If there was no error during the
 * execution of this method, it should contain the Aria and aria properties giving access to the embedded Aria Templates
 * instance. An execTimeouts method is also available to call all currently registered timeouts in this javascript
 * context (which is useful to make calls to an Aria Templates asynchronous method synchronous in node).
 */
exports.createContext = function (ariaBootstrapFileName, readLogicalPathSync, console) {

    var vm = require('vm');

    var timeouts = [];
    var timeoutId = 0;

    var setTimeout = function (fn, delay) {
        timeoutId++;
        var id = "" + timeoutId;
        timeouts.push({
            id : id,
            fn : fn,
            delay : delay
        });
        return id;
    };
    var clearTimeout = function (id) {
        for (var i = 0, l = timeouts.length; i < l; i++) {
            var item = timeouts[i];
            if (item.id === id) {
                timeouts.splice(i, 1);
                return;
            }
        }
    };

    var XMLHttpRequest = function () {};
    XMLHttpRequest.prototype = new createXMLHttpRequest();
    XMLHttpRequest.prototype._readLogicalPathSync = readLogicalPathSync;
    XMLHttpRequest.prototype._setTimeout = setTimeout;

    var atContext = vm.createContext({
        XMLHttpRequest : XMLHttpRequest,
        console : console,
        setTimeout : setTimeout,
        clearTimeout : clearTimeout,
        setInterval : setTimeout, // implements the setInterval method as a setTimeout (only call it once)
        clearInterval : clearTimeout,
        execTimeouts : function () {
            var l = timeouts.length;
            while (l > 0) {
                var minIndex = 0;
                for (var i = 1; i < l; i++) {
                    if (timeouts[i].delay < timeouts[minIndex].delay) {
                        minIndex = i;
                    }
                }
                var minItem = timeouts[minIndex];
                timeouts.splice(minIndex, 1);
                minItem.fn.call(atContext);
                // The function called at the previous line can add or remove items from timeouts, so it's necessary to
                // check again the length:
                l = timeouts.length;
            }
        },
        load : function (filePath) {
            try {
                var fileContent = readLogicalPathSync(filePath);
                vm.runInContext(fileContent, atContext, filePath);
            } catch (err) {
                console.error("Error while trying to execute " + filePath, err);
            }
        },
        Aria : {
            rootFolderPath : './'
        }
    });

    atContext.load(ariaBootstrapFileName);

    return atContext;
};<|endoftext|>


<commit_before>function extend (target, source) {
    Object.keys(source).forEach(function (property) {
        target[property] = source[property];
    });

    return target;
}

var assert = extend(exports, require("assert"));

assert.isNull = function (value, message) {
    if (value !== null) {
        assert.fail(value, null, message, "===", assert.isNull);
    }
}

assert.isNotNull = function (value, message) {
    if (value === null) {
        assert.fail(value, null, message, "!==", assert.isNotNull);
    }
}

function typeOf (value, type, message, stackStart) {
    if (typeof value != type) {
        assert.fail(value, type, message, "typeof", stackStart);
    }
}

function notTypeOf (value, type, message, stackStart) {
    if (typeof value == type) {
        assert.fail(value, type, message, "!typeof", stackStart);
    }
}

assert.isTypeOf = function (value, type, message) {
    typeOf(value, type, message, assert.isTypeOf);
};

assert.isNotTypeOf = function (value, type, message) {
    notTypeOf(value, type, message, assert.isNotTypeOf);
};

assert.isObject = function (value, message) {
    typeOf(value, "object", message, assert.isObject);
};

assert.isFunction = function (value, message) {
    typeOf(value, "function", message, assert.isFunction);
};

assert.isString = function (value, message) {
    typeOf(value, "string", message, assert.isString);
};

assert.isBoolean = function (value, message) {
    typeOf(value, "boolean", message, assert.isBoolean);
};

assert.isNumber = function (value, message) {
    typeOf(value, "number", message, assert.isNumber);
};

assert.isUndefined = function (value, message) {
    typeOf(value, "undefined", message, assert.isUndefined);
};

assert.isNotUndefined = function (value, message) {
    notTypeOf(value, "undefined", message, assert.isNotUndefined);
};

assert.isArray = function (value, message) {
    if (Object.prototype.toString.call(value) != "[object Array]") {
        assert.fail(value, "Array", message, "[[Class]]", assert.isArray);
    }
};

assert.isNaN = function (value, message) {
    if (!isNaN(value)) {
        assert.fail(value, "NaN", message, "==", assert.isNaN);
    }
}

assert.isNotNaN = function (value, message) {
    if (isNaN(value)) {
        assert.fail(value, "NaN", message, "!=", assert.isNotNaN);
    }
}

assert.match = function (value, pattern, message) {
    if (!pattern.test(value)) {
        assert.fail(value, pattern, message, "test", assert.match);
    }
}

assert.noMatch = function (value, pattern, message) {
    if (pattern.test(value)) {
        assert.fail(value, pattern, message, "!test", assert.noMatch);
    }
}

assert.isPrototypeOf = function (proto, object, message) {
    if (!proto.isPrototypeOf(object)) {
        assert.fail(proto, object, message, "isPrototypeOf", assert.isPrototypeOf);
    }
}

assert.isNotPrototypeOf = function (proto, object, message) {
    if (proto.isPrototypeOf(object)) {
        assert.fail(proto, object, message, "!isPrototypeOf", assert.isNotPrototypeOf);
    }
}

assert.isWritable = function (object, property, message) {
    var original = object[property];
    var newValue = original + " overwritten";
    object[property] = newValue;

    if (object[property] != newValue) {
        assert.fail(object, property, message, "isWritable", assert.isWritable);
    }

    object[property] = original;
}

assert.isNotWritable = function (object, property, message) {
    var original = object[property];
    var newValue = original + " overwritten";
    object[property] = newValue;

    if (object[property] == newValue) {
        object[property] = original;
        assert.fail(object, property, message, "isNotWritable", assert.isWritable);
    }
}

assert.isConfigurable = function (object, property, message) {
    var original = object[property];
    delete object[property];

    if (object.hasOwnProperty(property)) {
        assert.fail(object, property, message, "isConfigurable", assert.isWritable);
    }

    object[property] = original;
}

assert.isNotConfigurable = function (object, property, message) {
    var original = object[property];
    delete object[property];

    if (!object.hasOwnProperty(property)) {
        object[property] = original;
        assert.fail(object, property, message, "isNotConfigurable", assert.isWritable);
    }
}

assert.isEnumerable = function (object, property, message) {
    if (Object.keys(object).indexOf(property) < 0) {
        assert.fail(object, property, message, "isEnumerable", assert.isWritable);
    }
}

assert.isNotEnumerable = function (object, property, message) {
    if (Object.keys(object).indexOf(property) >= 0) {
        assert.fail(object, property, message, "isNotEnumerable", assert.isWritable);
    }
}
<commit_msg>Use property descriptors in property attribute assertions<commit_after>function extend (target, source) {
    Object.keys(source).forEach(function (property) {
        target[property] = source[property];
    });

    return target;
}

var assert = extend(exports, require("assert"));

assert.isNull = function (value, message) {
    if (value !== null) {
        assert.fail(value, null, message, "===", assert.isNull);
    }
}

assert.isNotNull = function (value, message) {
    if (value === null) {
        assert.fail(value, null, message, "!==", assert.isNotNull);
    }
}

function typeOf (value, type, message, stackStart) {
    if (typeof value != type) {
        assert.fail(value, type, message, "typeof", stackStart);
    }
}

function notTypeOf (value, type, message, stackStart) {
    if (typeof value == type) {
        assert.fail(value, type, message, "!typeof", stackStart);
    }
}

assert.isTypeOf = function (value, type, message) {
    typeOf(value, type, message, assert.isTypeOf);
};

assert.isNotTypeOf = function (value, type, message) {
    notTypeOf(value, type, message, assert.isNotTypeOf);
};

assert.isObject = function (value, message) {
    typeOf(value, "object", message, assert.isObject);
};

assert.isFunction = function (value, message) {
    typeOf(value, "function", message, assert.isFunction);
};

assert.isString = function (value, message) {
    typeOf(value, "string", message, assert.isString);
};

assert.isBoolean = function (value, message) {
    typeOf(value, "boolean", message, assert.isBoolean);
};

assert.isNumber = function (value, message) {
    typeOf(value, "number", message, assert.isNumber);
};

assert.isUndefined = function (value, message) {
    typeOf(value, "undefined", message, assert.isUndefined);
};

assert.isNotUndefined = function (value, message) {
    notTypeOf(value, "undefined", message, assert.isNotUndefined);
};

assert.isArray = function (value, message) {
    if (Object.prototype.toString.call(value) != "[object Array]") {
        assert.fail(value, "Array", message, "[[Class]]", assert.isArray);
    }
};

assert.isNaN = function (value, message) {
    if (!isNaN(value)) {
        assert.fail(value, "NaN", message, "==", assert.isNaN);
    }
}

assert.isNotNaN = function (value, message) {
    if (isNaN(value)) {
        assert.fail(value, "NaN", message, "!=", assert.isNotNaN);
    }
}

assert.match = function (value, pattern, message) {
    if (!pattern.test(value)) {
        assert.fail(value, pattern, message, "test", assert.match);
    }
}

assert.noMatch = function (value, pattern, message) {
    if (pattern.test(value)) {
        assert.fail(value, pattern, message, "!test", assert.noMatch);
    }
}

assert.isPrototypeOf = function (proto, object, message) {
    if (!proto.isPrototypeOf(object)) {
        assert.fail(proto, object, message, "isPrototypeOf", assert.isPrototypeOf);
    }
}

assert.isNotPrototypeOf = function (proto, object, message) {
    if (proto.isPrototypeOf(object)) {
        assert.fail(proto, object, message, "!isPrototypeOf", assert.isNotPrototypeOf);
    }
}

assert.isWritable = function (object, property, message) {
    var descriptor = Object.getOwnPropertyDescriptor(object, property);

    if (!descriptor.writable) {
        assert.fail(object, property, message, "isWritable", assert.isWritable);
    }
}

assert.isNotWritable = function (object, property, message) {
    var descriptor = Object.getOwnPropertyDescriptor(object, property);

    if (descriptor.writable) {
        assert.fail(object, property, message, "isNotWritable", assert.isWritable);
    }
}

assert.isConfigurable = function (object, property, message) {
    var descriptor = Object.getOwnPropertyDescriptor(object, property);

    if (!descriptor.configurable) {
        assert.fail(object, property, message, "isConfigurable", assert.isWritable);
    }
}

assert.isNotConfigurable = function (object, property, message) {
    var descriptor = Object.getOwnPropertyDescriptor(object, property);

    if (descriptor.configurable) {
        assert.fail(object, property, message, "isNotConfigurable", assert.isWritable);
    }
}

assert.isEnumerable = function (object, property, message) {
    var descriptor = Object.getOwnPropertyDescriptor(object, property);

    if (!descriptor.enumerable) {
        assert.fail(object, property, message, "isEnumerable", assert.isWritable);
    }
}

assert.isNotEnumerable = function (object, property, message) {
    var descriptor = Object.getOwnPropertyDescriptor(object, property);

    if (descriptor.enumerable) {
        assert.fail(object, property, message, "isNotEnumerable", assert.isWritable);
    }
}
<|endoftext|>


<commit_before>/* eslint-disable global-require */

module.exports = function createOpts(
  env,
  react,
  { presets: otherPresets, plugins: otherPlugins } = {}
) {
  const production = !env.endsWith('-dev');

  if (!production) {
    env = env.slice(0, -4);
  }

  if (env === 'doc') {
    return {
      presets: [
        'jsdoc',
        react && 'babel-preset-pob-react',
        require.resolve('babel-preset-stage-1'),
      ].filter(Boolean),
      plugins: [
        'add-jsdoc-annotations',
        require.resolve('babel-plugin-transform-flow-strip-types'),
      ],
    };
  }

  let transpilationPreset;
  let browser;

  switch (env) {
    case 'es5':
      throw new Error('use olderNode instead.');

    case 'node7':
      transpilationPreset = ['latest-node', { target: 7.6 }];
      browser = false;
      break;

    case 'node6':
      transpilationPreset = ['latest-node', { target: 6.5 }];
      browser = false;
      break;

    case 'older-node':
      transpilationPreset = 'latest';
      browser = false;
      break;

    case 'module-node7':
    case 'webpack-node7':
      transpilationPreset = ['latest-node', { target: 7.6, modules: false }];
      browser = false;
      break;

    case 'module':
    case 'webpack':
      transpilationPreset = ['latest', { es2015: { modules: false } }];
      browser = true;
      break;

    case 'module-modern-browsers':
    case 'webpack-modern-browsers':
      transpilationPreset = ['modern-browsers', { modules: false }];
      browser = true;
      break;

    case 'browsers':
      transpilationPreset = 'latest';
      browser = true;
      break;

    default:
      throw new Error(`Unsupported env ${env}`);
  }

  return {
    // preset order is last to first, so we reverse it for clarity.
    presets: [
      // add react preset with jsx
      react && ['babel-preset-pob-react', { production }],
      // add stage-1 to stage-3 features
      require.resolve('babel-preset-pob-stages'),
      // pob preset: flow, import `src`, export default function name, replacements
      [require.resolve('babel-preset-pob'), {
        production,
        replacements: {
          BROWSER: browser,
          NODEJS: !browser,
          SERVER: !browser,
        },
      }],
      // optimizations: remove dead-code
      require.resolve('babel-preset-babili-optimizations'),
      // discard unused imports (like production-only or node-only imports)
      { plugins: [require.resolve('babel-plugin-discard-module-references')] },
      // transpile for specified target
      transpilationPreset,
    ].reverse().concat(otherPresets || []).filter(Boolean),
    plugins: (otherPlugins || []).filter(Boolean),
  };
};
<commit_msg>feat: use babel-preset-env<commit_after>/* eslint-disable global-require */

module.exports = function createOpts(
  env,
  react,
  { presets: otherPresets, plugins: otherPlugins } = {}
) {
  const production = !env.endsWith('-dev');

  if (!production) {
    env = env.slice(0, -4);
  }

  if (env === 'doc') {
    return {
      presets: [
        'jsdoc',
        react && 'babel-preset-pob-react',
        require.resolve('babel-preset-stage-1'),
      ].filter(Boolean),
      plugins: [
        'add-jsdoc-annotations',
        require.resolve('babel-plugin-transform-flow-strip-types'),
      ],
    };
  }

  let transpilationPreset;
  let browser;

  switch (env) {
    case 'es5':
      throw new Error('use olderNode instead.');

    case 'node7':
      transpilationPreset = ['latest-node', { target: 7.6 }];
      browser = false;
      break;

    case 'node6':
      transpilationPreset = ['latest-node', { target: 6.5 }];
      browser = false;
      break;

    case 'older-node':
      transpilationPreset = 'latest';
      browser = false;
      break;

    case 'module-node7':
    case 'webpack-node7':
      transpilationPreset = ['latest-node', { target: 7.6, modules: false }];
      browser = false;
      break;

    case 'module':
    case 'webpack':
      transpilationPreset = ['env', { modules: false }];
      browser = true;
      break;

    case 'module-modern-browsers':
    case 'webpack-modern-browsers':
      transpilationPreset = ['modern-browsers', { modules: false }];
      browser = true;
      break;

    case 'browsers':
      transpilationPreset = 'latest';
      browser = true;
      break;

    default:
      throw new Error(`Unsupported env ${env}`);
  }

  return {
    // preset order is last to first, so we reverse it for clarity.
    presets: [
      // add react preset with jsx
      react && ['babel-preset-pob-react', { production }],
      // add stage-1 to stage-3 features
      require.resolve('babel-preset-pob-stages'),
      // pob preset: flow, import `src`, export default function name, replacements
      [require.resolve('babel-preset-pob'), {
        production,
        replacements: {
          BROWSER: browser,
          NODEJS: !browser,
          SERVER: !browser,
        },
      }],
      // optimizations: remove dead-code
      require.resolve('babel-preset-babili-optimizations'),
      // discard unused imports (like production-only or node-only imports)
      { plugins: [require.resolve('babel-plugin-discard-module-references')] },
      // transpile for specified target
      transpilationPreset,
    ].reverse().concat(otherPresets || []).filter(Boolean),
    plugins: (otherPlugins || []).filter(Boolean),
  };
};
<|endoftext|>