<commit_before>/*
  Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint bitwise:true */
/*global esmangle:true, exports:true, define:true, require:true*/
(function (factory, global) {
    'use strict';

    var ex;

    function namespace(str, obj) {
        var i, iz, names, name;
        names = str.split('.');
        for (i = 0, iz = names.length; i < iz; ++i) {
            name = names[i];
            if (obj.hasOwnProperty(name)) {
                obj = obj[name];
            } else {
                obj = (obj[name] = {});
            }
        }
        return obj;
    }

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // and plain browser loading,
    if (typeof define === 'function' && define.amd) {
        define('esmangle/pass/remove-wasted-blocks', ['exports', 'esmangle/common'], factory);
    } else if (typeof exports !== 'undefined') {
        factory(exports, require('../common'));
    } else {
        factory(namespace('esmangle.pass', global), namespace('esmangle.common', global));
    }
}(function (exports, common) {
    'use strict';

    var Syntax, traverse, deepCopy, modified;

    Syntax = common.Syntax;
    traverse = common.traverse;
    deepCopy = common.deepCopy;

    function trailingIf(node) {
        switch (node.type) {
        case Syntax.IfStatement:
            if (!node.alternate) {
                return true;
            }
            return trailingIf(node.alternate);

        case Syntax.LabeledStatement:
        case Syntax.ForStatement:
        case Syntax.ForInStatement:
        case Syntax.WhileStatement:
        case Syntax.WithStatement:
            return trailingIf(node.body);
        }
        return false;
    }

    function remove(node) {
        while (node.type === Syntax.BlockStatement && node.body.length === 1) {
            modified = true;
            node = node.body[0];
        }
        return node;
    }

    function removeNotIfStatementTrailing(node) {
        while (node.type === Syntax.BlockStatement && node.body.length === 1 && !trailingIf(node.body[0])) {
            modified = true;
            node = node.body[0];
        }
        return node;
    }

    function removeWastedBlocks(tree, options) {
        var result;

        if (options == null) {
            options = { destructive: false };
        }

        if (options.destructive) {
            result = tree;
        } else {
            result = deepCopy(tree);
        }

        modified = false;

        traverse(result, {
            enter: function enter(node) {
                var i, iz;
                switch (node.type) {
                case Syntax.BlockStatement:
                case Syntax.Program:
                    for (i = 0, iz = node.body.length; i < iz; ++i) {
                        node.body[i] = remove(node.body[i]);
                    }
                    break;

                case Syntax.SwitchCase:
                    for (i = 0, iz = node.consequent.length; i < iz; ++i) {
                        node.consequent[i] = remove(node.consequent[i]);
                    }
                    break;

                case Syntax.IfStatement:
                    if (node.alternate) {
                        node.consequent = removeNotIfStatementTrailing(node.consequent);
                        node.alternate = remove(node.alternate);
                    } else {
                        node.consequent = remove(node.consequent);
                    }
                    break;

                case Syntax.LabeledStatement:
                case Syntax.DoWhileStatement:
                case Syntax.ForStatement:
                case Syntax.ForInStatement:
                case Syntax.WhileStatement:
                case Syntax.WithStatement:
                    node.body = remove(node.body);
                    break;
                }
            }
        });

        return {
            result: result,
            modified: modified
        };
    }

    removeWastedBlocks.passName = 'removeWastedBlocks';
    exports.removeWastedBlocks = removeWastedBlocks;
}, this));
/* vim: set sw=4 ts=4 et tw=80 : */
<commit_msg>Optimize trailingIf predicate implementation<commit_after>/*
  Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint bitwise:true */
/*global esmangle:true, exports:true, define:true, require:true*/
(function (factory, global) {
    'use strict';

    var ex;

    function namespace(str, obj) {
        var i, iz, names, name;
        names = str.split('.');
        for (i = 0, iz = names.length; i < iz; ++i) {
            name = names[i];
            if (obj.hasOwnProperty(name)) {
                obj = obj[name];
            } else {
                obj = (obj[name] = {});
            }
        }
        return obj;
    }

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // and plain browser loading,
    if (typeof define === 'function' && define.amd) {
        define('esmangle/pass/remove-wasted-blocks', ['exports', 'esmangle/common'], factory);
    } else if (typeof exports !== 'undefined') {
        factory(exports, require('../common'));
    } else {
        factory(namespace('esmangle.pass', global), namespace('esmangle.common', global));
    }
}(function (exports, common) {
    'use strict';

    var Syntax, traverse, deepCopy, modified;

    Syntax = common.Syntax;
    traverse = common.traverse;
    deepCopy = common.deepCopy;

    function trailingIf(node) {
        while (true) {
            switch (node.type) {
            case Syntax.IfStatement:
                if (!node.alternate) {
                    return true;
                }
                node = node.alternate;
                continue;

            case Syntax.LabeledStatement:
            case Syntax.ForStatement:
            case Syntax.ForInStatement:
            case Syntax.WhileStatement:
            case Syntax.WithStatement:
                node = node.body;
                continue;
            }
            return false;
        }
    }

    function remove(node) {
        while (node.type === Syntax.BlockStatement && node.body.length === 1) {
            modified = true;
            node = node.body[0];
        }
        return node;
    }

    function removeNotIfStatementTrailing(node) {
        while (node.type === Syntax.BlockStatement && node.body.length === 1 && !trailingIf(node.body[0])) {
            modified = true;
            node = node.body[0];
        }
        return node;
    }

    function removeWastedBlocks(tree, options) {
        var result;

        if (options == null) {
            options = { destructive: false };
        }

        if (options.destructive) {
            result = tree;
        } else {
            result = deepCopy(tree);
        }

        modified = false;

        traverse(result, {
            enter: function enter(node) {
                var i, iz;
                switch (node.type) {
                case Syntax.BlockStatement:
                case Syntax.Program:
                    for (i = 0, iz = node.body.length; i < iz; ++i) {
                        node.body[i] = remove(node.body[i]);
                    }
                    break;

                case Syntax.SwitchCase:
                    for (i = 0, iz = node.consequent.length; i < iz; ++i) {
                        node.consequent[i] = remove(node.consequent[i]);
                    }
                    break;

                case Syntax.IfStatement:
                    if (node.alternate) {
                        node.consequent = removeNotIfStatementTrailing(node.consequent);
                        node.alternate = remove(node.alternate);
                    } else {
                        node.consequent = remove(node.consequent);
                    }
                    break;

                case Syntax.LabeledStatement:
                case Syntax.DoWhileStatement:
                case Syntax.ForStatement:
                case Syntax.ForInStatement:
                case Syntax.WhileStatement:
                case Syntax.WithStatement:
                    node.body = remove(node.body);
                    break;
                }
            }
        });

        return {
            result: result,
            modified: modified
        };
    }

    removeWastedBlocks.passName = 'removeWastedBlocks';
    exports.removeWastedBlocks = removeWastedBlocks;
}, this));
/* vim: set sw=4 ts=4 et tw=80 : */
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Serienjunkies Customer
// @namespace   maha
// @include     http://serienjunkies.org/*
// @grant       none
// @require     http://code.jquery.com/jquery-2.1.0.min.js
// @run-at      document-end
// @version     0.4.10
// @updateURL   https://raw.githubusercontent.com/ymc-maha/sj/master/sj.meta.js
// @downloadURL https://raw.githubusercontent.com/ymc-maha/sj/master/sj.user.js
// ==/UserScript==

(function ($) {

    "use strict";

    var SerienJunkies = function (shows) {
        this.init(shows);
    };

    SerienJunkies.prototype = {

        constructor: SerienJunkies,

        init: function (shows) {
            this.shows = shows;
            this.$container = $('.post-content');
            this.$navigation = $('#gnav');
            this.$tpl = null;

            if (this.$navigation.find('.current_page_item a').text() == "Home") {
                this.createTemplate();
                this.findAndAppendLinks();
                this.$container.prepend(this.$tpl);
                this.initObserver();
            }
            this.findShow();

        },

        initObserver: function () {
            var that = this;
            this.$container.on('click', 'a.show', function (e) {
                e.preventDefault();
                that.storeItem($(this).text());
                document.location = $(this).data('target');
            });
        },

        storeItem: function (value) {
            window.localStorage.setItem('sj-show', value);
        },

        readItem: function () {
            return window.localStorage.getItem('sj-show');
        },

        removeItem: function () {
            window.localStorage.removeItem('sj-show');
        },

        createTemplate: function () {
            var $body = $('<fieldset class="personal"></fieldset>'),
                $title = $('<legend>Meine Serien</legend>'),
                $content = $('

');

            $body.append($title)
                .append($content);

            $(this.shows).each(function () {
                var $ul = $('

');
                $content.append($ul);
            });

            this.$tpl = $body;
        },

        findAndAppendLinks: function () {
            var that = this;

            this.$container.find('a').each(function () {
                var text = $(this).text(),
                    $a = that.prepareAnchor($(this));

                $(that.shows).each(function () {
                    if (text.indexOf(this.name) != -1 && text.indexOf(this.quality) != -1) {
                        var $li = $('

');
                        if (text.indexOf('German') != -1 || text.indexOf('GERMAN') != -1) {
                            that.$tpl.find('ul.' + this.id).append($li.append($a));
                        }

                    }
                });
            });
        },

        prepareAnchor: function ($anchor) {
            $anchor.attr('data-target', $anchor.attr('href')).attr('href', '#').addClass('show');
            return $anchor;
        },

        findShow: function () {
            var show = this.readItem();
            if (show) {
                var $target = $('strong:contains("'+show+'")');
                if ( typeof $target === 'object') {
                    this.scrollToShow($target);
                }
            }
        },

        scrollToShow: function ($target) {
            $($target).attr('style', 'background-color: red');
            $('html, body').animate({ scrollTop:$($target).offset().top },'slow');
            this.removeItem();
        }
    };

    var shows = [
        {
            id: 'mentalist',
            name: 'Mentalist',
            quality: '720p'
        },
        {
            id: 'ncisla',
            name: 'NCIS.Los.Angeles',
            quality: '720p'
        },
        {
            id: 'ncis',
            name: 'NCIS.S',
            quality: '720p'
        },
        {
            id: 'hawaii',
            name: 'Hawaii.Five.0',
            quality: '720p'
        },
        {
            id: 'brokegirls',
            name: '2.Broke.Girls',
            quality: '720p'
        },
        {
            id: 'mother',
            name: 'How.I.Met.Your.Mother',
            quality: '720p'
        },
        {
            id: 'bigbang',
            name: 'The.Big.Bang.Theory',
            quality: '720p'
        },
        {
            id: 'suburgatory',
            name: 'Suburgatory',
            quality: '720p'
        },
        {
            id: 'mum',
            name: 'Mike.und.Molly',
            quality: '720p'
        },
        {
            id: 'sherlock',
            name: 'Sherlock',
            quality: '720p'
        },
        {
            id: 'elementary',
            name: 'Elementary',
            quality: '720p'
        },
        {
            id: 'blacklist',
            name: 'The.Blacklist',
            quality: '720p'
        },
        {
            id: 'helix',
            name: 'Helix',
            quality: '720p'
        },
        {
            id: 'hart',
            name: 'Hart.of.Dixie',
            quality: '720p'
        },
        {
            id: 'greys',
            name: 'Greys.Anatomy',
            quality: '720p'
        },
        {
            id: 'glades',
            name: 'The.Glades',
            quality: '720p'
        },
        {
            id: 'bones',
            name: 'Bones',
            quality: '720p'
        },
        {
            id: 'diamond',
            name: 'Detective.Laura.Diamond',
            quality: '720p'
        },
        {
            id: 'mom',
            name: 'Mom',
            quality: '720p'
        },
        {
            id: 'rizzoli'
            name: 'Rizzoli'
            quality: '720p'
        }
    ];

    $(window).load(function () {
        new SerienJunkies(shows);
    });

}(window.jQuery));
<commit_msg>Add missing semicolons<commit_after>// ==UserScript==
// @name        Serienjunkies Customer
// @namespace   maha
// @include     http://serienjunkies.org/*
// @grant       none
// @require     http://code.jquery.com/jquery-2.1.0.min.js
// @run-at      document-end
// @version     0.4.11
// @updateURL   https://raw.githubusercontent.com/ymc-maha/sj/master/sj.meta.js
// @downloadURL https://raw.githubusercontent.com/ymc-maha/sj/master/sj.user.js
// ==/UserScript==

(function ($) {

    "use strict";

    var SerienJunkies = function (shows) {
        this.init(shows);
    };

    SerienJunkies.prototype = {

        constructor: SerienJunkies,

        init: function (shows) {
            this.shows = shows;
            this.$container = $('.post-content');
            this.$navigation = $('#gnav');
            this.$tpl = null;

            if (this.$navigation.find('.current_page_item a').text() == "Home") {
                this.createTemplate();
                this.findAndAppendLinks();
                this.$container.prepend(this.$tpl);
                this.initObserver();
            }
            this.findShow();

        },

        initObserver: function () {
            var that = this;
            this.$container.on('click', 'a.show', function (e) {
                e.preventDefault();
                that.storeItem($(this).text());
                document.location = $(this).data('target');
            });
        },

        storeItem: function (value) {
            window.localStorage.setItem('sj-show', value);
        },

        readItem: function () {
            return window.localStorage.getItem('sj-show');
        },

        removeItem: function () {
            window.localStorage.removeItem('sj-show');
        },

        createTemplate: function () {
            var $body = $('<fieldset class="personal"></fieldset>'),
                $title = $('<legend>Meine Serien</legend>'),
                $content = $('

');

            $body.append($title)
                .append($content);

            $(this.shows).each(function () {
                var $ul = $('

');
                $content.append($ul);
            });

            this.$tpl = $body;
        },

        findAndAppendLinks: function () {
            var that = this;

            this.$container.find('a').each(function () {
                var text = $(this).text(),
                    $a = that.prepareAnchor($(this));

                $(that.shows).each(function () {
                    if (text.indexOf(this.name) != -1 && text.indexOf(this.quality) != -1) {
                        var $li = $('

');
                        if (text.indexOf('German') != -1 || text.indexOf('GERMAN') != -1) {
                            that.$tpl.find('ul.' + this.id).append($li.append($a));
                        }

                    }
                });
            });
        },

        prepareAnchor: function ($anchor) {
            $anchor.attr('data-target', $anchor.attr('href')).attr('href', '#').addClass('show');
            return $anchor;
        },

        findShow: function () {
            var show = this.readItem();
            if (show) {
                var $target = $('strong:contains("'+show+'")');
                if ( typeof $target === 'object') {
                    this.scrollToShow($target);
                }
            }
        },

        scrollToShow: function ($target) {
            $($target).attr('style', 'background-color: red');
            $('html, body').animate({ scrollTop:$($target).offset().top },'slow');
            this.removeItem();
        }
    };

    var shows = [
        {
            id: 'mentalist',
            name: 'Mentalist',
            quality: '720p'
        },
        {
            id: 'ncisla',
            name: 'NCIS.Los.Angeles',
            quality: '720p'
        },
        {
            id: 'ncis',
            name: 'NCIS.S',
            quality: '720p'
        },
        {
            id: 'hawaii',
            name: 'Hawaii.Five.0',
            quality: '720p'
        },
        {
            id: 'brokegirls',
            name: '2.Broke.Girls',
            quality: '720p'
        },
        {
            id: 'mother',
            name: 'How.I.Met.Your.Mother',
            quality: '720p'
        },
        {
            id: 'bigbang',
            name: 'The.Big.Bang.Theory',
            quality: '720p'
        },
        {
            id: 'suburgatory',
            name: 'Suburgatory',
            quality: '720p'
        },
        {
            id: 'mum',
            name: 'Mike.und.Molly',
            quality: '720p'
        },
        {
            id: 'sherlock',
            name: 'Sherlock',
            quality: '720p'
        },
        {
            id: 'elementary',
            name: 'Elementary',
            quality: '720p'
        },
        {
            id: 'blacklist',
            name: 'The.Blacklist',
            quality: '720p'
        },
        {
            id: 'helix',
            name: 'Helix',
            quality: '720p'
        },
        {
            id: 'hart',
            name: 'Hart.of.Dixie',
            quality: '720p'
        },
        {
            id: 'greys',
            name: 'Greys.Anatomy',
            quality: '720p'
        },
        {
            id: 'glades',
            name: 'The.Glades',
            quality: '720p'
        },
        {
            id: 'bones',
            name: 'Bones',
            quality: '720p'
        },
        {
            id: 'diamond',
            name: 'Detective.Laura.Diamond',
            quality: '720p'
        },
        {
            id: 'mom',
            name: 'Mom',
            quality: '720p'
        },
        {
            id: 'rizzoli',
            name: 'Rizzoli',
            quality: '720p'
        }
    ];

    $(window).load(function () {
        new SerienJunkies(shows);
    });

}(window.jQuery));
<|endoftext|>


<commit_before>const Applause = require('applause');

module.exports = {
  // Here, you can strip out any non-JS content
  // and split into multiple strings to lint.
  preprocess(text, fileName) {
    const applause = Applause.create({
      patterns: [
        {
          match: /native\s+function\s+(\w+)\s*\(\)/g,
          replacement: 'var $1 = function() {}'
        }
      ]
    });

    const substitute = applause.replace(text);
    return [substitute.content];
  },
  // `messages` argument contains two-dimensional array of Message objects
  // where each top-level array item contains array of lint messages related
  // to the text that was returned in array from preprocess() method.
  postprocess(messages, fileName) {
    const message = messages[0];
    return message;
  }
};
<commit_msg>Return original text if it contains no native function declarations.<commit_after>const Applause = require('applause');

module.exports = {
  // Here, you can strip out any non-JS content
  // and split into multiple strings to lint.
  preprocess(text, fileName) {
    const applause = Applause.create({
      patterns: [
        {
          match: /native\s+function\s+(\w+)\s*\(\)/g,
          replacement: 'var $1 = function() {}'
        }
      ]
    });

    const substitute = applause.replace(text);
    return substitute.content ? [substitute.content] : [text];
  },
  // `messages` argument contains two-dimensional array of Message objects
  // where each top-level array item contains array of lint messages related
  // to the text that was returned in array from preprocess() method.
  postprocess(messages, fileName) {
    const message = messages[0];
    return message;
  }
};
<|endoftext|>


<commit_before>define([],
function () {
  window.logger = {
    debug: function() {
      if (console) {
        console.info.apply(console, arguments);
      }
    },
    error: function() {
      if (console) {
        console.error.apply(console, arguments);
      }
    },
    info: function() {
      if (console) {
        console.info.apply(console, arguments);
      }
    },
    log: function() {
      if (console) {
        console.log.apply(console, arguments);
      }
    },
    warn: function() {
      if (console) {
        console.warn.apply(console, arguments);
      }
    }
  };
});
<commit_msg>Remove client side logging<commit_after>define([],
function () {
  window.logger = {
    debug: function() {},
    error: function() {},
    info: function() {},
    log: function() {},
    warn: function() {}
  };
});
<|endoftext|>


<commit_before>/**
* Create a query params Object
* Joi is already converting the query and params for the short name to the JSONAPI format
* ex: occupation to filter[occupation]
*/
const queryParamsAll = require('./query-params-all');
const queryParamsObjects = require('./query-params-objects');
const queryParamsPeople = require('./query-params-people');
const queryParmasDocuments = require('./query-params-documents');

module.exports = (typeFormat, queryParams) => {
  var result = {};

  // Main values
  result.query = queryParams.query;
  result.q = queryParams.query.q ? queryParams.query.q.trim() : undefined;
  result.pageNumber = parseInt(queryParams.query['page[number]']) || 0;
  result.pageSize = parseInt(queryParams.query['page[size]']) || 50;
  result.pageType = queryParams.query['page[type]'] || 'search';
  result.pageSort = queryParams.query['page[sort]'] || 'default';
  result.type = queryParams.params.type || queryParams.query['fields[type]'] || 'all';
  result.random = queryParams.query.random;

  result.filter = {all: {}, objects: {}, people: {}, documents: {}};

  // All
  Object.assign(result.filter.all, queryParamsAll(typeFormat, queryParams));

  // Objects
  Object.assign(result.filter.objects, queryParamsObjects(typeFormat, queryParams));
  Object.assign(result.filter.objects.categories, formatCategoryNames(result.filter.objects.categories));
  // People
  Object.assign(result.filter.people, queryParamsPeople(typeFormat, queryParams));

  // Documents
  Object.assign(result.filter.documents, queryParmasDocuments(typeFormat, queryParams));

  return result;
};

/*
Some cateogires contains a dash in their name.
By default the application convert space to dash on the front end
and dash to space on the backend. This function add dash for the
specific categories.
see issue #1008
*/
function formatCategoryNames (categories) {
  const categoryNames = {
    'x rays': 'x-rays',
    'medical ceramic ware': 'medical ceramic-ware',
    'medical glass ware': 'medical glass-ware',
    'pharmacy ware': 'pharmacy ware',
    'penn gaskell collection': 'penn-gaskell collection'
  };
  return categories.map(c => {
    return categoryNames[c.toLowerCase()] || c;
  });
}
<commit_msg>check categories exist, #1008<commit_after>/**
* Create a query params Object
* Joi is already converting the query and params for the short name to the JSONAPI format
* ex: occupation to filter[occupation]
*/
const queryParamsAll = require('./query-params-all');
const queryParamsObjects = require('./query-params-objects');
const queryParamsPeople = require('./query-params-people');
const queryParmasDocuments = require('./query-params-documents');

module.exports = (typeFormat, queryParams) => {
  var result = {};

  // Main values
  result.query = queryParams.query;
  result.q = queryParams.query.q ? queryParams.query.q.trim() : undefined;
  result.pageNumber = parseInt(queryParams.query['page[number]']) || 0;
  result.pageSize = parseInt(queryParams.query['page[size]']) || 50;
  result.pageType = queryParams.query['page[type]'] || 'search';
  result.pageSort = queryParams.query['page[sort]'] || 'default';
  result.type = queryParams.params.type || queryParams.query['fields[type]'] || 'all';
  result.random = queryParams.query.random;

  result.filter = {all: {}, objects: {}, people: {}, documents: {}};

  // All
  Object.assign(result.filter.all, queryParamsAll(typeFormat, queryParams));

  // Objects
  Object.assign(result.filter.objects, queryParamsObjects(typeFormat, queryParams));
  Object.assign(result.filter.objects.categories, formatCategoryNames(result.filter.objects.categories));
  // People
  Object.assign(result.filter.people, queryParamsPeople(typeFormat, queryParams));

  // Documents
  Object.assign(result.filter.documents, queryParmasDocuments(typeFormat, queryParams));

  return result;
};

/*
Some cateogires contains a dash in their name.
By default the application convert space to dash on the front end
and dash to space on the backend. This function add dash for the
specific categories.
see issue #1008
*/
function formatCategoryNames (categories) {
 if (categories) {
   const categoryNames = {
     'x rays': 'x-rays',
     'medical ceramic ware': 'medical ceramic-ware',
     'medical glass ware': 'medical glass-ware',
     'pharmacy ware': 'pharmacy ware',
     'penn gaskell collection': 'penn-gaskell collection'
   };
   return categories.map(c => {
     return categoryNames[c.toLowerCase()] || c;
   });
 } else {
   return categories;
 }
}
<|endoftext|>


<commit_before>/*!
 * VERSION: 1.7.4
 * DATE: 2014-07-17
 * UPDATES AND DOCS AT: http://www.greensock.com
 *
 * @license Copyright (c) 2008-2015, GreenSock. All rights reserved.
 * This work is subject to the terms at http://greensock.com/standard-license or for
 * Club GreenSock members, the software agreement that was issued with your membership.
 *
 * @author: Jack Doyle, jack@greensock.com
 **/
var _gsScope="undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window;(_gsScope._gsQueue||(_gsScope._gsQueue=[])).push(function(){"use strict";var t=document.documentElement,e=window,i=function(i,r){var s="x"===r?"Width":"Height",n="scroll"+s,a="client"+s,o=document.body;return i===e||i===t||i===o?Math.max(t[n],o[n])-(e["inner"+s]||Math.max(t[a],o[a])):i[n]-i["offset"+s]},r=_gsScope._gsDefine.plugin({propName:"scrollTo",API:2,version:"1.7.4",init:function(t,r,s){return this._wdw=t===e,this._target=t,this._tween=s,"object"!=typeof r&&(r={y:r}),this.vars=r,this._autoKill=r.autoKill!==!1,this.x=this.xPrev=this.getX(),this.y=this.yPrev=this.getY(),null!=r.x?(this._addTween(this,"x",this.x,"max"===r.x?i(t,"x"):r.x,"scrollTo_x",!0),this._overwriteProps.push("scrollTo_x")):this.skipX=!0,null!=r.y?(this._addTween(this,"y",this.y,"max"===r.y?i(t,"y"):r.y,"scrollTo_y",!0),this._overwriteProps.push("scrollTo_y")):this.skipY=!0,!0},set:function(t){this._super.setRatio.call(this,t);var r=this._wdw||!this.skipX?this.getX():this.xPrev,s=this._wdw||!this.skipY?this.getY():this.yPrev,n=s-this.yPrev,a=r-this.xPrev;this._autoKill&&(!this.skipX&&(a>7||-7>a)&&i(this._target,"x")>r&&(this.skipX=!0),!this.skipY&&(n>7||-7>n)&&i(this._target,"y")>s&&(this.skipY=!0),this.skipX&&this.skipY&&(this._tween.kill(),this.vars.onAutoKill&&this.vars.onAutoKill.apply(this.vars.onAutoKillScope||this._tween,this.vars.onAutoKillParams||[]))),this._wdw?e.scrollTo(this.skipX?r:this.x,this.skipY?s:this.y):(this.skipY||(this._target.scrollTop=this.y),this.skipX||(this._target.scrollLeft=this.x)),this.xPrev=this.x,this.yPrev=this.y}}),s=r.prototype;r.max=i,s.getX=function(){return this._wdw?null!=e.pageXOffset?e.pageXOffset:null!=t.scrollLeft?t.scrollLeft:document.body.scrollLeft:this._target.scrollLeft},s.getY=function(){return this._wdw?null!=e.pageYOffset?e.pageYOffset:null!=t.scrollTop?t.scrollTop:document.body.scrollTop:this._target.scrollTop},s._kill=function(t){return t.scrollTo_x&&(this.skipX=!0),t.scrollTo_y&&(this.skipY=!0),this._super._kill.call(this,t)}}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()();

var controller = new ScrollMagic.Controller();

var $atomic_nav       = document.getElementById('nav'),
    $atomic_links     = $atomic_nav.children,
    atomic_scrollinks = {};

for (var i = 0, l = $atomic_links.length; i < l; i++) {
  var href = $atomic_links[i].hash.replace('#', ''),
      id   = $atomic_links[i].id,
      key  = href;

  atomic_scrollinks[key] = id;
}

for (var key in atomic_scrollinks) {
  new ScrollMagic.Scene({
      duration: $('#' + key).height(),
      triggerElement: '#' + key
    })
    .setClassToggle('#' + atomic_scrollinks[key], 'active')
    .addTo(controller);
}

controller.scrollTo(function(target) {

  TweenMax.to(window, 0.5, {
    scrollTo : {
      y: target,
      autoKill: true
    },

    ease : Cubic.easeInOut
  });

});

$atomic_nav.addEventListener('click', function(e) {

  if(e.target && e.target.nodeName == 'A') {

    var id = e.target.hash;

    if(id.length > 0) {
      e.preventDefault();

      controller.scrollTo(id);

      if (window.history && window.history.pushState) {
        history.pushState('', document.title, id);
      }
    }

  }

});<commit_msg>dynamic control for any nav links with a hash. includes back to top button now<commit_after>// Primary Navigation
// =======================================

var controller        = new ScrollMagic.Controller(),
    atomic_nav        = document.getElementById('nav'),
    atomic_links      = atomic_nav.children,
    atomic_scrollinks = {};

for (var i = 0, l = atomic_links.length; i < l; i++) {
  if(atomic_links[i].hash !== '') {
    var href = atomic_links[i].hash.replace('#', ''),
        id   = atomic_links[i].id,
        key  = href;

    atomic_scrollinks[key] = id;
  }
}

for (var key in atomic_scrollinks) {
  new ScrollMagic.Scene({
      duration: document.getElementById(key).scrollHeight,
      triggerElement: '#' + key
    })
    .setClassToggle('#' + atomic_scrollinks[key], 'active')
    .addTo(controller);
}

function scrollToTween(target) {
  TweenMax.to(window, 0.675, {
    scrollTo : {
      y: target,
      autoKill: true
    },

    ease : Cubic.easeInOut
  });
}

function scrollToTrigger(e) {
  if(e.target && e.target.nodeName == 'A') {
    var id = e.target.hash;

    if(id.length > 0) {
      e.preventDefault();
      controller.scrollTo(id);

      if (window.history && window.history.pushState) {
        history.pushState('', document.title, id);
      }
    }
  }
}

controller.scrollTo(function(target) {
  scrollToTween(target);
});

atomic_nav.addEventListener('click', function(e) {
  scrollToTrigger(e);
});

// Back To Top Button
// =======================================

var button_id = 'scroll-top';
var button_scene = new ScrollMagic.Scene({
  offset: document.getElementsByTagName('header')[0].offsetHeight,
  reverse: true
}).addTo(controller);

function hideTopButton(event, id) {
  var el = document.getElementById(id);
  el.style.opacity = 0;
}

function makeTopButton(event, id) {
  var top_hash = document.body.getAttribute('id');

  if(document.getElementById(id) === null) {
    var el = document.createElement('a');

    el.innerHTML = 'topside';

    document.body.appendChild(el);

    el.setAttribute('id', id);
    el.setAttribute('href', '#' + top_hash);

    el.addEventListener('click', function(e) {
      scrollToTrigger(e);
    });
  } else {
    document.getElementById(id).style.opacity = 1;
  }
}

button_scene.on('enter', function(event) {
  makeTopButton(event, button_id);
}).on('leave', function(event) {
  hideTopButton(event, button_id);
});
<|endoftext|>


<commit_before>var WAITING = 1;
var NOT_WAITING = 0;

function status() {
  return localStorage["__auto-wait"];
}

function setStatus(st) {
  localStorage["__auto-wait"] = st;
}

function isWaiting() {
  return (status() == WAITING);
}

function setWaiting() {
  setStatus(WAITING);
}

function setNotWaiting() {
  setStatus(NOT_WAITING);
}

function setDefaultStatus() {
	setWaiting();
}

function firstTime() {
	return status() == null;
}

if (firstTime()) {
  setWaiting();
}

function video_played() {
  setWaiting();
}

function video_paused() {
  setNotWaiting();
}

function pause_video(v) {
  if (html5) {
    v.pause();
  } else {
    v.pauseVideo();
  }
}

function enable_autoplay(v) {
  // do nothing, youtube videos should be autoplay by default
  // v.autoplay = "";
}

function disable_autoplay(v) {
  pause_video(v);
}

function correct_autoplay(v) {
  if (isWaiting()) {
    disable_autoplay(v);
  } else {
    enable_autoplay(v);
  }
}

function modify_video(v) {
  correct_autoplay(v);
  v.addEventListener("play", video_played, false);
  v.addEventListener("pause", video_paused, false);
}

html5 = document.getElementsByClassName("video-stream")[0];
flash = document.getElementById("movie_player");

video = flash || html5

if (flash) {
  setTimeout(function() { if (isWaiting()) { video.pauseVideo(); } else { setWaiting(); } }, 1000);
} else {
  modify_video(video);
}

if (flash) {
  window.onbeforeunload = function() { pause_video(video); setNotWaiting(); }
} else {
  window.onbeforeunload = function() { pause_video(video); };
}
<commit_msg>Whitespace only: indent characters.<commit_after>var WAITING = 1;
var NOT_WAITING = 0;

function status() {
  return localStorage["__auto-wait"];
}

function setStatus(st) {
  localStorage["__auto-wait"] = st;
}

function isWaiting() {
  return (status() == WAITING);
}

function setWaiting() {
  setStatus(WAITING);
}

function setNotWaiting() {
  setStatus(NOT_WAITING);
}

function setDefaultStatus() {
  setWaiting();
}

function firstTime() {
  return status() == null;
}

if (firstTime()) {
  setWaiting();
}

function video_played() {
  setWaiting();
}

function video_paused() {
  setNotWaiting();
}

function pause_video(v) {
  if (html5) {
    v.pause();
  } else {
    v.pauseVideo();
  }
}

function enable_autoplay(v) {
  // do nothing, youtube videos should be autoplay by default
  // v.autoplay = "";
}

function disable_autoplay(v) {
  pause_video(v);
}

function correct_autoplay(v) {
  if (isWaiting()) {
    disable_autoplay(v);
  } else {
    enable_autoplay(v);
  }
}

function modify_video(v) {
  correct_autoplay(v);
  v.addEventListener("play", video_played, false);
  v.addEventListener("pause", video_paused, false);
}

html5 = document.getElementsByClassName("video-stream")[0];
flash = document.getElementById("movie_player");

video = flash || html5

if (flash) {
  setTimeout(function() { if (isWaiting()) { video.pauseVideo(); } else { setWaiting(); } }, 1000);
} else {
  modify_video(video);
}

if (flash) {
  window.onbeforeunload = function() { pause_video(video); setNotWaiting(); }
} else {
  window.onbeforeunload = function() { pause_video(video); };
}
<|endoftext|>


<commit_before>"use strict"

var Promise = require("promise"),
    moment = require("moment"),
    rdm = require("./index"),
    util = require("util");

var aws = require("aws-sdk-promise")(),
    ci = aws.Cognito();

const debug = util.debuglog("redis_model::authorization");

var IdentityPool = {
    Id: process.env["AWS_COGNITO_IDENTITY_POOL_ID"],
    Origin: process.env["ORIGIN_AUTHORITY"],
};

// Created duration for temporary credentials
const credDuration = moment.duration(59, "m").asSeconds();

var credentialSchema = rdm.Schema("Credentials", {
    // Temporary credentials to AWS resource
    AccessKeyId: String,
    SecretKey: String,
    SessionToken: String,
    Expiration: moment,
});

credentialSchema.methods.get = function() {
    return Promise.resolve(new aws.Credentials(
        this.AccessKeyId.valueOf(),
        this.SecretKey.valueOf(),
        this.SessionToken.valueOf()
    ));
};

credentialSchema.methods.valid = function() {
    return !this.Expiration || moment().isBefore(this.Expiration);
};

var authorizationSchema = rdm.Schema("Authorization", {
    // Refresh Token for temporary credentials to AWS resource
    _token: String,

    // Temporary credentials to AWS resource
    _credentials: credentialSchema,

    // Abstraction of permission in terms of business logic
    rights: Set,
});

authorizationSchema.methods.NewCred = function() {
    var self = this;
    if (self._credentials && self._credentials.valid()) {
        return self._credentials.get();
    } else {
        var iden = self._id.valueOf();
        var token = self._token.valueOf();
        var params = {
            IdentityPoolId: IdentityPool.Id,
            IdentityId: iden,
            Logins: ci.NewLogins("Origin", token),
        };
        return ci.GetCredentials(params)
            .then(function(c) {
                var Credentials = self.r.model("Credentials");
                self._credentials = new Credentials(c.data.Credentials);
                return self.save({_credentials: {duration: credDuration}});
            })
            .then(function() {
                return self._credentials.get();
            });
    }
};

authorizationSchema.methods.check = function(action) {
    return this.rights.has(action);
};

authorizationSchema.methods.addPermission = function(rights) {
    for (let one of rights) {
        this.rights.add(one);
    }
};

authorizationSchema.methods.removePermission = function(rights) {
    for (let one of rights) {
        this.rights.delete(one);
    }
};

module.exports.authorizationSchema = authorizationSchema;

module.exports.build = function(context) {
    var Auth = context.model(authorizationSchema);
    Auth.OpenID = function(login, accnt) {
        return ci.GetOpenIdTokenForDeveloperIdentity(login).then(function(id) {
            var authorize = new Auth({
                // Global Identity
                _id: id.IdentityId,
                // Token for exchanging temporary credentials
                _token: id.Token,
                // Delayed credential setup
                _credentials: null,
                // User's current rights
                rights: accnt.rights,
            });
            return authorize;
        });
    };
    Auth.IdentityPool = IdentityPool;
    return Auth;
};
<commit_msg>FIX: detach credential save from main authorization<commit_after>"use strict"

var Promise = require("promise"),
    moment = require("moment"),
    rdm = require("./index"),
    util = require("util");

var aws = require("aws-sdk-promise")(),
    ci = aws.Cognito();

const debug = util.debuglog("redis_model::authorization");

var IdentityPool = {
    Id: process.env["AWS_COGNITO_IDENTITY_POOL_ID"],
    Origin: process.env["ORIGIN_AUTHORITY"],
};

// Created duration for temporary credentials
const credDuration = moment.duration(59, "m").asSeconds();

var credentialSchema = rdm.Schema("Credentials", {
    // Temporary credentials to AWS resource
    AccessKeyId: String,
    SecretKey: String,
    SessionToken: String,
    Expiration: moment,
});

credentialSchema.methods.get = function() {
    return Promise.resolve(new aws.Credentials(
        this.AccessKeyId.valueOf(),
        this.SecretKey.valueOf(),
        this.SessionToken.valueOf()
    ));
};

credentialSchema.methods.valid = function() {
    return !this.Expiration || moment().isBefore(this.Expiration);
};

var authorizationSchema = rdm.Schema("Authorization", {
    // Refresh Token for temporary credentials to AWS resource
    _token: String,

    // Temporary credentials to AWS resource
    _credentials: credentialSchema,

    // Abstraction of permission in terms of business logic
    rights: Set,
});

authorizationSchema.methods.NewCred = function() {
    var self = this;
    if (self._credentials && self._credentials.valid()) {
        return self._credentials.get();
    } else {
        var iden = self._id.valueOf();
        var token = self._token.valueOf();
        var params = {
            IdentityPoolId: IdentityPool.Id,
            IdentityId: iden,
            Logins: ci.NewLogins("Origin", token),
        };
        return ci.GetCredentials(params)
            .then(function(c) {
                var Credentials = self.r.model("Credentials");
                self._credentials = new Credentials({
                    // inherit this identity from predecessor
                    _id: self._credentials._id.valueOf(),
                    // Credential data for AWS asset
                    AccessKeyId: c.data.Credentials.AccessKeyId,
                    SecretKey: c.data.Credentials.SecretKey,
                    SessionToken: c.data.Credentials.SessionToken,
                    // Extra info for credential expire datetime
                    Expiration: c.data.Credentials.Expiration,
                });
                return self._credentials.save({duration: credDuration});
            })
            .then(function() {
                return self._credentials.get();
            });
    }
};

authorizationSchema.methods.check = function(action) {
    return this.rights.has(action);
};

authorizationSchema.methods.addPermission = function(rights) {
    for (let one of rights) {
        this.rights.add(one);
    }
};

authorizationSchema.methods.removePermission = function(rights) {
    for (let one of rights) {
        this.rights.delete(one);
    }
};

module.exports.authorizationSchema = authorizationSchema;

module.exports.build = function(context) {
    var Auth = context.model(authorizationSchema);
    Auth.OpenID = function(login, accnt) {
        return ci.GetOpenIdTokenForDeveloperIdentity(login).then(function(id) {
            var authorize = new Auth({
                // Global Identity
                _id: id.IdentityId,
                // Token for exchanging temporary credentials
                _token: id.Token,
                // Delayed credential setup
                _credentials: new Auth.Credentials({}),
                // User's current rights
                rights: accnt.rights,
            });
            // TODO: purge old Credentials?
            return authorize;
        });
    };
    Auth.IdentityPool = IdentityPool;
    return Auth;
};
<|endoftext|>


<commit_before>import React from 'react';

import { Thieseract, Anatta336 } from 'MAINTAINERS';
import Wrapper from 'common/Wrapper';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

export default [
  {
    date: new Date('2018-01-29'),
    changes: <Wrapper>Added low energy <SpellLink id={SPELLS.FEROCIOUS_BITE.id} /> tracking</Wrapper>,
    contributors: [Anatta336],
  },
  {
    date: new Date('2018-01-24'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.ASHAMANES_RIP.id} /> uptime tracking</Wrapper>,
    contributors: [Anatta336],
  },
  {
    date: new Date('2017-09-22'),
    changes: 'Added 5 combo point finisher tracking',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-11'),
    changes: 'Refactored combo point tracking properties',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-11'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.SAVAGE_ROAR_TALENT.id} icon /> damage contribution</Wrapper>,
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-10'),
    changes: 'Changed exceptions to conditional assignment on combo point tracker',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-06'),
    changes: 'Updated combo point tracking to handle non standard generator and spenders',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'Cleaned up this.owner modules where possible',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'Added combo point tracking',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'Added bleed uptime tracking',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'CooldownTracker configured',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-03'),
    changes: 'Initial commit. Damage done, ABC, and Abilities added',
    contributors: [Thieseract],
  },
];
<commit_msg>Updated changelog<commit_after>import React from 'react';

import { Thieseract, Anatta336, sref } from 'MAINTAINERS';
import Wrapper from 'common/Wrapper';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

export default [
  {
    date: new Date('2018-02-10'),
    changes: <Wrapper><SpellLink id={SPELLS.PRIMAL_FURY.id} /> procs from an ability used at 4 CPs no longer count as 'wasted' CPs because it's not within the player's control. Also, <SpellLink id={SPELLS.PRIMAL_FURY.id} /> procs will no longer be shown in the Cooldowns tab.</Wrapper>,
    contributors: [sref],
  },
  {
    date: new Date('2018-01-29'),
    changes: <Wrapper>Added low energy <SpellLink id={SPELLS.FEROCIOUS_BITE.id} /> tracking</Wrapper>,
    contributors: [Anatta336],
  },
  {
    date: new Date('2018-01-24'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.ASHAMANES_RIP.id} /> uptime tracking</Wrapper>,
    contributors: [Anatta336],
  },
  {
    date: new Date('2017-09-22'),
    changes: 'Added 5 combo point finisher tracking',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-11'),
    changes: 'Refactored combo point tracking properties',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-11'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.SAVAGE_ROAR_TALENT.id} icon /> damage contribution</Wrapper>,
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-10'),
    changes: 'Changed exceptions to conditional assignment on combo point tracker',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-06'),
    changes: 'Updated combo point tracking to handle non standard generator and spenders',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'Cleaned up this.owner modules where possible',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'Added combo point tracking',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'Added bleed uptime tracking',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-04'),
    changes: 'CooldownTracker configured',
    contributors: [Thieseract],
  },
  {
    date: new Date('2017-09-03'),
    changes: 'Initial commit. Damage done, ABC, and Abilities added',
    contributors: [Thieseract],
  },
];
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var Transform = require('readable-stream/transform');

function Finder (file, markers) {
    Transform.call(this);
    this.markers = markers;
    this.file = file;
}

util.inherits(Finder, Transform);

// this directly manipulates the markers object.
// TODO abstract it away?
// TODO this could be a read stream except this allows
// option to replace on same pass as find.
Finder.prototype._transform = function (chunk, enc, done) {
    var content = chunk.toString('utf8');
    var m = this.markers.m;
    var tags = this.markers.getMarkerTags();
    var file = this.file;

    tags.forEach(function (tag) {
        var matches = content.match(m[tag].regexgm);

        if (matches) {
            if (!m[tag].files[file.path]) {
                m[tag].files[file.path] = {};
            }
            // TODO I don't think the groups are needed except for debugging
            var decoded = matches.map(match => {
                var res = m[tag].regexm.exec(match);
                return {match: res[0], groups: res.slice(1)};
            });
            m[tag].files[file.path] = decoded;
        }
    });
    // no transform, but maybe will be
    done(null, content);
}

function Replacer (file, markers) {
    Transform.call(this);
    this.markers = markers;
    this.file = file;
}

util.inherits(Replacer, Transform);

Replacer.prototype._transform = function (chunk, enc, done) {
    var content = chunk.toString('utf8');
    var m = this.markers.m;
    var tags = this.markers.getMarkerTags();
    var file = this.file;

    // go through each tag using the supplied regex with the 'gm'
    // flags so RegExp.exec can be used to iterate over each match
    // in this file.
    tags.forEach(function (tag) {
        // if this tag wants access to the file information pass it
        // as the first argument (in front of string.replace arguments).
        var context = {
            tag: tag,
            data: m[tag].data,
            file: {cwd: file.cwd, base: file.base, path: file.path}
        };
        var replacer;
        if (typeof m[tag].replace === 'string') {
            replacer = m[tag].replace;
        } else {
            replacer = function() {
                var args = Array.prototype.slice.call(arguments);
                args.unshift(context);
                return m[tag].replace.apply(null, args);
            }
        }

        content = content.replace(m[tag].regexgm, replacer);
    });

    done(null, content);
}

module.exports = {Finder: Finder, Replacer: Replacer};
<commit_msg>Store per-file matches correctly. Add debug option.<commit_after>'use strict';

var util = require('util');
var Transform = require('readable-stream/transform');

function Finder (file, markers, debug) {
    Transform.call(this);
    this.markers = markers;
    this.file = file;
    this.debug = debug;
}

util.inherits(Finder, Transform);

// this directly manipulates the markers object.
// TODO abstract it away?
// TODO this could be a read stream except this allows
// option to replace on same pass as find.
Finder.prototype._transform = function (chunk, enc, done) {
    var content = chunk.toString('utf8');
    var m = this.markers.m;
    var tags = this.markers.getMarkerTags();
    var file = this.file;
    var debug = this.debug;

    // find matches for each tag.
    tags.forEach(function (tag) {
        var matches = content.match(m[tag].regexgm);

        if (matches) {
            if (!m[tag].files[file.path]) {
                m[tag].files[file.path] = {};
            }
            // TODO I don't think the groups are needed except for debugging
            var decoded = matches.map(match => {
                var res = m[tag].regexm.exec(match);
                return {match: res[0], groups: res.slice(1)};
            });
            // use the source regex as the hash
            m[tag].files[file.path][m[tag].re] = decoded;
        }
    });

    // return unmodified content.
    done(null, content);
}

function Replacer (file, markers) {
    Transform.call(this);
    this.markers = markers;
    this.file = file;
}

util.inherits(Replacer, Transform);

Replacer.prototype._transform = function (chunk, enc, done) {
    var content = chunk.toString('utf8');
    var m = this.markers.m;
    var tags = this.markers.getMarkerTags();
    var file = this.file;

    // go through each tag using the supplied regex with the 'gm'
    // flags so RegExp.exec can be used to iterate over each match
    // in this file.
    tags.forEach(function (tag) {
        // if this tag wants access to the file information pass it
        // as the first argument (in front of string.replace arguments).
        var context = {
            tag: tag,
            data: m[tag].data,
            file: {cwd: file.cwd, base: file.base, path: file.path}
        };
        var replacer;
        if (typeof m[tag].replace === 'string') {
            replacer = m[tag].replace;
        } else {
            replacer = function() {
                var args = Array.prototype.slice.call(arguments);
                args.unshift(context);
                return m[tag].replace.apply(null, args);
            }
        }

        content = content.replace(m[tag].regexgm, replacer);
    });

    done(null, content);
}

module.exports = {Finder: Finder, Replacer: Replacer};
<|endoftext|>


<commit_before>'use strict';

const client_id = process.env.CLIENT_ID; // Your client id
const client_secret = process.env.CLIENT_SECRET;
const request = require('request');
const Manager = require('../model/manager');
let user_id;
let access_token;

module.exports = function(req, res, next) {

  let time = Date.now();
  let manager = res.manager;
  access_token = manager.accessToken;
  user_id = manager.username;
  let authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
    form: {
      grant_type: 'refresh_token',
      refresh_token: manager.refreshToken
    },
    json: true
  };
  console.log('time', time);
  console.log('token expires', manager.tokenExpires);
  if (manager.tokenExpires < time) {
    request.post(authOptions, getNewToken);
  }
  next();
};

function getNewToken(err, res, body) {
  console.log('POSTING TO SPOTIFY');
  if (!err && res.statusCode === 200) {
    let expires_in = body.expires_in * 1000;
    let access_token = body.access_token;
    let refresh_token;
    refresh_token ? body.refresh_token : null;
    console.log('successfully requested a new token from spotify');
    Manager.findOneAndUpdate({username: user_id}, { $set: {accessToken: access_token, refreshToken: refresh_token, tokenExpires: expires_in + Date.now()}}, (err) => {
      if (err) console.log(err);
    });
    console.log('response from spotify', body);
  }
}
<commit_msg>refresh token remains now on the manager.. used to request new access tokens<commit_after>'use strict';

const client_id = process.env.CLIENT_ID; // Your client id
const client_secret = process.env.CLIENT_SECRET;
const request = require('request');
const Manager = require('../model/manager');
let user_id;

module.exports = function(req, res, next) {

  let time = Date.now();
  let manager = res.manager;
  user_id = manager.username;
  let authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
    form: {
      grant_type: 'refresh_token',
      refresh_token: manager.refreshToken
    },
    json: true
  };
  console.log('time', time);
  console.log('token expires', manager.tokenExpires);
  if (manager.tokenExpires < time) {
    request.post(authOptions, getNewToken);
  }
  next();
};

function getNewToken(err, res, body) {
  console.log('POSTING TO SPOTIFY');
  if (!err && res.statusCode === 200) {
    let expires_in = body.expires_in * 1000;
    let access_token = body.access_token;
    console.log('successfully requested a new token from spotify');
    Manager.findOneAndUpdate({username: user_id}, { $set: {accessToken: access_token, tokenExpires: expires_in + Date.now()}}, (err) => {
      if (err) console.log(err);
    });
    console.log('response from spotify', body);
  }
}
<|endoftext|>


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

!function( $ ){

  "use strict"

 /* Collection PUBLIC CLASS DEFINITION
  * ============================== */

  var Collection = function ( element, options ) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.collection.defaults, options)

    var embeddedForms = 'div'+this.options.collection_id+'>.collection.controls>.collection-item';
    this.options.index = $( embeddedForms ).length - 1;
  }

  Collection.prototype = {

      constructor: Collection

    , add: function ( ) {
		var index = ++this.options.index;
		if($.isFunction(this.options.addcheckfunc) && !addcheckfunc()){
			if($.isFunction(this.options.addfailedfunc)) this.options.addfailedfunc()
			return false;
		}
		var row = $(this.options.collection_id).attr('data-prototype').replace(/\$\$name\$\$/g, index);
		$(this.options.collection_id + ' div.collection.controls').append(row);
		event.preventDefault();
      }
    , remove: function ( ) {
		//this is called for a specific input inside the row...

		if(this.$element.parents('.collection-item').length){
			this.$element.parents('.collection-item').remove();
		}
	}

  }

 /* COLLECTION PLUGIN DEFINITION
  * ======================== */

  $.fn.collection = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , collection_id = '#'+$this.data('collection-add-btn')
        , collection = $(collection_id)
        , data = $this.data('collection')
        , options = typeof option == 'object' ? option : {}

      options.collection_id = collection_id;

      if (!data) $this.data('collection', (data = new Collection(this, options)))
      data.options.collection_id = collection_id;
      if (option == 'add') data.add()
      if (option == 'remove') data.remove()
    })
  }

  $.fn.collection.defaults = {
	collection_id: null,
    addcheckfunc: false,
    addfailedfunc: false
  }

  $.fn.collection.Constructor = Collection

 /* COLLECTION DATA-API
  * =============== */

  $(function () {
    $('body').on('click.collection.data-api', '[data-collection-add-btn]', function ( e ) {
      var $btn = $(e.target)
      if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
      $btn.collection('add')
    })
    $('body').on('click.collection.data-api', '[data-collection-remove-btn]', function ( e ) {
      var $btn = $(e.target)
      if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
      $btn.collection('remove')
    })
  })

}( window.jQuery );
<commit_msg>Adapted Form Component change - Fixed #8<commit_after>/* ============================================================
 * bootstrap-collection.js v1.0.0
 * http://bootstrap.mohrenweiserpartner.de/mopa/bootstrap/forms/extended
 * ============================================================
 * Copyright 2012 Mohrenweiser & Partner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

!function( $ ){

  "use strict"

 /* Collection PUBLIC CLASS DEFINITION
  * ============================== */

  var Collection = function ( element, options ) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.collection.defaults, options)

    var embeddedForms = 'div'+this.options.collection_id+'>.collection.controls>.collection-item';
    this.options.index = $( embeddedForms ).length - 1;
  }

  Collection.prototype = {

      constructor: Collection

    , add: function ( ) {
		var index = ++this.options.index;
		if($.isFunction(this.options.addcheckfunc) && !addcheckfunc()){
			if($.isFunction(this.options.addfailedfunc)) this.options.addfailedfunc()
			return false;
		}
		var row = $(this.options.collection_id).attr('data-prototype').replace(/__name__/g, index);
		$(this.options.collection_id + ' div.collection.controls').append(row);
		event.preventDefault();
      }
    , remove: function ( ) {
		//this is called for a specific input inside the row...

		if(this.$element.parents('.collection-item').length){
			this.$element.parents('.collection-item').remove();
		}
	}

  }

 /* COLLECTION PLUGIN DEFINITION
  * ======================== */

  $.fn.collection = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , collection_id = '#'+$this.data('collection-add-btn')
        , collection = $(collection_id)
        , data = $this.data('collection')
        , options = typeof option == 'object' ? option : {}

      options.collection_id = collection_id;

      if (!data) $this.data('collection', (data = new Collection(this, options)))
      data.options.collection_id = collection_id;
      if (option == 'add') data.add()
      if (option == 'remove') data.remove()
    })
  }

  $.fn.collection.defaults = {
	collection_id: null,
    addcheckfunc: false,
    addfailedfunc: false
  }

  $.fn.collection.Constructor = Collection

 /* COLLECTION DATA-API
  * =============== */

  $(function () {
    $('body').on('click.collection.data-api', '[data-collection-add-btn]', function ( e ) {
      var $btn = $(e.target)
      if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
      $btn.collection('add')
    })
    $('body').on('click.collection.data-api', '[data-collection-remove-btn]', function ( e ) {
      var $btn = $(e.target)
      if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
      $btn.collection('remove')
    })
  })

}( window.jQuery );
<|endoftext|>


<commit_before>/*!
 * .______    _______     ___      .______       ______     ___   .__________.
 * (   _  )  (   ____)   /   \     (   _  )     (      )   /   \  (          )
 * |  |_)  ) |  |__     /  ^  \    |  |_)  )   |  ,----'  /  ^  \ `---|  |---`
 * |   _  <  |   __)   /  /_\  \   |      )    |  |      /  /_\  \    |  |
 * |  |_)  ) |  |____ /  _____  \  |  |)  ----.|  `----./  _____  \   |  |
 * (______)  (_______/__/     \__\ ( _| `.____) (______)__/     \__\  |__|
 *
 * Bearcat PropertiesLoader
 * Copyright(c) 2015 fantasyni <fantasyni@163.com>
 * MIT Licensed
 */

var logger = require('pomelo-logger').getLogger('bearcat', 'PropertiesLoader');
var FileUtil = require('../util/fileUtil');
var Utils = require('../util/utils');

/**
 * PropertiesLoader constructor function.
 *
 * @api public
 */
var PropertiesLoader = function() {

}

module.exports = PropertiesLoader;

/**
 * PropertiesLoader load properties from load path with env.
 *
 * @param    {String} lpath load path
 * @param    {String} env environment
 * @return   {Object} properties
 * @api public
 */
PropertiesLoader.prototype.loadProperties = function(lpath, env) {
	var meta = {};

	this.loadDir(meta, lpath);
	this.loadDir(meta, lpath + '/' + env);

	return meta;
}

/**
 * PropertiesLoader load properties from directory.
 *
 * @param    {Object} meta properties
 * @param    {String} lpath load path
 * @api private
 */
PropertiesLoader.prototype.loadDir = function(meta, lpath) {
	if (!FileUtil.existsSync(lpath)) {
		return;
	}
	if (!Utils.isDir(lpath)) {
		return;
	}

	var files = FileUtil.readdirSync(lpath);

	if (lpath.charAt(lpath.length - 1) !== '/') {
		lpath += '/';
	}

	var fp, fn, m;
	for (var i = 0, l = files.length; i < l; i++) {
		fn = files[i];
		fp = lpath + fn;

		if (Utils.isDir(fp)) {
			this.loadDir(meta, fp);
		}

		if (!Utils.isFile(fp) || !Utils.checkFileType(fp, 'json')) {
			// only load json properties files
			continue;
		}

		m = Utils.myRequire(fp);
		if (!Utils.isNotNull(m) || !Utils.checkObject(m)) {
			continue;
		}

		for (var key in m) {
			if (Utils.isNotNull(m[key])) {
				meta[key] = m[key];
			}
		}
	}
}<commit_msg>consistent configuration properties loader first directory does not load subdirectory<commit_after>/*!
 * .______    _______     ___      .______       ______     ___   .__________.
 * (   _  )  (   ____)   /   \     (   _  )     (      )   /   \  (          )
 * |  |_)  ) |  |__     /  ^  \    |  |_)  )   |  ,----'  /  ^  \ `---|  |---`
 * |   _  <  |   __)   /  /_\  \   |      )    |  |      /  /_\  \    |  |
 * |  |_)  ) |  |____ /  _____  \  |  |)  ----.|  `----./  _____  \   |  |
 * (______)  (_______/__/     \__\ ( _| `.____) (______)__/     \__\  |__|
 *
 * Bearcat PropertiesLoader
 * Copyright(c) 2015 fantasyni <fantasyni@163.com>
 * MIT Licensed
 */

var logger = require('pomelo-logger').getLogger('bearcat', 'PropertiesLoader');
var FileUtil = require('../util/fileUtil');
var Utils = require('../util/utils');

/**
 * PropertiesLoader constructor function.
 *
 * @api public
 */
var PropertiesLoader = function() {

}

module.exports = PropertiesLoader;

/**
 * PropertiesLoader load properties from load path with env.
 *
 * @param    {String} lpath load path
 * @param    {String} env environment
 * @return   {Object} properties
 * @api public
 */
PropertiesLoader.prototype.loadProperties = function(lpath, env) {
	var meta = {};

	this.loadDir(meta, lpath, true);
	this.loadDir(meta, lpath + '/' + env);

	return meta;
}

/**
 * PropertiesLoader load properties from directory.
 *
 * @param    {Object}  meta properties
 * @param    {String}  lpath load path
 * @param    {Boolean} lflag if not load subdirectory or not, true not
 * @api private
 */
PropertiesLoader.prototype.loadDir = function(meta, lpath, lflag) {
	if (!FileUtil.existsSync(lpath)) {
		return;
	}

	if (!Utils.isDir(lpath)) {
		return;
	}

	var files = FileUtil.readdirSync(lpath);

	if (lpath.charAt(lpath.length - 1) !== '/') {
		lpath += '/';
	}

	var fp, fn, m;
	for (var i = 0, l = files.length; i < l; i++) {
		fn = files[i];
		fp = lpath + fn;

		if (!lflag && Utils.isDir(fp)) {
			this.loadDir(meta, fp);
		}

		if (!Utils.isFile(fp) || !Utils.checkFileType(fp, 'json')) {
			// only load json properties files
			continue;
		}

		m = Utils.myRequire(fp);
		if (!Utils.isNotNull(m) || !Utils.checkObject(m)) {
			continue;
		}

		for (var key in m) {
			if (Utils.isNotNull(m[key])) {
				meta[key] = m[key];
			}
		}
	}
}<|endoftext|>


<commit_before>

var fs = require('fs'),
    path = require('path'),
    gruntMod = require('grunt'),
    helpers = require('./helpers');

var compiler = {};

/**
 * Perform validations for given options
 *
 * @param  {Object} options [description]
 * @return {boolean} boolean.
 */
compiler.validateOpts = function validate( options ) {
  // check for closure compiler file
  var compilerJar = options.compilerFile;
  //
  // check compilerJar's existence
  //
  if (!gruntMod.file.isFile( compilerJar )) {
    helpers.log.error('compiler Jar file path not valid: ' + compilerJar.red);
    return false;
  }
  return true;
};

/**
 * Validates a grunt file object
 * @param  {Object} fileObj Grunt file object
 * @return {boolean} yez or noz.
 */
compiler.validateFile = function validateFile( fileObj ) {

  var warningMsg = 'WARNING :: No "src" files were defined';
  //
  // Check for js source files
  //
  if ( !fileObj.src || 0 === gruntMod.file.expand( fileObj.src )) {
    helpers.log.warn(warningMsg);
  }

  return true;
};

/**
 * Prepare and compile the compiler command we will execute
 *
 * @param {Object} options The options.
 * @return {string|boolean} boolean false if we failed,
 *   command string if all ok.
 */
compiler.compileCommand = function compileCommand( options, fileObj ) {

  var cmd = 'java ' +
    // adding compiling speed optimizations as found by Igor Minar
    // http://than.pol.as/NfzB
    ' -client' +
    ' -d32' +
    ' -jar ' + options.compilerFile + ' ';

  //
  // check for js files
  //
  var src = gruntMod.file.expand({nonull: true}, fileObj.src || []);
  if (0 < src.length) {
    cmd += helpers.makeParam(src, '--js');
  }

  //
  // Process output file
  //
  var dest = fileObj.dest;
  if('string' === typeof(dest)) {
    dest = gruntMod.template.process(dest);
  }

  // check if output file is defined
  if (dest && dest.length) {

    // create the directories if not there already
    gruntMod.file.mkdir(path.dirname( dest ));

    // if we want to check the source files timestamps enter this loop.
    if (options.checkModified && fs.existsSync( dest )) {
        var doCompile = false;
        var outMtime = fs.lstatSync( dest ).mtime;

        for(var i = 0, len = src.length ; i < len ; i++) {
            if ( fs.lstatSync( src[i] ).mtime > outMtime ) {
                doCompile = true;
                break;
            }
        }
        if (!doCompile) {
            helpers.log.info('Skipping ' + src.blue + ' (Not modified)');
            return false;
        }
    }

    cmd += ' --js_output_file=' + dest;
  }

  //
  // start digging on compiler options
  //

  // create an options object if it's not there
  var opts = options.compilerOpts || {};

  for(var directive in opts) {

    // look for 'externs' special case
    if ('externs' === directive) {
      opts[directive] = gruntMod.file.expand( opts[directive] );
    }

    cmd += helpers.makeParam( opts[directive], '--' + directive );
  }

  return cmd;

};

module.exports = compiler;
<commit_msg>removed compiling optimization, up 0.7.7<commit_after>

var fs = require('fs'),
    path = require('path'),
    gruntMod = require('grunt'),
    helpers = require('./helpers');

var compiler = {};

/**
 * Perform validations for given options
 *
 * @param  {Object} options [description]
 * @return {boolean} boolean.
 */
compiler.validateOpts = function validate( options ) {
  // check for closure compiler file
  var compilerJar = options.compilerFile;
  //
  // check compilerJar's existence
  //
  if (!gruntMod.file.isFile( compilerJar )) {
    helpers.log.error('compiler Jar file path not valid: ' + compilerJar.red);
    return false;
  }
  return true;
};

/**
 * Validates a grunt file object
 * @param  {Object} fileObj Grunt file object
 * @return {boolean} yez or noz.
 */
compiler.validateFile = function validateFile( fileObj ) {

  var warningMsg = 'WARNING :: No "src" files were defined';
  //
  // Check for js source files
  //
  if ( !fileObj.src || 0 === gruntMod.file.expand( fileObj.src )) {
    helpers.log.warn(warningMsg);
  }

  return true;
};

/**
 * Prepare and compile the compiler command we will execute
 *
 * @param {Object} options The options.
 * @return {string|boolean} boolean false if we failed,
 *   command string if all ok.
 */
compiler.compileCommand = function compileCommand( options, fileObj ) {

  var cmd = 'java ' +
    // adding compiling speed optimizations as found by Igor Minar
    // http://than.pol.as/NfzB
    // no, don't add it for now, it breaks travis-builds
    // https://travis-ci.org/closureplease/grunt-closure-tools/builds/5625329
    //' -client' +
    //' -d32' +
    ' -jar ' + options.compilerFile + ' ';

  //
  // check for js files
  //
  var src = gruntMod.file.expand({nonull: true}, fileObj.src || []);
  if (0 < src.length) {
    cmd += helpers.makeParam(src, '--js');
  }

  //
  // Process output file
  //
  var dest = fileObj.dest;
  if('string' === typeof(dest)) {
    dest = gruntMod.template.process(dest);
  }

  // check if output file is defined
  if (dest && dest.length) {

    // create the directories if not there already
    gruntMod.file.mkdir(path.dirname( dest ));

    // if we want to check the source files timestamps enter this loop.
    if (options.checkModified && fs.existsSync( dest )) {
        var doCompile = false;
        var outMtime = fs.lstatSync( dest ).mtime;

        for(var i = 0, len = src.length ; i < len ; i++) {
            if ( fs.lstatSync( src[i] ).mtime > outMtime ) {
                doCompile = true;
                break;
            }
        }
        if (!doCompile) {
            helpers.log.info('Skipping ' + src.blue + ' (Not modified)');
            return false;
        }
    }

    cmd += ' --js_output_file=' + dest;
  }

  //
  // start digging on compiler options
  //

  // create an options object if it's not there
  var opts = options.compilerOpts || {};

  for(var directive in opts) {

    // look for 'externs' special case
    if ('externs' === directive) {
      opts[directive] = gruntMod.file.expand( opts[directive] );
    }

    cmd += helpers.makeParam( opts[directive], '--' + directive );
  }

  return cmd;

};

module.exports = compiler;
<|endoftext|>


<commit_before>var yaml = require('js-yaml')
  , fs = require('fs')
  , rimraf = require('rimraf')
  , Server = require('./server').Server
  , spawn = require('child_process').spawn
  , tap = require('tap')
  , path = require('path')
  , async = require('async')

var tempDir = (function(){
    var platform = process.platform
    if (platform === 'win32')
        return 'C:\\Windows\\Temp'
    else
        return '/tmp'
}())

var userHomeDir = process.env.HOME || process.env.USERPROFILE

function browsersForPlatform(){
    var platform = process.platform
    if (platform === 'win32'){
        return  [
            {
                name: "IE7",
                exe: "C:\\Program Files\\Internet Explorer\\iexplore.exe",
                setup: function(app, done){
                    app.server.ieCompatMode = 'EmulateIE7'
                    done()
                }
            },
            {
                name: "IE8",
                exe: "C:\\Program Files\\Internet Explorer\\iexplore.exe",
                setup: function(app, done){
                    app.server.ieCompatMode = 'EmulateIE8'
                    done()
                }
            },
            {
                name: "IE9",
                exe: "C:\\Program Files\\Internet Explorer\\iexplore.exe",
                setup: function(app, done){
                    app.server.ieCompatMode = '9'
                    done()
                }
            },
            {
                name: "Firefox",
                exe: "C:\\Program Files\\Mozilla Firefox\\firefox.exe"
            },
            {
                name: "Chrome",
                exe: userHomeDir + "\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe",
                //args: ["--start-maximized"]
                args: ["--user-data-dir=" + tempDir + "\\testem.chrome", "--no-default-browser-check", "--no-first-run"],
                setup: function(app, done){
                    rimraf(tempDir + '\\testem.chrome', done)
                }
            },
            {
                name: "Safari",
                exe: "C:\\Program Files\\Safari\\safari.exe"
            },
            {
                name: "Opera",
                exe: "C:\\Program Files\\Opera\\opera.exe",
                args: ["-pd", tempDir + "\\testem.opera"],
                setup: function(app, done){
                    rimraf(tempDir + '\\testem.opera', done)
                }
            }
        ]
    }else if (platform === 'darwin'){
        return [
            {
                name: "Chrome",
                exe: "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome",
                args: ["--user-data-dir=" + tempDir + "/testem.chrome", "--no-default-browser-check", "--no-first-run"],
                setup: function(app, done){
                    rimraf(tempDir + '/testem.chrome', done)
                }
            },
            {
                name: "Firefox",
                exe: "/Applications/Firefox.app/Contents/MacOS/firefox"
            },
            {
                name: "Safari",
                exe: "/Applications/Safari.app/Contents/MacOS/Safari",
                args: [path.dirname(__dirname) + '/assets/safari_start.html']
            }
        ]
    }else if (platform === 'linux'){
        return []
    }
}

function App(config){
    this.config = config
    this.browsers = browsersForPlatform()
    if (config.browsers){
        var wantedBrowsers = config.browsers.toLowerCase().split(',')
        this.browsers = this.browsers.filter(function(browser){
            return wantedBrowsers.indexOf(browser.name.toLowerCase()) !== -1
        })
    }
    if (config.skip){
        var unwantedBrowsers = config.skip.toLowerCase().split(',')
        this.browsers = this.browsers.filter(function(browser){
            return unwantedBrowsers.indexOf(browser.name.toLowerCase()) === -1
        })
    }
    if (config.list){
        this.printAvailableBrowsers()
    }else{
        this.initialize()
    }
}

App.prototype = {
    configFile: 'testem.yml',
    initialize: function(){
        var config = this.config
        this.tapProducer = new tap.Producer(true)
        this.tapProducer.pipe(process.stdout)
        this.testId = 1
        this.failed = false
        this.testsStarted = false
        this.configure(function(){
            this.server = new Server(this)
            this.server.on('browsers-changed', this.onBrowsersChanged.bind(this))
            this.server.on('test-result', this.onTestResult.bind(this))
            this.server.on('all-test-results', this.onAllTestResults.bind(this))
            this.server.on('server-start', this.onServerStart.bind(this))
        })
    },
    configure: function(callback){
        var self = this
        var config = this.config
        if (config.f)
            this.configFile = config.f
        fs.readFile(this.configFile, function(err, data){
            if (err) return
            var cfg = yaml.load(String(data))
            for (var key in cfg)
                config[key] = cfg[key]
            if (callback) callback.call(self, config)
        })
    },
    onBrowsersChanged: function(){
        if (!this.testsStarted){
            this.server.startTests()
            this.testsStarted = true
        }
    },
    onServerStart: function(){
        this.launchNextBrowser()
    },
    onTestResult: function(){
        process.stdout.write('.')
    },
    launchNextBrowser: function(){
        var url = 'http://localhost:' + this.config.port
        var browser = this.currentBrowser = this.browsers.shift()
        if (!browser){
            this.quit()
        }
        var doit = function(){
            path.exists(browser.exe, function(yes){
                if (!yes){
                    // executable is not there, skip to the next
                    this.launchNextBrowser()
                }else{
                    console.log("# Launching " + browser.name)
                    process.stdout.write('# ')
                    var args = (browser.args || []).concat(url)
                    this.browserProcess = spawn(browser.exe, args)
                    this.browserProcess.on('exit', function(code){
                        this.launchNextBrowser()
                    }.bind(this))
                }
            }.bind(this))
        }.bind(this)
        if (browser.setup){
            browser.setup(this, doit)
        }else{
            doit()
        }
    },
    onAllTestResults: function(results, browser){
        var doit = function(){
            this.outputTap(results, browser)
            this.browserProcess.kill('SIGTERM')
        }.bind(this)
        if (this.currentBrowser.teardown)
            this.currentBrowser.teardown(doit)
        else
            doit()

    },
    outputTap: function(results, browser){
        var config = this.config
          , dir = config.output
          , producer = this.tapProducer

        console.log()

        results.tests.forEach(function(test){
            var testName = ' - ' + browser.name + '  ' + test.name
            if (test.failed === 0){
                producer.write({
                    id: this.testId++,
                    ok: true,
                    name: testName
                })
            }else{
                this.failed = true
                var item = test.items.filter(function(i){
                    return !i.passed
                })[0]

                producer.write({
                    id: this.testId++,
                    ok: false,
                    name: testName,
                    message: item.message
                })

                // TODO: add stacktraces and file and line number
            }
        }.bind(this))

    },
    printAvailableBrowsers: function(){
        function browserExeExists(browser, cb){
            path.exists(browser.exe, cb)
        }
        async.filter(this.browsers, browserExeExists, function(browsers){
            console.log('Browsers available on this system: ')
            console.log(browsers.map(function(b){return b.name}).join('\n'))
        })
    },
    quit: function(){
        this.tapProducer.end()
        var code = this.failed ? 1 : 0
        process.exit(code)
    }
}

module.exports = App<commit_msg>Added Firefox profile<commit_after>var yaml = require('js-yaml')
  , fs = require('fs')
  , rimraf = require('rimraf')
  , Server = require('./server').Server
  , spawn = require('child_process').spawn
  , tap = require('tap')
  , path = require('path')
  , async = require('async')

var tempDir = (function(){
    var platform = process.platform
    if (platform === 'win32')
        return 'C:\\Windows\\Temp'
    else
        return '/tmp'
}())

var userHomeDir = process.env.HOME || process.env.USERPROFILE

function browsersForPlatform(){
    var platform = process.platform
    if (platform === 'win32'){
        return  [
            {
                name: "IE7",
                exe: "C:\\Program Files\\Internet Explorer\\iexplore.exe",
                setup: function(app, done){
                    app.server.ieCompatMode = 'EmulateIE7'
                    done()
                }
            },
            {
                name: "IE8",
                exe: "C:\\Program Files\\Internet Explorer\\iexplore.exe",
                setup: function(app, done){
                    app.server.ieCompatMode = 'EmulateIE8'
                    done()
                }
            },
            {
                name: "IE9",
                exe: "C:\\Program Files\\Internet Explorer\\iexplore.exe",
                setup: function(app, done){
                    app.server.ieCompatMode = '9'
                    done()
                }
            },
            {
                name: "Firefox",
                exe: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
                args: ["-profile", tempDir + "\\testem.firefox"],
                setup: function(app, done){
                    rimraf(tempDir + '\\testem.firefox', done)
                }
            },
            {
                name: "Chrome",
                exe: userHomeDir + "\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe",
                //args: ["--start-maximized"]
                args: ["--user-data-dir=" + tempDir + "\\testem.chrome", "--no-default-browser-check", "--no-first-run"],
                setup: function(app, done){
                    rimraf(tempDir + '\\testem.chrome', done)
                }
            },
            {
                name: "Safari",
                exe: "C:\\Program Files\\Safari\\safari.exe"
            },
            {
                name: "Opera",
                exe: "C:\\Program Files\\Opera\\opera.exe",
                args: ["-pd", tempDir + "\\testem.opera"],
                setup: function(app, done){
                    rimraf(tempDir + '\\testem.opera', done)
                }
            }
        ]
    }else if (platform === 'darwin'){
        return [
            {
                name: "Chrome",
                exe: "/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome",
                args: ["--user-data-dir=" + tempDir + "/testem.chrome", "--no-default-browser-check", "--no-first-run"],
                setup: function(app, done){
                    rimraf(tempDir + '/testem.chrome', done)
                }
            },
            {
                name: "Firefox",
                exe: "/Applications/Firefox.app/Contents/MacOS/firefox"
            },
            {
                name: "Safari",
                exe: "/Applications/Safari.app/Contents/MacOS/Safari",
                args: [path.dirname(__dirname) + '/assets/safari_start.html']
            }
        ]
    }else if (platform === 'linux'){
        return []
    }
}

function App(config){
    this.config = config
    this.browsers = browsersForPlatform()
    if (config.browsers){
        var wantedBrowsers = config.browsers.toLowerCase().split(',')
        this.browsers = this.browsers.filter(function(browser){
            return wantedBrowsers.indexOf(browser.name.toLowerCase()) !== -1
        })
    }
    if (config.skip){
        var unwantedBrowsers = config.skip.toLowerCase().split(',')
        this.browsers = this.browsers.filter(function(browser){
            return unwantedBrowsers.indexOf(browser.name.toLowerCase()) === -1
        })
    }
    if (config.list){
        this.printAvailableBrowsers()
    }else{
        this.initialize()
    }
}

App.prototype = {
    configFile: 'testem.yml',
    initialize: function(){
        var config = this.config
        this.tapProducer = new tap.Producer(true)
        this.tapProducer.pipe(process.stdout)
        this.testId = 1
        this.failed = false
        this.testsStarted = false
        this.configure(function(){
            this.server = new Server(this)
            this.server.on('browsers-changed', this.onBrowsersChanged.bind(this))
            this.server.on('test-result', this.onTestResult.bind(this))
            this.server.on('all-test-results', this.onAllTestResults.bind(this))
            this.server.on('server-start', this.onServerStart.bind(this))
        })
    },
    configure: function(callback){
        var self = this
        var config = this.config
        if (config.f)
            this.configFile = config.f
        fs.readFile(this.configFile, function(err, data){
            if (err) return
            var cfg = yaml.load(String(data))
            for (var key in cfg)
                config[key] = cfg[key]
            if (callback) callback.call(self, config)
        })
    },
    onBrowsersChanged: function(){
        if (!this.testsStarted){
            this.server.startTests()
            this.testsStarted = true
        }
    },
    onServerStart: function(){
        this.launchNextBrowser()
    },
    onTestResult: function(){
        process.stdout.write('.')
    },
    launchNextBrowser: function(){
        var url = 'http://localhost:' + this.config.port
        var browser = this.currentBrowser = this.browsers.shift()
        if (!browser){
            this.quit()
        }
        var doit = function(){
            path.exists(browser.exe, function(yes){
                if (!yes){
                    // executable is not there, skip to the next
                    this.launchNextBrowser()
                }else{
                    console.log("# Launching " + browser.name)
                    process.stdout.write('# ')
                    var args = (browser.args || []).concat(url)
                    this.browserProcess = spawn(browser.exe, args)
                    this.browserProcess.on('exit', function(code){
                        this.launchNextBrowser()
                    }.bind(this))
                }
            }.bind(this))
        }.bind(this)
        if (browser.setup){
            browser.setup(this, doit)
        }else{
            doit()
        }
    },
    onAllTestResults: function(results, browser){
        var doit = function(){
            this.outputTap(results, browser)
            this.browserProcess.kill('SIGTERM')
        }.bind(this)
        if (this.currentBrowser.teardown)
            this.currentBrowser.teardown(doit)
        else
            doit()

    },
    outputTap: function(results, browser){
        var config = this.config
          , dir = config.output
          , producer = this.tapProducer

        console.log()

        results.tests.forEach(function(test){
            var testName = ' - ' + browser.name + '  ' + test.name
            if (test.failed === 0){
                producer.write({
                    id: this.testId++,
                    ok: true,
                    name: testName
                })
            }else{
                this.failed = true
                var item = test.items.filter(function(i){
                    return !i.passed
                })[0]

                producer.write({
                    id: this.testId++,
                    ok: false,
                    name: testName,
                    message: item.message
                })

                // TODO: add stacktraces and file and line number
            }
        }.bind(this))

    },
    printAvailableBrowsers: function(){
        function browserExeExists(browser, cb){
            path.exists(browser.exe, cb)
        }
        async.filter(this.browsers, browserExeExists, function(browsers){
            console.log('Browsers available on this system: ')
            console.log(browsers.map(function(b){return b.name}).join('\n'))
        })
    },
    quit: function(){
        this.tapProducer.end()
        var code = this.failed ? 1 : 0
        process.exit(code)
    }
}

module.exports = App<|endoftext|>


<commit_before>"use strict";

/**
* @namespace
* @name validity.opts
*/

var validity = (function (validity) {
	var opts = {},
		storage,
		bools = [
			"collapseResults"
		];

	opts.option = function(opt, value) {
		var bools = [
				"collapseResults"
			],
			storage = opts.storage();

		if (value === undefined) {
			//	Return option's value.
			value = storage[opt];

			for (var i = 0; i < bools.length; i++) {
				if (opt === bools[i]) {
					//	Cast to boolean.
					value = validity.util.toBool(value);
				}
			}
		}
		else {
			//	Set option to value.
			storage[opt] = value;

			value = storage[opt];
		}

		return value;
	};

	/**
	* @method
	* @name storage
	*/
	opts.storage = function(mock) {
		if (mock) {
			storage = mock;
		}
		else if (storage === undefined) {
			storage = window.localStorage;
		}

		return storage;
	};

	validity.opts = opts;
	return validity;
})(validity || {});<commit_msg>Implemented _load() and _save functions in opts.js.<commit_after>"use strict";

/**
* @namespace
* @name validity.opts
*/

var validity = (function (validity) {
	var opts = {},
		options = {},
		storage,
		bools = [
			"collapseResults"
		];

	opts.option = function(opt, value) {
		var bools = [
				"collapseResults"
			],
			storage = opts.storage();

		if (value === undefined) {
			//	Return option's value.
			value = storage[opt];

			for (var i = 0; i < bools.length; i++) {
				if (opt === bools[i]) {
					//	Cast to boolean.
					value = validity.util.toBool(value);
				}
			}
		}
		else {
			//	Set option to value.
			storage[opt] = value;

			value = storage[opt];
		}

		return value;
	};

	/**
	* @method
	* @name storage
	*/
	opts.storage = function(mock) {
		if (mock) {
			storage = mock;
		}
		else if (storage === undefined) {
			storage = window.localStorage;
		}

		return storage;
	};

	function _load() {
		options = JSON.parse(opts.storage()['options']);
	}

	function _save() {
		opts.storage()['options'] = JSON.stringify(options);
	}

	validity.opts = opts;
	return validity;
})(validity || {});
<|endoftext|>


<commit_before>'use strict'
/**
 * @module lib/client-hook
 */
const azure = require('azure')
const Amqputil = require('./amqp-util')
const SenecaHook = require('./hook')
const AMQPSenecaClient = require('./client')
const AMQPClient = require('amqp10').Client
const Policy = require('amqp10').Policy

module.exports =
  class AMQPClientHook extends SenecaHook {
    createTransport (args, callback) {
      var that = this
      var client = new AMQPClient(args.policy || Policy.ServiceBusTopic)
      var sbService = azure.createServiceBusService(args.connection_string)

      var url = Amqputil.parseConnectionString(args.connection_string)
      client.connect(url)
      .then(function () {
        var qres = args.queues.response
        var queueName = Amqputil.resolveClientQueue(qres)

        sbService.createQueueIfNotExists(queueName, function (err, created, response) {
          if (err) return err
          client.createReceiver(queueName, Policy.ServiceBusQueue)
            .then(function (receiver) {
              return callback.call(that, {
                receiver,
                client,
                queue: queueName
              })
            })
        })
      })
    }

    createActor (args, transport, done) {
      transport.receiver.on('error', done)
      var client = new AMQPSenecaClient(this.seneca, transport, args)
      return this.utils.make_client(this.seneca, client.callback(), args, done)
    }

  }
<commit_msg>expose azure service cli<commit_after>'use strict'
/**
 * @module lib/client-hook
 */
const azure = require('azure')
const Amqputil = require('./amqp-util')
const SenecaHook = require('./hook')
const AMQPSenecaClient = require('./client')
const AMQPClient = require('amqp10').Client
const Policy = require('amqp10').Policy

module.exports =
  class AMQPClientHook extends SenecaHook {
    createTransport (args, callback) {
      var that = this
      var client = new AMQPClient(args.policy || Policy.ServiceBusTopic)
      var sbService = azure.createServiceBusService(args.connection_string)

      var url = Amqputil.parseConnectionString(args.connection_string)
      client.connect(url)
      .then(function () {
        var qres = args.queues.response
        var queueName = Amqputil.resolveClientQueue(qres)

        sbService.createQueueIfNotExists(queueName, function (err, created, response) {
          if (err) return err
          client.createReceiver(queueName, Policy.ServiceBusQueue)
            .then(function (receiver) {
              return callback.call(that, {
                receiver,
                client,
                queue: queueName,
                service: sbService
              })
            })
        })
      })
    }

    createActor (args, transport, done) {
      transport.receiver.on('error', done)
      var client = new AMQPSenecaClient(this.seneca, transport, args)
      return this.utils.make_client(this.seneca, client.callback(), args, done)
    }

  }
<|endoftext|>