<commit_before>var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
var trPlugin = require('l10n-tr-plugin');
var injectFilenamePath = path.join(process.cwd(), 'grunt/webpack/inject-filename-loader');
var clientHelpersPath = path.join(process.cwd(), 'website-guts/client-helpers');
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;

module.exports = function(opts) {
  var jshintOpts = require('../jshint');
  var jshintEnvConfig = opts.env === 'dev' ? jshintOpts.clientDev.options : jshintOpts.clientProd.options;

  var jshintConfig = _.merge({}, {
    emitErrors: true,
    failOnHint: true,
  }, jshintEnvConfig, jshintOpts.options);

  var preloaders = [
    {
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /bower_components/,
        /libraries/
      ],
      loader: 'inject-filename-loader?' + opts.injectFileNameParams
    },
    {
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /bower_components/,
        /libraries/,
        /equal_height_grid/,
        /form-filler/,
        /guid_sprintf/,
        /oform_globals/,
        /trim-mixpanel-cookie/,
        /uri/,
        /get_url_parameter/
      ],
      loader: 'jshint-loader'
    }
  ];

  /**
   * Loaders to
   * -- compile hbs client side templates
   * -- compile es6
   */
  var loaders = [
    { test: /\.hbs$/, loader: 'handlebars-loader?helperDirs[]=' + clientHelpersPath },
    {test: /\.js?$/, exclude: ['bower_components', 'node_modules'], loader: 'babel-loader'}
  ];

  /**
   * Plugins to
   * -- resolve all bower components from the main file specified in module's bower.json
   * -- no assets are emitted containing errors http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
   */
  var plugins = [
    new webpack.ResolverPlugin(new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])),
    new webpack.NoErrorsPlugin(),
    new CommonsChunkPlugin({
      name: 'vendor',
      filename: 'commons.js',
      minChunks: 0
    }),
    new trPlugin()
  ];

  //TODO: Add webpack dev server for Hot Module Replacment
  var devPlugins = [
    //new webpack.HotModuleReplacementPlugin()
  ];

  /**
   * Plugins specific to production
   * -- Uglifiy JS and strip comments
   * -- Deduplicates equal or similar files http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
   * -- Defines a global production variable that can be used in JS if necessary
  */
  var prodPlugins = [
    new webpack.optimize.UglifyJsPlugin({
      output: {
        comments: false
      },
      compress: {
        conditionals: false,
        warnings: false,
      },
      sourceMap: false
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    })
  ];

  if(opts.env === 'dev') {
    plugins.push.apply(plugins, devPlugins);
  } else {
    plugins.push.apply(plugins, prodPlugins);
  }

  var webpackConfig = {
    node: {
      __filename: true,
      fs: 'empty'
    },
    jshint: jshintConfig,
    entry: opts.entry,
    output: {
      path: './' + opts.outputPath,
      publicPath: opts.publicPath,
      filename: '[name].js'
    },
    resolve: {
      //all these extensions will be resolved without specifying extension in the `require` function
      extensions: ['', '.js', '.hbs'],
      //files in these directory can be required without a relative path
      modulesDirectories: [
        'node_modules',
        'bower_components',
        'website-guts/templates/client',
        'website-guts/assets/js/globals',
        'website-guts/assets/js/libraries'
      ]
    },
    module: {
      preLoaders: preloaders,
      loaders: loaders
    },
    plugins: plugins
  };

  if(opts.env === 'dev') {
    webpackConfig.devtool = 'inline-source-map';
  }

  return webpackConfig;
};
<commit_msg>remove uglify options<commit_after>var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
var trPlugin = require('l10n-tr-plugin');
var injectFilenamePath = path.join(process.cwd(), 'grunt/webpack/inject-filename-loader');
var clientHelpersPath = path.join(process.cwd(), 'website-guts/client-helpers');
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;

module.exports = function(opts) {
  var jshintOpts = require('../jshint');
  var jshintEnvConfig = opts.env === 'dev' ? jshintOpts.clientDev.options : jshintOpts.clientProd.options;

  var jshintConfig = _.merge({}, {
    emitErrors: true,
    failOnHint: true,
  }, jshintEnvConfig, jshintOpts.options);

  var preloaders = [
    {
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /bower_components/,
        /libraries/
      ],
      loader: 'inject-filename-loader?' + opts.injectFileNameParams
    },
    {
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /bower_components/,
        /libraries/,
        /equal_height_grid/,
        /form-filler/,
        /guid_sprintf/,
        /oform_globals/,
        /trim-mixpanel-cookie/,
        /uri/,
        /get_url_parameter/
      ],
      loader: 'jshint-loader'
    }
  ];

  /**
   * Loaders to
   * -- compile hbs client side templates
   * -- compile es6
   */
  var loaders = [
    { test: /\.hbs$/, loader: 'handlebars-loader?helperDirs[]=' + clientHelpersPath },
    {test: /\.js?$/, exclude: ['bower_components', 'node_modules'], loader: 'babel-loader'}
  ];

  /**
   * Plugins to
   * -- resolve all bower components from the main file specified in module's bower.json
   * -- no assets are emitted containing errors http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
   */
  var plugins = [
    new webpack.ResolverPlugin(new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])),
    new webpack.NoErrorsPlugin(),
    new CommonsChunkPlugin({
      name: 'vendor',
      filename: 'commons.js',
      minChunks: 0
    }),
    new trPlugin()
  ];

  //TODO: Add webpack dev server for Hot Module Replacment
  var devPlugins = [
    //new webpack.HotModuleReplacementPlugin()
  ];

  /**
   * Plugins specific to production
   * -- Uglifiy JS and strip comments
   * -- Deduplicates equal or similar files http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
   * -- Defines a global production variable that can be used in JS if necessary
  */
  var prodPlugins = [
    new webpack.optimize.UglifyJsPlugin({
      output: {
        comments: false
      },
      //compress: {
        //conditionals: false,
        //warnings: false,
      //},
      sourceMap: false
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    })
  ];

  if(opts.env === 'dev') {
    plugins.push.apply(plugins, devPlugins);
  } else {
    plugins.push.apply(plugins, prodPlugins);
  }

  var webpackConfig = {
    node: {
      __filename: true,
      fs: 'empty'
    },
    jshint: jshintConfig,
    entry: opts.entry,
    output: {
      path: './' + opts.outputPath,
      publicPath: opts.publicPath,
      filename: '[name].js'
    },
    resolve: {
      //all these extensions will be resolved without specifying extension in the `require` function
      extensions: ['', '.js', '.hbs'],
      //files in these directory can be required without a relative path
      modulesDirectories: [
        'node_modules',
        'bower_components',
        'website-guts/templates/client',
        'website-guts/assets/js/globals',
        'website-guts/assets/js/libraries'
      ]
    },
    module: {
      preLoaders: preloaders,
      loaders: loaders
    },
    plugins: plugins
  };

  if(opts.env === 'dev') {
    webpackConfig.devtool = 'inline-source-map';
  }

  return webpackConfig;
};
<|endoftext|>


<commit_before>const spawn = require('child_process').spawn;

exports.handler = function (event, context, callback) {
  process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];
  const executable = './halma-telegram-bot-serverless';
  const main = spawn(executable, { stdio: ['pipe', process.stdout, process.stderr] });

  main.on('error', function (err) {
    console.error('error: ' + err);
    callback(err, err);
  });

  main.on('exit', function (code) {
    if (code !== 0) {
      callback(new Error(
        "'" + executable + "' exited with non-zero exit code. Please check stderr for details."
      ));
    } else {
      callback(null, "success");
    }
  });

  main.stdin.write(event.body);
  main.stdin.end();
};
<commit_msg>Correct response from lambda-handler.js<commit_after>const spawn = require('child_process').spawn;

exports.handler = function (event, context, callback) {
  process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];
  const executable = './halma-telegram-bot-serverless';
  const main = spawn(executable, { stdio: ['pipe', process.stdout, process.stderr] });

  main.on('error', function (err) {
    console.error('error: ' + err);
    callback(err, err);
  });

  main.on('exit', function (code) {
    if (code !== 0) {
      callback(new Error(
        "'" + executable + "' exited with non-zero exit code. Please check stderr for details."
      ));
    } else {
      callback(null, {
        statusCode: 200,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ "ok": true, "description": "update has been processed" })
      });
    }
  });

  main.stdin.write(event.body);
  main.stdin.end();
};
<|endoftext|>


<commit_before>CKEDITOR.dialog.add( 'highlight_js', function( editor ) {
    return {
        title: "test",
        minWidth: 800,
        minHeight: 500,
        contents: [
            {
                id: 'tab-basic',
                label: 'Basic Settings',
                elements: [
                    {
                        type: 'select',
                        id: 'code_lan',
                        label: 'Select code language',
                        items: [
                                [ 'Auto' ],
                                [ 'no-highlight' ],
                                [ 'Bash' ],
                                [ 'Diff' ],
                                [ 'JSON' ],
                                [ 'C#' ],
                                [ 'HTML' ],
                                [ 'JAVA' ],
                                [ 'Python' ],
                                [ 'C++' ],
                                [ 'HTTP' ],
                                [ 'JavaScript' ],
                                [ 'Ruby' ],
                                [ 'CSS' ],
                                [ 'PHP' ],
                                [ 'ini' ],
                                [ 'SQL' ],
                                [ 'Perl' ],
                                [ " 1C " ],
                                [ "AVR Assembler" ],
                                [ "ActionScript" ],
                                [ "Apache" ],
                                [ "AppleScript" ],
                                [ "Axapta" ],
                                [ "Brainfuck" ],
                                [ "CMake" ],
                                [ "Clojure" ],
                                [ "CoffeeScript" ],
                                [ "D" ],
                                [ "DOS .bat" ],
                                [ "Delphi" ],
                                [ "Django" ],
                                [ "Erlang" ],
                                [ "Erlang REPL" ],
                                [ "GLSL" ],
                                [ "Go" ],
                                [ 'Haskell' ],
                                [ "Lisp" ],
                                [ "Lua" ],
                                [ "MEL" ],
                                [ "Markdown" ],
                                [ "Matlab" ],
                                [ "Nginx" ],
                                [ "Objective C" ],
                                [ "Parser3" ],
                                [ "Python profile" ],
                                [ "R" ],
                                [ "RenderMan RIB" ],
                                [ "RenderMan RSL" ],
                                [ "Rust" ],
                                [ "Scala" ],
                                [ "Smalltalk" ],
                                [ "TeX" ],
                                [ "VBScript" ],
                                [ "VHDL" ],
                                [ "Vala" ]
                              ],
                        'default': 'Auto',
                        onChange: function( api ) {
                        // this = CKEDITOR.ui.dialog.select
                         alert( 'Current value: ' + this.getValue() );
                        }
                    },
                    {
                        type: 'textarea',
                        id: 'pre_code',
                        rows: 22,
                        style: "width: 100%"
                        /*setup: function(data) {
                            if (data.code)
                                this.setValue(data.code);
                        },
                        commit: function(data) {
                            data.code = this.getValue();
                        }*/
                    }
                ]
            }

        ],
        onOk: function() {
            var dialog = this;

            var pre = editor.document.createElement( 'pre' );
            var code = editor.document.createElement( 'code' );
            var code_class = dialog.getValueOf( 'tab-basic', 'code_lan' ).toLowerCase();

            if(code_class !== "auto"){
                code.setAttribute( 'class', code_class );
            }

            code.setText( dialog.getValueOf( 'tab-basic', 'pre_code' ) );

            pre.append(code);

            editor.insertElement(pre);
        }
    };
});
<commit_msg>little changes<commit_after>CKEDITOR.dialog.add( 'highlight_js', function( editor ) {
    return {
        title: "test",
        minWidth: 800,
        minHeight: 500,
        contents: [
            {
                id: 'tab-basic',
                label: 'Basic Settings',
                elements: [
                    {
                        type: 'select',
                        id: 'code_lan',
                        label: 'Select code language',
                        items: [
                                [ 'Auto' ],
                                [ 'no-highlight' ],
                                [ 'Bash' ],
                                [ 'Diff' ],
                                [ 'JSON' ],
                                [ 'C#' ],
                                [ 'HTML' ],
                                [ 'JAVA' ],
                                [ 'Python' ],
                                [ 'C++' ],
                                [ 'HTTP' ],
                                [ 'JavaScript' ],
                                [ 'Ruby' ],
                                [ 'CSS' ],
                                [ 'PHP' ],
                                [ 'ini' ],
                                [ 'SQL' ],
                                [ 'Perl' ],
                                [ " 1C " ],
                                [ "AVR Assembler" ],
                                [ "ActionScript" ],
                                [ "Apache" ],
                                [ "AppleScript" ],
                                [ "Axapta" ],
                                [ "Brainfuck" ],
                                [ "CMake" ],
                                [ "Clojure" ],
                                [ "CoffeeScript" ],
                                [ "D" ],
                                [ "DOS .bat" ],
                                [ "Delphi" ],
                                [ "Django" ],
                                [ "Erlang" ],
                                [ "Erlang REPL" ],
                                [ "GLSL" ],
                                [ "Go" ],
                                [ 'Haskell' ],
                                [ "Lisp" ],
                                [ "Lua" ],
                                [ "MEL" ],
                                [ "Markdown" ],
                                [ "Matlab" ],
                                [ "Nginx" ],
                                [ "Objective C" ],
                                [ "Parser3" ],
                                [ "Python profile" ],
                                [ "R" ],
                                [ "RenderMan RIB" ],
                                [ "RenderMan RSL" ],
                                [ "Rust" ],
                                [ "Scala" ],
                                [ "Smalltalk" ],
                                [ "TeX" ],
                                [ "VBScript" ],
                                [ "VHDL" ],
                                [ "Vala" ]
                              ],
                        'default': 'Auto',
                        onChange: function( api ) {
                        // this = CKEDITOR.ui.dialog.select
                         //alert( 'Current value: ' + this.getValue() );
                        }
                    },
                    {
                        type: 'textarea',
                        id: 'pre_code',
                        rows: 22,
                        style: "width: 100%"
                        /*setup: function(data) {
                            if (data.code)
                                this.setValue(data.code);
                        },
                        commit: function(data) {
                            data.code = this.getValue();
                        }*/
                    }
                ]
            }

        ],
        onOk: function() {
            var dialog = this;

            var pre = editor.document.createElement( 'pre' );
            var code = editor.document.createElement( 'code' );
            var code_class = dialog.getValueOf( 'tab-basic', 'code_lan' ).toLowerCase();

            if(code_class !== "auto"){
                code.setAttribute( 'class', code_class );
            }

            code.setText( dialog.getValueOf( 'tab-basic', 'pre_code' ) );

            pre.append(code);

            editor.insertElement(pre);
        }
    };
});
<|endoftext|>


<commit_before>/*!
Deck JS - deck.smarkdown
Copyright (c) 2014-2014 Rémi Emonet
Licensed under the MIT license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
*/

/*
This module provides a support for a shorter syntax for slides, with a syntax that is closer to plain markdown.
TODO:
- configurize the .smark and the default duration also
- have a shortcut for {slide}?

*/

(function($, deck, undefined) {
    var $d = $(document);
    var may = function(f) {return f ? f : function() {}};
    var endsWith = function(longStr, part) {return longStr.indexOf(part, longStr.length - part.length) !== -1;}
    var REST = null;
    var startsWith = function(longStr, part) {
        if (part == "%+class:") alert(":::"+longStr+":::");
        var res = longStr.substr(0, part.length) == part;
        REST = res ? longStr.slice(part.length) : null;
        RESTRIM = res ? REST.replace(/^ */, "") : null;
        return res;
    }
    var startsWithIgnoreCase = function(longStr, part) {
        var res = longStr.substr(0, part.length).toUpperCase() == part.toUpperCase();
        REST = res ? longStr.slice(part.length) : null;
        RESTRIM = res ? REST.replace(/^ */, "") : null;
        return res;
    }

    // the animation duration is stateful across the smarkdown sections
    var animationDuration = 400;

    function clone(a) { return JSON.parse(JSON.stringify(a)) }
    function findTag(tree, regexp, startAt=0) {
        var i = startAt;
        while (i < tree.length) {
            if (Array.isArray(tree[i]) && tree[i][0].match(regexp)) {
                return i;
            }
            i++;
        }
        return -1;
    }
    function addSpaceSeparatedAttr(o, a, c) {
        ensureHasAttributes(o);
        if (o[1][a])
            o[1][a] += " " + c;
        else
            o[1][a] = c;
    }
    function addClass(o, c) {
        addSpaceSeparatedAttr(o, 'class', c);
    }
    function isObject(o) {
        return !Array.isArray(o) && typeof(o) === 'object';
    }
    function ensureHasAttributes(tree) {
        if (!isObject(tree[1])) {
            tree.splice(1, 0, {});
            return true;
        }
        return false;
    }
    function lazyGetAttributes(tree) {
        if (isObject(tree[1])) {
            return tree[1];
        } else {
            return {};
        }
    }
    function lazyUnsetAttributes(tree) {
        if (isObject(tree[1])) {
            tree.splice(1, 1);
        }
    }
    function hasIDOrClassDecoration(s) {
        return s.match(/^(.*)\{([^{}<>]*)\}$/);
    }
    function maybeProcessCopySlide(tree, index) {
        var slide = tree[index];
        ensureHasAttributes(slide);
        if (slide.length != 3) return false;
        if (slide[2][0] != "h1") return false;
        ensureHasAttributes(slide[2]);
        if (startsWithIgnoreCase(slide[2][2], "@COPY:#")) {
            var main = RESTRIM.split(/:/);
            var idOfBase = main[0];
            var animPart = main.slice(1).join(":");
            var hasAnim = ! animPart.match(/^\s*$/);
            var base = null;
            for (i in tree) {
                if (i == 0 || (i==1 && isObject(tree[1]))) continue;
                ensureHasAttributes(tree[i]);
                if (tree[i][1].id == idOfBase) {
                    base = tree[i];
                    break;
                }
            }
            if (base == null) { alert("pb"); return false; } // TODO should alert based on options
            var content = [["div", {}, "@anim:" + animPart]];
            content = Array.concat(content, clone(base.slice(2)));
            slide[1] = clone(base[1]);
            delete slide[1].id;
            if (hasAnim) addClass(slide, "anim-continue");
            slide.splice.apply(slide, Array.concat([2, 1], content)); // replace the h1 with content
            return true;
        }
        return false;
    }
    function processIDOrClassDecoration(tree, index) {
        var matched = hasIDOrClassDecoration(tree[index]); // make sure the group is set
        if (!matched) { alert("should call processIDOrClassDecoration() only if hasIDOrClassDecoration is true"); return; }
        var base = RegExp.$1;
        var decorations = RegExp.$2.split(/ +/);
        if (ensureHasAttributes(tree)) {
            if (index>0) index++;
        }
        tree[index] = base;
        for (d in decorations) {
            // allow .class and class notations
            if (startsWith(decorations[d], ".")) decorations[d] = decorations[d].slice(1);

            if (startsWith(decorations[d], "#")) {
                tree[1].id = decorations[d].slice(1);
            } else {
                if (startsWith(decorations[d], "*") | startsWith(decorations[d], "/")) {
                    addSpaceSeparatedAttr(tree, "data-container-class", decorations[d].slice(1));
                } else {
                    addClass(tree, decorations[d]);
                }
            }
        }
    }
    function possiblyHideIfEmpty(tree) { // if it contains only anim stuf etc
        var hide = false;
        var i = isObject(tree[1]) ? 2 : 1;
        function onlyDivAnims(tt) {
            var only = true;
            var start = isObject(tt[1]) ? 2 : 1;
            Array.forEach(tt.slice(start), function(e) {
                if (!Array.isArray(e) || !isObject(e[1]) || (" "+e[1]["class"]).indexOf(" anim-") == -1) {
                    only = false;
                }
            });
            return only;
        }

        if (onlyDivAnims(tree)) hide = true;
        else if (tree.length == i+1 && Array.isArray(tree[i]) && tree[i][0] == "p"
                 && onlyDivAnims(tree[i])) hide = true;
        if (hide) {
            ensureHasAttributes(tree);
            tree[1].style = "display: none";
        }
    }
    function maybeProcessComment(tree, index) {
        var line = tree[index];
        var clean = function(s) { return s;}; //return s.replace(/\/\\\//g, '//'); };
        if (line.match(/^(.*?)[\n\s]*\/\/ +(.*)/)) {
            var obj = ["div", {
                'class': "comment"
            }, clean(RegExp.$2)];
            tree.splice(index, 1, RegExp.$1, obj);
            return true;
        }
        tree[index] = clean(tree[index]);
        return false;
    }
    function maybeProcessAtSomething(tree, index) {
        var line = tree[index];
        if (startsWithIgnoreCase(line, "@SVG:")) {
            var content = RESTRIM
            var parts = content.split(/ +/);
            if (hasIDOrClassDecoration(content) || parts.length == 3) {
                // new version
                var obj = ["div", {
                    'data-src': parts[0],
                    'data-width': parts[1],
                    'data-height': parts[2],
                    'class': "svg-object"
                }, parts.slice(3).join(" ")];
                // TODO: alert when wrong number of args
                if (hasIDOrClassDecoration(content)) processIDOrClassDecoration(obj, 2);
                tree[index] = obj;
            } else {
                // TODO allow this only when an option is set option
                // old, smartsyntax version
                var obj = ["div", {
                    'data-src': parts[1],
                    'data-width': parts[2],
                    'data-height': parts[3],
                    'class': "svg-object"
                }, ""];
                Array.forEach(parts[0].split(/,/), function (p) { addClass(obj, p); });
                tree[index] = obj;
            }
        } else if (startsWithIgnoreCase(line, "@ANIM:")) {
            line = RESTRIM.replace(/%[+]/i, "%%"); // protect the "%+class" from being split
            var allToAdd = [];
            var parts = line.split(/ *\| */); // TODO: configurize + reconsider all separators?
            for (i in parts) {
                // process each group of simultaneous animations
                var subparts = parts[i].split(/ *\+ */);
                for (ii in subparts) {
                    var what = subparts[ii];
                    if (what == "") continue; // as a good side effect, this allows to set a "anim-continue" on all elements (e.g., put a + at the end of the line)
                    var continuating  = ii != subparts.length-1;
                    var toAdd = ["div", {}, ""];
                    addClass(toAdd, "slide");
                    // process the individual element (reminder: animationDuration is global)
                    function dw() { addSpaceSeparatedAttr(toAdd, "data-what", REST); }
                    function dd() { addSpaceSeparatedAttr(toAdd, "data-dur", ""+animationDuration); }
                    if (startsWithIgnoreCase(what, "%duration:")) {
                        animationDuration = RESTRIM;
                        continue;
                    } else if (startsWithIgnoreCase(what, "%dur:")) {
                        animationDuration = RESTRIM;
                        continue;
                    } else if (startsWithIgnoreCase(what, "%play:")) {
                        addClass(toAdd, "anim-play");
                        dw();
                    } else if (startsWithIgnoreCase(what, "%pause:")) {
                        addClass(toAdd, "anim-pause");
                        dw();
                    } else if (startsWith(what, "%viewbox:")) {
                        addClass(toAdd, "anim-viewboxas");
                        // TODO: if REST contains ':', two params (then the target is specified, else it is just all SVGs root elements)
                        addSpaceSeparatedAttr(toAdd, "data-as", REST);
                        addSpaceSeparatedAttr(toAdd, "data-what", "svg");
                        dd();
                    } else if (startsWith(what, "%attr:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-attribute");
                        addSpaceSeparatedAttr(toAdd, "data-what", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-attr", main.slice(1).join(":"));
                        dd();
                    } else if (startsWith(what, "%along:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-along");
                        if (startsWith(main[0], "-")) {
                            main[0] = RESTRIM;
                            addSpaceSeparatedAttr(toAdd, "data-reverse", "true");
                        }
                        addSpaceSeparatedAttr(toAdd, "data-path", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-what", main.slice(1).join(":"));
                        dd();
                    } else if (startsWith(what, "%%class:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-addclass");
                        addSpaceSeparatedAttr(toAdd, "data-class", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-what", main.slice(1).join(":"));
                    } else if (startsWith(what, "%-class:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-removeclass");
                        addSpaceSeparatedAttr(toAdd, "data-class", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-what", main.slice(1).join(":"));
                    } else if (startsWith(what, "+")) {
                        addClass(toAdd, "anim-show");
                        dw();
                    } else if (startsWith(what, "-")) {
                        addClass(toAdd, "anim-hide");
                        dw(); dd();
                    } else {
                        addClass(toAdd, "anim-show");
                        addSpaceSeparatedAttr(toAdd, "data-what", what);
                        dd();
                    }
                    if (continuating) addClass(toAdd, "anim-continue");
                    allToAdd.push(toAdd);
                }
            }
            tree.splice.apply(tree, Array.concat([index, 1], allToAdd)); // just replacing the text with allToAdd elements
        } else {
            return false;
        }
        // TODO? handle the decorations for comments
        return true;
    }
    function processMath(content) {
        return content.replace(/\$([^$][^$]*)\$/g, '\\displaystyle $1').replace(/\$\$/, '$');
    }

    var interpretationOfSmartLanguage = function(smark, doc) {
        var jstree = markdown.toHTMLTree(smark);

        // split at each h2 or h1
        (function makeTopLevelDivs(jsTree) {
            var firstIndex = findTag(jsTree, /^(h1|h2)$/);
            if (firstIndex == -1) return;
            var secondIndex = findTag(jsTree, /^(h1|h2)$/, firstIndex+1);
            if (secondIndex == -1) secondIndex = jsTree.length;
            var slide = Array.concat(
                ["section"], // we will add the 'slide' class later below
                jsTree.splice(firstIndex, secondIndex - firstIndex));
            jsTree.splice(firstIndex, 0, slide);
            makeTopLevelDivs(jsTree);
        })(jstree);

        // process:
        // - the class and id decorations like    {#first hightlight slide}
        // - the @... custom notations
        // - the // for comments
        for (s in jstree) {
            if (s == 0 || (s==1 && isObject(jstree[1]))) continue;
            var slide = jstree[s];
            ensureHasAttributes(slide);
            if (maybeProcessCopySlide(jstree, s)) {
                //continue;
                // actually we want to apply anims to it
            }
            // cleanup: first, remove first "p" in a "li" (happens when one put an empty line in a bullet list, but it would break the decorations)
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) {
                        if (tree[i][0] === "li") {
                            var li = tree[i];
                            if (Array.isArray(li[1]) && li[1][0] === "p") {
                                li.splice.apply(li, Array.concat( [1, 1], li[1].slice(1)));
                                continue;
                            }
                        }
                        patch(tree[i]);
                    }
                    i++;
                }
            })(slide);
            // process @anim... and {} decoration
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) patch(tree[i]);
                    else if (typeof(tree[i]) == 'string') {
                        if (maybeProcessComment(tree, i)) continue;
                        else if (maybeProcessAtSomething(tree, i)) continue;
                        else if (hasIDOrClassDecoration(tree[i])) processIDOrClassDecoration(tree, i);
                    }
                    i++;
                }
            })(slide);
            // cleanup: hide empty "li" after @anim processing
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) {
                        if (tree[i][0] === "li" && possiblyHideIfEmpty(tree[i])) continue;
                        else patch(tree[i]);
                    }
                    i++;
                }
            })(slide);
            // process the $math$
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) patch(tree[i]);
                    else if (typeof(tree[i]) == 'string') {
                        tree[i] = processMath(tree[i]);
                    }
                    i++;
                }
            })(slide);
            // now propagate to the slide
            var hAttributes = lazyGetAttributes(slide[2]);
            if (slide[1]['class']) {
                var cl = slide[1]['class'];
                slide[1] = clone(hAttributes);
                addClass(slide, cl);
            } else {
                slide[1] = clone(hAttributes);
            }
            lazyUnsetAttributes(slide[2]);
            addClass(slide, 'slide');
        }

        return markdown.renderJsonML(jstree);
    }

    // this have to be executed before the deck init
    $d.bind('deck.beforeInit', function() {
        $('.smark').each(function() { // TODO make it configurable
            var it = this;
            var slides = interpretationOfSmartLanguage(it.innerHTML, document);
            $(it).after(slides);
            // remove the smart node (to avoid having an empty non-slide sibling (e.g., in the presenter view))
            $(it).remove();
        });
        $[deck]('reInitSlidesArray')
    });

})(jQuery, 'deck');
<commit_msg>[smarkdown] (internal) fix default value for findTag<commit_after>/*!
Deck JS - deck.smarkdown
Copyright (c) 2014-2014 Rémi Emonet
Licensed under the MIT license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
*/

/*
This module provides a support for a shorter syntax for slides, with a syntax that is closer to plain markdown.
TODO:
- configurize the .smark and the default duration also
- have a shortcut for {slide}?

*/

(function($, deck, undefined) {
    var $d = $(document);
    var may = function(f) {return f ? f : function() {}};
    var endsWith = function(longStr, part) {return longStr.indexOf(part, longStr.length - part.length) !== -1;}
    var REST = null;
    var startsWith = function(longStr, part) {
        if (part == "%+class:") alert(":::"+longStr+":::");
        var res = longStr.substr(0, part.length) == part;
        REST = res ? longStr.slice(part.length) : null;
        RESTRIM = res ? REST.replace(/^ */, "") : null;
        return res;
    }
    var startsWithIgnoreCase = function(longStr, part) {
        var res = longStr.substr(0, part.length).toUpperCase() == part.toUpperCase();
        REST = res ? longStr.slice(part.length) : null;
        RESTRIM = res ? REST.replace(/^ */, "") : null;
        return res;
    }

    // the animation duration is stateful across the smarkdown sections
    var animationDuration = 400;

    function clone(a) { return JSON.parse(JSON.stringify(a)) }
    function findTag(tree, regexp, startAt) {
        var i = startAt || 0;
        while (i < tree.length) {
            if (Array.isArray(tree[i]) && tree[i][0].match(regexp)) {
                return i;
            }
            i++;
        }
        return -1;
    }
    function addSpaceSeparatedAttr(o, a, c) {
        ensureHasAttributes(o);
        if (o[1][a])
            o[1][a] += " " + c;
        else
            o[1][a] = c;
    }
    function addClass(o, c) {
        addSpaceSeparatedAttr(o, 'class', c);
    }
    function isObject(o) {
        return !Array.isArray(o) && typeof(o) === 'object';
    }
    function ensureHasAttributes(tree) {
        if (!isObject(tree[1])) {
            tree.splice(1, 0, {});
            return true;
        }
        return false;
    }
    function lazyGetAttributes(tree) {
        if (isObject(tree[1])) {
            return tree[1];
        } else {
            return {};
        }
    }
    function lazyUnsetAttributes(tree) {
        if (isObject(tree[1])) {
            tree.splice(1, 1);
        }
    }
    function hasIDOrClassDecoration(s) {
        return s.match(/^(.*)\{([^{}<>]*)\}$/);
    }
    function maybeProcessCopySlide(tree, index) {
        var slide = tree[index];
        ensureHasAttributes(slide);
        if (slide.length != 3) return false;
        if (slide[2][0] != "h1") return false;
        ensureHasAttributes(slide[2]);
        if (startsWithIgnoreCase(slide[2][2], "@COPY:#")) {
            var main = RESTRIM.split(/:/);
            var idOfBase = main[0];
            var animPart = main.slice(1).join(":");
            var hasAnim = ! animPart.match(/^\s*$/);
            var base = null;
            for (i in tree) {
                if (i == 0 || (i==1 && isObject(tree[1]))) continue;
                ensureHasAttributes(tree[i]);
                if (tree[i][1].id == idOfBase) {
                    base = tree[i];
                    break;
                }
            }
            if (base == null) { alert("pb"); return false; } // TODO should alert based on options
            var content = [["div", {}, "@anim:" + animPart]];
            content = Array.concat(content, clone(base.slice(2)));
            slide[1] = clone(base[1]);
            delete slide[1].id;
            if (hasAnim) addClass(slide, "anim-continue");
            slide.splice.apply(slide, Array.concat([2, 1], content)); // replace the h1 with content
            return true;
        }
        return false;
    }
    function processIDOrClassDecoration(tree, index) {
        var matched = hasIDOrClassDecoration(tree[index]); // make sure the group is set
        if (!matched) { alert("should call processIDOrClassDecoration() only if hasIDOrClassDecoration is true"); return; }
        var base = RegExp.$1;
        var decorations = RegExp.$2.split(/ +/);
        if (ensureHasAttributes(tree)) {
            if (index>0) index++;
        }
        tree[index] = base;
        for (d in decorations) {
            // allow .class and class notations
            if (startsWith(decorations[d], ".")) decorations[d] = decorations[d].slice(1);

            if (startsWith(decorations[d], "#")) {
                tree[1].id = decorations[d].slice(1);
            } else {
                if (startsWith(decorations[d], "*") | startsWith(decorations[d], "/")) {
                    addSpaceSeparatedAttr(tree, "data-container-class", decorations[d].slice(1));
                } else {
                    addClass(tree, decorations[d]);
                }
            }
        }
    }
    function possiblyHideIfEmpty(tree) { // if it contains only anim stuf etc
        var hide = false;
        var i = isObject(tree[1]) ? 2 : 1;
        function onlyDivAnims(tt) {
            var only = true;
            var start = isObject(tt[1]) ? 2 : 1;
            Array.forEach(tt.slice(start), function(e) {
                if (!Array.isArray(e) || !isObject(e[1]) || (" "+e[1]["class"]).indexOf(" anim-") == -1) {
                    only = false;
                }
            });
            return only;
        }

        if (onlyDivAnims(tree)) hide = true;
        else if (tree.length == i+1 && Array.isArray(tree[i]) && tree[i][0] == "p"
                 && onlyDivAnims(tree[i])) hide = true;
        if (hide) {
            ensureHasAttributes(tree);
            tree[1].style = "display: none";
        }
    }
    function maybeProcessComment(tree, index) {
        var line = tree[index];
        var clean = function(s) { return s;}; //return s.replace(/\/\\\//g, '//'); };
        if (line.match(/^(.*?)[\n\s]*\/\/ +(.*)/)) {
            var obj = ["div", {
                'class': "comment"
            }, clean(RegExp.$2)];
            tree.splice(index, 1, RegExp.$1, obj);
            return true;
        }
        tree[index] = clean(tree[index]);
        return false;
    }
    function maybeProcessAtSomething(tree, index) {
        var line = tree[index];
        if (startsWithIgnoreCase(line, "@SVG:")) {
            var content = RESTRIM
            var parts = content.split(/ +/);
            if (hasIDOrClassDecoration(content) || parts.length == 3) {
                // new version
                var obj = ["div", {
                    'data-src': parts[0],
                    'data-width': parts[1],
                    'data-height': parts[2],
                    'class': "svg-object"
                }, parts.slice(3).join(" ")];
                // TODO: alert when wrong number of args
                if (hasIDOrClassDecoration(content)) processIDOrClassDecoration(obj, 2);
                tree[index] = obj;
            } else {
                // TODO allow this only when an option is set option
                // old, smartsyntax version
                var obj = ["div", {
                    'data-src': parts[1],
                    'data-width': parts[2],
                    'data-height': parts[3],
                    'class': "svg-object"
                }, ""];
                Array.forEach(parts[0].split(/,/), function (p) { addClass(obj, p); });
                tree[index] = obj;
            }
        } else if (startsWithIgnoreCase(line, "@ANIM:")) {
            line = RESTRIM.replace(/%[+]/i, "%%"); // protect the "%+class" from being split
            var allToAdd = [];
            var parts = line.split(/ *\| */); // TODO: configurize + reconsider all separators?
            for (i in parts) {
                // process each group of simultaneous animations
                var subparts = parts[i].split(/ *\+ */);
                for (ii in subparts) {
                    var what = subparts[ii];
                    if (what == "") continue; // as a good side effect, this allows to set a "anim-continue" on all elements (e.g., put a + at the end of the line)
                    var continuating  = ii != subparts.length-1;
                    var toAdd = ["div", {}, ""];
                    addClass(toAdd, "slide");
                    // process the individual element (reminder: animationDuration is global)
                    function dw() { addSpaceSeparatedAttr(toAdd, "data-what", REST); }
                    function dd() { addSpaceSeparatedAttr(toAdd, "data-dur", ""+animationDuration); }
                    if (startsWithIgnoreCase(what, "%duration:")) {
                        animationDuration = RESTRIM;
                        continue;
                    } else if (startsWithIgnoreCase(what, "%dur:")) {
                        animationDuration = RESTRIM;
                        continue;
                    } else if (startsWithIgnoreCase(what, "%play:")) {
                        addClass(toAdd, "anim-play");
                        dw();
                    } else if (startsWithIgnoreCase(what, "%pause:")) {
                        addClass(toAdd, "anim-pause");
                        dw();
                    } else if (startsWith(what, "%viewbox:")) {
                        addClass(toAdd, "anim-viewboxas");
                        // TODO: if REST contains ':', two params (then the target is specified, else it is just all SVGs root elements)
                        addSpaceSeparatedAttr(toAdd, "data-as", REST);
                        addSpaceSeparatedAttr(toAdd, "data-what", "svg");
                        dd();
                    } else if (startsWith(what, "%attr:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-attribute");
                        addSpaceSeparatedAttr(toAdd, "data-what", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-attr", main.slice(1).join(":"));
                        dd();
                    } else if (startsWith(what, "%along:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-along");
                        if (startsWith(main[0], "-")) {
                            main[0] = RESTRIM;
                            addSpaceSeparatedAttr(toAdd, "data-reverse", "true");
                        }
                        addSpaceSeparatedAttr(toAdd, "data-path", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-what", main.slice(1).join(":"));
                        dd();
                    } else if (startsWith(what, "%%class:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-addclass");
                        addSpaceSeparatedAttr(toAdd, "data-class", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-what", main.slice(1).join(":"));
                    } else if (startsWith(what, "%-class:")) {
                        var main = RESTRIM.split(/ *: */);
                        addClass(toAdd, "anim-removeclass");
                        addSpaceSeparatedAttr(toAdd, "data-class", main[0]);
                        addSpaceSeparatedAttr(toAdd, "data-what", main.slice(1).join(":"));
                    } else if (startsWith(what, "+")) {
                        addClass(toAdd, "anim-show");
                        dw();
                    } else if (startsWith(what, "-")) {
                        addClass(toAdd, "anim-hide");
                        dw(); dd();
                    } else {
                        addClass(toAdd, "anim-show");
                        addSpaceSeparatedAttr(toAdd, "data-what", what);
                        dd();
                    }
                    if (continuating) addClass(toAdd, "anim-continue");
                    allToAdd.push(toAdd);
                }
            }
            tree.splice.apply(tree, Array.concat([index, 1], allToAdd)); // just replacing the text with allToAdd elements
        } else {
            return false;
        }
        // TODO? handle the decorations for comments
        return true;
    }
    function processMath(content) {
        return content.replace(/\$([^$][^$]*)\$/g, '\\displaystyle $1').replace(/\$\$/, '$');
    }

    var interpretationOfSmartLanguage = function(smark, doc) {
        var jstree = markdown.toHTMLTree(smark);

        // split at each h2 or h1
        (function makeTopLevelDivs(jsTree) {
            var firstIndex = findTag(jsTree, /^(h1|h2)$/);
            if (firstIndex == -1) return;
            var secondIndex = findTag(jsTree, /^(h1|h2)$/, firstIndex+1);
            if (secondIndex == -1) secondIndex = jsTree.length;
            var slide = Array.concat(
                ["section"], // we will add the 'slide' class later below
                jsTree.splice(firstIndex, secondIndex - firstIndex));
            jsTree.splice(firstIndex, 0, slide);
            makeTopLevelDivs(jsTree);
        })(jstree);

        // process:
        // - the class and id decorations like    {#first hightlight slide}
        // - the @... custom notations
        // - the // for comments
        for (s in jstree) {
            if (s == 0 || (s==1 && isObject(jstree[1]))) continue;
            var slide = jstree[s];
            ensureHasAttributes(slide);
            if (maybeProcessCopySlide(jstree, s)) {
                //continue;
                // actually we want to apply anims to it
            }
            // cleanup: first, remove first "p" in a "li" (happens when one put an empty line in a bullet list, but it would break the decorations)
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) {
                        if (tree[i][0] === "li") {
                            var li = tree[i];
                            if (Array.isArray(li[1]) && li[1][0] === "p") {
                                li.splice.apply(li, Array.concat( [1, 1], li[1].slice(1)));
                                continue;
                            }
                        }
                        patch(tree[i]);
                    }
                    i++;
                }
            })(slide);
            // process @anim... and {} decoration
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) patch(tree[i]);
                    else if (typeof(tree[i]) == 'string') {
                        if (maybeProcessComment(tree, i)) continue;
                        else if (maybeProcessAtSomething(tree, i)) continue;
                        else if (hasIDOrClassDecoration(tree[i])) processIDOrClassDecoration(tree, i);
                    }
                    i++;
                }
            })(slide);
            // cleanup: hide empty "li" after @anim processing
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) {
                        if (tree[i][0] === "li" && possiblyHideIfEmpty(tree[i])) continue;
                        else patch(tree[i]);
                    }
                    i++;
                }
            })(slide);
            // process the $math$
            (function patch(tree){ // tree is slide or a subelement
                var i = 1;
                while (i < tree.length) {
                    if (Array.isArray(tree[i])) patch(tree[i]);
                    else if (typeof(tree[i]) == 'string') {
                        tree[i] = processMath(tree[i]);
                    }
                    i++;
                }
            })(slide);
            // now propagate to the slide
            var hAttributes = lazyGetAttributes(slide[2]);
            if (slide[1]['class']) {
                var cl = slide[1]['class'];
                slide[1] = clone(hAttributes);
                addClass(slide, cl);
            } else {
                slide[1] = clone(hAttributes);
            }
            lazyUnsetAttributes(slide[2]);
            addClass(slide, 'slide');
        }

        return markdown.renderJsonML(jstree);
    }

    // this have to be executed before the deck init
    $d.bind('deck.beforeInit', function() {
        $('.smark').each(function() { // TODO make it configurable
            var it = this;
            var slides = interpretationOfSmartLanguage(it.innerHTML, document);
            $(it).after(slides);
            // remove the smart node (to avoid having an empty non-slide sibling (e.g., in the presenter view))
            $(it).remove();
        });
        $[deck]('reInitSlidesArray')
    });

})(jQuery, 'deck');
<|endoftext|>


<commit_before>// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	// A fully qualified URL to the Intern proxy
	proxyUrl: 'http://localhost:9000/',

	// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
	// specified browser environments in the `environments` array below as well. See
	// https://code.google.com/p/selenium/wiki/DesiredCapabilities for standard Selenium capabilities and
	// https://saucelabs.com/docs/additional-config#desired-capabilities for Sauce Labs capabilities.
	// Note that the `build` capability will be filled in with the current commit ID from the Travis CI environment
	// automatically
	capabilities: {
		'selenium-version': '2.41.0'
	},

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Name of the tunnel class to use for WebDriver tests
	tunnel: 'SauceLabsTunnel',

	// The desired AMD loader to use when running unit tests (client.html/client.js). Omit to use the default Dojo
	// loader
	useLoader: {
		'host-node': 'dojo/dojo',
		'host-browser': 'node_modules/dojo/dojo.js'
	},

	// Configuration options for the module loader; any AMD configuration options supported by the specified AMD loader
	// can be used here
	loader: {
		// Packages that should be registered with the loader in each testing environment
		packages: [
			{
				name: 'angular', location: 'client/src/bower_components/angular'
			},
			{
				name: 'angular-mocks', location: 'client/src/bower_components/angular-mocks'
			}
		]
	},

	// Non-functional test suite(s) to run in each browser
	suites: [
		'tests/server/wifi-tool'
	],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation: /^(?:tests|client\/src\/bower_components|node_modules)\//
});
<commit_msg>Cleaning server intern config file<commit_after>// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	// A fully qualified URL to the Intern proxy
	proxyUrl: 'http://localhost:9000/',

	// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
	// specified browser environments in the `environments` array below as well. See
	// https://code.google.com/p/selenium/wiki/DesiredCapabilities for standard Selenium capabilities and
	// https://saucelabs.com/docs/additional-config#desired-capabilities for Sauce Labs capabilities.
	// Note that the `build` capability will be filled in with the current commit ID from the Travis CI environment
	// automatically
	capabilities: {
		'selenium-version': '2.41.0'
	},

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Name of the tunnel class to use for WebDriver tests
	tunnel: 'SauceLabsTunnel',

	// The desired AMD loader to use when running unit tests (client.html/client.js). Omit to use the default Dojo
	// loader
	useLoader: {
		'host-node': 'dojo/dojo',
		'host-browser': 'node_modules/dojo/dojo.js'
	},

	// Non-functional test suite(s) to run in each browser
	suites: [
		'tests/server/wifi-tool'
	],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation: /^(?:tests|client\/src\/bower_components|node_modules)\//
});
<|endoftext|>


<commit_before>/**
 * Geojson2Wkt
 * @author Oliver Roick <https://github.com/oliverroick>
 * @version 0.0.1
 * Date: 11/14/2012
 * Homepage: https://github.com/oliverroick/geo-converter
 */

/*
 * Constructor
 */

function Geojson2Wkt () {
	if (Geojson2Wkt.caller != Geojson2Wkt.getInstance) throw new Error("This object cannot be instanciated");
}

/*
 * Returns string containing the coordinates of a point geometry
 * @function
 * @private
 */
Geojson2Wkt.parsePointGeometry = function (coordinates) {
	return [coordinates[0], coordinates[1]].join(' ');
};

/*
 * Returns string containing the coordinates of a line geometry. Breaks coordinates array into single
 * latitude-/longitude pairs and uses parsePointGeometry to parse node.
 * @function
 * @private
 */
Geojson2Wkt.parseLineGeometry = function (coordinates) {
	var lineWkt = [];
	for (var i = 0; i < coordinates.length; i++) {
		if (i > 0) lineWkt.push(', ');
		lineWkt.push(this.parsePointGeometry(coordinates[i]));
	}
	return lineWkt.join('');
};

/*
 * Returns string containing the coordinates of a polygon geometry. Breaks linstring array into single
 * latitude-/longitude pairs and uses parseLineGeometry to parse line segments.
 * @function
 * @private
 */
Geojson2Wkt.parsePolygonGeometry = function (coordinates) {
	var polygonWkt = [];
	for (var i = 0; i < coordinates.length; i++) {
		polygonWkt.push('(');
		if (i > 0) polygonWkt.push(', ');
		polygonWkt.push(this.parseLineGeometry(coordinates[i]));
		polygonWkt.push(')');
	}
	return polygonWkt.join('');
};

/*
 * Returns string WKT represenation of the GeoJSON geometry passed to the method.
 *
 * @param json {string|object} The GeoJSON gemetry to be parsed.
 *
 */
Geojson2Wkt.prototype.convert = function (json) {
		var wkt = [], coordinates;

		if (!json) new Error('No geojson object passed to the method.');

		// check if JSON is passed as String and convert to object
		if (typeof json.coordinates === 'string') coordinates = JSON.parse(json.coordinates);
			else coordinates = json.coordinates;

		switch (json.type) {
			case 'Point':
				wkt.push('POINT(');
				wkt.push(this.parsePointGeometry(coordinates));
				wkt.push(')');
				break;
			case 'LineString':
				wkt.push('LINETSTRING(');
				wkt.push(this.parseLineGeometry(coordinates));
				wkt.push(')');
				break;
			case 'Polygon':
				wkt.push('POLYGON(');
				wkt.push(this.parsePolygonGeometry(coordinates));
				wkt.push(')');
				break;
			default:
				throw new Error('Not able to parse geometry. Property type not set in GeoJSON object.');
		}
		return wkt.join('');
}

/* ************************************************************************
SINGLETON CLASS DEFINITION
************************************************************************ */

Geojson2Wkt.instance = null;

/**
 * Singleton getInstance definition
 * @return singleton class
 */

Geojson2Wkt.getInstance = function () {
    if(this.instance === null) this.instance = new Geojson2Wkt();
    return this.instance;
}

module.exports = Geojson2Wkt.getInstance();<commit_msg>Minor changes<commit_after>/**
 * Geojson2Wkt
 * @author Oliver Roick <https://github.com/oliverroick>
 * @version 0.0.1
 * Date: 11/14/2012
 * Homepage: https://github.com/oliverroick/geo-converter
 */

/*
 * Constructor
 */

function Geojson2Wkt () {
	if (Geojson2Wkt.caller != Geojson2Wkt.getInstance) throw new Error("This object cannot be instanciated");
}

/*
 * Returns string containing the coordinates of a point geometry
 * @function
 * @private
 */
Geojson2Wkt.parsePointGeometry = function (coordinates) {
	return [coordinates[0], coordinates[1]].join(' ');
};

/*
 * Returns string containing the coordinates of a line geometry. Breaks coordinates array into single
 * latitude-/longitude pairs and uses parsePointGeometry to parse node.
 * @function
 * @private
 */
Geojson2Wkt.parseLineGeometry = function (coordinates) {
	var lineWkt = [];
	for (var i = 0; i < coordinates.length; i++) {
		if (i > 0) lineWkt.push(', ');
		lineWkt.push(this.parsePointGeometry(coordinates[i]));
	}
	return lineWkt.join('');
};

/*
 * Returns string containing the coordinates of a polygon geometry. Breaks linstring array into single
 * latitude-/longitude pairs and uses parseLineGeometry to parse line segments.
 * @function
 * @private
 */
Geojson2Wkt.parsePolygonGeometry = function (coordinates) {
	var polygonWkt = [];
	for (var i = 0; i < coordinates.length; i++) {
		polygonWkt.push('(');
		if (i > 0) polygonWkt.push(', ');
		polygonWkt.push(this.parseLineGeometry(coordinates[i]));
		polygonWkt.push(')');
	}
	return polygonWkt.join('');
};

/*
 * Returns string WKT represenation of the GeoJSON geometry passed to the method.
 *
 * @param json {string|object} The GeoJSON gemetry to be parsed.
 *
 */
Geojson2Wkt.prototype.convert = function (json) {
	var wkt = [], coordinates;

	if (!json) new Error('No geojson object passed to the method.');

	// check if JSON is passed as String and convert to object
	if (typeof json.coordinates === 'string') coordinates = JSON.parse(json.coordinates);
		else coordinates = json.coordinates;

	switch (json.type) {
		case 'Point':
			wkt.push('POINT(');
			wkt.push(this.parsePointGeometry(coordinates));
			wkt.push(')');
			break;
		case 'LineString':
			wkt.push('LINETSTRING(');
			wkt.push(this.parseLineGeometry(coordinates));
			wkt.push(')');
			break;
		case 'Polygon':
			wkt.push('POLYGON(');
			wkt.push(this.parsePolygonGeometry(coordinates));
			wkt.push(')');
			break;
		default:
			throw new Error('Not able to parse geometry. Property type not set in GeoJSON object.');
	}
	return wkt.join('');
}

/* ************************************************************************
SINGLETON CLASS DEFINITION
************************************************************************ */

Geojson2Wkt.instance = null;

/**
 * Singleton getInstance definition
 * @return singleton class
 */

Geojson2Wkt.getInstance = function () {
    if(this.instance === null) this.instance = new Geojson2Wkt();
    return this.instance;
}

module.exports = Geojson2Wkt.getInstance();<|endoftext|>


<commit_before>var favouriteReads = JSON.stringify( require( "../data/person-favourite-reads.json" ) );
var dataWithNesting = JSON.stringify( require( "../data/data-with-nesting.json" ) );
var ldQuery = require( "../../src/ld-query" );
var should = require( "should" );

module.exports = function() {

     // a fallback for missing Array.isArray
    var isArray = Array.isArray || function( arg ) {

        return Object.prototype.toString.call( arg ) === "[object Array]";

    };

    this.Given(/^the sample data containing favourite reads is loaded$/, function () {

        this.data = JSON.parse( favouriteReads );

    } );

    this.Given(/^the sample data containing recursive constructs is loaded$/, function () {

         this.data = JSON.parse( dataWithNesting );

    } );

    this.Given(/^I construct an ldQuery object using <context>$/, function (table) {

        this.context = JSON.parse( table.hashes()[ 0 ].context );
        this.query = ldQuery( this.data, this.context );

    } );

    this.When(/^I query for( all)? "([^"]*)"$/, function ( isAll, selector ) {

        this.result = isAll ? this.query.queryAll( selector ) : this.query.query( selector );

    } );

    this.When( /^then I query the result for( all)? "([^"]*)"$/, function (isAll, selector ) {

        if ( this.result.isFinal )  {

            throw new Error( "Result was final - can't query any further" );

        }
        const querySite = [].concat( this.result || [] )[ 0 ];
        this.result = isAll ? querySite.queryAll( selector ) : querySite.query( selector );

    } );

    this.Then(/^the result should be a QueryNode object$/, function() {

        should.exist( this.result, "No query object found" );
        should.exist( this.result.query, "No query method found" );
        should.exist( this.result.queryAll, "No queryAll method found" );

    } );

    this.Then(/^the result should be "([^"]*)"$/, function( expected ) {

        this.result.should.eql( expected );

    } );

    this.When(/^I query the result for "([^"]*)"$/, function( selector ) {

        this.result = this.result.query( selector );

    } );

    this.When(/^I get the result's json$/, function () {

       this.json = this.result.json();

    } );

    this.Then(/^the json should match$/, function (table) {

        var actual = JSON.stringify( JSON.parse( table.hashes()[ 0 ].json ) );
        var expected = JSON.stringify( this.json );
        actual.should.match( expected );

    } );

    this.Then(/^the result should be an array of (\d+) QueryNodes$/, function ( nodeCount ) {

        should.exist( this.result, "No query list object found" );
        this.result.length.should.eql( parseInt( nodeCount ) );
        if ( nodeCount > 0 ) {

            var sample = this.result[ 0 ];
            should.exist( sample.query, "No query method found" );
            should.exist( sample.queryAll, "No queryAll method found" );

        }

    } );

    this.Then(/^the result should be an array (\[ [^\]]* \])$/, function ( csv ) {

        var expected = JSON.stringify( JSON.parse( csv ) );
        var actual = JSON.stringify( this.result );
        actual.should.eql( expected );

    } );

    this.When(/^I get the json for each result$/, function () {

        this.json = this.result.map( queryNode => queryNode.json() );

    } );

    this.Then(/^the the first json should match$/, function ( table ) {

        var expected = JSON.stringify( JSON.parse( table.hashes()[ 0 ].json ) );
        var actual = JSON.stringify( this.json[ 0 ] );
        actual.should.match( expected );

    } );

    this.Then(/^the second json should match$/, function ( table ) {

        var expected = JSON.stringify( JSON.parse( table.hashes()[ 0 ].json ) );
        var actual = JSON.stringify( this.json[ 1 ] );
        actual.should.match( expected );

    } );

};
<commit_msg>Removing use of fat arrow, which is breaking travis checks<commit_after>var favouriteReads = JSON.stringify( require( "../data/person-favourite-reads.json" ) );
var dataWithNesting = JSON.stringify( require( "../data/data-with-nesting.json" ) );
var ldQuery = require( "../../src/ld-query" );
var should = require( "should" );

module.exports = function() {

     // a fallback for missing Array.isArray
    var isArray = Array.isArray || function( arg ) {

        return Object.prototype.toString.call( arg ) === "[object Array]";

    };

    this.Given(/^the sample data containing favourite reads is loaded$/, function () {

        this.data = JSON.parse( favouriteReads );

    } );

    this.Given(/^the sample data containing recursive constructs is loaded$/, function () {

         this.data = JSON.parse( dataWithNesting );

    } );

    this.Given(/^I construct an ldQuery object using <context>$/, function (table) {

        this.context = JSON.parse( table.hashes()[ 0 ].context );
        this.query = ldQuery( this.data, this.context );

    } );

    this.When(/^I query for( all)? "([^"]*)"$/, function ( isAll, selector ) {

        this.result = isAll ? this.query.queryAll( selector ) : this.query.query( selector );

    } );

    this.When( /^then I query the result for( all)? "([^"]*)"$/, function (isAll, selector ) {

        if ( this.result.isFinal )  {

            throw new Error( "Result was final - can't query any further" );

        }
        var querySite = [].concat( this.result || [] )[ 0 ];
        this.result = isAll ? querySite.queryAll( selector ) : querySite.query( selector );

    } );

    this.Then(/^the result should be a QueryNode object$/, function() {

        should.exist( this.result, "No query object found" );
        should.exist( this.result.query, "No query method found" );
        should.exist( this.result.queryAll, "No queryAll method found" );

    } );

    this.Then(/^the result should be "([^"]*)"$/, function( expected ) {

        this.result.should.eql( expected );

    } );

    this.When(/^I query the result for "([^"]*)"$/, function( selector ) {

        this.result = this.result.query( selector );

    } );

    this.When(/^I get the result's json$/, function () {

       this.json = this.result.json();

    } );

    this.Then(/^the json should match$/, function (table) {

        var actual = JSON.stringify( JSON.parse( table.hashes()[ 0 ].json ) );
        var expected = JSON.stringify( this.json );
        actual.should.match( expected );

    } );

    this.Then(/^the result should be an array of (\d+) QueryNodes$/, function ( nodeCount ) {

        should.exist( this.result, "No query list object found" );
        this.result.length.should.eql( parseInt( nodeCount ) );
        if ( nodeCount > 0 ) {

            var sample = this.result[ 0 ];
            should.exist( sample.query, "No query method found" );
            should.exist( sample.queryAll, "No queryAll method found" );

        }

    } );

    this.Then(/^the result should be an array (\[ [^\]]* \])$/, function ( csv ) {

        var expected = JSON.stringify( JSON.parse( csv ) );
        var actual = JSON.stringify( this.result );
        actual.should.eql( expected );

    } );

    this.When(/^I get the json for each result$/, function () {

        this.json = this.result.map( function( queryNode ) { return queryNode.json() } );

    } );

    this.Then(/^the the first json should match$/, function ( table ) {

        var expected = JSON.stringify( JSON.parse( table.hashes()[ 0 ].json ) );
        var actual = JSON.stringify( this.json[ 0 ] );
        actual.should.match( expected );

    } );

    this.Then(/^the second json should match$/, function ( table ) {

        var expected = JSON.stringify( JSON.parse( table.hashes()[ 0 ].json ) );
        var actual = JSON.stringify( this.json[ 1 ] );
        actual.should.match( expected );

    } );

};
<|endoftext|>


<commit_before>angular.module("fifaworldcup", [
	"ngRoute",
	"matchesControllers",
	"teamsModule",
	"playersModule"
])
.config(["$routeProvider", function($routeProvider) {
	$routeProvider
	.when("/", {
		templateUrl: "template/home.html"
	})
	.when("/teams", {
		controller: "teamsController",
		templateUrl: "template/teams.html"
	})
	.when("/players", {
		controller: "playersController",
		templateUrl: "template/players.html"
	});
}]);<commit_msg>step-02 : added common handling for 401 in XHR call<commit_after>angular.module("fifaworldcup", [
	"ngRoute",
	"matchesControllers",
	"teamsModule",
	"playersModule"
])
.config(["$routeProvider", function($routeProvider) {
	$routeProvider
	.when("/", {
		templateUrl: "template/home.html"
	})
	.when("/teams", {
		controller: "teamsController",
		templateUrl: "template/teams.html"
	})
	.when("/players", {
		controller: "playersController",
		templateUrl: "template/players.html"
	});
}])
.config(["$httpProvider", function($httpProvider) {
	$httpProvider.interceptors.push(['$q', '$location','$rootScope', function($q, $location, $rootScope) {
		return {
			'responseError' : function(rejection) {
				if(rejection.status == 401) {
					window.location.href = "/fifaworldcup/readytoplay";
				}
				return $q.reject(rejection);
			}
		}
	}]);
}]);<|endoftext|>


<commit_before><commit_msg>Update project validator to 4.6.1<commit_after><|endoftext|>


<commit_before>var roleBuilder = require('role.builder');

module.exports = {
  run: function(creep) {
    if (creep.spawning === false) {
      var numEnergySources = 2;
      if (creep.memory.sourcenum == undefined || creep.memory.sourcenum > 1) {
        // var numEnergySources = creep.room.lookForAtArea(LOOK_SOURCES, 0, 0, 49, 49, true).length;
        creep.memory.sourcenum = Math.floor(Math.random() * (numEnergySources + 1));
      }
      if (creep.memory.working === true) {
        if (creep.carry.energy === 0) {
          creep.memory.working = false;
        }
        var target = undefined;
        // This creates 11 possible percentages.
        for (let percentage = 0.0001; percentage <= 1; percentage = percentage * 2.782559402206) {
          let minHitsWalls = (300 * 1000 * 1000) * percentage;
          let minHitsRamparts = (300 * 1000 * 1000) * percentage;
          target = creep.pos.findClosestByPath(FIND_STRUCTURES, {
            filter: (s) => {
              return (s.structureType === STRUCTURE_RAMPART && s.hits < minHitsRamparts && s.hits < s.hitsMax) ||
                (s.structureType === STRUCTURE_WALL && s.hits < minHitsWalls && s.hits < s.hitsMax);
            }
          });
          if (target) {
            break;
          }
        }
        if (target) {
          if (creep.repair(target) === ERR_NOT_IN_RANGE) {
            creep.moveTo(target);
          }
        } else {
          roleBuilder.run(creep);
        }
      } else {
        if (creep.carry.energy === creep.carryCapacity) {
          creep.memory.working = true;
        }
        var targets = creep.room.find(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType === STRUCTURE_CONTAINER ||
              structure.structureType === STRUCTURE_STORAGE) &&
              structure.store.energy > creep.carryCapacity;
          }
        });
        if (targets.length > 0) {
          var source = targets[0];
          if (creep.withdraw(source, RESOURCE_ENERGY, creep.carryCapacity - creep.carry) === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          }
        } else {
          var source = creep.room.find(FIND_SOURCES)[creep.memory.sourcenum];
          if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          }
        }
      }
    }
  }
};
<commit_msg>Keep out of enemies distance when repairing<commit_after>var roleBuilder = require('role.builder');

module.exports = {
  run: function(creep) {
    if (creep.spawning === false) {
      var numEnergySources = 2;
      if (creep.memory.sourcenum == undefined || creep.memory.sourcenum > 1) {
        // var numEnergySources = creep.room.lookForAtArea(LOOK_SOURCES, 0, 0, 49, 49, true).length;
        creep.memory.sourcenum = Math.floor(Math.random() * (numEnergySources + 1));
      }
      if (creep.memory.working === true) {
        if (creep.carry.energy === 0) {
          creep.memory.working = false;
        }
        var target = undefined;
        // This creates 11 possible percentages.
        for (let percentage = 0.0001; percentage <= 1; percentage = percentage * 2.782559402206) {
          let minHitsWalls = (300 * 1000 * 1000) * percentage;
          let minHitsRamparts = (300 * 1000 * 1000) * percentage;
          target = creep.pos.findClosestByPath(FIND_STRUCTURES, {
            filter: (s) => {
              return (s.structureType === STRUCTURE_RAMPART && s.hits < minHitsRamparts && s.hits < s.hitsMax) ||
                (s.structureType === STRUCTURE_WALL && s.hits < minHitsWalls && s.hits < s.hitsMax);
            }
          });
          if (target) {
            break;
          }
        }
        if (target) {
          if (creep.pos.findInRange(FIND_HOSTILE_CREEPS, 4).length === 0) {
            if (creep.repair(target) === ERR_NOT_IN_RANGE) {
              creep.moveTo(target);
            }
          } else {
            creep.moveTo(Game.spawns.Spawn1.pos);
          }
        } else {
          roleBuilder.run(creep);
        }
      } else {
        if (creep.carry.energy === creep.carryCapacity) {
          creep.memory.working = true;
        }
        var targets = creep.room.find(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType === STRUCTURE_CONTAINER ||
              structure.structureType === STRUCTURE_STORAGE) &&
              structure.store.energy > creep.carryCapacity;
          }
        });
        if (targets.length > 0) {
          var source = targets[0];
          if (creep.withdraw(source, RESOURCE_ENERGY, creep.carryCapacity - creep.carry) === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          }
        } else {
          var source = creep.room.find(FIND_SOURCES)[creep.memory.sourcenum];
          if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          }
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>FACING = ["up", "left", "down", "right"];

function DrawnRobot(){
  imgElement = document.getElementById('robot-icon');
  this.body = new fabric.Image(imgElement, {
    left: 200,
    top: 390,
    fill: '#006569',
    width: 20,
    height: 20,
    originX: 'center',
    originY: 'center',
    selectable: false,
    crashed: false
  });
  this.facing =  FACING[0];
  this.canvas = new fabric.Canvas('myCanvas');
  this.queuedInstructions = [];
}

DrawnRobot.prototype.doTheseFrames = function(instructionsArr){
  this.queuedInstructions = instructionsArr;
};

DrawnRobot.prototype.getNextInstruction = function(){
  var robot = this;
  if(robot.queuedInstructions.length > 0){
    console.log("Number of instructions left: " + robot.queuedInstructions.length);
    eval(robot.queuedInstructions.shift());
  }else{
      $(".game-console-button").show();
      $(".hint-link").show();
      $(".challenge-navigation a").show();
  }

};

DrawnRobot.prototype.setFacingRight = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex -= 1;
  if (facingIndex === -1) {
      facingIndex = 3;
  }
  this.facing = FACING[facingIndex];
};

DrawnRobot.prototype.setFacingLeft = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex += 1;
  if (facingIndex === 4) {
      facingIndex = 0;
  }
  this.facing = FACING[facingIndex];
  console.log(this.facing);
};

DrawnRobot.prototype.turnLeft = function(){
  var canvas = this.canvas;
  var robot = this;
  robot.setFacingLeft();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '-=90', canvasData);
};

DrawnRobot.prototype.turnRight = function(){
  var robot = this;
  var canvas = this.canvas;
  robot.setFacingRight();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '+=90', canvasData);
  // console.log(this.facing);
};

DrawnRobot.prototype.upInSmoke = function(){
  var robot = this;
  var smokeTop = robot.body.top;
  var smokeSide = robot.body.left;
  robot.canvas.remove(robot.body);
  imgElement = document.getElementById('cloud');
  smoke = new fabric.Image(imgElement, {
    left: smokeSide,
    top: smokeTop,
    fill: '#006569',
    width: 20,
    height: 20,
    originX: 'center',
    originY: 'center',
    selectable: false,
    evented: false
  });
  robot.canvas.add(smoke);
  robot.crashed = true;
  alert("Try Again!")
};

DrawnRobot.prototype.moveForward = function(amt){
  if(typeof amt === 'undefined' || typeof amt === 'string') amt = 1;
  var distance, line, robot, canvas, canvasData;
  robot = this;
  canvas = robot.canvas;
  canvasData = {
    onChange: function(){
      if (robot.body.top >= 400){
        robot.upInSmoke();
      }else if(robot.body.top <= 0){
        robot.upInSmoke();
      }else if(robot.body.left >= 400){
        robot.upInSmoke();
      }else if(robot.body.left <= 0){
        robot.upInSmoke();
      }
    canvas.renderAll.bind(canvas);
  },
  abort: function(){
    return robot.crashed;
  },
  duration: 1500,
  onComplete: function(){
      robot.getNextInstruction();
    }
  };

  canvasLineData = { onChange: canvas.renderAll.bind(canvas),
    duration: 1500,
     onComplete: function(){
    }
  };
  distance = amt * 50;
  line = robot.lineTrail();
  canvas.add(line);
  canvas.sendToBack(line);
  if (robot.facing === "up") {
    robot.body.animate('top', '-=' + distance.toString(), canvasData);
    line.animate('height', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "left") {
      robot.body.animate('left', '-=' + distance.toString(), canvasData);
      line.animate('width', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "down") {
      robot.body.animate('top', '+=' + distance.toString(), canvasData);
      line.animate('height', '+=' + distance.toString(), canvasLineData);
  } else {
      robot.body.animate('left', '+=' + distance.toString(), canvasData);
      line.animate('width', '+=' + distance.toString(), canvasLineData);
  }
};

DrawnRobot.prototype.lineTrail = function() {
    var line = new fabric.Line([ this.body.left - 3, this.body.top -3, this.body.left -3, this.body.top - 3], {
      stroke: '#006569',
      strokeWidth: 5,
      strokeDashArray: [5, 5],
      selectable: false,
      lockMovementY: true,
      lockMovementX: true
  });
  return line;
};

// DrawnRobot.prototype.turnAround = function(){
//   var canvas = this.canvas;
//   var robot = this;

//   this.body.animate('angle', '-=180', {
//     onChange: canvas.renderAll.bind(canvas),
//     duration: 1000,
//     onComplete: function() { robot.getNextInstruction(); }
//   });

//   facingIndex = FACING.indexOf(this.facing);

//   facingIndex += 2;
//     if (facingIndex === 4) {
//       facingIndex = 0;
//   } else if (facingIndex === 5) {
//       facingIndex = 1;
//   } else {
//     return facingIndex;
//   }
//   this.facing = FACING[facingIndex];
//   console.log(this.facing);
// };

<commit_msg>make cloud slightly bigger<commit_after>FACING = ["up", "left", "down", "right"];

function DrawnRobot(){
  imgElement = document.getElementById('robot-icon');
  this.body = new fabric.Image(imgElement, {
    left: 200,
    top: 390,
    fill: '#006569',
    width: 20,
    height: 20,
    originX: 'center',
    originY: 'center',
    selectable: false,
    crashed: false
  });
  this.facing =  FACING[0];
  this.canvas = new fabric.Canvas('myCanvas');
  this.queuedInstructions = [];
}

DrawnRobot.prototype.doTheseFrames = function(instructionsArr){
  this.queuedInstructions = instructionsArr;
};

DrawnRobot.prototype.getNextInstruction = function(){
  var robot = this;
  if(robot.queuedInstructions.length > 0){
    console.log("Number of instructions left: " + robot.queuedInstructions.length);
    eval(robot.queuedInstructions.shift());
  }else{
      $(".game-console-button").show();
      $(".hint-link").show();
      $(".challenge-navigation a").show();
  }

};

DrawnRobot.prototype.setFacingRight = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex -= 1;
  if (facingIndex === -1) {
      facingIndex = 3;
  }
  this.facing = FACING[facingIndex];
};

DrawnRobot.prototype.setFacingLeft = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex += 1;
  if (facingIndex === 4) {
      facingIndex = 0;
  }
  this.facing = FACING[facingIndex];
  console.log(this.facing);
};

DrawnRobot.prototype.turnLeft = function(){
  var canvas = this.canvas;
  var robot = this;
  robot.setFacingLeft();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '-=90', canvasData);
};

DrawnRobot.prototype.turnRight = function(){
  var robot = this;
  var canvas = this.canvas;
  robot.setFacingRight();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '+=90', canvasData);
  // console.log(this.facing);
};

DrawnRobot.prototype.upInSmoke = function(){
  var robot = this;
  var smokeTop = robot.body.top;
  var smokeSide = robot.body.left;
  robot.canvas.remove(robot.body);
  imgElement = document.getElementById('cloud');
  smoke = new fabric.Image(imgElement, {
    left: smokeSide,
    top: smokeTop,
    fill: '#006569',
    width: 28,
    height: 28,
    originX: 'center',
    originY: 'center',
    selectable: false,
    evented: false
  });
  robot.canvas.add(smoke);
  robot.crashed = true;
  alert("Try Again!")
};

DrawnRobot.prototype.moveForward = function(amt){
  if(typeof amt === 'undefined' || typeof amt === 'string') amt = 1;
  var distance, line, robot, canvas, canvasData;
  robot = this;
  canvas = robot.canvas;
  canvasData = {
    onChange: function(){
      if (robot.body.top >= 400){
        robot.upInSmoke();
      }else if(robot.body.top <= 0){
        robot.upInSmoke();
      }else if(robot.body.left >= 400){
        robot.upInSmoke();
      }else if(robot.body.left <= 0){
        robot.upInSmoke();
      }
    canvas.renderAll.bind(canvas);
  },
  abort: function(){
    return robot.crashed;
  },
  duration: 1500,
  onComplete: function(){
      robot.getNextInstruction();
    }
  };

  canvasLineData = { onChange: canvas.renderAll.bind(canvas),
    duration: 1500,
     onComplete: function(){
    }
  };
  distance = amt * 50;
  line = robot.lineTrail();
  canvas.add(line);
  canvas.sendToBack(line);
  if (robot.facing === "up") {
    robot.body.animate('top', '-=' + distance.toString(), canvasData);
    line.animate('height', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "left") {
      robot.body.animate('left', '-=' + distance.toString(), canvasData);
      line.animate('width', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "down") {
      robot.body.animate('top', '+=' + distance.toString(), canvasData);
      line.animate('height', '+=' + distance.toString(), canvasLineData);
  } else {
      robot.body.animate('left', '+=' + distance.toString(), canvasData);
      line.animate('width', '+=' + distance.toString(), canvasLineData);
  }
};

DrawnRobot.prototype.lineTrail = function() {
    var line = new fabric.Line([ this.body.left - 3, this.body.top -3, this.body.left -3, this.body.top - 3], {
      stroke: '#006569',
      strokeWidth: 5,
      strokeDashArray: [5, 5],
      selectable: false,
      lockMovementY: true,
      lockMovementX: true
  });
  return line;
};

// DrawnRobot.prototype.turnAround = function(){
//   var canvas = this.canvas;
//   var robot = this;

//   this.body.animate('angle', '-=180', {
//     onChange: canvas.renderAll.bind(canvas),
//     duration: 1000,
//     onComplete: function() { robot.getNextInstruction(); }
//   });

//   facingIndex = FACING.indexOf(this.facing);

//   facingIndex += 2;
//     if (facingIndex === 4) {
//       facingIndex = 0;
//   } else if (facingIndex === 5) {
//       facingIndex = 1;
//   } else {
//     return facingIndex;
//   }
//   this.facing = FACING[facingIndex];
//   console.log(this.facing);
// };

<|endoftext|>