<commit_before>/*
 * Copyright (c) 2011, Intel Corporation
 * All rights reserved.
 *
 * 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
 *
 */

// To run the River Trail tests:

// 1. install the 'nodeunit' npm package with `npm install nodeunit`

// 2. in `node_modules/nodeunit`, run `make browser`

// 3. if step (2) fails because uglify is missing, run `npm install
// uglify-js` in `node_modules/nodeunit` (it will be installed under
// `node_modules/nodeunit/node_modules`, which is what you want)

// 4. load up 'tests.html' in Firefox

this.ParallelArrayTests = {
    'pa0': function(test) {
        var pa0 = new ParallelArray();

        test.expect(2);
        test.equal(pa0.toString(), "[]", "create an empty ParallelArray");
        test.equal(pa0.shape.toString(), "0", "with shape 0");
        test.done();
    },

    'pa1': function(test) {
        var pa1 = new ParallelArray([ [0,1], [2,3], [4,5] ]);

        test.expect(2);
        test.equal(pa1.toString(),
                   "[0, 1, 2, 3, 4, 5]",
                   "create a ParallelArray out of a nested JS array");
        test.equal(pa1.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa2': function(test) {
        var pa1 = new ParallelArray([ [0,1], [2,3], [4,5] ]);
        var pa2 = new ParallelArray(pa1);

        test.expect(2);
        test.equal(pa2.toString(),
                   "[0, 1, 2, 3, 4, 5]",
                   "create a ParallelArray from another ParallelArray");
        test.equal(pa2.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa3': function(test) {
        var pa3 = new ParallelArray([0,1], [2,3]);

        test.expect(2);
        test.equal(pa3.toString(),
                   "[0, 1, 2, 3]",
                   "create a nested ParallelArray from two arrays");
        test.equal(pa3.shape.toString(), "2,2", "with shape 2,2");
        test.done();
    },

    'pa6': function(test) {
        var pa6 = new ParallelArray(3, function (i) { return [i, i+1]; });

        test.expect(2);
        test.equal(pa6.toString(),
                   "[0, 1, 1, 2, 2, 3]",
                   "create a ParallelArray using the comprehension constructor");
        test.equal(pa6.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa7': function(test) {
        var pa7 = new ParallelArray([3,2], function (iv) { return iv[0] * iv[1]; });

        test.expect(2);
        test.equal(pa7.toString(),
                   "[0, 0, 0, 1, 0, 2]",
                   "create a ParallelArray with a shape vector");
        test.equal(pa7.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa8': function(test) {
        var pa8 = new ParallelArray(document.createElement("canvas"));

        // canvas elements default to width 300 and height 150

        test.expect(4);
        test.equal(typeof(pa8),
                   "object",
                   "create a ParallelArray from a canvas element");
        test.equal(pa8.shape[0], "150", "with height 150");
        test.equal(pa8.shape[1], "300", "and width 300");
        test.equal(pa8.shape[2], "4", "and RGBA values for each pixel");
        test.done();
    },

};

this.mapTests = {
    'm0': function(test) {
        var pa = new ParallelArray([1,2,3,4,5]);
        var paIdentical = pa.map(function(val){ return val; });

        test.expect(2);
        test.equal(pa.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray");
        test.equal(paIdentical.toString(), "[1, 2, 3, 4, 5]", "use `map` to create an identical ParallelArray");
        test.done();
    },

    'm1': function(test) {
        var source = new ParallelArray([1,2,3,4,5]);
        var plusOne = source.map(function inc(v) { return v+1; });

        test.expect(2);
        test.equal(plusOne.toString(), "[2, 3, 4, 5, 6]", "add 1 to every element in a ParallelArray");
        test.equal(plusOne.shape.toString(), "5", "with shape 5");
        test.done();
    },

};

this.flattenTests = {
    'f0': function(test) {
        var pa = new ParallelArray([ [1,2], [3,4] ]);
        var paFlat = pa.flatten();

        test.expect(4);
        test.equal(pa.shape.toString(), "2,2", "given a 2x2 ParallelArray");
        test.equal(paFlat.toString(), "[1, 2, 3, 4]", "flatten it");
        test.equal(paFlat.shape.toString(), "4", "to one dimension with four elements");
        test.equal(paFlat.get(0).toString(), "1", "where 1 is the first element");
        test.done();
    },

    'f1': function(test) {
        var pa = new ParallelArray([ [ [1, 1], [2, 2] ], [ [3, 3], [4, 4] ] ]);
        var paFlat = pa.flatten();

        test.expect(4);
        test.equal(pa.shape.toString(), "2,2,2", "given a 2x2x2 ParallelArray");
        test.equal(paFlat.toString(), "[1, 1, 2, 2, 3, 3, 4, 4]", "flatten it");
        test.equal(paFlat.shape.toString(), "4,2", "to two dimensions");
        test.equal(paFlat.get(0).toString(), "[1, 1]", "where [1, 1] is the first element");
        test.done();
    },

};

this.combineTests = {

    'c0': function(test) {
        var pa = new ParallelArray([1,2,3,4,5]);
        var paIdentical = pa.combine(function(i){return this.get(i);});

        test.expect(2);
        test.equal(pa.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray");
        test.equal(paIdentical.toString(), "[1, 2, 3, 4, 5]", "use `combine` to create an identical ParallelArray");
        test.done();
    },

    'c1': function(test) {

        var pa1 = new ParallelArray([1,2,3,4,5]);
        var pa2 = new ParallelArray([1,2,3,4,5]);
        var res = pa1.combine(function(iv, pa2){return this.get(iv) + pa2.get(iv);}, pa2);

        test.expect(1);
        test.equal(res.toString(), "[2, 4, 6, 8, 10]", "add the elements of two ParallelArrays using `combine`");
        test.done();
    },

    'c2': function(test) {

        var source = new ParallelArray([1,2,3,4,5]);
        var plusOne = source.combine(function inc(i) { return this.get(i)+1; });

        test.expect(1);
        test.equal(plusOne.toString(), "[2, 3, 4, 5, 6]", "increment each element of a ParallelArray by 1 using `combine`");
        test.done();
    },

    'c3': function(test) {

        var source = new ParallelArray([1,2,3,4,5]);
        var reverse = source.combine(function rev(i) { return this.get(this.length-i[0]-1); });

        test.expect(1);
        test.equal(reverse.toString(), "[5, 4, 3, 2, 1]", "reverse the elements in a ParallelArray using `combine`");
        test.done();
    },

    'c4': function(test) {

        // LK: This used to appear on the `combine` wiki page:

        // transpose a matrix using a depth of 2
        var source = new ParallelArray([4,4], function (iv) { return iv[0]*iv[1]; });
        var transpose = source.combine(2, function rev(iv) {
            return this.get([this.getShape()[0]-iv[0]-1,
                             this.getShape()[1]-iv[1]-1]); });

        // I don't think it's correct.

        // Original matrix:
        // [[0, 0, 0, 0],
        //  [0, 1, 2, 3],
        //  [0, 2, 4, 6],
        //  [0, 3, 6, 9]]

        // Wouldn't the transposed be the same as the original? Is this a bug in `get`?

        test.expect(0);
        // TODO: figure out how to write a test for this.
        test.done();

    },

};

this.filterTests = {

    'f0': function(test) {
        var pa = new ParallelArray([1,2,3,4,5]);
        var paIdentical = pa.filter(function(){return true;})

        test.expect(2);
        test.equal(pa.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray");
        test.equal(paIdentical.toString(), "[1, 2, 3, 4, 5]", "use `filter` to create an identical ParallelArray");
        test.done();
    },

    'f1': function(test) {
        var source = new ParallelArray([1,2,3,4,5]);
        var even = source.filter(function even(iv) { return (this.get(iv) % 2) == 0; });

        test.expect(2);
        test.equal(source.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray of integers");
        test.equal(even.toString(), "[2, 4]", "use `filter` to filter out the odd ones");
        test.done();
    },
};

this.issueTests = {
    'issue48': function(test) {
        var pa = new ParallelArray([0,1,2,3,4], [10,11,12,13,14], [20,21,22,23,24]);

        test.expect(3);
        test.equal(pa.get(1).toString(), "[10, 11, 12, 13, 14]", "get the array at index 1 of a nested ParallelArray");
        test.equal(pa.get(1).map(function(e) { return e; }).toString(), "[10, 11, 12, 13, 14]", "and map the identity function over it");
        test.equal(pa.get(1).map(function(e) { return e+1; }).toString(), "[11, 12, 13, 14, 15]", "and map the increment function over it");
        test.done();
    },

};
<commit_msg>Add more testing stuff for `ParallelArray`.<commit_after>/*
 * Copyright (c) 2011, Intel Corporation
 * All rights reserved.
 *
 * 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
 *
 */

// To run the River Trail tests:

// 1. install the 'nodeunit' npm package with `npm install nodeunit`

// 2. in `node_modules/nodeunit`, run `make browser`

// 3. if step (2) fails because uglify is missing, run `npm install
// uglify-js` in `node_modules/nodeunit` (it will be installed under
// `node_modules/nodeunit/node_modules`, which is what you want)

// 4. load up 'tests.html' in Firefox

this.ParallelArrayTests = {
    'pa0': function(test) {
        var pa0 = new ParallelArray();

        test.expect(2);
        test.equal(pa0.toString(), "[]", "create an empty ParallelArray");
        test.equal(pa0.shape.toString(), "0", "with shape 0");
        test.done();
    },

    'pa1': function(test) {
        var pa1 = new ParallelArray([ [0,1], [2,3], [4,5] ]);

        test.expect(2);
        test.equal(pa1.toString(),
                   "[0, 1, 2, 3, 4, 5]",
                   "create a ParallelArray out of a nested JS array");
        test.equal(pa1.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa2': function(test) {
        var pa1 = new ParallelArray([ [0,1], [2,3], [4,5] ]);
        var pa2 = new ParallelArray(pa1);

        test.expect(2);
        test.equal(pa2.toString(),
                   "[0, 1, 2, 3, 4, 5]",
                   "create a ParallelArray from another ParallelArray");
        test.equal(pa2.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa3': function(test) {
        var pa3 = new ParallelArray([0,1], [2,3]);

        test.expect(2);
        test.equal(pa3.toString(),
                   "[0, 1, 2, 3]",
                   "create a nested ParallelArray from two arrays");
        test.equal(pa3.shape.toString(), "2,2", "with shape 2,2");
        test.done();
    },

    'pa4': function(test) {
        var pa4 = new ParallelArray([ [0, 1], [2] ]);

        test.expect(0);
        test.done();

        // TODO: Figure out how to test this.

        // The tutorial says, "Multi-dimensional ParallelArrays are
        // also required to be uniform (also called rectangular). That
        // is, the length of all inner arrays in a particular
        // dimension must be the same. For example, [[0, 1], [2], [3,
        // 4]] would be non-uniform and is not allowed." But what does
        // "not allowed" mean?  We're clearly still able to call
        // `ParallelArray` with this argument, and it still returns
        // something.

    },

    'pa5': function(test) {
        var elem0 = new ParallelArray([0, 1]);
        var elem1 = new ParallelArray([2]);
        var pa5 = new ParallelArray([ elem0, elem1 ]);

        test.expect(0);
        test.done();

        // TODO: Figure out how to test this.

        // This is like the above, except that the inner arrays are
        // already ParallelArrays.  What happens then?  Is it like the
        // above case?

    },

    'pa6': function(test) {
        var pa6 = new ParallelArray(3, function (i) { return [i, i+1]; });

        test.expect(2);
        test.equal(pa6.toString(),
                   "[0, 1, 1, 2, 2, 3]",
                   "create a ParallelArray using the comprehension constructor");
        test.equal(pa6.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa7': function(test) {
        var pa7 = new ParallelArray([3,2], function (iv) { return iv[0] * iv[1]; });

        test.expect(2);
        test.equal(pa7.toString(),
                   "[0, 0, 0, 1, 0, 2]",
                   "create a ParallelArray with a shape vector");
        test.equal(pa7.shape.toString(), "3,2", "with shape 3,2");
        test.done();
    },

    'pa8': function(test) {
        var pa8 = new ParallelArray(document.createElement("canvas"));

        // canvas elements default to width 300 and height 150

        test.expect(4);
        test.equal(typeof(pa8),
                   "object",
                   "create a ParallelArray from a canvas element");
        test.equal(pa8.shape[0], "150", "with height 150");
        test.equal(pa8.shape[1], "300", "and width 300");
        test.equal(pa8.shape[2], "4", "and RGBA values for each pixel");
        test.done();
    },

    // TODO: it would be great to have tests for the special cases
    // mentioned under "Discussion" on
    // https://github.com/IntelLabs/RiverTrail/wiki/ParallelArray .

};

this.mapTests = {
    'm0': function(test) {
        var pa = new ParallelArray([1,2,3,4,5]);
        var paIdentical = pa.map(function(val){ return val; });

        test.expect(2);
        test.equal(pa.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray");
        test.equal(paIdentical.toString(), "[1, 2, 3, 4, 5]", "use `map` to create an identical ParallelArray");
        test.done();
    },

    'm1': function(test) {
        var source = new ParallelArray([1,2,3,4,5]);
        var plusOne = source.map(function inc(v) { return v+1; });

        test.expect(2);
        test.equal(plusOne.toString(), "[2, 3, 4, 5, 6]", "add 1 to every element in a ParallelArray");
        test.equal(plusOne.shape.toString(), "5", "with shape 5");
        test.done();
    },

};

this.flattenTests = {
    'f0': function(test) {
        var pa = new ParallelArray([ [1,2], [3,4] ]);
        var paFlat = pa.flatten();

        test.expect(4);
        test.equal(pa.shape.toString(), "2,2", "given a 2x2 ParallelArray");
        test.equal(paFlat.toString(), "[1, 2, 3, 4]", "flatten it");
        test.equal(paFlat.shape.toString(), "4", "to one dimension with four elements");
        test.equal(paFlat.get(0).toString(), "1", "where 1 is the first element");
        test.done();
    },

    'f1': function(test) {
        var pa = new ParallelArray([ [ [1, 1], [2, 2] ], [ [3, 3], [4, 4] ] ]);
        var paFlat = pa.flatten();

        test.expect(4);
        test.equal(pa.shape.toString(), "2,2,2", "given a 2x2x2 ParallelArray");
        test.equal(paFlat.toString(), "[1, 1, 2, 2, 3, 3, 4, 4]", "flatten it");
        test.equal(paFlat.shape.toString(), "4,2", "to two dimensions");
        test.equal(paFlat.get(0).toString(), "[1, 1]", "where [1, 1] is the first element");
        test.done();
    },

};

this.combineTests = {

    'c0': function(test) {
        var pa = new ParallelArray([1,2,3,4,5]);
        var paIdentical = pa.combine(function(i){return this.get(i);});

        test.expect(2);
        test.equal(pa.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray");
        test.equal(paIdentical.toString(), "[1, 2, 3, 4, 5]", "use `combine` to create an identical ParallelArray");
        test.done();
    },

    'c1': function(test) {

        var pa1 = new ParallelArray([1,2,3,4,5]);
        var pa2 = new ParallelArray([1,2,3,4,5]);
        var res = pa1.combine(function(iv, pa2){return this.get(iv) + pa2.get(iv);}, pa2);

        test.expect(1);
        test.equal(res.toString(), "[2, 4, 6, 8, 10]", "add the elements of two ParallelArrays using `combine`");
        test.done();
    },

    'c2': function(test) {

        var source = new ParallelArray([1,2,3,4,5]);
        var plusOne = source.combine(function inc(i) { return this.get(i)+1; });

        test.expect(1);
        test.equal(plusOne.toString(), "[2, 3, 4, 5, 6]", "increment each element of a ParallelArray by 1 using `combine`");
        test.done();
    },

    'c3': function(test) {

        var source = new ParallelArray([1,2,3,4,5]);
        var reverse = source.combine(function rev(i) { return this.get(this.length-i[0]-1); });

        test.expect(1);
        test.equal(reverse.toString(), "[5, 4, 3, 2, 1]", "reverse the elements in a ParallelArray using `combine`");
        test.done();
    },

    'c4': function(test) {

        // LK: This used to appear on the `combine` wiki page:

        // transpose a matrix using a depth of 2
        var source = new ParallelArray([4,4], function (iv) { return iv[0]*iv[1]; });
        var transpose = source.combine(2, function rev(iv) {
            return this.get([this.getShape()[0]-iv[0]-1,
                             this.getShape()[1]-iv[1]-1]); });

        // I don't think it's correct.

        // Original matrix:
        // [[0, 0, 0, 0],
        //  [0, 1, 2, 3],
        //  [0, 2, 4, 6],
        //  [0, 3, 6, 9]]

        // Wouldn't the transposed be the same as the original? Is this a bug in `get`?

        test.expect(0);
        // TODO: figure out how to write a test for this.
        test.done();

    },

};

this.filterTests = {

    'f0': function(test) {
        var pa = new ParallelArray([1,2,3,4,5]);
        var paIdentical = pa.filter(function(){return true;})

        test.expect(2);
        test.equal(pa.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray");
        test.equal(paIdentical.toString(), "[1, 2, 3, 4, 5]", "use `filter` to create an identical ParallelArray");
        test.done();
    },

    'f1': function(test) {
        var source = new ParallelArray([1,2,3,4,5]);
        var even = source.filter(function even(iv) { return (this.get(iv) % 2) == 0; });

        test.expect(2);
        test.equal(source.toString(), "[1, 2, 3, 4, 5]", "given a ParallelArray of integers");
        test.equal(even.toString(), "[2, 4]", "use `filter` to filter out the odd ones");
        test.done();
    },
};

this.issueTests = {
    'issue48': function(test) {
        var pa = new ParallelArray([0,1,2,3,4], [10,11,12,13,14], [20,21,22,23,24]);

        test.expect(3);
        test.equal(pa.get(1).toString(), "[10, 11, 12, 13, 14]", "get the array at index 1 of a nested ParallelArray");
        test.equal(pa.get(1).map(function(e) { return e; }).toString(), "[10, 11, 12, 13, 14]", "and map the identity function over it");
        test.equal(pa.get(1).map(function(e) { return e+1; }).toString(), "[11, 12, 13, 14, 15]", "and map the increment function over it");
        test.done();
    },

};
<|endoftext|>


<commit_before>Astro.createValidator({
  name: 'switch',
  validate: function(fieldValue, fieldName, options) {
    var doc = this;

    if (!_.has(options, 'cases') || !_.isObject(options.cases)) {
      throw new Error(
        'The "cases" option in the "switch" validator is required'
      );
    }

    if (_.has(options, 'expression') && !_.isFunction(options.expression)) {
      throw new Error(
        'The "expression" option in the "switch" validator has to be a function'
      );
    }

    var expression;
    if (_.has(options, 'expression')) {
      expression = options.expression.call(doc, fieldValue, fieldName);
    } else {
      expression = fieldValue;
    }

    if (_.contains(_.keys(options.cases), expression)) {
      return options.cases[expression].validate(doc, fieldName, fieldValue);
    }

    return true;
  }
});
<commit_msg>Don't cast to string a case value in the switch validator<commit_after>Astro.createValidator({
  name: 'switch',
  validate: function(fieldValue, fieldName, options) {
    var doc = this;

    if (!_.has(options, 'cases') || !_.isObject(options.cases)) {
      throw new Error(
        'The "cases" option in the "switch" validator is required'
      );
    }

    if (_.has(options, 'expression') && !_.isFunction(options.expression)) {
      throw new Error(
        'The "expression" option in the "switch" validator has to be a function'
      );
    }

    var expression;
    if (_.has(options, 'expression')) {
      expression = options.expression.call(doc, fieldValue, fieldName);
    } else {
      expression = fieldValue;
    }

    if (_.has(options.cases, expression)) {
      return options.cases[expression].validate(doc, fieldName, fieldValue);
    }

    return true;
  }
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function() {
    return new (require('webpack-polyfills-plugin'))([
        '_enqueueMicrotask',
        'Array/prototype/find'
    ]);
};
<commit_msg>added ie9 polyfills<commit_after>"use strict";

module.exports = function() {
    return new (require('webpack-polyfills-plugin'))([
        '_enqueueMicrotask',
        'Array/prototype/find',
        'DOMTokenList',
        'Element/prototype/classList'
    ]);
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */
'use strict';

/**
 * Nexus 5X metrics adapted from emulated_devices/module.json
 */
const NEXUS5X_EMULATION_METRICS = {
  mobile: true,
  screenWidth: 412,
  screenHeight: 732,
  width: 412,
  height: 732,
  positionX: 0,
  positionY: 0,
  scale: 1,
  deviceScaleFactor: 2.625,
  fitWindow: false,
  screenOrientation: {
    angle: 0,
    type: 'portraitPrimary'
  }
};

const NEXUS5X_USERAGENT = {
  userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36' +
    '(KHTML, like Gecko) Chrome/52.0.2743.8 Mobile Safari/537.36'
};

const TYPICAL_MOBILE_THROTTLING_METRICS = {
  latency: 150, // 150ms
  downloadThroughput: Math.floor(1.6 * 1024 * 1024 / 8), // 1.6Mbps
  uploadThroughput: Math.floor(750 * 1024 / 8), // 750Kbps
  offline: false
};

const OFFLINE_METRICS = {
  offline: true,
  // values of 0 remove any active throttling. crbug.com/456324#c9
  latency: 0,
  downloadThroughput: 0,
  uploadThroughput: 0
};

const NO_THROTTLING_METRICS = {
  latency: 0,
  downloadThroughput: 0,
  uploadThroughput: 0,
  offline: false
};

const NO_CPU_THROTTLE_METRICS = {
  rate: 1
};
const CPU_THROTTLE_METRICS = {
  rate: 5
};

function enableNexus5X(driver) {
  /**
   * Finalizes touch emulation by enabling `"ontouchstart" in window` feature detect
   * to work. Messy hack, though copied verbatim from DevTools' emulation/TouchModel.js
   * where it's been working for years. addScriptToEvaluateOnLoad runs before any of the
   * page's JavaScript executes.
   */
  /* eslint-disable no-proto */ /* global window, document */ /* istanbul ignore next */
  const injectedTouchEventsFunction = function() {
    const touchEvents = ['ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel'];
    const recepients = [window.__proto__, document.__proto__];
    for (let i = 0; i < touchEvents.length; ++i) {
      for (let j = 0; j < recepients.length; ++j) {
        if (!(touchEvents[i] in recepients[j])) {
          Object.defineProperty(recepients[j], touchEvents[i], {
            value: null, writable: true, configurable: true, enumerable: true
          });
        }
      }
    }
  };
  /* eslint-enable */

  return Promise.all([
    driver.sendCommand('Emulation.setDeviceMetricsOverride', NEXUS5X_EMULATION_METRICS),
    // required for screenshotting emulated page size, rather than full size
    driver.sendCommand('Emulation.setVisibleSize', {
      width: NEXUS5X_EMULATION_METRICS.screenWidth,
      height: NEXUS5X_EMULATION_METRICS.screenHeight
    }),
    // Network.enable must be called for UA overriding to work
    driver.sendCommand('Network.enable'),
    driver.sendCommand('Network.setUserAgentOverride', NEXUS5X_USERAGENT),
    driver.sendCommand('Emulation.setTouchEmulationEnabled', {
      enabled: true,
      configuration: 'mobile'
    }),
    driver.sendCommand('Page.addScriptToEvaluateOnLoad', {
      scriptSource: '(' + injectedTouchEventsFunction.toString() + ')()'
    })
  ]);
}

function enableNetworkThrottling(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', TYPICAL_MOBILE_THROTTLING_METRICS);
}

function disableNetworkThrottling(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', NO_THROTTLING_METRICS);
}

function goOffline(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', OFFLINE_METRICS);
}

function enableCPUThrottling(driver) {
  return driver.sendCommand('Emulation.setCPUThrottlingRate', CPU_THROTTLE_METRICS);
}

function disableCPUThrottling(driver) {
  return driver.sendCommand('Emulation.setCPUThrottlingRate', NO_CPU_THROTTLE_METRICS);
}

function getEmulationDesc() {
  const {latency, downloadThroughput, uploadThroughput} = TYPICAL_MOBILE_THROTTLING_METRICS;
  const byteToMbit = bytes => (bytes / 1024 / 1024 * 8).toFixed(1);
  return {
    'deviceEmulation': 'Nexus 5X',
    'cpuThrottling': `${CPU_THROTTLE_METRICS.rate}x slowdown`,
    'networkThrottling': `${latency}ms RTT, ${byteToMbit(downloadThroughput)}Mbps down, ` +
        `${byteToMbit(uploadThroughput)}Mbps up`
  };
}

module.exports = {
  enableNexus5X,
  enableNetworkThrottling,
  disableNetworkThrottling,
  enableCPUThrottling,
  disableCPUThrottling,
  goOffline,
  getEmulationDesc
};
<commit_msg>bump Chrome version in emulated UA to m59 (#1846)<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */
'use strict';

/**
 * Nexus 5X metrics adapted from emulated_devices/module.json
 */
const NEXUS5X_EMULATION_METRICS = {
  mobile: true,
  screenWidth: 412,
  screenHeight: 732,
  width: 412,
  height: 732,
  positionX: 0,
  positionY: 0,
  scale: 1,
  deviceScaleFactor: 2.625,
  fitWindow: false,
  screenOrientation: {
    angle: 0,
    type: 'portraitPrimary'
  }
};

const NEXUS5X_USERAGENT = {
  userAgent: 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36' +
    '(KHTML, like Gecko) Chrome/59.0.3033.0 Mobile Safari/537.36'
};

const TYPICAL_MOBILE_THROTTLING_METRICS = {
  latency: 150, // 150ms
  downloadThroughput: Math.floor(1.6 * 1024 * 1024 / 8), // 1.6Mbps
  uploadThroughput: Math.floor(750 * 1024 / 8), // 750Kbps
  offline: false
};

const OFFLINE_METRICS = {
  offline: true,
  // values of 0 remove any active throttling. crbug.com/456324#c9
  latency: 0,
  downloadThroughput: 0,
  uploadThroughput: 0
};

const NO_THROTTLING_METRICS = {
  latency: 0,
  downloadThroughput: 0,
  uploadThroughput: 0,
  offline: false
};

const NO_CPU_THROTTLE_METRICS = {
  rate: 1
};
const CPU_THROTTLE_METRICS = {
  rate: 5
};

function enableNexus5X(driver) {
  /**
   * Finalizes touch emulation by enabling `"ontouchstart" in window` feature detect
   * to work. Messy hack, though copied verbatim from DevTools' emulation/TouchModel.js
   * where it's been working for years. addScriptToEvaluateOnLoad runs before any of the
   * page's JavaScript executes.
   */
  /* eslint-disable no-proto */ /* global window, document */ /* istanbul ignore next */
  const injectedTouchEventsFunction = function() {
    const touchEvents = ['ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel'];
    const recepients = [window.__proto__, document.__proto__];
    for (let i = 0; i < touchEvents.length; ++i) {
      for (let j = 0; j < recepients.length; ++j) {
        if (!(touchEvents[i] in recepients[j])) {
          Object.defineProperty(recepients[j], touchEvents[i], {
            value: null, writable: true, configurable: true, enumerable: true
          });
        }
      }
    }
  };
  /* eslint-enable */

  return Promise.all([
    driver.sendCommand('Emulation.setDeviceMetricsOverride', NEXUS5X_EMULATION_METRICS),
    // required for screenshotting emulated page size, rather than full size
    driver.sendCommand('Emulation.setVisibleSize', {
      width: NEXUS5X_EMULATION_METRICS.screenWidth,
      height: NEXUS5X_EMULATION_METRICS.screenHeight
    }),
    // Network.enable must be called for UA overriding to work
    driver.sendCommand('Network.enable'),
    driver.sendCommand('Network.setUserAgentOverride', NEXUS5X_USERAGENT),
    driver.sendCommand('Emulation.setTouchEmulationEnabled', {
      enabled: true,
      configuration: 'mobile'
    }),
    driver.sendCommand('Page.addScriptToEvaluateOnLoad', {
      scriptSource: '(' + injectedTouchEventsFunction.toString() + ')()'
    })
  ]);
}

function enableNetworkThrottling(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', TYPICAL_MOBILE_THROTTLING_METRICS);
}

function disableNetworkThrottling(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', NO_THROTTLING_METRICS);
}

function goOffline(driver) {
  return driver.sendCommand('Network.emulateNetworkConditions', OFFLINE_METRICS);
}

function enableCPUThrottling(driver) {
  return driver.sendCommand('Emulation.setCPUThrottlingRate', CPU_THROTTLE_METRICS);
}

function disableCPUThrottling(driver) {
  return driver.sendCommand('Emulation.setCPUThrottlingRate', NO_CPU_THROTTLE_METRICS);
}

function getEmulationDesc() {
  const {latency, downloadThroughput, uploadThroughput} = TYPICAL_MOBILE_THROTTLING_METRICS;
  const byteToMbit = bytes => (bytes / 1024 / 1024 * 8).toFixed(1);
  return {
    'deviceEmulation': 'Nexus 5X',
    'cpuThrottling': `${CPU_THROTTLE_METRICS.rate}x slowdown`,
    'networkThrottling': `${latency}ms RTT, ${byteToMbit(downloadThroughput)}Mbps down, ` +
        `${byteToMbit(uploadThroughput)}Mbps up`
  };
}

module.exports = {
  enableNexus5X,
  enableNetworkThrottling,
  disableNetworkThrottling,
  enableCPUThrottling,
  disableCPUThrottling,
  goOffline,
  getEmulationDesc
};
<|endoftext|>


<commit_before>if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
    module.exports = OAuth;
    var CryptoJS = require("crypto-js");
}

/**
 * Constructor
 * @param {Object} opts consumer key and secret
 */
function OAuth(opts) {
    if(!(this instanceof OAuth)) {
        return new OAuth(opts);
    }

    if(!opts.consumer) {
        throw new Error('consumer option is required');
    }

    this.consumer            = opts.consumer;
    this.signature_method    = opts.signature_method || 'HMAC-SHA1';
    this.nonce_length        = opts.nonce_length || 32;
    this.version             = opts.version || '1.0';
    this.parameter_seperator = opts.parameter_seperator || ', ';

    if(typeof opts.last_ampersand === 'undefined') {
        this.last_ampersand = true;
    } else {
        this.last_ampersand = opts.last_ampersand;
    }

    switch (this.signature_method) {
        case 'HMAC-SHA1':
            this.hash = function(base_string, key) {
                return CryptoJS.HmacSHA1(base_string, key).toString(CryptoJS.enc.Base64);
            };
            break;
        case 'PLAINTEXT':
            this.hash = function(base_string, key) {
                return key;
            };
            break;
        case 'RSA-SHA1':
            throw new Error('oauth-1.0a does not support this signature method right now. Coming Soon...');
        default:
            throw new Error('The OAuth 1.0a protocol defines three signature methods: HMAC-SHA1, RSA-SHA1, and PLAINTEXT only');
    }
}

/**
 * OAuth request authorize
 * @param  {Object} request data
 * {
 *     method,
 *     url,
 *     data
 * }
 * @param  {Object} public and secret token
 * @return {Object} OAuth Authorized data
 */
OAuth.prototype.authorize = function(request, token) {
    var oauth_data = {
        oauth_consumer_key: this.consumer.public,
        oauth_nonce: this.getNonce(),
        oauth_signature_method: this.signature_method,
        oauth_timestamp: this.getTimeStamp(),
        oauth_version: this.version
    };

    if(!token) {
        token = {};
    }

    if(token.public) {
        oauth_data.oauth_token = token.public;
    }

    oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data);

    return oauth_data;
};

/**
 * Create a OAuth Signature
 * @param  {Object} request data
 * @param  {Object} token_secret public and secret token
 * @param  {Object} oauth_data   OAuth data
 * @return {String} Signature
 */
OAuth.prototype.getSignature = function(request, token_secret, oauth_data) {
    return this.hash(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret));
};

/**
 * Base String = Method + Base Url + ParameterString
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {String} Base String
 */
OAuth.prototype.getBaseString = function(request, oauth_data) {
    return request.method.toUpperCase() + '&' + this.percentEncode(this.getBaseUrl(request.url)) + '&' + this.percentEncode(this.getParameterString(request, oauth_data));
};

/**
 * Get data from url
 * -> merge with oauth data
 * -> percent encode key & value
 * -> sort
 *
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {Object} Parameter string data
 */
OAuth.prototype.getParameterString = function(request, oauth_data) {
    var base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url)))));

    var data_str = '';

    //base_string_data to string
    for(var key in base_string_data) {
        data_str += key + '=' + base_string_data[key] + '&';
    }

    //remove the last character
    data_str = data_str.substr(0, data_str.length - 1);
    return data_str;
};

/**
 * Create a Signing Key
 * @param  {String} token_secret Secret Token
 * @return {String} Signing Key
 */
OAuth.prototype.getSigningKey = function(token_secret) {
    token_secret = token_secret || '';

    if(!this.last_ampersand && !token_secret) {
        return this.percentEncode(this.consumer.secret);
    }

    return this.percentEncode(this.consumer.secret) + '&' + this.percentEncode(token_secret);
};

/**
 * Get base url
 * @param  {String} url
 * @return {String}
 */
OAuth.prototype.getBaseUrl = function(url) {
    return url.split('?')[0];
};

/**
 * Get data from String
 * @param  {String} string
 * @return {Object}
 */
OAuth.prototype.deParam = function(string) {
    var arr = decodeURIComponent(string).split('&');
    var data = {};

    for(var i = 0; i < arr.length; i++) {
        var item = arr[i].split('=');
        data[item[0]] = item[1];
    }
    return data;
};

/**
 * Get data from url
 * @param  {String} url
 * @return {Object}
 */
OAuth.prototype.deParamUrl = function(url) {
    var tmp = url.split('?');

    if (tmp.length === 1)
        return {};

    return this.deParam(tmp[1]);
};

/**
 * Percent Encode
 * @param  {String} str
 * @return {String} percent encoded string
 */
OAuth.prototype.percentEncode = function(str) {
    return encodeURIComponent(str)
        .replace(/\!/g, "%21")
        .replace(/\*/g, "%2A")
        .replace(/\'/g, "%27")
        .replace(/\(/g, "%28")
        .replace(/\)/g, "%29");
};

/**
 * Percent Encode Object
 * @param  {Object} data
 * @return {Object} percent encoded data
 */
OAuth.prototype.percentEncodeData = function(data) {
    var result = {};

    for(var key in data) {
        result[this.percentEncode(key)] = this.percentEncode(data[key]);
    }

    return result;
};

/**
 * Get OAuth data as Header
 * @param  {Object} oauth_data
 * @return {String} Header data key - value
 */
OAuth.prototype.toHeader = function(oauth_data) {
    oauth_data = this.sortObject(oauth_data);

    var header_value = 'OAuth ';

    for(var key in oauth_data) {
        if (key.indexOf('oauth_') === -1)
            continue;
        header_value += this.percentEncode(key) + '="' + this.percentEncode(oauth_data[key]) + '"' + this.parameter_seperator;
    }

    return {
        Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) //cut the last chars
    };
};

/**
 * Create a random word characters string with input length
 * @return {String} a random word characters string
 */
OAuth.prototype.getNonce = function() {
    var word_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var result = '';

    for(var i = 0; i < this.nonce_length; i++) {
        result += word_characters[parseInt(Math.random() * word_characters.length, 10)];
    }

    return result;
};

/**
 * Get Current Unix TimeStamp
 * @return {Int} current unix timestamp
 */
OAuth.prototype.getTimeStamp = function() {
    return parseInt(new Date().getTime()/1000, 10);
};

////////////////////// HELPER FUNCTIONS //////////////////////

/**
 * Merge object
 * @param  {Object} obj1
 * @param  {Object} obj2
 * @return {Object}
 */
OAuth.prototype.mergeObject = function(obj1, obj2) {
    var merged_obj = obj1;
    for(var key in obj2) {
        merged_obj[key] = obj2[key];
    }
    return merged_obj;
};

/**
 * Sort object by key
 * @param  {Object} data
 * @return {Object} sorted object
 */
OAuth.prototype.sortObject = function(data) {
    var keys = Object.keys(data);
    var result = {};

    keys.sort();

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        result[key] = data[key];
    }

    return result;
};
<commit_msg>init opts<commit_after>if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
    module.exports = OAuth;
    var CryptoJS = require("crypto-js");
}

/**
 * Constructor
 * @param {Object} opts consumer key and secret
 */
function OAuth(opts) {
    if(!(this instanceof OAuth)) {
        return new OAuth(opts);
    }

    if(!opts) {
        opts = {};
    }

    if(!opts.consumer) {
        throw new Error('consumer option is required');
    }

    this.consumer            = opts.consumer;
    this.signature_method    = opts.signature_method || 'HMAC-SHA1';
    this.nonce_length        = opts.nonce_length || 32;
    this.version             = opts.version || '1.0';
    this.parameter_seperator = opts.parameter_seperator || ', ';

    if(typeof opts.last_ampersand === 'undefined') {
        this.last_ampersand = true;
    } else {
        this.last_ampersand = opts.last_ampersand;
    }

    switch (this.signature_method) {
        case 'HMAC-SHA1':
            this.hash = function(base_string, key) {
                return CryptoJS.HmacSHA1(base_string, key).toString(CryptoJS.enc.Base64);
            };
            break;
        case 'PLAINTEXT':
            this.hash = function(base_string, key) {
                return key;
            };
            break;
        case 'RSA-SHA1':
            throw new Error('oauth-1.0a does not support this signature method right now. Coming Soon...');
        default:
            throw new Error('The OAuth 1.0a protocol defines three signature methods: HMAC-SHA1, RSA-SHA1, and PLAINTEXT only');
    }
}

/**
 * OAuth request authorize
 * @param  {Object} request data
 * {
 *     method,
 *     url,
 *     data
 * }
 * @param  {Object} public and secret token
 * @return {Object} OAuth Authorized data
 */
OAuth.prototype.authorize = function(request, token) {
    var oauth_data = {
        oauth_consumer_key: this.consumer.public,
        oauth_nonce: this.getNonce(),
        oauth_signature_method: this.signature_method,
        oauth_timestamp: this.getTimeStamp(),
        oauth_version: this.version
    };

    if(!token) {
        token = {};
    }

    if(token.public) {
        oauth_data.oauth_token = token.public;
    }

    oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data);

    return oauth_data;
};

/**
 * Create a OAuth Signature
 * @param  {Object} request data
 * @param  {Object} token_secret public and secret token
 * @param  {Object} oauth_data   OAuth data
 * @return {String} Signature
 */
OAuth.prototype.getSignature = function(request, token_secret, oauth_data) {
    return this.hash(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret));
};

/**
 * Base String = Method + Base Url + ParameterString
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {String} Base String
 */
OAuth.prototype.getBaseString = function(request, oauth_data) {
    return request.method.toUpperCase() + '&' + this.percentEncode(this.getBaseUrl(request.url)) + '&' + this.percentEncode(this.getParameterString(request, oauth_data));
};

/**
 * Get data from url
 * -> merge with oauth data
 * -> percent encode key & value
 * -> sort
 *
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {Object} Parameter string data
 */
OAuth.prototype.getParameterString = function(request, oauth_data) {
    var base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url)))));

    var data_str = '';

    //base_string_data to string
    for(var key in base_string_data) {
        data_str += key + '=' + base_string_data[key] + '&';
    }

    //remove the last character
    data_str = data_str.substr(0, data_str.length - 1);
    return data_str;
};

/**
 * Create a Signing Key
 * @param  {String} token_secret Secret Token
 * @return {String} Signing Key
 */
OAuth.prototype.getSigningKey = function(token_secret) {
    token_secret = token_secret || '';

    if(!this.last_ampersand && !token_secret) {
        return this.percentEncode(this.consumer.secret);
    }

    return this.percentEncode(this.consumer.secret) + '&' + this.percentEncode(token_secret);
};

/**
 * Get base url
 * @param  {String} url
 * @return {String}
 */
OAuth.prototype.getBaseUrl = function(url) {
    return url.split('?')[0];
};

/**
 * Get data from String
 * @param  {String} string
 * @return {Object}
 */
OAuth.prototype.deParam = function(string) {
    var arr = decodeURIComponent(string).split('&');
    var data = {};

    for(var i = 0; i < arr.length; i++) {
        var item = arr[i].split('=');
        data[item[0]] = item[1];
    }
    return data;
};

/**
 * Get data from url
 * @param  {String} url
 * @return {Object}
 */
OAuth.prototype.deParamUrl = function(url) {
    var tmp = url.split('?');

    if (tmp.length === 1)
        return {};

    return this.deParam(tmp[1]);
};

/**
 * Percent Encode
 * @param  {String} str
 * @return {String} percent encoded string
 */
OAuth.prototype.percentEncode = function(str) {
    return encodeURIComponent(str)
        .replace(/\!/g, "%21")
        .replace(/\*/g, "%2A")
        .replace(/\'/g, "%27")
        .replace(/\(/g, "%28")
        .replace(/\)/g, "%29");
};

/**
 * Percent Encode Object
 * @param  {Object} data
 * @return {Object} percent encoded data
 */
OAuth.prototype.percentEncodeData = function(data) {
    var result = {};

    for(var key in data) {
        result[this.percentEncode(key)] = this.percentEncode(data[key]);
    }

    return result;
};

/**
 * Get OAuth data as Header
 * @param  {Object} oauth_data
 * @return {String} Header data key - value
 */
OAuth.prototype.toHeader = function(oauth_data) {
    oauth_data = this.sortObject(oauth_data);

    var header_value = 'OAuth ';

    for(var key in oauth_data) {
        if (key.indexOf('oauth_') === -1)
            continue;
        header_value += this.percentEncode(key) + '="' + this.percentEncode(oauth_data[key]) + '"' + this.parameter_seperator;
    }

    return {
        Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) //cut the last chars
    };
};

/**
 * Create a random word characters string with input length
 * @return {String} a random word characters string
 */
OAuth.prototype.getNonce = function() {
    var word_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var result = '';

    for(var i = 0; i < this.nonce_length; i++) {
        result += word_characters[parseInt(Math.random() * word_characters.length, 10)];
    }

    return result;
};

/**
 * Get Current Unix TimeStamp
 * @return {Int} current unix timestamp
 */
OAuth.prototype.getTimeStamp = function() {
    return parseInt(new Date().getTime()/1000, 10);
};

////////////////////// HELPER FUNCTIONS //////////////////////

/**
 * Merge object
 * @param  {Object} obj1
 * @param  {Object} obj2
 * @return {Object}
 */
OAuth.prototype.mergeObject = function(obj1, obj2) {
    var merged_obj = obj1;
    for(var key in obj2) {
        merged_obj[key] = obj2[key];
    }
    return merged_obj;
};

/**
 * Sort object by key
 * @param  {Object} data
 * @return {Object} sorted object
 */
OAuth.prototype.sortObject = function(data) {
    var keys = Object.keys(data);
    var result = {};

    keys.sort();

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        result[key] = data[key];
    }

    return result;
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name           Manga Reader Offline
// @namespace      zackad's script
// @author         zackad
// @version        0.2.3
// @description    read manga offline from your folder collection
// @include        file:///*/*
// @copyright      2015 zackad
// @require        http://code.jquery.com/jquery-1.10.1.min.js
// ==/UserScript==
$(document).ready(function(){
    var gvar = function(){};
    gvar.__DEBUG__ = 0;     //DEBUG MODE

	gvar.style = ''
		+''
		;
	var container = ''
		+'
'
		+''
		+'
'
		;
	var loc_wrp = ''
		+'
'
		+'
'
		;
	var imgSelector = ''
		+'a[href$=".jpg"],'
		+'a[href$=".jpeg"],'
		+'a[href$=".png"],'
		+'a[href$=".PNG"],'
		+'a[href$=".JPG"],'
		+'a[href$=".JPEG"],'
		+'a[href$=".gif"]';
	var img = $(imgSelector);
    //var controler = 'disable';
    var controler = ''
        //+'<button id="disable" value="Disable">'
        +''
        //+'<button id="enable">Read this folder</button>'
        ;

	function enable(){
		if (img.length != 0){
			$('body').children().remove();
			$('head').children().remove();
			$('head').append(gvar.style);
			$('body').append(container)
				.append(loc_wrp)
				.prepend(loc_wrp)
				.css('background-color','black');
			//$('.location-container').append('controler');
		}
		img.each(function(){
			var temp = $(this).attr('href');
			var image = '
';
			$('#container center').append(image);
		});

    }
    //find current location
    function getLoc(){
        var loc = function(){};
        loc.current = window.location.href;
        loc.current = decodeURI(loc.current);
        loc.current = loc.current.split('/');
        loc.i = loc.current.length;
        loc.temp = '';
        for (var i=3; i < loc.current.length-1; i++){
            loc.temp += loc.current[i]+ '/';
            if (i == loc.i-2){
                loc.a = '' + loc.current[i] +' / ';
                //title
                $('head').append('<title>'+loc.current[i]+'</title>');
            } else {
                loc.a = '' + loc.current[i] +' / ';
            }
            clog(loc.a);
            $('.location-container').append(loc.a);
            clog(loc.temp);
        }
        //$('.location-container').append(controler);
    }
    function clog(x){
        if(!gvar.__DEBUG__) return;
        console && console.log && console.log(x);
    }
    function here(){
        return window.location.href;
    }
    function disable(){
        //$('body').load((here());
        clog(here());
    }
	function init(){
		var temp = $('body').children();
		//$('body').children().remove();
		$('head').append(gvar.style);
        $('body').prepend(container);
		$('body').prepend(loc_wrp);
        $('.container-container').append(controler);
		/* var fLink = $('table a');
		fLink.href.sort(naturalSort);
		clog(fLink.href); */
	}
    function lets_roll(){
		if (img.length == 0) return;
        init();
		enable();
        getLoc();
        $('#enable').hide();
	}
/*
 * Natural Sort algorithm for Javascript - Version 0.8 - Released under MIT license
 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
 */
function naturalSort (a, b) {
    var re = /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[\da-fA-F]+$|\d+)/g,
        sre = /^\s+|\s+$/g,   // trim pre-post whitespace
        snre = /\s+/g,        // normalize all whitespace to single ' ' character
        dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
        hre = /^0x[0-9a-f]+$/i,
        ore = /^0/,
        i = function(s) {
            return (naturalSort.insensitive && ('' + s).toLowerCase() || '' + s).replace(sre, '');
        },
        // convert all to strings strip whitespace
        x = i(a) || '',
        y = i(b) || '',
        // chunk/tokenize
        xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
        yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
        // numeric, hex or date detection
        xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
        yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
        normChunk = function(s, l) {
            // normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
            return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
        },
        oFxNcL, oFyNcL;
    // first try and sort Hex codes or Dates
    if (yD) {
        if ( xD < yD ) { return -1; }
        else if ( xD > yD ) { return 1; }
    }
    // natural sorting through split numeric strings and default strings
    for(var cLoc=0, xNl = xN.length, yNl = yN.length, numS=Math.max(xNl, yNl); cLoc < numS; cLoc++) {
        oFxNcL = normChunk(xN[cLoc], xNl);
        oFyNcL = normChunk(yN[cLoc], yNl);
        // handle numeric vs string comparison - number < string - (Kyle Adams)
        if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
        // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
        else if (typeof oFxNcL !== typeof oFyNcL) {
            oFxNcL += '';
            oFyNcL += '';
        }
        if (oFxNcL < oFyNcL) { return -1; }
        if (oFxNcL > oFyNcL) { return 1; }
    }
    return 0;
}
    init();
    getLoc();
    $('#disable').click(disable);
    $('#enable').click(lets_roll);

    /* Hotkey */
    window.addEventListener('keydown', function(e) {
    var keyCode = e.keyCode;
    var CSA = [e.ctrlKey, e.shiftKey, e.altKey];
    //console.log(keyCode);
    //console.log(String(CSA) + '; '+keyCode);

    // caseof : Enter
    if(keyCode == 13 ){
        lets_roll();
    }
        // caseof : \ 'backslash'
    if(keyCode == 220){
        if(img.length == 0) return;
        window.location.reload();
    }
}, true);
}
);<commit_msg>css; file-listing;<commit_after>// ==UserScript==
// @name           Manga Reader Offline
// @namespace      zackad's script
// @author         zackad
// @version        0.2.4
// @description    read manga offline from your folder collection
// @include        file:///*/*
// @copyright      2015 zackad
// @require        http://code.jquery.com/jquery-1.10.1.min.js
// ==/UserScript==
$(document).ready(function(){
    var gvar = function(){};
    gvar.__DEBUG__ = 0;     //DEBUG MODE

	gvar.style = ''
		+''
		;
	var container = ''
		+'
'
		+''
		+'
'
		;
	var loc_wrp = ''
		+'
'
		+'
'
		;
	var imgSelector = ''
		+'a[href$=".jpg"],'
		+'a[href$=".jpeg"],'
		+'a[href$=".png"],'
		+'a[href$=".PNG"],'
		+'a[href$=".JPG"],'
		+'a[href$=".JPEG"],'
		+'a[href$=".gif"]';
	var img = $(imgSelector);
    //var controler = 'disable';
    var controler = ''
        //+'<button id="disable" value="Disable">'
        +''
        //+'<button id="enable">Read this folder</button>'
        ;

	function enable(){
		if (img.length != 0){
			$('body').children().remove();
			$('head').children().remove();
			$('head').append(gvar.style);
			$('body').append(container)
				.append(loc_wrp)
				.prepend(loc_wrp)
				.css('background-color','black');
			//$('.location-container').append('controler');
		}
		img.each(function(){
			var temp = $(this).attr('href');
			var image = '
';
			$('#container center').append(image);
		});

    }
    //find current location
    function getLoc(){
        var loc = function(){};
        loc.current = window.location.href;
        loc.current = decodeURI(loc.current);
        loc.current = loc.current.split('/');
        loc.i = loc.current.length;
        loc.temp = '';
        for (var i=3; i < loc.current.length-1; i++){
            loc.temp += loc.current[i]+ '/';
            if (i == loc.i-2){
                loc.a = '' + loc.current[i] +' / ';
                //title
                $('head').append('<title>'+loc.current[i]+'</title>');
            } else {
                loc.a = '' + loc.current[i] +' / ';
            }
            clog(loc.a);
            $('.location-container').append(loc.a);
            clog(loc.temp);
        }
        //$('.location-container').append(controler);
    }
    function clog(x){
        if(!gvar.__DEBUG__) return;
        console && console.log && console.log(x);
    }
    function here(){
        return window.location.href;
    }
    function disable(){
        //$('body').load((here());
        clog(here());
    }
	function init(){
		var temp = $('body').children();
		//$('body').children().remove();
		$('head').append(gvar.style);
        $('body').prepend(container);
		$('body').prepend(loc_wrp);
		$('h1, .up').remove();
//      $('.container-container').append(controler);
//		var fLink = $('table a').attr('href');
//		fLink.sort(naturalSort);
//		clog(fLink);
	}
    function lets_roll(){
		if (img.length == 0) return;
        init();
		enable();
        getLoc();
        $('#enable').hide();
	}
/*
 * Natural Sort algorithm for Javascript - Version 0.8 - Released under MIT license
 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
 */
function naturalSort (a, b) {
    var re = /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[\da-fA-F]+$|\d+)/g,
        sre = /^\s+|\s+$/g,   // trim pre-post whitespace
        snre = /\s+/g,        // normalize all whitespace to single ' ' character
        dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
        hre = /^0x[0-9a-f]+$/i,
        ore = /^0/,
        i = function(s) {
            return (naturalSort.insensitive && ('' + s).toLowerCase() || '' + s).replace(sre, '');
        },
        // convert all to strings strip whitespace
        x = i(a) || '',
        y = i(b) || '',
        // chunk/tokenize
        xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
        yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
        // numeric, hex or date detection
        xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
        yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
        normChunk = function(s, l) {
            // normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
            return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
        },
        oFxNcL, oFyNcL;
    // first try and sort Hex codes or Dates
    if (yD) {
        if ( xD < yD ) { return -1; }
        else if ( xD > yD ) { return 1; }
    }
    // natural sorting through split numeric strings and default strings
    for(var cLoc=0, xNl = xN.length, yNl = yN.length, numS=Math.max(xNl, yNl); cLoc < numS; cLoc++) {
        oFxNcL = normChunk(xN[cLoc], xNl);
        oFyNcL = normChunk(yN[cLoc], yNl);
        // handle numeric vs string comparison - number < string - (Kyle Adams)
        if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
        // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
        else if (typeof oFxNcL !== typeof oFyNcL) {
            oFxNcL += '';
            oFyNcL += '';
        }
        if (oFxNcL < oFyNcL) { return -1; }
        if (oFxNcL > oFyNcL) { return 1; }
    }
    return 0;
}
    init();
    getLoc();
    $('#disable').click(disable);
    $('#enable').click(lets_roll);

    /* Hotkey */
    window.addEventListener('keydown', function(e) {
    var keyCode = e.keyCode;
    var CSA = [e.ctrlKey, e.shiftKey, e.altKey];
    //console.log(keyCode);
    //console.log(String(CSA) + '; '+keyCode);

    // caseof : Enter
    if(keyCode == 13 ){
        lets_roll();
    }
        // caseof : \ 'backslash'
    if(keyCode == 220){
        if(img.length == 0) return;
        window.location.reload();
    }
}, true);
}
);<|endoftext|>


<commit_before>/*
	JsonML_DOM.js
	DOM to JsonML utility

	Created: 2007-02-15-2235
	Modified: 2008-08-31-2206

	Copyright (c)2006-2009 Stephen M. McKamey
	Distributed under an open-source license: http://jsonml.org/license
*/

var JsonML;
if ("undefined" === typeof JsonML) {
	JsonML = {};
}

/*JsonML*/ JsonML.parseDOM = function(/*DOM*/ elem, /*function*/ filter) {
	if (!elem || !elem.nodeType) {
		// free references
		elem = null;
		return null;
	}

	var i, jml;
	switch (elem.nodeType) {
		case 1:  // element
		case 9:  // document
		case 11: // documentFragment
			jml = [elem.tagName||""];

			var a = elem.attributes,
				att = {},
				hasAttrib = false;

			for (i=0; a && i<a.length; i++) {
				if (a[i].specified) {
					if (a[i].name === "style") {
						att.style = elem.style.cssText ? elem.style.cssText : a[i].value;
					} else if ("string" === typeof a[i].value) {
						att[a[i].name] = a[i].value;
					}
					hasAttrib = true;
				}
			}
			if (hasAttrib) {
				jml.push(att);
			}

			var c;
			switch (jml[0].toLowerCase()) {
				case "frame":
				case "iframe":
					try {
						if ("undefined" !== typeof elem.contentDocument) {
							// W3C
							c = elem.contentDocument;
						} else if ("undefined" !== typeof elem.contentWindow) {
							// Microsoft
							c = elem.contentWindow.document;
						} else if ("undefined" !== typeof elem.document) {
							// deprecated
							c = elem.document;
						}

						c = JsonML.parseDOM(c, filter);
						if (c) {
							jml.push(c);
						}
					} catch (ex) {}
					break;
				default:
					if (elem.hasChildNodes()) {
						for (i=0; i<elem.childNodes.length; i++) {
							c = elem.childNodes[i];
							c = JsonML.parseDOM(c, filter);
							if (c) {
								jml.push(c);
							}
						}
					}
					break;
			}

			// filter result
			if ("function" === typeof filter) {
				jml = filter(jml, elem);
			}

			// free references
			elem = null;
			return jml;
		case 3: // text node
		case 4: // CDATA node
			var str = String(elem.nodeValue);
			// free references
			elem = null;
			return str;
		case 10: // doctype
			jml = ["!"];

			var type = ["DOCTYPE", (elem.name || "html").toLowerCase()];

			if (elem.publicId) {
				type.push("PUBLIC", '"' + elem.publicId + '"');
			}

			if (elem.systemId) {
				type.push('"' + elem.systemId + '"');
			}

			jml.push(type.join(" "));

			// filter result
			if ("function" === typeof filter) {
				jml = filter(jml, elem);
			}

			// free references
			elem = null;
			return jml;
		case 8: // comment node
			if ((elem.nodeValue||"").indexOf("DOCTYPE") !== 0) {
				// free references
				elem = null;
				return null;
			}

			jml = ["!",
					elem.nodeValue];

			// filter result
			if ("function" === typeof filter) {
				jml = filter(jml, elem);
			}

			// free references
			elem = null;
			return jml;
		default: // etc.
			// free references
			elem = null;
			return null;
	}
};

/*JsonML*/ JsonML.parseHTML = function(/*string*/ html, /*function*/ filter) {
	var elem = document.createElement("div");
	elem.innerHTML = html;
	var jml = JsonML.parseDOM(elem, filter);

	// free references
	elem = null;

	if (jml.length === 2) {
		return jml[1];
	}

	// make wrapper a document fragment
	jml[0] = "";
	return jml;
};
<commit_msg>- IE style blocks<commit_after>/*
	JsonML_DOM.js
	DOM to JsonML utility

	Created: 2007-02-15-2235
	Modified: 2008-08-31-2206

	Copyright (c)2006-2009 Stephen M. McKamey
	Distributed under an open-source license: http://jsonml.org/license
*/

var JsonML;
if ("undefined" === typeof JsonML) {
	JsonML = {};
}

/*JsonML*/ JsonML.parseDOM = function(/*DOM*/ elem, /*function*/ filter) {
	if (!elem || !elem.nodeType) {
		// free references
		elem = null;
		return null;
	}

	var i, jml;
	switch (elem.nodeType) {
		case 1:  // element
		case 9:  // document
		case 11: // documentFragment
			jml = [elem.tagName||""];

			var a = elem.attributes,
				att = {},
				hasAttrib = false;

			for (i=0; a && i<a.length; i++) {
				if (a[i].specified) {
					if (a[i].name === "style") {
						att.style = elem.style.cssText || a[i].value;
					} else if ("string" === typeof a[i].value) {
						att[a[i].name] = a[i].value;
					}
					hasAttrib = true;
				}
			}
			if (hasAttrib) {
				jml.push(att);
			}

			var c;
			switch (jml[0].toLowerCase()) {
				case "frame":
				case "iframe":
					try {
						if ("undefined" !== typeof elem.contentDocument) {
							// W3C
							c = elem.contentDocument;
						} else if ("undefined" !== typeof elem.contentWindow) {
							// Microsoft
							c = elem.contentWindow.document;
						} else if ("undefined" !== typeof elem.document) {
							// deprecated
							c = elem.document;
						}

						c = JsonML.parseDOM(c, filter);
						if (c) {
							jml.push(c);
						}
					} catch (ex) {}
					break;
				case "style":
					c = elem.styleSheet && elem.styleSheet.cssText;
					if (c) {
						jml.push(c);
					} else if (elem.hasChildNodes()) {
						for (i=0; i<elem.childNodes.length; i++) {
							c = elem.childNodes[i];
							c = JsonML.parseDOM(c, filter);
							if (c) {
								jml.push(c);
							}
						}
					}
					break;
				default:
					if (elem.hasChildNodes()) {
						for (i=0; i<elem.childNodes.length; i++) {
							c = elem.childNodes[i];
							c = JsonML.parseDOM(c, filter);
							if (c) {
								jml.push(c);
							}
						}
					}
					break;
			}

			// filter result
			if ("function" === typeof filter) {
				jml = filter(jml, elem);
			}

			// free references
			elem = null;
			return jml;
		case 3: // text node
		case 4: // CDATA node
			var str = String(elem.nodeValue);
			// free references
			elem = null;
			return str;
		case 10: // doctype
			jml = ["!"];

			var type = ["DOCTYPE", (elem.name || "html").toLowerCase()];

			if (elem.publicId) {
				type.push("PUBLIC", '"' + elem.publicId + '"');
			}

			if (elem.systemId) {
				type.push('"' + elem.systemId + '"');
			}

			jml.push(type.join(" "));

			// filter result
			if ("function" === typeof filter) {
				jml = filter(jml, elem);
			}

			// free references
			elem = null;
			return jml;
		case 8: // comment node
			if ((elem.nodeValue||"").indexOf("DOCTYPE") !== 0) {
				// free references
				elem = null;
				return null;
			}

			jml = ["!",
					elem.nodeValue];

			// filter result
			if ("function" === typeof filter) {
				jml = filter(jml, elem);
			}

			// free references
			elem = null;
			return jml;
		default: // etc.
			// free references
			elem = null;
			return null;
	}
};

/*JsonML*/ JsonML.parseHTML = function(/*string*/ html, /*function*/ filter) {
	var elem = document.createElement("div");
	elem.innerHTML = html;
	var jml = JsonML.parseDOM(elem, filter);

	// free references
	elem = null;

	if (jml.length === 2) {
		return jml[1];
	}

	// make wrapper a document fragment
	jml[0] = "";
	return jml;
};
<|endoftext|>


<commit_before>$(function () {

    hcc.config.dialogClass = "dnnFormPopup hc-popup-dialog";

    var forms = $('div[data-type="form"]');

    forms.on("keydown", "input:text", function (event) {
        var form = $(this).closest('div[data-type="form"]');
        if (event.which == 13) {
            var inputElement = form.find("input:submit:not([data-nosubmit]), input:image:not([data-nosubmit])").first();
            if (inputElement)
                inputElement.click();

            event.preventDefault();
        }
    });

    forms.on("click", "input:submit:not([data-nosubmit]), input:image:not([data-nosubmit])", function (event) {
        var form = $(this).closest('div[data-type="form"]');
        var submitEl = $(event.target);

        var confirmMessage = submitEl.data("confirm");
        if (confirmMessage && !confirm(confirmMessage)) {
            event.stopPropagation();
            event.preventDefault();
            return;
        }

        var validator = $.data(form[0], 'validator');
        if (validator && !validator.form()) {
            event.stopPropagation();
            event.preventDefault();
            return;
        }

        var action = form.data("action");
        var method = form.data("method");
        var moduleid = form.data("moduleid");
        var skipxy = form.data("skipxy");

        var elements = form.find("select, input, textarea").serializeArray();

        if (moduleid && method != "get")
            elements.push({ "name": "moduleid", "value": moduleid });

        if (submitEl.attr("name")) {
            elements.push({ "name": submitEl.attr("name"), "value": submitEl.val() });
        }

        if (submitEl.attr("type") == "image" && !skipxy) {
            addXYImageParams(elements, submitEl, event);
        }

        var postdata = $.param(elements);

        var hcMvcView = $(this).closest('.hcMvcView');
        hcMvcView.ajaxLoader("start");

        if (method == "get") {
            setTimeout(function () {
                window.location = action + (action.indexOf("?") > -1 ? "&" : "?") + postdata;
            }, 0);
        }
        else {
            $.ajax({
                type: method,
                url: action,
                data: postdata,
                beforeSend: function (jqXHR, settings) {
                    jqXHR.setRequestHeader("CustomRedirect", "1");
                },
                success: function (data, textStatus, jqXHR) {
                    //we do not post to other url so this is not used
                    //if (window.location.href != this.url) {
                    //    //html5 feature. Won't work in IE < 10
                    //    if (history && history.pushState) {
                    //        //failes on second call in FIrefox due to replacement of whole document on previous one
                    //        history.pushState({}, document.title, this.url);
                    //    }
                    //    else {
                    //        //window.location.replace(this.url);
                    //        window.location = this.url;
                    //        return;
                    //    }
                    //}

                    document.open();
                    document.write(data);
                    document.close();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status != 333)
                        if (console && console.log)
                            console.log(errorThrown);
                },
                complete: function (jqXHR, textStatus) {

                },
                statusCode: {
                    333: function (jqXHR, textStatus, errorThrown) {
                        var location = jqXHR.getResponseHeader("CustomLocation");
                        window.location = location;
                    }
                }
            });
        }
        event.preventDefault();
    });

    function addXYImageParams(elements, submitEl, event) {
        var nameX = "x";
        var nameY = "y";
        var name = submitEl.attr("name");
        if (name) {
            nameX = [name, ".", nameX].join("");
            nameY = [name, ".", nameY].join("");
        }

        var valueX = event.offsetX;
        var valueY = event.offsetY;
        valueX = (valueX == undefined || valueX == "") ? 0 : valueX;
        valueY = (valueY == undefined || valueY == "") ? 0 : valueY;

        elements.push({ "name": nameX, "value": valueX });
        elements.push({ "name": nameY, "value": valueY });
    }

    $('.hc-dialog').click(function () {
        var myModal = $(this).attr('href');
        $(myModal).hcDialog();
        return false;
    });

    // NOTE: Obsolete dialog handler. Use "hc-dialog" class instead.
    $('.hc-popup').click(function () {
        var myTitle = $(this).attr('title');
        var modalWidth = $(this).data('width');
        var modalHeight = $(this).data('height');
        var modalMinHeight = $(this).data('min-height');
        var modalMinWidth = $(this).data('min-width');
        var myModal = $(this).attr('href');
        $(myModal).dialog({
            width: modalWidth,
            maxHeight: modalHeight,
            minHeight: modalMinHeight,
            minWidth: modalMinWidth,
            title: myTitle,
            modal: true,
            closeOnEscape: true,
            position: "center",
            dialogClass: "dnnFormPopup hc-popup-dialog"
        });
        return false;
    });

    hcc.autoHeight('.hc-record-grid .hc-recimage');

    if ($.validator) {
        $.validator.setDefaults({ ignore: ".ignore-val, :hidden" });
    }

    $.fn.hcFormMessage = function (status, message) {
        var $this = $(this).html(message).addClass("dnnFormMessage");

        if (status == 'OK')
            $this.removeClass("dnnFormValidationSummary");
        else
            $this.addClass("dnnFormValidationSummary");

        $("body").scrollTo($this);
    };
});
<commit_msg>Fix moduleid Confict in hcc.vews.js<commit_after>$(function () {

    hcc.config.dialogClass = "dnnFormPopup hc-popup-dialog";

    var forms = $('div[data-type="form"]');

    forms.on("keydown", "input:text", function (event) {
        var form = $(this).closest('div[data-type="form"]');
        if (event.which == 13) {
            var inputElement = form.find("input:submit:not([data-nosubmit]), input:image:not([data-nosubmit])").first();
            if (inputElement)
                inputElement.click();

            event.preventDefault();
        }
    });

    forms.on("click", "input:submit:not([data-nosubmit]), input:image:not([data-nosubmit])", function (event) {
        var form = $(this).closest('div[data-type="form"]');
        var submitEl = $(event.target);

        var confirmMessage = submitEl.data("confirm");
        if (confirmMessage && !confirm(confirmMessage)) {
            event.stopPropagation();
            event.preventDefault();
            return;
        }

        var validator = $.data(form[0], 'validator');
        if (validator && !validator.form()) {
            event.stopPropagation();
            event.preventDefault();
            return;
        }

        var action = form.data("action");
        var method = form.data("method");
        var moduleidjs = form.data("moduleid");
        var skipxy = form.data("skipxy");

        var elements = form.find("select, input, textarea").serializeArray();

        if (moduleidjs && method != "get")
            elements.push({ "name": "moduleid", "value": moduleidjs });

        if (submitEl.attr("name")) {
            elements.push({ "name": submitEl.attr("name"), "value": submitEl.val() });
        }

        if (submitEl.attr("type") == "image" && !skipxy) {
            addXYImageParams(elements, submitEl, event);
        }

        var postdata = $.param(elements);

        var hcMvcView = $(this).closest('.hcMvcView');
        hcMvcView.ajaxLoader("start");

        if (method == "get") {
            setTimeout(function () {
                window.location = action + (action.indexOf("?") > -1 ? "&" : "?") + postdata;
            }, 0);
        }
        else {
            $.ajax({
                type: method,
                url: action,
                data: postdata,
                beforeSend: function (jqXHR, settings) {
                    jqXHR.setRequestHeader("CustomRedirect", "1");
                },
                success: function (data, textStatus, jqXHR) {
                    //we do not post to other url so this is not used
                    //if (window.location.href != this.url) {
                    //    //html5 feature. Won't work in IE < 10
                    //    if (history && history.pushState) {
                    //        //failes on second call in FIrefox due to replacement of whole document on previous one
                    //        history.pushState({}, document.title, this.url);
                    //    }
                    //    else {
                    //        //window.location.replace(this.url);
                    //        window.location = this.url;
                    //        return;
                    //    }
                    //}

                    document.open();
                    document.write(data);
                    document.close();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status != 333)
                        if (console && console.log)
                            console.log(errorThrown);
                },
                complete: function (jqXHR, textStatus) {

                },
                statusCode: {
                    333: function (jqXHR, textStatus, errorThrown) {
                        var location = jqXHR.getResponseHeader("CustomLocation");
                        window.location = location;
                    }
                }
            });
        }
        event.preventDefault();
    });

    function addXYImageParams(elements, submitEl, event) {
        var nameX = "x";
        var nameY = "y";
        var name = submitEl.attr("name");
        if (name) {
            nameX = [name, ".", nameX].join("");
            nameY = [name, ".", nameY].join("");
        }

        var valueX = event.offsetX;
        var valueY = event.offsetY;
        valueX = (valueX == undefined || valueX == "") ? 0 : valueX;
        valueY = (valueY == undefined || valueY == "") ? 0 : valueY;

        elements.push({ "name": nameX, "value": valueX });
        elements.push({ "name": nameY, "value": valueY });
    }

    $('.hc-dialog').click(function () {
        var myModal = $(this).attr('href');
        $(myModal).hcDialog();
        return false;
    });

    // NOTE: Obsolete dialog handler. Use "hc-dialog" class instead.
    $('.hc-popup').click(function () {
        var myTitle = $(this).attr('title');
        var modalWidth = $(this).data('width');
        var modalHeight = $(this).data('height');
        var modalMinHeight = $(this).data('min-height');
        var modalMinWidth = $(this).data('min-width');
        var myModal = $(this).attr('href');
        $(myModal).dialog({
            width: modalWidth,
            maxHeight: modalHeight,
            minHeight: modalMinHeight,
            minWidth: modalMinWidth,
            title: myTitle,
            modal: true,
            closeOnEscape: true,
            position: "center",
            dialogClass: "dnnFormPopup hc-popup-dialog"
        });
        return false;
    });

    hcc.autoHeight('.hc-record-grid .hc-recimage');

    if ($.validator) {
        $.validator.setDefaults({ ignore: ".ignore-val, :hidden" });
    }

    $.fn.hcFormMessage = function (status, message) {
        var $this = $(this).html(message).addClass("dnnFormMessage");

        if (status == 'OK')
            $this.removeClass("dnnFormValidationSummary");
        else
            $this.addClass("dnnFormValidationSummary");

        $("body").scrollTo($this);
    };
});
<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
         'Widgets/CesiumInspector/CesiumInspectorViewModel',
         'Specs/createScene',
         'Specs/destroyScene',
         'Core/Extent',
         'Core/defined',
         'Scene/ExtentPrimitive',
         'Scene/Tile',
         'Scene/WebMercatorTilingScheme',
         'Scene/Material',
         'Scene/CentralBody',
         'Core/Math'
     ], function(
         CesiumInspectorViewModel,
         createScene,
         destroyScene,
         Extent,
         defined,
         ExtentPrimitive,
         Tile,
         WebMercatorTilingScheme,
         Material,
         CentralBody,
         CesiumMath) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    var scene;
    beforeAll(function() {
        scene = createScene();
    });

    afterAll(function() {
        destroyScene(scene);
    });

    beforeEach(function() {
        scene.getPrimitives().setCentralBody(new CentralBody());
        scene.initializeFrame();
    });

    afterEach(function() {
        scene.getPrimitives().removeAll();
    });

    it('constructor sets values', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        expect(viewModel.scene).toBe(scene);
    });

    it('throws if scene is undefined', function() {
        expect(function() {
            return new CesiumInspectorViewModel();
        }).toThrow();
    });

    it('show frustums', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.frustums = true;
        viewModel.showFrustums();
        expect(viewModel.scene.debugShowFrustums).toBe(true);
        setTimeout(function(){
            viewModel.frustums = false;
            viewModel.showFrustums();
            expect(viewModel.scene.debugShowFrustums).toBe(false);
        }, 250);
    });

    it('show performance', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.performance = true;
        viewModel.showPerformance();
        scene.render();
        expect(viewModel.scene.getPrimitives().getLength()).toBe(1);

        viewModel.performance = false;
        viewModel.showPerformance();
        scene.render();
        expect(viewModel.scene.getPrimitives().getLength()).toBe(0);
    });

    it ('primitive bounding sphere', function() {
        var p = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-110.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-90.0),
                    CesiumMath.toRadians(20.0)),
                rotation : CesiumMath.toRadians(45),
                material : Material.fromType(Material.ColorType)
            })
        );
        var viewModel = new CesiumInspectorViewModel(scene);
        scene.render();
        viewModel.primitive = {primitive: p};
        viewModel.primitiveBoundingSphere = true;
        viewModel.showPrimitiveBoundingSphere();
        expect(p.debugShowBoundingVolume).toEqual(true);

        viewModel.primitiveBoundingSphere = false;
        viewModel.showPrimitiveBoundingSphere();
        scene.render();
        expect(p.debugShowBoundingVolume).toEqual(false);
    });

    it ('primitive reference frame', function() {
        var p = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-110.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-90.0),
                    CesiumMath.toRadians(20.0)),
                rotation : CesiumMath.toRadians(45),
                material : Material.fromType(Material.ColorType)
            })
        );
        var viewModel = new CesiumInspectorViewModel(scene);
        scene.render();
        viewModel.primitive = {primitive: p};
        viewModel.primitiveRefFrame = true;
        viewModel.showPrimitiveRefFrame();
        expect(scene.getPrimitives().getLength()).toEqual(2);

        viewModel.primitiveRefFrame = false;
        viewModel.showPrimitiveRefFrame();
        scene.render();
        expect(scene.getPrimitives().getLength()).toEqual(1);
    });

    it ('primitive filter', function() {
        var p = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-110.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-90.0),
                    CesiumMath.toRadians(20.0)),
                rotation : CesiumMath.toRadians(45),
                material : Material.fromType(Material.ColorType)
            })
        );

        var q = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-10.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-9.0),
                    CesiumMath.toRadians(20.0)),
                material : Material.fromType(Material.ColorType)
            })
        );

        var viewModel = new CesiumInspectorViewModel(scene);
        scene.render();
        viewModel.primitive = {primitive: p};
        viewModel.filterPrimitive = true;
        viewModel.doFilterPrimitive();
        expect(defined(scene.debugCommandFilter)).toEqual(true);
        expect(scene.debugCommandFilter({owner: p})).toEqual(true);
        expect(scene.debugCommandFilter({owner: q})).toEqual(false);

        viewModel.filterPrimitive = false;
        viewModel.doFilterPrimitive();
        expect(defined(scene.debugCommandFilter)).toEqual(false);
    });

    it ('primitive reference frame', function() {
        var p = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-110.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-90.0),
                    CesiumMath.toRadians(20.0)),
                rotation : CesiumMath.toRadians(45),
                material : Material.fromType(Material.ColorType)
            })
        );
        var viewModel = new CesiumInspectorViewModel(scene);
        scene.render();
        viewModel.primitive = {primitive: p};
        viewModel.primitiveRefFrame = true;
        viewModel.showPrimitiveRefFrame();
        expect(scene.getPrimitives().getLength()).toEqual(2);

        viewModel.primitiveRefFrame = false;
        viewModel.showPrimitiveRefFrame();
        scene.render();
        expect(scene.getPrimitives().getLength()).toEqual(1);
    });

    it('show wireframe', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.wireframe = true;
        viewModel.showWireframe();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.wireframe).toBe(true);

        viewModel.wireframe = false;
        viewModel.showWireframe();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.wireframe).toBe(false);
    });

    it('suspend updates', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.suspendUpdates = true;
        viewModel.doSuspendUpdates();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.suspendLodUpdate).toBe(true);

        viewModel.suspendUpdates = false;
        viewModel.doSuspendUpdates();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.suspendLodUpdate).toBe(false);
    });

    it('show tile coords', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        expect(viewModel.scene.getPrimitives().getCentralBody().getImageryLayers().getLength()).toBe(0);

        viewModel.tileCoords  = true;
        viewModel.showTileCoords();
        expect(viewModel.scene.getPrimitives().getCentralBody().getImageryLayers().getLength()).toBe(1);

        viewModel.tileCoords = false;
        viewModel.showTileCoords();
        expect(viewModel.scene.getPrimitives().getCentralBody().getImageryLayers().getLength()).toBe(0);
    });

    it('show tile bounding sphere', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        var tile = new Tile({tilingScheme : new WebMercatorTilingScheme(), x : 0, y : 0, level : 0});
        viewModel.tile = tile;

        viewModel.tileBoundingSphere  = true;
        viewModel.showTileBoundingSphere();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.boundingSphereTile).toBe(tile);

        viewModel.tileBoundingSphere = false;
        viewModel.showTileBoundingSphere();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.boundingSphereTile).toBe(undefined);
    });

    it('filter tile', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        var tile = new Tile({tilingScheme : new WebMercatorTilingScheme(), x : 0, y : 0, level : 0});
        viewModel.tile = tile;

        viewModel.filterTile  = true;
        viewModel.doFilterTile();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._tilesToRenderByTextureCount[0][0]).toBe(tile);
        expect(viewModel.suspendUpdates).toBe(true);

        viewModel.filterTile = false;
        viewModel.doFilterTile();
        expect(viewModel.suspendUpdates).toBe(false);
    });

}, 'WebGL');<commit_msg>correct tests<commit_after>/*global defineSuite*/
defineSuite([
         'Widgets/CesiumInspector/CesiumInspectorViewModel',
         'Specs/createScene',
         'Specs/destroyScene',
         'Core/Extent',
         'Core/defined',
         'Scene/ExtentPrimitive',
         'Scene/Tile',
         'Scene/WebMercatorTilingScheme',
         'Scene/Material',
         'Scene/CentralBody',
         'Core/Math'
     ], function(
         CesiumInspectorViewModel,
         createScene,
         destroyScene,
         Extent,
         defined,
         ExtentPrimitive,
         Tile,
         WebMercatorTilingScheme,
         Material,
         CentralBody,
         CesiumMath) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/

    var scene;
    beforeAll(function() {
        scene = createScene();
    });

    afterAll(function() {
        destroyScene(scene);
    });

    beforeEach(function() {
        scene.getPrimitives().setCentralBody(new CentralBody());
        scene.initializeFrame();
    });

    afterEach(function() {
        scene.getPrimitives().removeAll();
    });

    it('constructor sets values', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        expect(viewModel.scene).toBe(scene);
    });

    it('throws if scene is undefined', function() {
        expect(function() {
            return new CesiumInspectorViewModel();
        }).toThrow();
    });

    it('show frustums', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.frustums = true;
        viewModel.showFrustums();
        expect(viewModel.scene.debugShowFrustums).toBe(true);
        setTimeout(function(){
            viewModel.frustums = false;
            viewModel.showFrustums();
            expect(viewModel.scene.debugShowFrustums).toBe(false);
        }, 250);
    });

    it('show performance', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.performance = true;
        viewModel.showPerformance();
        scene.render();
        expect(viewModel.scene.getPrimitives().getLength()).toBe(1);

        viewModel.performance = false;
        viewModel.showPerformance();
        scene.render();
        expect(viewModel.scene.getPrimitives().getLength()).toBe(0);
    });

    it ('primitive bounding sphere', function() {
        var p = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-110.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-90.0),
                    CesiumMath.toRadians(20.0)),
                rotation : CesiumMath.toRadians(45),
                material : Material.fromType(Material.ColorType)
            })
        );
        var viewModel = new CesiumInspectorViewModel(scene);
        scene.render();
        viewModel.primitive = p;
        viewModel.primitiveBoundingSphere = true;
        viewModel.showPrimitiveBoundingSphere();
        expect(p.debugShowBoundingVolume).toEqual(true);

        viewModel.primitiveBoundingSphere = false;
        viewModel.showPrimitiveBoundingSphere();
        scene.render();
        expect(p.debugShowBoundingVolume).toEqual(false);
    });

    it ('primitive filter', function() {
        var p = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-110.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-90.0),
                    CesiumMath.toRadians(20.0)),
                rotation : CesiumMath.toRadians(45),
                material : Material.fromType(Material.ColorType)
            })
        );

        var q = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-10.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-9.0),
                    CesiumMath.toRadians(20.0)),
                material : Material.fromType(Material.ColorType)
            })
        );

        var viewModel = new CesiumInspectorViewModel(scene);
        scene.render();
        viewModel.primitive = p;
        viewModel.filterPrimitive = true;
        viewModel.doFilterPrimitive();
        expect(defined(scene.debugCommandFilter)).toEqual(true);
        expect(scene.debugCommandFilter({owner: p})).toEqual(true);
        expect(scene.debugCommandFilter({owner: q})).toEqual(false);

        viewModel.filterPrimitive = false;
        viewModel.doFilterPrimitive();
        expect(defined(scene.debugCommandFilter)).toEqual(false);
    });

    it ('primitive reference frame', function() {
        var p = scene.getPrimitives().add(new ExtentPrimitive({
            extent : new Extent(
                    CesiumMath.toRadians(-110.0),
                    CesiumMath.toRadians(0.0),
                    CesiumMath.toRadians(-90.0),
                    CesiumMath.toRadians(20.0)),
                rotation : CesiumMath.toRadians(45),
                material : Material.fromType(Material.ColorType)
            })
        );
        var viewModel = new CesiumInspectorViewModel(scene);
        scene.render();
        viewModel.primitive = p;
        viewModel.primitiveReferenceFrame = true;
        viewModel.showPrimitiveReferenceFrame();
        expect(scene.getPrimitives().getLength()).toEqual(2);

        viewModel.primitiveReferenceFrame = false;
        viewModel.showPrimitiveReferenceFrame();
        scene.render();
        expect(scene.getPrimitives().getLength()).toEqual(1);
    });

    it('show wireframe', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.wireframe = true;
        viewModel.showWireframe();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.wireframe).toBe(true);

        viewModel.wireframe = false;
        viewModel.showWireframe();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.wireframe).toBe(false);
    });

    it('suspend updates', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        viewModel.suspendUpdates = true;
        viewModel.doSuspendUpdates();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.suspendLodUpdate).toBe(true);

        viewModel.suspendUpdates = false;
        viewModel.doSuspendUpdates();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.suspendLodUpdate).toBe(false);
    });

    it('show tile coords', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        expect(viewModel.scene.getPrimitives().getCentralBody().getImageryLayers().getLength()).toBe(0);

        viewModel.tileCoordinates  = true;
        viewModel.showTileCoordinates();
        expect(viewModel.scene.getPrimitives().getCentralBody().getImageryLayers().getLength()).toBe(1);

        viewModel.tileCoordinates = false;
        viewModel.showTileCoordinates();
        expect(viewModel.scene.getPrimitives().getCentralBody().getImageryLayers().getLength()).toBe(0);
    });

    it('show tile bounding sphere', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        var tile = new Tile({tilingScheme : new WebMercatorTilingScheme(), x : 0, y : 0, level : 0});
        viewModel.tile = tile;

        viewModel.tileBoundingSphere  = true;
        viewModel.showTileBoundingSphere();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.boundingSphereTile).toBe(tile);

        viewModel.tileBoundingSphere = false;
        viewModel.showTileBoundingSphere();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._debug.boundingSphereTile).toBe(undefined);
    });

    it('filter tile', function() {
        var viewModel = new CesiumInspectorViewModel(scene);
        var tile = new Tile({tilingScheme : new WebMercatorTilingScheme(), x : 0, y : 0, level : 0});
        viewModel.tile = tile;

        viewModel.filterTile  = true;
        viewModel.doFilterTile();
        expect(viewModel.scene.getPrimitives().getCentralBody()._surface._tilesToRenderByTextureCount[0][0]).toBe(tile);
        expect(viewModel.suspendUpdates).toBe(true);

        viewModel.filterTile = false;
        viewModel.doFilterTile();
        expect(viewModel.suspendUpdates).toBe(false);
    });

}, 'WebGL');<|endoftext|>