<commit_before>/**
 * WYSIHTML5 Editor
 *
 * @param {Element} textareaElement Reference to the textarea which should be turned into a rich text interface
 * @param {Object} [config] See defaultConfig object below for explanation of each individual config option
 *
 * @events
 *    load
 *    beforeload (for internal use only)
 *    focus
 *    focus:composer
 *    focus:textarea
 *    blur
 *    blur:composer
 *    blur:textarea
 *    change
 *    change:composer
 *    change:textarea
 *    paste
 *    paste:composer
 *    paste:textarea
 *    newword:composer
 *    destroy:composer
 *    undo:composer
 *    redo:composer
 *    beforecommand:composer
 *    aftercommand:composer
 *    enable:composer
 *    disable:composer
 *    change_view
 */
(function(wysihtml5) {
  var undef;

  var defaultConfig = {
    // Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body
    name:                 undef,
    // Whether the editor should look like the textarea (by adopting styles)
    style:                true,
    // Id of the toolbar element, pass falsey value if you don't want any toolbar logic
    toolbar:              undef,
    // Whether urls, entered by the user should automatically become clickable-links
    autoLink:             true,
    // Whether dialogs should automatically open when the caret is in a relevant node
    autoOpenDialogs:             true,
    // Object which includes parser rules to apply when html gets inserted via copy & paste
    // See parser_rules/*.js for examples
    parserRules:          { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} },
    // Parser method to use when the user inserts content via copy & paste
    parser:               wysihtml5.dom.parse,
    // Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option
    composerClassName:    "wysihtml5-editor",
    // Class name to add to the body when the wysihtml5 editor is supported
    bodyClassName:        "wysihtml5-supported",
    // By default wysihtml5 will insert a
 for line breaks, set this to false to use

    useLineBreaks:        true,
    // Array (or single string) of stylesheet urls to be loaded in the editor's iframe
    stylesheets:          [],
    // Placeholder text to use, defaults to the placeholder attribute on the textarea element
    placeholderText:      undef,
    // Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5)
    supportTouchDevices:  true
  };

  wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend(
    /** @scope wysihtml5.Editor.prototype */ {
    constructor: function(textareaElement, config) {
      this.textareaElement  = typeof(textareaElement) === "string" ? document.getElementById(textareaElement) : textareaElement;
      this.config           = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get();
      this.textarea         = new wysihtml5.views.Textarea(this, this.textareaElement, this.config);
      this.currentView      = this.textarea;
      this._isCompatible    = wysihtml5.browser.supported();

      // Sort out unsupported/unwanted browsers here
      if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) {
        var that = this;
        setTimeout(function() { that.fire("beforeload").fire("load"); }, 0);
        return;
      }

      // Add class name to body, to indicate that the editor is supported
      wysihtml5.dom.addClass(document.body, this.config.bodyClassName);

      this.composer = new wysihtml5.views.Composer(this, this.textareaElement, this.config);
      this.currentView = this.composer;

      if (typeof(this.config.parser) === "function") {
        this._initParser();
      }

      this.on("beforeload", function() {
        this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer);
        if (this.config.toolbar) {
          this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar);
        }
      });

      try {
        console.log("Heya! This page is using wysihtml5 for rich text editing. Check out https://github.com/xing/wysihtml5");
      } catch(e) {}
    },

    isCompatible: function() {
      return this._isCompatible;
    },

    clear: function() {
      this.currentView.clear();
      return this;
    },

    getValue: function(parse) {
      return this.currentView.getValue(parse);
    },

    setValue: function(html, parse) {
      this.fire("unset_placeholder");

      if (!html) {
        return this.clear();
      }

      this.currentView.setValue(html, parse);
      return this;
    },

    focus: function(setToEnd) {
      this.currentView.focus(setToEnd);
      return this;
    },

    /**
     * Deactivate editor (make it readonly)
     */
    disable: function() {
      this.currentView.disable();
      return this;
    },

    /**
     * Activate editor
     */
    enable: function() {
      this.currentView.enable();
      return this;
    },

    isEmpty: function() {
      return this.currentView.isEmpty();
    },

    hasPlaceholderSet: function() {
      return this.currentView.hasPlaceholderSet();
    },

    parse: function(htmlOrElement) {
      var returnValue = this.config.parser(htmlOrElement, this.config.parserRules, this.composer.sandbox.getDocument(), true);
      if (typeof(htmlOrElement) === "object") {
        wysihtml5.quirks.redraw(htmlOrElement);
      }
      return returnValue;
    },

    /**
     * Prepare html parser logic
     *  - Observes for paste and drop
     */
    _initParser: function() {
      this.on("paste:composer", function() {
        var keepScrollPosition  = true,
            that                = this;
        that.composer.selection.executeAndRestore(function() {
          wysihtml5.quirks.cleanPastedHTML(that.composer.element);
          that.parse(that.composer.element);
        }, keepScrollPosition);
      });
    }
  });
})(wysihtml5);<commit_msg>Remove "Heya" message<commit_after>/**
 * WYSIHTML5 Editor
 *
 * @param {Element} textareaElement Reference to the textarea which should be turned into a rich text interface
 * @param {Object} [config] See defaultConfig object below for explanation of each individual config option
 *
 * @events
 *    load
 *    beforeload (for internal use only)
 *    focus
 *    focus:composer
 *    focus:textarea
 *    blur
 *    blur:composer
 *    blur:textarea
 *    change
 *    change:composer
 *    change:textarea
 *    paste
 *    paste:composer
 *    paste:textarea
 *    newword:composer
 *    destroy:composer
 *    undo:composer
 *    redo:composer
 *    beforecommand:composer
 *    aftercommand:composer
 *    enable:composer
 *    disable:composer
 *    change_view
 */
(function(wysihtml5) {
  var undef;

  var defaultConfig = {
    // Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body
    name:                 undef,
    // Whether the editor should look like the textarea (by adopting styles)
    style:                true,
    // Id of the toolbar element, pass falsey value if you don't want any toolbar logic
    toolbar:              undef,
    // Whether urls, entered by the user should automatically become clickable-links
    autoLink:             true,
    // Whether dialogs should automatically open when the caret is in a relevant node
    autoOpenDialogs:             true,
    // Object which includes parser rules to apply when html gets inserted via copy & paste
    // See parser_rules/*.js for examples
    parserRules:          { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} },
    // Parser method to use when the user inserts content via copy & paste
    parser:               wysihtml5.dom.parse,
    // Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option
    composerClassName:    "wysihtml5-editor",
    // Class name to add to the body when the wysihtml5 editor is supported
    bodyClassName:        "wysihtml5-supported",
    // By default wysihtml5 will insert a
 for line breaks, set this to false to use

    useLineBreaks:        true,
    // Array (or single string) of stylesheet urls to be loaded in the editor's iframe
    stylesheets:          [],
    // Placeholder text to use, defaults to the placeholder attribute on the textarea element
    placeholderText:      undef,
    // Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5)
    supportTouchDevices:  true
  };

  wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend(
    /** @scope wysihtml5.Editor.prototype */ {
    constructor: function(textareaElement, config) {
      this.textareaElement  = typeof(textareaElement) === "string" ? document.getElementById(textareaElement) : textareaElement;
      this.config           = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get();
      this.textarea         = new wysihtml5.views.Textarea(this, this.textareaElement, this.config);
      this.currentView      = this.textarea;
      this._isCompatible    = wysihtml5.browser.supported();

      // Sort out unsupported/unwanted browsers here
      if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) {
        var that = this;
        setTimeout(function() { that.fire("beforeload").fire("load"); }, 0);
        return;
      }

      // Add class name to body, to indicate that the editor is supported
      wysihtml5.dom.addClass(document.body, this.config.bodyClassName);

      this.composer = new wysihtml5.views.Composer(this, this.textareaElement, this.config);
      this.currentView = this.composer;

      if (typeof(this.config.parser) === "function") {
        this._initParser();
      }

      this.on("beforeload", function() {
        this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer);
        if (this.config.toolbar) {
          this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar);
        }
      });
    },

    isCompatible: function() {
      return this._isCompatible;
    },

    clear: function() {
      this.currentView.clear();
      return this;
    },

    getValue: function(parse) {
      return this.currentView.getValue(parse);
    },

    setValue: function(html, parse) {
      this.fire("unset_placeholder");

      if (!html) {
        return this.clear();
      }

      this.currentView.setValue(html, parse);
      return this;
    },

    focus: function(setToEnd) {
      this.currentView.focus(setToEnd);
      return this;
    },

    /**
     * Deactivate editor (make it readonly)
     */
    disable: function() {
      this.currentView.disable();
      return this;
    },

    /**
     * Activate editor
     */
    enable: function() {
      this.currentView.enable();
      return this;
    },

    isEmpty: function() {
      return this.currentView.isEmpty();
    },

    hasPlaceholderSet: function() {
      return this.currentView.hasPlaceholderSet();
    },

    parse: function(htmlOrElement) {
      var returnValue = this.config.parser(htmlOrElement, this.config.parserRules, this.composer.sandbox.getDocument(), true);
      if (typeof(htmlOrElement) === "object") {
        wysihtml5.quirks.redraw(htmlOrElement);
      }
      return returnValue;
    },

    /**
     * Prepare html parser logic
     *  - Observes for paste and drop
     */
    _initParser: function() {
      this.on("paste:composer", function() {
        var keepScrollPosition  = true,
            that                = this;
        that.composer.selection.executeAndRestore(function() {
          wysihtml5.quirks.cleanPastedHTML(that.composer.element);
          that.parse(that.composer.element);
        }, keepScrollPosition);
      });
    }
  });
})(wysihtml5);<|endoftext|>


<commit_before>/**
 * Created by JanJJ on 18.10.2016.
 */

var maze = {};

maze.config = {
    selectorMap: '.js-map',
    SelectorLoadingIcon: '.js-map-loading-icon ',
    length: 17,
    width: 17,
    chars: {
        0: ' ',
        1: '#',
        2: '©'
    },

    splitChar: "-"

};

maze.validatePosition = function(x,y, char) {
    var element = jQuery("#" + x+maze.config.splitChar+y);
    if (element.text() == char) {
        return true;
    }
    return false;
}
maze.isWall = function (x, y) {
    return maze.validatePosition(x, y, maze.config.chars[1]);
}
maze.isCandy = function (x, y) {
    var element = jQuery("#" + x+maze.config.splitChar+y);
    if (element.hasClass("candy"))
        return true;
    return false;
}
maze.isOnExit = function (x, y) {
    if (x == (maze.config.width-1) && y == (maze.config.length-1))
        return true;
    return false;
}
//maze.candyInPosition = function (x, y) {
//    if (maze.isCandy(x, y)) {
//        jQuery("#" + x+maze.config.splitChar+y).html(maze.config.chars[0]);
//        game.collectedCandys++;
//    }
//}

maze.isLoaded = false;

//maze.candyInPosition = function (x, y) {
//    if (maze.isCandy(x, y)) {
//        jQuery("#" + x+maze.config.splitChar+y).html(maze.config.chars[0]);
//        game.collectedCandys++;
//    }
//}

game.keyevent = function () {
    jQuery(document).on("keydown", function (event) {
        if (event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40 || event.keyCode == 37) {
            var playerPos = game.player.getPos();
            var playerPosXY = playerPos.split(maze.config.splitChar);
            switch (event.keyCode) {
                case 37:
                    game.player.setPos(parseInt(playerPosXY[0]), parseInt(playerPosXY[1])-1);
                    break;
                case 38:
                    game.player.setPos(parseInt(playerPosXY[0])-1, parseInt(playerPosXY[1]));
                    break;
                case 39:
                    game.player.setPos(parseInt(playerPosXY[0]), parseInt(playerPosXY[1])+1);
                    break;
                case 40:
                    game.player.setPos(parseInt(playerPosXY[0])+1, parseInt(playerPosXY[1]));
                    break;
            }
        }
    });
}

game.calculateScore = function (candy, )

maze.loadMap = function (map) {
    if (!maze.isLoaded) {
        $.each(map, function (index, value) {
            var singleLine = "";
            singleLine += maze.createStructure('', index, 'start');

            for (var i = 0; i < value.length; i++) {
                singleLine += maze.createStructure(maze.config.chars[value[i]], index, i);
            }

            singleLine += maze.createStructure('', 'map', index, 'end');
            $(maze.config.selectorMap).append(singleLine);
        });
    }
};

maze.createStructure = function (character, x, y) {
    var env;
    var candyclass = "";
    if (character == "©")
        candyclass = "class='candy'";
    if (y === "start") {
        env = '
' + character;
    } else if (y === "end") {
        env = character + '
';
    } else {
        env = '' + character + '';
    }
    return env;
};

function loadJson() {
    var url = location.protocol
                + '//'
                + location.host
                + location.pathname
                + 'api/maze?x='
                + maze.config.width
                +'&y='
                + maze.config.length;
    $(maze.config.SelectorLoadingIcon).show();
    $(maze.config.selectorMap).html('');
    $.get(url, function (response) {
        $(maze.config.SelectorLoadingIcon).hide();
        //console.log(response);
        maze.loadMap(response);
    });
}

function saveScore(name, points, timeInSeconds) {
    var url = location.protocol + '//' + location.host + location.pathname + 'api/highscore';
    $.ajax({
        type: "POST",
        url: url,
        dataType: 'json',
        data: JSON.stringify({
            name: name,
            score: points,
            level: 1,
            elapsedTime: timeInSeconds
        })
    });
}

$(function () {
    if($(maze.config.selectorMap).length)
    loadJson();
});<commit_msg>[ADD] score calculator<commit_after>/**
 * Created by JanJJ on 18.10.2016.
 */

var maze = {};

maze.config = {
    selectorMap: '.js-map',
    SelectorLoadingIcon: '.js-map-loading-icon ',
    length: 17,
    width: 17,
    chars: {
        0: ' ',
        1: '#',
        2: '©'
    },

    splitChar: "-"

};

maze.validatePosition = function(x,y, char) {
    var element = jQuery("#" + x+maze.config.splitChar+y);
    if (element.text() == char) {
        return true;
    }
    return false;
}
maze.isWall = function (x, y) {
    return maze.validatePosition(x, y, maze.config.chars[1]);
}
maze.isCandy = function (x, y) {
    var element = jQuery("#" + x+maze.config.splitChar+y);
    if (element.hasClass("candy"))
        return true;
    return false;
}
maze.isOnExit = function (x, y) {
    if (x == (maze.config.width-1) && y == (maze.config.length-1))
        return true;
    return false;
}
//maze.candyInPosition = function (x, y) {
//    if (maze.isCandy(x, y)) {
//        jQuery("#" + x+maze.config.splitChar+y).html(maze.config.chars[0]);
//        game.collectedCandys++;
//    }
//}

maze.isLoaded = false;

//maze.candyInPosition = function (x, y) {
//    if (maze.isCandy(x, y)) {
//        jQuery("#" + x+maze.config.splitChar+y).html(maze.config.chars[0]);
//        game.collectedCandys++;
//    }
//}

game.keyevent = function () {
    jQuery(document).on("keydown", function (event) {
        if (event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40 || event.keyCode == 37) {
            var playerPos = game.player.getPos();
            var playerPosXY = playerPos.split(maze.config.splitChar);
            switch (event.keyCode) {
                case 37:
                    game.player.setPos(parseInt(playerPosXY[0]), parseInt(playerPosXY[1])-1);
                    break;
                case 38:
                    game.player.setPos(parseInt(playerPosXY[0])-1, parseInt(playerPosXY[1]));
                    break;
                case 39:
                    game.player.setPos(parseInt(playerPosXY[0]), parseInt(playerPosXY[1])+1);
                    break;
                case 40:
                    game.player.setPos(parseInt(playerPosXY[0])+1, parseInt(playerPosXY[1]));
                    break;
            }
        }
    });
}

game.calculateScore = function (candy, time) {
    var result = (1/(Math.sqrt(time)) * (candy*Math.PI))
    return Math.round(Math.abs(result*Math.sqrt(candy)));
}

maze.loadMap = function (map) {
    if (!maze.isLoaded) {
        $.each(map, function (index, value) {
            var singleLine = "";
            singleLine += maze.createStructure('', index, 'start');

            for (var i = 0; i < value.length; i++) {
                singleLine += maze.createStructure(maze.config.chars[value[i]], index, i);
            }

            singleLine += maze.createStructure('', 'map', index, 'end');
            $(maze.config.selectorMap).append(singleLine);
        });
    }
};

maze.createStructure = function (character, x, y) {
    var env;
    var candyclass = "";
    if (character == "©")
        candyclass = "class='candy'";
    if (y === "start") {
        env = '
' + character;
    } else if (y === "end") {
        env = character + '
';
    } else {
        env = '' + character + '';
    }
    return env;
};

function loadJson() {
    var url = location.protocol
                + '//'
                + location.host
                + location.pathname
                + 'api/maze?x='
                + maze.config.width
                +'&y='
                + maze.config.length;
    $(maze.config.SelectorLoadingIcon).show();
    $(maze.config.selectorMap).html('');
    $.get(url, function (response) {
        $(maze.config.SelectorLoadingIcon).hide();
        //console.log(response);
        maze.loadMap(response);
    });
}

function saveScore(name, points, timeInSeconds) {
    var url = location.protocol + '//' + location.host + location.pathname + 'api/highscore';
    $.ajax({
        type: "POST",
        url: url,
        dataType: 'json',
        data: JSON.stringify({
            name: name,
            score: points,
            level: 1,
            elapsedTime: timeInSeconds
        })
    });
}

$(function () {
    if($(maze.config.selectorMap).length)
    loadJson();
});<|endoftext|>


<commit_before><commit_msg>Add first movement function to CarbonMolecule class: moveAcrossRight()<commit_after><|endoftext|>


<commit_before>var webpack = require('webpack'),
    path = require('path');

module.exports = {
    entry: [
        './src/quagga.js',
    ],
    devtool: 'inline-source-map',
    module: {
        rules: [
            {
                test: /\.(t|j)sx?$/,
                use: { loader: 'babel-loader' },
            },
            {
                enforce: 'pre',
                test: /\.(t|j)sx?$/,
                loader: 'source-map-loader',
            },
        ],
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
        modules: [
            path.resolve('./src'),
            'node_modules',
        ],
    },
    output: {
        path: __dirname + '/../dist',
        publicPath: '/',
        libraryTarget: 'umd',
        library: 'quagga',
        filename: 'quagga.js',
    },
    devServer: {
        contentBase: './',
        hot: true,
    },
    plugins: [
        new webpack.DefinePlugin({
            ENV: require(path.join(__dirname, './env/', process.env.BUILD_ENV)),
        }),
    ],
    optimization: {
        minimize: false,
    },
    mode: 'production',
};
<commit_msg>Expose library on the global namespace under Quagga<commit_after>var webpack = require('webpack'),
    path = require('path');

module.exports = {
    entry: [
        './src/quagga.js',
    ],
    devtool: 'inline-source-map',
    module: {
        rules: [
            {
                test: /\.(t|j)sx?$/,
                use: { loader: 'babel-loader' },
            },
            {
                enforce: 'pre',
                test: /\.(t|j)sx?$/,
                loader: 'source-map-loader',
            },
        ],
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
        modules: [
            path.resolve('./src'),
            'node_modules',
        ],
    },
    output: {
        path: __dirname + '/../dist',
        publicPath: '/',
        libraryTarget: 'umd',
        libraryExport: 'default',
        library: 'Quagga',
        filename: 'quagga.js',
    },
    devServer: {
        contentBase: './',
        hot: true,
    },
    plugins: [
        new webpack.DefinePlugin({
            ENV: require(path.join(__dirname, './env/', process.env.BUILD_ENV)),
        }),
    ],
    optimization: {
        minimize: false,
    },
    mode: 'production',
};
<|endoftext|>


<commit_before>'use strict';

let AbstractAccessor = require('./AbstractAccessor');
let Group            = require('../Model/Group');

/**
 * Groups accessor
 */
class Groups extends AbstractAccessor {
  /**
   * Constructor
   *
   * @param {Client} client Client
   */
  constructor(client) {
    super(client);

    this.Group = Group;
  }

  /**
   * Get groups
   *
   * @return {Promise} Promise for chaining
   */
  getAll() {
    let GetGroups = require('../Command/Group/GetGroups');

    return this.client.invokeCommand(new GetGroups);
  }

  /**
   * Get group by id
   *
   * @param {string} id Group Id
   *
   * @return {Promise} Promise for chaining
   */
  getById(id) {
    let GetGroup = require('../Command/Group/GetGroup');

    return this.client.invokeCommand(new GetGroup(id));
  }

  /**
   * Create group
   *
   * @param {Group} group Group
   *
   * @return {Promise} Promise for chaining
   */
  create(group) {
    let CreateGroup = require('../Command/Group/CreateGroup');

    return this.client.invokeCommand(new CreateGroup(group));
  }

  /**
   * Save group
   *
   * @param {Group} group Group
   *
   * @return {Promise} Promise for chaining
   */
  save(group) {
    let SaveGroup      = require('../Command/Group/SaveGroup');
    let SaveGroupState = require('../Command/Group/SaveGroupState');

    return Promise.all([
      this.client.invokeCommand(new SaveGroup(group)),
      this.client.invokeCommand(new SaveGroupState(group))
    ]).then(() => {
      return group;
    });
  }

  /**
   * Delete group
   *
   * @param {Group} group Group object or group Id
   *
   * @return {Promise} Promise for chaining
   */
  delete(group) {
    let DeleteGroup = require('../Command/Group/DeleteGroup');

    return this.client.invokeCommand(new DeleteGroup(group));
  }
}

module.exports = Groups;
<commit_msg>GitHub #14 - Import commands<commit_after>'use strict';

let AbstractAccessor = require('./AbstractAccessor');
let Group            = require('../Model/Group');
let GetGroups        = require('../Command/Group/GetGroups');
let GetGroup         = require('../Command/Group/GetGroup');
let CreateGroup      = require('../Command/Group/CreateGroup');
let SaveGroup        = require('../Command/Group/SaveGroup');
let SaveGroupState   = require('../Command/Group/SaveGroupState');
let DeleteGroup      = require('../Command/Group/DeleteGroup');

/**
 * Groups accessor
 */
class Groups extends AbstractAccessor {
  /**
   * Constructor
   *
   * @param {Client} client Client
   */
  constructor(client) {
    super(client);

    this.Group = Group;
  }

  /**
   * Get groups
   *
   * @return {Promise} Promise for chaining
   */
  getAll() {
    return this.client.invokeCommand(new GetGroups);
  }

  /**
   * Get group by id
   *
   * @param {string} id Group Id
   *
   * @return {Promise} Promise for chaining
   */
  getById(id) {
    return this.client.invokeCommand(new GetGroup(id));
  }

  /**
   * Create group
   *
   * @param {Group} group Group
   *
   * @return {Promise} Promise for chaining
   */
  create(group) {
    return this.client.invokeCommand(new CreateGroup(group));
  }

  /**
   * Save group
   *
   * @param {Group} group Group
   *
   * @return {Promise} Promise for chaining
   */
  save(group) {
    return Promise.all([
      this.client.invokeCommand(new SaveGroup(group)),
      this.client.invokeCommand(new SaveGroupState(group))
    ]).then(() => {
      return group;
    });
  }

  /**
   * Delete group
   *
   * @param {Group} group Group object or group Id
   *
   * @return {Promise} Promise for chaining
   */
  delete(group) {
    return this.client.invokeCommand(new DeleteGroup(group));
  }
}

module.exports = Groups;
<|endoftext|>


<commit_before>/* eslint-env node */

var FeedParser = require('feedparser'); // to parse feeds
// var Feed = require('feed'); // to write feeds (but not necessary to require here because we should get a Feed object from app.js -- which seems wrong)
var async = require('async');
// var request = require('request'); // TODO let's abstract this so that we can switch it out (e.g., to fs.readFile )
var fs = require('fs');

exports.feedmerger = function(feedsJson, feedObject, mergedCallback) {
  'use strict';
  // TODO some error handling; checking the arguments etc.

  var getFeed = function(feed, callback) {
    var feedparser = new FeedParser();
    var req = fs.createReadStream(feed); // request(feed);
    req.on('error', function(error) {
        console.error(error);
    });
    req.on('readable', function() {
      var stream = this;
      stream.pipe(feedparser);
    });
    // req.on('response', function(res) {
    //   var stream = this;
    //   if (res.statusCode !== 200) {
    //     return this.emit('error', new Error('Bad status code'));
    //   }
    //   //    stream.pipe(process.stdout); //works
    //   stream.pipe(feedparser);
    // });
    feedparser.on('error', function(error) {
      console.error(feed + ' as a parsing error' + error);
    });
    feedparser.on('readable', function() {
      // This is where the action is!
      var stream = this;
      //    var meta = this.meta; // **NOTE** the "meta" is always available in the context of the feedparser instance
      var item;
      while ( (item = stream.read())) {
        var itemTitle = item.title;
        var itemLink = item.link;
        var itemDescription = item.description;
        var itemDate = item.date;
        var itemAuthor = [{ name: item.author.toString(), email: '', link: ''}];//TODO handle multiple authors??? npm/feed supports that
        feedObject.addItem({
          title: itemTitle,
          link: itemLink,
          description: itemDescription,
          date: itemDate,
          author: itemAuthor
        });
      }
    });
    feedparser.on('finish', function() {
      callback();
    });
  };

  //  console.log(feedsJson);
  async.each(feedsJson, getFeed, function(err) {
    if (err) {
      throw err;
    }
    feedObject.items.sort(function(a, b) { //sort by date for creating pages later
      return b.date - a.date;
    });
    //   console.log("feedmerger completed!");
    //     console.log(feedObject.render('atom-1.0'));
    return mergedCallback(null, feedObject);
  });
};

//    exports.feedmerger = new feedmerger();
<commit_msg>change feedmerger: drop null in returen; switch: use title of feed for author tags; might need to become more complex (multiple authors etc) at some point in the future".<commit_after>/* eslint-env node */

var FeedParser = require('feedparser'); // to parse feeds
// var Feed = require('feed'); // to write feeds (but not necessary to require here because we should get a Feed object from app.js -- which seems wrong)
var async = require('async');
// var request = require('request'); // TODO let's abstract this so that we can switch it out (e.g., to fs.readFile )
var fs = require('fs');

exports.feedmerger = function(feedsJson, feedObject, mergedCallback) {
  'use strict';
  // TODO some error handling; checking the arguments etc.

  var getFeed = function(feed, callback) {
    var feedparser = new FeedParser();
    var req = fs.createReadStream(feed); // request(feed);
    req.on('error', function(error) {
        console.error(error);
    });
    req.on('readable', function() {
      var stream = this;
      stream.pipe(feedparser);
    });
    // req.on('response', function(res) {
    //   var stream = this;
    //   if (res.statusCode !== 200) {
    //     return this.emit('error', new Error('Bad status code'));
    //   }
    //   //    stream.pipe(process.stdout); //works
    //   stream.pipe(feedparser);
    // });
    feedparser.on('error', function(error) {
      console.error(feed + ' as a parsing error' + error);
    });
    feedparser.on('readable', function() {
      // This is where the action is!
      var stream = this;
      //    var meta = this.meta; // **NOTE** the "meta" is always available in the context of the feedparser instance
      var item;
      while ( (item = stream.read())) {
        var itemTitle = item.title;
        var itemLink = item.link;
        var itemDescription = item.description;
        var itemDate = item.date;
        var itemAuthor = [{ name: stream.meta.title, email: '', link: ''}];//TODO used to be item.author.toString() for name -- should we combine title and author name? Should we handle multiple authors??? npm/feed supports multiple authors
        feedObject.addItem({
          title: itemTitle,
          link: itemLink,
          description: itemDescription,
          date: itemDate,
          author: itemAuthor
        });
      }
    });
    feedparser.on('finish', function() {
      callback();
    });
  };

  //  console.log(feedsJson);
  async.each(feedsJson, getFeed, function(err) {
    if (err) {
      throw err;
    }
    feedObject.items.sort(function(a, b) { //sort by date for creating pages later
      return b.date - a.date;
    });
    //   console.log("feedmerger completed!");
    //     console.log(feedObject.render('atom-1.0'));
    return mergedCallback(feedObject);
  });
};

//    exports.feedmerger = new feedmerger();
<|endoftext|>


<commit_before>import Ember from 'ember';

const {
  Mixin,
  run,
  merge,
  assert
} = Ember;

const DEFAULT_LISTENER_OPTIONS = {
  passive: true
};

let shouldAssertPassive = false;

export function setShouldAssertPassive(value) {
  shouldAssertPassive = value && window.Proxy;
}

function assertOnlyPassiveEventUsageProxy(event) {
  return new window.Proxy(event, {
    get(obj, prop) {
      if (prop === 'preventDefault') {
        throw new Error('Passive event listeners cannot call preventDefault, please pass `{passive: false}`');
      }
      if (prop === 'stopPropagation') {
        throw new Error('Passive event listeners cannot call stopPropagation, please pass `{passive: false}`');
      }
      return obj[prop];
    }
  });
}

function listenerDataFor(element, eventName) {
  /* Object to cache passive listener data */
  let passiveListeners = getOrCreateProperty(element, '_passiveListeners');

  let passiveListenersForEvent = passiveListeners[eventName];
  /* Set an object for the event */
  if (!passiveListenersForEvent) {
    passiveListenersForEvent = {
      handlers: [],
      listener: null
    };
    passiveListeners[eventName] = passiveListenersForEvent;
  }

  return passiveListenersForEvent;
}

function removeHandlerFromListenerData(handler) {
  let listenerData = listenerDataFor(handler.element, handler.eventName);

  /*
   * Splice the handler out of the handlers list
   */
  let index = listenerData.handlers.indexOf(handler.callback);
  listenerData.handlers.splice(index, 1);

  /*
   * If no more handlers remain, detach the passive listener from the
   * element and reset the listenerData cache.
   */
  if (listenerData.handlers.length === 0) {
    handler.element.removeEventListener(handler.eventName, listenerData.listener, false);
    listenerData.listener = null;
    listenerData.handlers = [];
  }
}

function getOrCreateProperty(element, name) {
  let value = element[name];

  if (!value) {
    value = {};

    Object.defineProperty(element, name, {
      value,
      configurable: true
    });
  }

  return value;
}

/**
 ContextBoundEventListenersMixin provides a mechanism to attach event listeners
 with runloops and automatic removal when the host object is removed from DOM.

 These capabilities are very commonly needed, so this mixin is by default
 included into all `Ember.View` and `Ember.Component` instances.

 @class ContextBoundEventListenersMixin
 @public
 */
export default Mixin.create({
  init() {
    this._super(...arguments);

    this._listeners = undefined;
    this._coalescedHandlers = undefined;
  },
  /**
   Attaches an event listener that will automatically be removed when the host
   object is dropped from DOM.

   Example:

   ```js
   import Component from 'ember-component';
   import ContextBoundEventListenersMixin from 'ember-lifeline/mixins/dom';

   export default Component.extend(ContextBoundEventListenersMixin, {
     didInsertElement() {
       this.addEventListener('.some-item', 'click', (e) => {
         console.log('.some-item was clicked');
       });
     }
   });
   ```

   @method addEventListener
   @param { String } selector the DOM selector or element
   @param { String } _eventName the event name to listen for
   @param { Function } _callback the callback to run for that event
   @public
   */
  addEventListener(selector, eventName, callback, _options) {
    assert('Must provide an element (not a DOM selector) when using addEventListener in a tagless component.', this.tagName !== '' || typeof selector !== 'string');
    assert('Called addEventListener before the component was rendered', this._currentState === this._states.inDOM);

    // Ember.assign would be better here, but Ember < 2.5 doesn't have that :(
    let options = merge(merge({}, DEFAULT_LISTENER_OPTIONS), _options);
    let element = findElement(this.element, selector);
    let eventNames = eventName.split(' ');

    for (let i = 0; i < eventNames.length; i++) {
      eventName = eventNames[i];

      if (options.passive) {
        this._addCoalescedEventListener(element, eventName, callback);
      } else {
        this._addEventListener(element, eventName, callback);
      }
    }
  },

  /**

   @param { String } selector the DOM selector or element
   @param { String } _eventName the event name to listen for
   @param { Function } _callback the callback to run for that event
   @public
   */
  removeEventListener(selector, eventName, callback, _options) {
    assert('Must provide an element (not a DOM selector) when using addEventListener in a tagless component.', this.tagName !== '' || typeof selector !== 'string');

    let options = merge(merge({}, DEFAULT_LISTENER_OPTIONS), _options);
    let element = findElement(this.element, selector);
    let eventNames = eventName.split(' ');

    for (let i = 0; i < eventNames.length; i++) {
      eventName = eventNames[i];

      if (options.passive) {
        this._removeCoalescedEventListener(element, eventName, callback);
      } else {
        this._removeEventListener(element, eventName, callback);
      }
    }
  },

  _addCoalescedEventListener(element, eventName, _callback) {
    let callback = run.bind(this, _callback);
    /*
     * listenerData caches the handler list and listener callback on the
     * element as a property.
     */
    let listenerData = listenerDataFor(element, eventName);

    /*
     * If listenerData has no handlers, we must setup the listener.
     */
    if (listenerData.handlers.length === 0) {

      /*
       * Create a callback that walks over all handlers and calls them in
       * order. In dev mode, wrap the event in a proxy to ensure active
       * steps like stopPropogation or preventDefault are not called.
       */
      let coalescedCallback = (event, ...callbackArgs) => {
        let eventForHandlers = event;
        if (shouldAssertPassive) {
          eventForHandlers = assertOnlyPassiveEventUsageProxy(event);
        }

        run(() => {
          listenerData.handlers.forEach((h) => {
            h.apply(this, [eventForHandlers, ...callbackArgs]);
          });
        });
      };

      /*
       * Attach the listener and cache the listener for teardown
       */
      element.addEventListener(eventName, coalescedCallback);
      listenerData.listener = coalescedCallback;
    }

    /*
     * Finally, push the handler onto the list of handlers. Do this on the
     * listenerData for execution of the hooks, and on the context for
     * teardown.
     */
    listenerData.handlers.push(callback);

    this._getOrAllocateArray('_coalescedHandlers').push({ element, eventName, callback, _callback });
  },

  _addEventListener(element, eventName, _callback) {
    let callback = run.bind(this, _callback);
    element.addEventListener(eventName, callback);
    this._getOrAllocateArray('_listeners').push({ element, eventName, callback, _callback });
  },

  _removeCoalescedEventListener(element, eventName, _callback) {
    if (!this._coalescedHandlers) {
      return;
    }

    for (let i = 0; i < this._coalescedHandlers.length; i++) {
      let handler = this._coalescedHandlers[i];
      if (
        handler.element === element
        && handler.eventName === eventName
        && handler._callback === _callback
      ) {
        removeHandlerFromListenerData(handler);
        break;
      }
    }
  },

  _removeEventListener(element, eventName, _callback) {
    if (!this._listeners) {
      return;
    }

    // We cannot use Array.findIndex as we cannot rely on babel/polyfill being present
    for (let i = 0; i < this._listeners.length; i++) {
      let listener = this._listeners[i];
      if (
        listener.element === element
        && listener.eventName === eventName
        && listener._callback === _callback
      ) {
        /*
         * Drop the event listener and remove the listener object
         */
        element.removeEventListener(eventName, listener.callback);
        this._listeners.splice(i, 1);
        break;
      }
    }
  },

  willDestroyElement() {
    this._super(...arguments);

    if (this._listeners) {
      /* Drop non-passive event listeners */
      for (let i = 0; i < this._listeners.length; i++) {
        let { element, eventName, callback } = this._listeners[i];
        element.removeEventListener(eventName, callback);
      }
      this._listeners.length = 0;
    }

    if (this._coalescedHandlers) {
      /* Drop passive event listeners */
      for (let i = 0; i < this._coalescedHandlers.length; i++) {
        let handler = this._coalescedHandlers[i];
        removeHandlerFromListenerData(handler);
      }
      this._coalescedHandlers.length = 0;
    }
  },

  _getOrAllocateArray(propertyName) {
    if (!this[propertyName]) {
      this[propertyName] = [];
    }

    return this[propertyName];
  }
});

function findElement(contextElement, selector) {
  let selectorType = typeof selector;
  let element;

  if (selectorType === 'string') {
    element = contextElement.querySelector(selector);
  } else if (selector.nodeType || selector === window) {
    element = selector;
  }

  assert(`Called addEventListener with selector not found in DOM: ${selector}`, !!element);

  return element;
}
<commit_msg>Removing defineProperty call in favor of the simpler approach<commit_after>import Ember from 'ember';

const {
  Mixin,
  run,
  merge,
  assert
} = Ember;

const DEFAULT_LISTENER_OPTIONS = {
  passive: true
};

let shouldAssertPassive = false;

export function setShouldAssertPassive(value) {
  shouldAssertPassive = value && window.Proxy;
}

function assertOnlyPassiveEventUsageProxy(event) {
  return new window.Proxy(event, {
    get(obj, prop) {
      if (prop === 'preventDefault') {
        throw new Error('Passive event listeners cannot call preventDefault, please pass `{passive: false}`');
      }
      if (prop === 'stopPropagation') {
        throw new Error('Passive event listeners cannot call stopPropagation, please pass `{passive: false}`');
      }
      return obj[prop];
    }
  });
}

function listenerDataFor(element, eventName) {
  /* Object to cache passive listener data */
  let passiveListeners = element._passiveListeners;

  if (!passiveListeners) {
    passiveListeners = {};
    element._passiveListeners = passiveListeners;
  }

  let passiveListenersForEvent = passiveListeners[eventName];
  /* Set an object for the event */
  if (!passiveListenersForEvent) {
    passiveListenersForEvent = {
      handlers: [],
      listener: null
    };
    passiveListeners[eventName] = passiveListenersForEvent;
  }

  return passiveListenersForEvent;
}

function removeHandlerFromListenerData(handler) {
  let listenerData = listenerDataFor(handler.element, handler.eventName);

  /*
   * Splice the handler out of the handlers list
   */
  let index = listenerData.handlers.indexOf(handler.callback);
  listenerData.handlers.splice(index, 1);

  /*
   * If no more handlers remain, detach the passive listener from the
   * element and reset the listenerData cache.
   */
  if (listenerData.handlers.length === 0) {
    handler.element.removeEventListener(handler.eventName, listenerData.listener, false);
    listenerData.listener = null;
    listenerData.handlers = [];
  }
}

/**
 ContextBoundEventListenersMixin provides a mechanism to attach event listeners
 with runloops and automatic removal when the host object is removed from DOM.

 These capabilities are very commonly needed, so this mixin is by default
 included into all `Ember.View` and `Ember.Component` instances.

 @class ContextBoundEventListenersMixin
 @public
 */
export default Mixin.create({
  init() {
    this._super(...arguments);

    this._listeners = undefined;
    this._coalescedHandlers = undefined;
  },
  /**
   Attaches an event listener that will automatically be removed when the host
   object is dropped from DOM.

   Example:

   ```js
   import Component from 'ember-component';
   import ContextBoundEventListenersMixin from 'ember-lifeline/mixins/dom';

   export default Component.extend(ContextBoundEventListenersMixin, {
     didInsertElement() {
       this.addEventListener('.some-item', 'click', (e) => {
         console.log('.some-item was clicked');
       });
     }
   });
   ```

   @method addEventListener
   @param { String } selector the DOM selector or element
   @param { String } _eventName the event name to listen for
   @param { Function } _callback the callback to run for that event
   @public
   */
  addEventListener(selector, eventName, callback, _options) {
    assert('Must provide an element (not a DOM selector) when using addEventListener in a tagless component.', this.tagName !== '' || typeof selector !== 'string');
    assert('Called addEventListener before the component was rendered', this._currentState === this._states.inDOM);

    // Ember.assign would be better here, but Ember < 2.5 doesn't have that :(
    let options = merge(merge({}, DEFAULT_LISTENER_OPTIONS), _options);
    let element = findElement(this.element, selector);
    let eventNames = eventName.split(' ');

    for (let i = 0; i < eventNames.length; i++) {
      eventName = eventNames[i];

      if (options.passive) {
        this._addCoalescedEventListener(element, eventName, callback);
      } else {
        this._addEventListener(element, eventName, callback);
      }
    }
  },

  /**

   @param { String } selector the DOM selector or element
   @param { String } _eventName the event name to listen for
   @param { Function } _callback the callback to run for that event
   @public
   */
  removeEventListener(selector, eventName, callback, _options) {
    assert('Must provide an element (not a DOM selector) when using addEventListener in a tagless component.', this.tagName !== '' || typeof selector !== 'string');

    let options = merge(merge({}, DEFAULT_LISTENER_OPTIONS), _options);
    let element = findElement(this.element, selector);
    let eventNames = eventName.split(' ');

    for (let i = 0; i < eventNames.length; i++) {
      eventName = eventNames[i];

      if (options.passive) {
        this._removeCoalescedEventListener(element, eventName, callback);
      } else {
        this._removeEventListener(element, eventName, callback);
      }
    }
  },

  _addCoalescedEventListener(element, eventName, _callback) {
    let callback = run.bind(this, _callback);
    /*
     * listenerData caches the handler list and listener callback on the
     * element as a property.
     */
    let listenerData = listenerDataFor(element, eventName);

    /*
     * If listenerData has no handlers, we must setup the listener.
     */
    if (listenerData.handlers.length === 0) {

      /*
       * Create a callback that walks over all handlers and calls them in
       * order. In dev mode, wrap the event in a proxy to ensure active
       * steps like stopPropogation or preventDefault are not called.
       */
      let coalescedCallback = (event, ...callbackArgs) => {
        let eventForHandlers = event;
        if (shouldAssertPassive) {
          eventForHandlers = assertOnlyPassiveEventUsageProxy(event);
        }

        run(() => {
          listenerData.handlers.forEach((h) => {
            h.apply(this, [eventForHandlers, ...callbackArgs]);
          });
        });
      };

      /*
       * Attach the listener and cache the listener for teardown
       */
      element.addEventListener(eventName, coalescedCallback);
      listenerData.listener = coalescedCallback;
    }

    /*
     * Finally, push the handler onto the list of handlers. Do this on the
     * listenerData for execution of the hooks, and on the context for
     * teardown.
     */
    listenerData.handlers.push(callback);

    this._getOrAllocateArray('_coalescedHandlers').push({ element, eventName, callback, _callback });
  },

  _addEventListener(element, eventName, _callback) {
    let callback = run.bind(this, _callback);
    element.addEventListener(eventName, callback);
    this._getOrAllocateArray('_listeners').push({ element, eventName, callback, _callback });
  },

  _removeCoalescedEventListener(element, eventName, _callback) {
    if (!this._coalescedHandlers) {
      return;
    }

    for (let i = 0; i < this._coalescedHandlers.length; i++) {
      let handler = this._coalescedHandlers[i];
      if (
        handler.element === element
        && handler.eventName === eventName
        && handler._callback === _callback
      ) {
        removeHandlerFromListenerData(handler);
        break;
      }
    }
  },

  _removeEventListener(element, eventName, _callback) {
    if (!this._listeners) {
      return;
    }

    // We cannot use Array.findIndex as we cannot rely on babel/polyfill being present
    for (let i = 0; i < this._listeners.length; i++) {
      let listener = this._listeners[i];
      if (
        listener.element === element
        && listener.eventName === eventName
        && listener._callback === _callback
      ) {
        /*
         * Drop the event listener and remove the listener object
         */
        element.removeEventListener(eventName, listener.callback);
        this._listeners.splice(i, 1);
        break;
      }
    }
  },

  willDestroyElement() {
    this._super(...arguments);

    if (this._listeners) {
      /* Drop non-passive event listeners */
      for (let i = 0; i < this._listeners.length; i++) {
        let { element, eventName, callback } = this._listeners[i];
        element.removeEventListener(eventName, callback);
      }
      this._listeners.length = 0;
    }

    if (this._coalescedHandlers) {
      /* Drop passive event listeners */
      for (let i = 0; i < this._coalescedHandlers.length; i++) {
        let handler = this._coalescedHandlers[i];
        removeHandlerFromListenerData(handler);
      }
      this._coalescedHandlers.length = 0;
    }
  },

  _getOrAllocateArray(propertyName) {
    if (!this[propertyName]) {
      this[propertyName] = [];
    }

    return this[propertyName];
  }
});

function findElement(contextElement, selector) {
  let selectorType = typeof selector;
  let element;

  if (selectorType === 'string') {
    element = contextElement.querySelector(selector);
  } else if (selector.nodeType || selector === window) {
    element = selector;
  }

  assert(`Called addEventListener with selector not found in DOM: ${selector}`, !!element);

  return element;
}
<|endoftext|>


<commit_before>/**
 * Content component.
 * @author Dmitriy Yurchenko <evildev@evildev.ru>
 * @license MIT
 */

var request = require('request'),
	userAgent = require('random-useragent'),
	cheerio = require('cheerio')
	fs = require('fs');

/**
 * @class ContentComponent
 */
module.exports = function() {
	/**
	 * @type {object}
	 * @private
	 */
	this._config = {};

	/**
	 * @type {number}
	 * @private
	 */
	this._attempts = 16;

	/**
	 * Init conponent.
	 * @param {object} config
	 */
	this.init = function(config) {
		var defer = _.Q.defer();

		if (config && config.components && config.components.content) {
			this._config = config.components.content;
			console.info('Use proxy:', this._config.useProxy || false);
		}

		defer.resolve();

		return defer.promise;
	};

	/**
	 * Return html page via get method.
	 * @param url
	 * @param params
	 * @param isOnlyDom
	 * @returns {promise|*|Q.promise}
	 */
	this.get = function(url, params, isNeedAnswer) {
		var defer = _.Q.defer();

		function loop() {
			params = this.configure(url, params);

			//	Request.
			var req = request(params, function(error, response, body) {
				params.attempts = _.isNumber(params.attempts) ? params.attempts : this._attempts;

				//	Check result.
				if (!error && response && response.statusCode === 200) {
					if (params.regexp && !params.regexp.test(body)) {
					}
					else {
						//	DONE!
						defer.resolve(!isNeedAnswer ? cheerio.load(body) : {
							response: response,
							$: cheerio.load(body),
							body: body
						});
						return;
					}
				}

				//	Try again.
				--params.attempts;
				if (params.attempts <= 0) {
					defer.reject(new Error('Fail load page "' + url + '", can\'t try again :( [' + params.proxy + ']'));
					return;
				}

				if (params.log !== false) {
					console.error('Fail load page "' + url + '" try again (' + params.attempts + ')');
				}

				//	Switch ip of proxy address and useragent.
				params = _.extend(params, {
					proxy: Nyama.app().proxy.getRand(),
					headers: {
						'User-Agent': userAgent.getRandom()
					}
				});

				_.Q.whenDelay(loop, defer, this);
			}.bind(this));

			//	If neew download file.
			if (params.writeStream) {
				req.pipe(params.writeStream);
			}
		}

		_.Q.nextTick(loop.bind(this));

		return defer.promise;
	};

	/**
	 * Download file and save on disk.
	 * @param {string} url
	 * @param {string} fileName
	 * @param {object} params
	 */
	this.download = function(url, fileName, params) {
		var defer = _.Q.defer();

		function loop() {
			//	DOWNLOAD FILE
			var writeStream = fs.createWriteStream(fileName);

			console.info('Download file ' + url + ' to ' + fileName);

			writeStream.on('error', function(error) {
				if (error) {
					//	TODO: unlink
					_.Q.whenDelay(loop, defer, this);
				}
			}.bind(this));

			writeStream.on('close', function(error) {
				if (error) {
					//	TODO: unlink
					_.Q.whenDelay(loop, defer, this);
				}
			}.bind(this));

			this.get(url, _.extend(params || {}, { writeStream: writeStream }))
				.then(function() {
					defer.resolve();
				});
		}

		_.Q.nextTick(loop.bind(this));

		return defer.promise;
	},

	/**
	 * @param config
	 */
	this.configure = function(url, config) {
		return _.extend(
			this._config.useProxy ? { proxy: Nyama.app().proxy.getRand() } : {},
			this._config,
			{
				url: url,
				type: 'GET',
				timeout: 30000,
				followAllRedirects: true,
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'User-Agent': userAgent.getRandom()
				}
			},
			config
		);
	};
};<commit_msg>Fix reject if can't download page<commit_after>/**
 * Content component.
 * @author Dmitriy Yurchenko <evildev@evildev.ru>
 * @license MIT
 */

var request = require('request'),
	userAgent = require('random-useragent'),
	cheerio = require('cheerio')
	fs = require('fs');

/**
 * @class ContentComponent
 */
module.exports = function() {
	/**
	 * @type {object}
	 * @private
	 */
	this._config = {};

	/**
	 * @type {number}
	 * @private
	 */
	this._attempts = 16;

	/**
	 * Init conponent.
	 * @param {object} config
	 */
	this.init = function(config) {
		var defer = _.Q.defer();

		if (config && config.components && config.components.content) {
			this._config = config.components.content;
			console.info('Use proxy:', this._config.useProxy || false);
		}

		defer.resolve();

		return defer.promise;
	};

	/**
	 * Return html page via get method.
	 * @param url
	 * @param params
	 * @param isOnlyDom
	 * @returns {promise|*|Q.promise}
	 */
	this.get = function(url, params, isNeedAnswer) {
		var defer = _.Q.defer();

		function loop() {
			params = this.configure(url, params);

			//	Request.
			var req = request(params, function(error, response, body) {
				params.attempts = _.isNumber(params.attempts) ? params.attempts : this._attempts;

				//	Check result.
				if (!error && response && response.statusCode === 200) {
					if (params.regexp && !params.regexp.test(body)) {
					}
					else {
						//	DONE!
						defer.resolve(!isNeedAnswer ? cheerio.load(body) : {
							response: response,
							$: cheerio.load(body),
							body: body
						});
						return;
					}
				}

				//	Try again.
				--params.attempts;
				if (params.attempts <= 0) {
					console.error('Fail load page "' + url + '", can\'t try again :( [' + params.proxy + ']');
					defer.resolve(false);
					return;
				}

				if (params.log !== false) {
					console.warn('Fail load page "' + url + '" try again (' + params.attempts + ')');
				}

				//	Switch ip of proxy address and useragent.
				params = _.extend(params, {
					proxy: Nyama.app().proxy.getRand(),
					headers: {
						'User-Agent': userAgent.getRandom()
					}
				});

				_.Q.whenDelay(loop, defer, this);
			}.bind(this));

			//	If neew download file.
			if (params.writeStream) {
				req.pipe(params.writeStream);
			}
		}

		_.Q.nextTick(loop.bind(this));

		return defer.promise;
	};

	/**
	 * Download file and save on disk.
	 * @param {string} url
	 * @param {string} fileName
	 * @param {object} params
	 */
	this.download = function(url, fileName, params) {
		var defer = _.Q.defer();

		function loop() {
			//	DOWNLOAD FILE
			var writeStream = fs.createWriteStream(fileName);

			console.info('Download file ' + url + ' to ' + fileName);

			writeStream.on('error', function(error) {
				if (error) {
					//	TODO: unlink
					_.Q.whenDelay(loop, defer, this);
				}
			}.bind(this));

			writeStream.on('close', function(error) {
				if (error) {
					//	TODO: unlink
					_.Q.whenDelay(loop, defer, this);
				}
			}.bind(this));

			this.get(url, _.extend(params || {}, { writeStream: writeStream }))
				.then(function() {
					defer.resolve();
				});
		}

		_.Q.nextTick(loop.bind(this));

		return defer.promise;
	},

	/**
	 * @param config
	 */
	this.configure = function(url, config) {
		return _.extend(
			this._config.useProxy ? { proxy: Nyama.app().proxy.getRand() } : {},
			this._config,
			{
				url: url,
				type: 'GET',
				timeout: 30000,
				followAllRedirects: true,
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'User-Agent': userAgent.getRandom()
				}
			},
			config
		);
	};
};<|endoftext|>


<commit_before>const paramCase = require('param-case')

function normalizeName(value, entity) {
  if (typeof value !== 'string' || value.length === 0) {
    throw new Error(`An option ${entity} must be a non-empty string`)
  }

  if (value.charAt(0) === '-') {
    value = value.substr(1)
  }

  if (value.charAt(0) === '-') {
    value = value.substr(1)
  }

  if (value.charAt(0) === '-') {
    throw new Error(
      `A hyphen is not allowed as the first character of an option ${entity}`
    )
  }

  return paramCase(value)
}

class Option {
  constructor(name, command) {
    if (!name) {
      throw new Error('Either a name or config is required to define an option')
    }

    let config = typeof name === 'string' ? { name } : name

    if (!config.name) {
      throw new Error('A name is required to define an option')
    }

    this.command = command
    this.config = {}
    this.set(config)
  }

  set(config) {
    let { name, alias, description, required } = config

    if (name) {
      this.name(name)
    }

    if (alias) {
      this.alias(alias)
    }

    if (description) {
      this.description(description)
    }

    if (typeof required !== 'undefined') {
      this.required(required)
    }

    return this
  }

  name(name) {
    name = normalizeName(name, 'name')

    let config = this.config
    config.name = name
    config.names = config.alias ? [config.name, ...config.alias] : [config.name]

    return this
  }

  alias(alias) {
    let isArray = Array.isArray(alias)

    if (typeof alias !== 'string' || !isArray) {
      throw new TypeError(
        'The argument of alias() must be either a string or an array'
      )
    }

    if (isArray) {
      alias = [normalizeName(alias, 'alias')]
    } else {
      alias = alias.map((a) => normalizeName(a, 'alias'))
    }

    let config = this.config
    config.alias = isArray ? alias : [alias]
    config.names = config.alias ? [config.name, ...config.alias] : [config.name]

    return this
  }

  description(description) {
    if (typeof description !== 'string' || description.length === 0) {
      throw new TypeError('A description must be a non-empty string')
    }

    this.config.description = description
    return this
  }

  required(value) {
    if (typeof value !== 'undefined' && typeof value !== 'boolean') {
      throw new Error(
        'The argument of required() must be either boolean or undefined'
      )
    }

    value = arguments.length === 0 ? false : value
    this.config.required = value
    return this
  }

  getConfig() {
    return Object.assign({}, this.config)
  }
}

module.exports = Option
<commit_msg>Add option() and type() methods to Option<commit_after>const paramCase = require('param-case')

function normalizeName(value, entity) {
  if (typeof value !== 'string' || value.length === 0) {
    throw new Error(`An option ${entity} must be a non-empty string`)
  }

  if (value.charAt(0) === '-') {
    value = value.substr(1)
  }

  if (value.charAt(0) === '-') {
    value = value.substr(1)
  }

  if (value.charAt(0) === '-') {
    throw new Error(
      `A hyphen is not allowed as the first character of an option ${entity}`
    )
  }

  return paramCase(value)
}

class Option {
  constructor(name, command) {
    if (!name) {
      throw new Error('Either a name or config is required to define an option')
    }

    let config = typeof name === 'string' ? { name } : name

    if (!config.name) {
      throw new Error('A name is required to define an option')
    }

    this.command = command
    this.config = {
      type: 'boolean',
    }
    this.set(config)
  }

  set(config) {
    let { name, alias, description, required } = config

    if (name) {
      this.name(name)
    }

    if (alias) {
      this.alias(alias)
    }

    if (description) {
      this.description(description)
    }

    if (typeof required !== 'undefined') {
      this.required(required)
    }

    return this
  }

  name(name) {
    name = normalizeName(name, 'name')

    let config = this.config
    config.name = name
    config.names = config.alias ? [config.name, ...config.alias] : [config.name]

    return this
  }

  alias(alias) {
    let isArray = Array.isArray(alias)

    if (typeof alias !== 'string' || !isArray) {
      throw new TypeError(
        'The argument of alias() must be either a string or an array'
      )
    }

    if (isArray) {
      alias = [normalizeName(alias, 'alias')]
    } else {
      alias = alias.map((a) => normalizeName(a, 'alias'))
    }

    let config = this.config
    config.alias = isArray ? alias : [alias]
    config.names = config.alias ? [config.name, ...config.alias] : [config.name]

    return this
  }

  description(description) {
    if (typeof description !== 'string' || description.length === 0) {
      throw new TypeError('A description must be a non-empty string')
    }

    this.config.description = description
    return this
  }

  required(value) {
    if (typeof value !== 'undefined' && typeof value !== 'boolean') {
      throw new Error(
        'The argument of required() must be either boolean or undefined'
      )
    }

    value = arguments.length === 0 ? false : value
    this.config.required = value
    return this
  }

  type(type) {
    if (!type || typeof type !== 'string') {
      throw new TypeError('A type must be a non-empty string')
    }

    this.config.type = type
  }

  option(...args) {
    return this.command.option(...args)
  }

  getConfig() {
    return Object.assign({}, this.config)
  }
}

module.exports = Option
<|endoftext|>


<commit_before>angular.module('mewpipe')
       .run(run);

run.$inject = ['$rootScope','$location','$auth'];

function run($rootScope, $location, $auth){

	$rootScope.$on('$routeChangeStart', function(event, next){

		var acceptAnonymous = next.data.authentication.anonymous;
		var acceptConnected = next.data.authentication.connected;

		if(acceptAnonymous && acceptConnected) return;

		var isAuthenticated = $auth.isAuthenticated();

		if( isAuthenticated  && acceptConnected || !isAuthenticated && acceptAnonymous) return;

		//$location.path('/login');

	});

}<commit_msg>Middleware authentication 2<commit_after>angular.module('mewpipe')
       .run(run);

run.$inject = ['$rootScope','$location','$auth'];

function run($rootScope, $location, $auth){

	$rootScope.$on('$routeChangeStart', function(event, next){

		var acceptAnonymous = next.data.authentication.anonymous;
		var acceptConnected = next.data.authentication.connected;
		var isAuthenticated = $auth.isAuthenticated();

		if(	isAuthenticated  && !acceptConnected ||	!isAuthenticated && !acceptAnonymous ){
			//$location.path('/login');
		}

	});

}<|endoftext|>


<commit_before>import Service from '@ember/service';
import ENV from 'openxpki/config/environment';

export default class OxiConfigService extends Service {
    localConfig = {};

    constructor() {
        super(...arguments);
        /* eslint-disable-next-line no-undef */
        let conf = OXI_LOCALCONFIG;
        if (typeof conf !== 'undefined') {
            /* eslint-disable-next-line no-undef */
            this.localConfig = conf;
            /* eslint-disable-next-line no-console */
            console.log("Using custom configuration in localconfig.js");
        }
        else {
            /* eslint-disable-next-line no-console */
            console.log("No localconfig.js found - using defaults");
        }
    }

    get backendPath() {
        return this.localConfig.backendPath || '/cgi-bin/webui.fcgi'; // Protocol + host/port are prepended automatically
    }

    get copyrightYear() {
        return this.localConfig.copyrightYear || ENV.buildYear;
    }

    get header() {
        return this.localConfig.header;
    }

    get footer() {
        return this.localConfig.footer;
    }
}
<commit_msg>JS: fix "OXI_LOCALCONFIG is not defined"<commit_after>import Service from '@ember/service';
import ENV from 'openxpki/config/environment';

export default class OxiConfigService extends Service {
    localConfig = {};

    constructor() {
        super(...arguments);
        /* eslint-disable-next-line no-undef */
        if (typeof OXI_LOCALCONFIG !== 'undefined') {
            /* eslint-disable-next-line no-undef */
            this.localConfig = OXI_LOCALCONFIG;
            /* eslint-disable-next-line no-console */
            console.log("Using custom configuration in localconfig.js");
        }
        else {
            /* eslint-disable-next-line no-console */
            console.log("No localconfig.js found - using defaults");
        }
    }

    get backendPath() {
        return this.localConfig.backendPath || '/cgi-bin/webui.fcgi'; // Protocol + host/port are prepended automatically
    }

    get copyrightYear() {
        return this.localConfig.copyrightYear || ENV.buildYear;
    }

    get header() {
        return this.localConfig.header;
    }

    get footer() {
        return this.localConfig.footer;
    }
}
<|endoftext|>


<commit_before>import 'dom-slider';
import getElements from '../utilities/getElements';

/**
 *  Toggle JS
 *  If `data-sprk-toggle="container"`
 *  elements are available in the DOM
 *  we listen for clicks on the trigger and
 *  call slideToggle to slide the content up or down.
 *  To support non JS scenarios we only hide the content
 *  if JS is detected.
 */

// Toggle the icon type
const toggleIconType = (toggleIcon, toggleIconUse, openIcon, closeIcon) => {
  // set xlink:href attribute to be the filled icon.
  if (toggleIcon.classList.contains('sprk-c-Icon--open')) {
    toggleIconUse.setAttribute('xlink:href', `#${openIcon}`);
  } else {
    toggleIconUse.setAttribute('xlink:href', `#${closeIcon}`);
  }
};

// Toggle the aria expanded attribute
// TODO - deprecate this and use the one in html/utilities
const toggleAriaExpanded = (toggleTrigger) => {
  // If the trigger has the attr then determine toggle state
  if (toggleTrigger.hasAttribute('aria-expanded')) {
    const isExpanded = toggleTrigger.getAttribute('aria-expanded');
    toggleTrigger.setAttribute('aria-expanded', isExpanded === 'false' ? 'true' : 'false');
  } else {
    // If it doesn't have it then set it to false initially
    toggleTrigger.setAttribute('aria-expanded', 'false');
  }
};

const handleToggleClick = (toggleContent, toggleIcon, toggleIconUse, element) => {
  const trigger = element;
  let isAccordion;
  let isMastheadAccordion;

  if (trigger.hasAttribute('data-sprk-toggle-type')) {
    isAccordion = trigger.getAttribute('data-sprk-toggle-type').includes('accordion');
    isMastheadAccordion = trigger.getAttribute('data-sprk-toggle-type') === 'masthead-accordion';
  }

  // Rotate the Icon
  if (toggleIcon) toggleIcon.classList.toggle('sprk-c-Icon--open');

  // Swap icon name based on if open or closed
  if (isAccordion && toggleIconUse) {
    toggleIconType(
      toggleIcon,
      toggleIconUse,
      'chevron-up-circle-two-color',
      'chevron-up-circle-two-color',
    );
  }

  if (isAccordion && !isMastheadAccordion) toggleContent.parentElement.classList.toggle('sprk-c-Accordion__item--open');
  if (isMastheadAccordion) toggleContent.parentElement.classList.toggle('sprk-c-MastheadAccordion__item--open');

  toggleContent.slideToggle(300).then(() => {
    // Enable clicks after animation runs
    trigger.style.pointerEvents = 'auto';
  });

  // Set aria expanded to true
  toggleAriaExpanded(element);
};

const bindToggleUIEvents = (element) => {
  // Get the toggle's trigger and content elements
  const toggleTrigger = element.querySelector('[data-sprk-toggle="trigger"]');
  const toggleContent = element.querySelector('[data-sprk-toggle="content"]');
  const toggleIcon = element.querySelector('[data-sprk-toggle="icon"]');
  const toggleIconUse = element.querySelector('[data-sprk-toggle="accordionIconUseElement"]');

  // Hide details content, initially shown for no-JS scenarios
  toggleContent.style.display = 'none';

  // Set aria-expanded to false initially
  toggleAriaExpanded(toggleTrigger);

  // Add click event listener to trigger for each toggle collection we find
  toggleTrigger.addEventListener('click', (e) => {
    e.preventDefault();
    // Disable clicks till animation runs
    e.currentTarget.style.pointerEvents = 'none';
    handleToggleClick(toggleContent, toggleIcon, toggleIconUse, e.currentTarget);
  });
};

const toggle = () => {
  getElements('[data-sprk-toggle="container"]', bindToggleUIEvents);
};

export {
  toggle, toggleIconType, toggleAriaExpanded, handleToggleClick, bindToggleUIEvents,
};
<commit_msg>Add aria-controls and id checks<commit_after>import 'dom-slider';
import getElements from '../utilities/getElements';
import { uniqueId } from 'lodash';

/**
 *  Toggle JS
 *  If `data-sprk-toggle="container"`
 *  elements are available in the DOM
 *  we listen for clicks on the trigger and
 *  call slideToggle to slide the content up or down.
 *  To support non JS scenarios we only hide the content
 *  if JS is detected.
 */

// Toggle the icon type
const toggleIconType = (toggleIcon, toggleIconUse, openIcon, closeIcon) => {
  // set xlink:href attribute to be the filled icon.
  if (toggleIcon.classList.contains('sprk-c-Icon--open')) {
    toggleIconUse.setAttribute('xlink:href', `#${openIcon}`);
  } else {
    toggleIconUse.setAttribute('xlink:href', `#${closeIcon}`);
  }
};

// Toggle the aria expanded attribute
// TODO - deprecate this and use the one in html/utilities
const toggleAriaExpanded = (toggleTrigger) => {
  // If the trigger has the attr then determine toggle state
  if (toggleTrigger.hasAttribute('aria-expanded')) {
    const isExpanded = toggleTrigger.getAttribute('aria-expanded');
    toggleTrigger.setAttribute('aria-expanded', isExpanded === 'false' ? 'true' : 'false');
  } else {
    // If it doesn't have it then set it to false initially
    toggleTrigger.setAttribute('aria-expanded', 'false');
  }
};

const handleToggleClick = (toggleContent, toggleIcon, toggleIconUse, element) => {
  const trigger = element;
  let isAccordion;
  let isMastheadAccordion;

  if (trigger.hasAttribute('data-sprk-toggle-type')) {
    isAccordion = trigger.getAttribute('data-sprk-toggle-type').includes('accordion');
    isMastheadAccordion = trigger.getAttribute('data-sprk-toggle-type') === 'masthead-accordion';
  }

  // Rotate the Icon
  if (toggleIcon) toggleIcon.classList.toggle('sprk-c-Icon--open');

  // Swap icon name based on if open or closed
  if (isAccordion && toggleIconUse) {
    toggleIconType(
      toggleIcon,
      toggleIconUse,
      'chevron-up-circle-two-color',
      'chevron-up-circle-two-color',
    );
  }

  if (isAccordion && !isMastheadAccordion) toggleContent.parentElement.classList.toggle('sprk-c-Accordion__item--open');
  if (isMastheadAccordion) toggleContent.parentElement.classList.toggle('sprk-c-MastheadAccordion__item--open');

  toggleContent.slideToggle(300).then(() => {
    // Enable clicks after animation runs
    trigger.style.pointerEvents = 'auto';
  });

  // Set aria expanded to true
  toggleAriaExpanded(element);
};

const bindToggleUIEvents = (element) => {
  // Get the toggle's trigger and content elements
  const toggleTrigger = element.querySelector('[data-sprk-toggle="trigger"]');
  const toggleContent = element.querySelector('[data-sprk-toggle="content"]');
  const toggleIcon = element.querySelector('[data-sprk-toggle="icon"]');
  const toggleIconUse = element.querySelector('[data-sprk-toggle="accordionIconUseElement"]');

  const toggleContentId = toggleContent.getAttribute('id');
  const toggleTriggerAriaControls = toggleTrigger.getAttribute('aria-controls');

  // If neither toggleTrigger or toggleContent has
  // id nor aria-controls, the set them with uniqueId
  if (!toggleContentId && !toggleTriggerAriaControls) {
    const ariaToggleId = uniqueId('toggle-content-');
    toggleContent.setAttribute('id', ariaToggleId);
    toggleTrigger.setAttribute('aria-controls', ariaToggleId);
  }

  // If toggle content has an id but its trigger doesn't have aria-controls,
  // add it to the trigger.
  if (toggleContentId && !toggleTriggerAriaControls) {
    toggleTrigger.setAttribute('aria-controls', toggleContentId);
  }

  // Warn if aria-controls and id doesn't match
  if (toggleContentId !== toggleTriggerAriaControls) {
    console.warn('Toggle Trigger id and Content Trigger aria-controls do not match.')
  }

  // Warn if aria-controls exist, but trigger doesn't have matching id
  if (toggleTriggerAriaControls && !toggleContentId) {
    console.warn('Toggle Trigger id and Content Trigger aria-controls do not match.')
  }

  // Hide details content, initially shown for no-JS scenarios
  toggleContent.style.display = 'none';

  // Set aria-expanded to false initially
  toggleAriaExpanded(toggleTrigger);

  // Add click event listener to trigger for each toggle collection we find
  toggleTrigger.addEventListener('click', (e) => {
    e.preventDefault();
    // Disable clicks till animation runs
    e.currentTarget.style.pointerEvents = 'none';
    handleToggleClick(toggleContent, toggleIcon, toggleIconUse, e.currentTarget);
  });
};

const toggle = () => {
  getElements('[data-sprk-toggle="container"]', bindToggleUIEvents);
};

export {
  toggle, toggleIconType, toggleAriaExpanded, handleToggleClick, bindToggleUIEvents,
};
<|endoftext|>


<commit_before>const lit = require('fountain-generator').lit;

module.exports = function karmaConf(props) {
  const conf = {
    basePath: '../',
    singleRun: props.singleRun,
    autoWatch: !props.singleRun,
    logLevel: 'INFO',
    junitReporter: {outputDir: 'test-reports'}
  };

  if (process.env.TRAVIS) {
    conf.browsers = ['Chrome_travis_ci'];
    conf.customLaunchers = lit`{
    Chrome_travis_ci: { // eslint-disable-line camelcase
      base: 'Chrome',
      flags: ['--no-sandbox']
    }
  }`;
  } else if (props.framework === 'angular2') {
    conf.browsers = ['Chrome'];
  } else {
    conf.browsers = ['PhantomJS'];
  }

  const pathSrcJs = lit`conf.path.src('index.spec.js')`;
  const pathSrcHtml = lit`conf.path.src('**/*.html')`;

  if (props.modules === 'systemjs') {
    conf.frameworks = ['jasmine', 'jspm'];
  } else if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.frameworks = ['phantomjs-shim', 'jasmine', 'angular-filesort'];
  } else {
    conf.frameworks = ['jasmine'];
  }

  if (props.modules === 'webpack') {
    conf.files = [
      'node_modules/es6-shim/es6-shim.js',
      pathSrcJs
    ];

    if (props.framework === 'angular1') {
      conf.files.push(pathSrcHtml);
    }
  }
  if (props.modules === 'inject') {
    conf.files = lit`listFiles()`;
  }

  if (props.modules === 'webpack' || props.framework === 'angular1') {
    conf.preprocessors = {};
  }
  if (props.modules === 'webpack') {
    conf.preprocessors[pathSrcJs] = ['webpack'];
  }
  if (props.framework === 'angular1') {
    conf.preprocessors[pathSrcHtml] = ['ng-html2js'];
    if (props.modules === 'systemjs' && props.js === 'typescript') {
      conf.preprocessors[pathSrcHtml].push('generic');
      conf.genericPreprocessor = {
        rules: [lit`{
        process(content, file, done) {
          file.path = file.path.replace(/\\.js$/, '.ts');
          done(content);
        }
      }`]
      };
    }
  }

  if (props.framework === 'angular1') {
    conf.ngHtml2JsPreprocessor = {};

    if (props.modules !== 'systemjs') {
      conf.ngHtml2JsPreprocessor.stripPrefix = lit`\`\${conf.paths.src}/\``;
    }

    if (props.modules === 'inject') {
      conf.ngHtml2JsPreprocessor.moduleName = 'app';
      conf.angularFilesort = {
        whitelist: [lit`conf.path.tmp('**/!(*.html|*.spec|*.mock).js')`]
      };
    }
  }

  if (props.modules === 'webpack') {
    conf.reporters = lit`['progress', 'coverage']`;
    conf.coverageReporter = {
      type: 'html',
      dir: 'coverage/'
    };
    conf.webpack = lit`require('./webpack-test.conf')`;
    conf.webpackMiddleware = {noInfo: true};
  }

  if (props.modules === 'systemjs') {
    conf.jspm = {
      loadFiles: [],
      config: 'jspm.config.js',
      browser: 'jspm.test.js'
    };

    if (props.js === 'typescript') {
      if (props.framework === 'react') {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.tsx')`);
      } else {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.ts')`);
      }
    } else {
      conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.js')`);
    }

    // if (props.framework !== 'react') {
    if (props.framework === 'angular1') {
      conf.jspm.loadFiles.push(lit`conf.path.src('**/*.html')`);
    }
  }

  conf.plugins = [
    lit`require('karma-jasmine')`,
    lit`require('karma-junit-reporter')`,
    lit`require('karma-coverage')`
  ];

  if (props.framework === 'angular2') {
    conf.plugins.push(lit`require('karma-chrome-launcher')`);
  } else {
    conf.plugins.push(lit`require('karma-phantomjs-launcher')`);
    conf.plugins.push(lit`require('karma-phantomjs-shim')`);
  }
  if (props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-ng-html2js-preprocessor')`);
  }
  if (props.modules === 'webpack') {
    conf.plugins.push(lit`require('karma-webpack')`);
  }
  if (props.modules === 'systemjs') {
    conf.plugins.push(lit`require('karma-jspm')`);
  }
  if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-angular-filesort')`);
  }
  if (props.modules === 'systemjs' && props.framework === 'angular1' && props.js === 'typescript') {
    conf.plugins.push(lit`require('karma-generic-preprocessor')`);
  }

  return conf;
};
<commit_msg>Fix wrong browser configuration<commit_after>const lit = require('fountain-generator').lit;

module.exports = function karmaConf(props) {
  const conf = {
    basePath: '../',
    singleRun: props.singleRun,
    autoWatch: !props.singleRun,
    logLevel: 'INFO',
    junitReporter: {outputDir: 'test-reports'}
  };

  if (props.framework === 'angular2') {
    if (process.env.TRAVIS) {
      conf.browsers = ['Chrome_travis_ci'];
      conf.customLaunchers = lit`{
      Chrome_travis_ci: { // eslint-disable-line camelcase
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    }`;
    } else {
      conf.browsers = ['Chrome'];
    }
  } else {
    conf.browsers = ['PhantomJS'];
  }

  const pathSrcJs = lit`conf.path.src('index.spec.js')`;
  const pathSrcHtml = lit`conf.path.src('**/*.html')`;

  if (props.modules === 'systemjs') {
    conf.frameworks = ['jasmine', 'jspm'];
  } else if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.frameworks = ['phantomjs-shim', 'jasmine', 'angular-filesort'];
  } else {
    conf.frameworks = ['jasmine'];
  }

  if (props.modules === 'webpack') {
    conf.files = [
      'node_modules/es6-shim/es6-shim.js',
      pathSrcJs
    ];

    if (props.framework === 'angular1') {
      conf.files.push(pathSrcHtml);
    }
  }
  if (props.modules === 'inject') {
    conf.files = lit`listFiles()`;
  }

  if (props.modules === 'webpack' || props.framework === 'angular1') {
    conf.preprocessors = {};
  }
  if (props.modules === 'webpack') {
    conf.preprocessors[pathSrcJs] = ['webpack'];
  }
  if (props.framework === 'angular1') {
    conf.preprocessors[pathSrcHtml] = ['ng-html2js'];
    if (props.modules === 'systemjs' && props.js === 'typescript') {
      conf.preprocessors[pathSrcHtml].push('generic');
      conf.genericPreprocessor = {
        rules: [lit`{
        process(content, file, done) {
          file.path = file.path.replace(/\\.js$/, '.ts');
          done(content);
        }
      }`]
      };
    }
  }

  if (props.framework === 'angular1') {
    conf.ngHtml2JsPreprocessor = {};

    if (props.modules !== 'systemjs') {
      conf.ngHtml2JsPreprocessor.stripPrefix = lit`\`\${conf.paths.src}/\``;
    }

    if (props.modules === 'inject') {
      conf.ngHtml2JsPreprocessor.moduleName = 'app';
      conf.angularFilesort = {
        whitelist: [lit`conf.path.tmp('**/!(*.html|*.spec|*.mock).js')`]
      };
    }
  }

  if (props.modules === 'webpack') {
    conf.reporters = lit`['progress', 'coverage']`;
    conf.coverageReporter = {
      type: 'html',
      dir: 'coverage/'
    };
    conf.webpack = lit`require('./webpack-test.conf')`;
    conf.webpackMiddleware = {noInfo: true};
  }

  if (props.modules === 'systemjs') {
    conf.jspm = {
      loadFiles: [],
      config: 'jspm.config.js',
      browser: 'jspm.test.js'
    };

    if (props.js === 'typescript') {
      if (props.framework === 'react') {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.tsx')`);
      } else {
        conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.ts')`);
      }
    } else {
      conf.jspm.loadFiles.push(lit`conf.path.src('app/**/*.js')`);
    }

    // if (props.framework !== 'react') {
    if (props.framework === 'angular1') {
      conf.jspm.loadFiles.push(lit`conf.path.src('**/*.html')`);
    }
  }

  conf.plugins = [
    lit`require('karma-jasmine')`,
    lit`require('karma-junit-reporter')`,
    lit`require('karma-coverage')`
  ];

  if (props.framework === 'angular2') {
    conf.plugins.push(lit`require('karma-chrome-launcher')`);
  } else {
    conf.plugins.push(lit`require('karma-phantomjs-launcher')`);
    conf.plugins.push(lit`require('karma-phantomjs-shim')`);
  }
  if (props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-ng-html2js-preprocessor')`);
  }
  if (props.modules === 'webpack') {
    conf.plugins.push(lit`require('karma-webpack')`);
  }
  if (props.modules === 'systemjs') {
    conf.plugins.push(lit`require('karma-jspm')`);
  }
  if (props.modules === 'inject' && props.framework === 'angular1') {
    conf.plugins.push(lit`require('karma-angular-filesort')`);
  }
  if (props.modules === 'systemjs' && props.framework === 'angular1' && props.js === 'typescript') {
    conf.plugins.push(lit`require('karma-generic-preprocessor')`);
  }

  return conf;
};
<|endoftext|>