<commit_before>
/**
 * Module dependencies.
 */

var should = require('should');

function err(fn, msg) {
  try {
    fn();
    should.fail('expected an error');
  } catch (err) {
    should.equal(msg, err.message);
  }
}

module.exports = {
  'test .version': function(){
    should.match(should.version, /^\d+\.\d+\.\d+$/);
  },

  'test assertion': function(){
    'test'.should.be.a.string;
  },

  'test true': function(){
    true.should.be.true;
    false.should.not.be.true;
    (1).should.not.be.true;

    err(function(){
      'test'.should.be.true;
    }, "expected 'test' to be true")
  },

  'test false': function(){
    false.should.be.false;
    true.should.not.be.false;
    (0).should.not.be.false;

    err(function(){
      ''.should.be.false;
    }, "expected '' to be false")
  },

  'test arguments': function(){
    var args = (function(){ return arguments; })(1,2,3);
    args.should.be.arguments;
    [].should.not.be.arguments;
  },

  'test .equal()': function(){
    var foo;
    should.equal(undefined, foo);
  },

  'test typeof': function(){
    'test'.should.be.a('string');

    err(function(){
      'test'.should.not.be.a('string');
    }, "expected 'test' not to be a string");

    (5).should.be.a('number');

    err(function(){
      (5).should.not.be.a('number');
    }, "expected 5 not to be a number");
  },

  'test instanceof': function(){
    function Foo(){}
    new Foo().should.be.an.instanceof(Foo);

    err(function(){
      (3).should.an.instanceof(Foo);
    }, "expected 3 to be an instance of Foo");
  },

  'test within(start, finish)': function(){
    (5).should.be.within(5, 10);
    (5).should.be.within(3,6);
    (5).should.be.within(3,5);
    (5).should.not.be.within(1,3);

    err(function(){
      (5).should.not.be.within(4,6);
    }, "expected 5 to not be within 4..6");

    err(function(){
      (10).should.be.within(50,100);
    }, "expected 10 to be within 50..100");
  },

  'test above(n)': function(){
    (5).should.be.above(2);
    (5).should.be.greaterThan(2);
    (5).should.not.be.above(5);
    (5).should.not.be.above(6);

    err(function(){
      (5).should.be.above(6);
    }, "expected 5 to be above 6");

    err(function(){
      (10).should.not.be.above(6);
    }, "expected 10 to be below 6");
  },

  'test match(regexp)': function(){
    'foobar'.should.match(/^foo/)
    'foobar'.should.not.match(/^bar/)

    err(function(){
      'foobar'.should.match(/^bar/i)
    }, "expected 'foobar' to match /^bar/i");

    err(function(){
      'foobar'.should.not.match(/^foo/i)
    }, "expected 'foobar' not to match /^foo/i");
  },

  'test length(n)': function(){
    'test'.should.have.length(4);
    'test'.should.not.have.length(3);
    [1,2,3].should.have.length(3);

    err(function(){
      (4).should.have.length(3);
    }, 'expected 4 to have a property \'length\'');

    err(function(){
      'asd'.should.not.have.length(3);
    }, "expected 'asd' to not have a length of 3");
  },

  'test eql(val)': function(){
    'test'.should.eql('test');
    ({ foo: 'bar' }).should.eql({ foo: 'bar' });
    (1).should.eql(1);
    '4'.should.eql(4);

    err(function(){
      (4).should.eql(3);
    }, 'expected 4 to equal 3');
  },

  'test equal(val)': function(){
    'test'.should.equal('test');
    (1).should.equal(1);

    err(function(){
      (4).should.equal(3);
    }, 'expected 4 to equal 3');

    err(function(){
      '4'.should.equal(4);
    }, "expected '4' to equal 4");
  },

  'test empty': function(){
    ''.should.be.empty;
    [].should.be.empty;
    ({ length: 0 }).should.be.empty;

    err(function(){
      ({}).should.be.empty;
    }, 'expected {} to have a property \'length\'');

    err(function(){
      'asd'.should.be.empty;
    }, "expected 'asd' to be empty");

    err(function(){
      ''.should.not.be.empty;
    }, "expected '' not to be empty");
  },

  'test property(name)': function(){
    'test'.should.have.property('length');
    (4).should.not.have.property('length');

    err(function(){
      'asd'.should.have.property('foo');
    }, "expected 'asd' to have a property 'foo'");
  },

  'test property(name, val)': function(){
    'test'.should.have.property('length', 4);
    'asd'.should.have.property('constructor', String);

    err(function(){
      'asd'.should.have.property('length', 4);
    }, "expected 'asd' to have a property 'length' of 4, but got 3");

    err(function(){
      'asd'.should.not.have.property('length', 3);
    }, "expected 'asd' to not have a property 'length' of 3");

    err(function(){
      'asd'.should.not.have.property('foo', 3);
    }, "'asd' has no property 'foo'");

    err(function(){
      'asd'.should.have.property('constructor', Number);
    }, "expected 'asd' to have a property 'constructor' of [Function: Number], but got [Function: String]");
  },

  'test ownProperty(name)': function(){
    'test'.should.have.ownProperty('length');
    'test'.should.haveOwnProperty('length');
    ({ length: 12 }).should.have.ownProperty('length');

    err(function(){
      ({ length: 12 }).should.not.have.ownProperty('length');
    }, "expected { length: 12 } to not have own property 'length'");
  },

  'test string()': function(){
    'foobar'.should.include.string('bar');
    'foobar'.should.include.string('foo');
    'foobar'.should.not.include.string('baz');

    err(function(){
      (3).should.include.string('baz');
    }, "expected 3 to be a string");

    err(function(){
      'foobar'.should.include.string('baz');
    }, "expected 'foobar' to include 'baz'");

    err(function(){
      'foobar'.should.not.include.string('bar');
    }, "expected 'foobar' to not include 'bar'");
  },

  'test contain()': function(){
    ['foo', 'bar'].should.contain('foo');
    ['foo', 'bar'].should.contain('foo');
    ['foo', 'bar'].should.contain('bar');
    [1,2].should.contain(1);
    ['foo', 'bar'].should.not.contain('baz');
    ['foo', 'bar'].should.not.contain(1);

    err(function(){
      ['foo'].should.contain('bar');
    }, "expected [ 'foo' ] to contain 'bar'");

    err(function(){
      ['bar', 'foo'].should.not.contain('foo');
    }, "expected [ 'bar', 'foo' ] to not contain 'foo'");
  },

  'test keys(array)': function(){
    ({ foo: 1 }).should.have.keys(['foo']);
    ({ foo: 1, bar: 2 }).should.have.keys(['foo', 'bar']);
    ({ foo: 1, bar: 2 }).should.have.keys('foo', 'bar');
    ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('foo', 'bar');
    ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('bar', 'foo');
    ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('baz');

    ({ foo: 1, bar: 2 }).should.include.keys('foo');
    ({ foo: 1, bar: 2 }).should.include.keys('bar', 'foo');
    ({ foo: 1, bar: 2 }).should.include.keys(['foo']);
    ({ foo: 1, bar: 2 }).should.include.keys(['bar']);
    ({ foo: 1, bar: 2 }).should.include.keys(['bar', 'foo']);

    ({ foo: 1, bar: 2 }).should.not.have.keys('baz');
    ({ foo: 1, bar: 2 }).should.not.have.keys('foo', 'baz');
    ({ foo: 1, bar: 2 }).should.not.include.keys('baz');
    ({ foo: 1, bar: 2 }).should.not.include.keys('foo', 'baz');
    ({ foo: 1, bar: 2 }).should.not.include.keys('baz', 'foo');

    err(function(){
      ({ foo: 1 }).should.have.keys();
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.have.keys([]);
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.not.have.keys([]);
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.include.keys([]);
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.have.keys(['bar']);
    }, "expected { foo: 1 } to have key 'bar'");

    err(function(){
      ({ foo: 1 }).should.have.keys(['bar', 'baz']);
    }, "expected { foo: 1 } to have keys 'bar', and 'baz'");

    err(function(){
      ({ foo: 1 }).should.have.keys(['foo', 'bar', 'baz']);
    }, "expected { foo: 1 } to have keys 'foo', 'bar', and 'baz'");

    err(function(){
      ({ foo: 1 }).should.not.have.keys(['foo']);
    }, "expected { foo: 1 } to not have key 'foo'");

    err(function(){
      ({ foo: 1 }).should.not.have.keys(['foo']);
    }, "expected { foo: 1 } to not have key 'foo'");

    err(function(){
      ({ foo: 1, bar: 2 }).should.not.have.keys(['foo', 'bar']);
    }, "expected { foo: 1, bar: 2 } to not have keys 'foo', and 'bar'");

    err(function(){
      ({ foo: 1 }).should.not.include.keys(['foo']);
    }, "expected { foo: 1 } to not include key 'foo'");

    err(function(){
      ({ foo: 1 }).should.include.keys('foo', 'bar');
    }, "expected { foo: 1 } to include keys 'foo', and 'bar'");
  },

  'test respondTo(method)': function(){
    'test'.should.respondTo('toString');
    'test'.should.not.respondTo('toBuffer');
  },

  'test chaining': function(){
    var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'] };
    user.should.have.property('pets').with.lengthOf(4);

    err(function(){
      user.should.have.property('pets').with.lengthOf(5);
    }, "expected [ 'tobi', 'loki', 'jane', 'bandit' ] to have a length of 5 but got 4");

    user.should.be.a('object').and.have.property('name', 'tj');
  }
};<commit_msg>fixed tests<commit_after>
/**
 * Module dependencies.
 */

var should = require('should');

function err(fn, msg) {
  try {
    fn();
    should.fail('expected an error');
  } catch (err) {
    should.equal(msg, err.message);
  }
}

module.exports = {
  'test .version': function(){
    should.version.should.match(/^\d+\.\d+\.\d+$/);
  },

  'test assertion': function(){
    'test'.should.be.a.string;
    should.equal('foo', 'foo');
  },

  'test true': function(){
    true.should.be.true;
    false.should.not.be.true;
    (1).should.not.be.true;

    err(function(){
      'test'.should.be.true;
    }, "expected 'test' to be true")
  },

  'test false': function(){
    false.should.be.false;
    true.should.not.be.false;
    (0).should.not.be.false;

    err(function(){
      ''.should.be.false;
    }, "expected '' to be false")
  },

  'test arguments': function(){
    var args = (function(){ return arguments; })(1,2,3);
    args.should.be.arguments;
    [].should.not.be.arguments;
  },

  'test .equal()': function(){
    var foo;
    should.equal(undefined, foo);
  },

  'test typeof': function(){
    'test'.should.be.a('string');

    err(function(){
      'test'.should.not.be.a('string');
    }, "expected 'test' not to be a string");

    (5).should.be.a('number');

    err(function(){
      (5).should.not.be.a('number');
    }, "expected 5 not to be a number");
  },

  'test instanceof': function(){
    function Foo(){}
    new Foo().should.be.an.instanceof(Foo);

    err(function(){
      (3).should.an.instanceof(Foo);
    }, "expected 3 to be an instance of Foo");
  },

  'test within(start, finish)': function(){
    (5).should.be.within(5, 10);
    (5).should.be.within(3,6);
    (5).should.be.within(3,5);
    (5).should.not.be.within(1,3);

    err(function(){
      (5).should.not.be.within(4,6);
    }, "expected 5 to not be within 4..6");

    err(function(){
      (10).should.be.within(50,100);
    }, "expected 10 to be within 50..100");
  },

  'test above(n)': function(){
    (5).should.be.above(2);
    (5).should.be.greaterThan(2);
    (5).should.not.be.above(5);
    (5).should.not.be.above(6);

    err(function(){
      (5).should.be.above(6);
    }, "expected 5 to be above 6");

    err(function(){
      (10).should.not.be.above(6);
    }, "expected 10 to be below 6");
  },

  'test match(regexp)': function(){
    'foobar'.should.match(/^foo/)
    'foobar'.should.not.match(/^bar/)

    err(function(){
      'foobar'.should.match(/^bar/i)
    }, "expected 'foobar' to match /^bar/i");

    err(function(){
      'foobar'.should.not.match(/^foo/i)
    }, "expected 'foobar' not to match /^foo/i");
  },

  'test length(n)': function(){
    'test'.should.have.length(4);
    'test'.should.not.have.length(3);
    [1,2,3].should.have.length(3);

    err(function(){
      (4).should.have.length(3);
    }, 'expected 4 to have a property \'length\'');

    err(function(){
      'asd'.should.not.have.length(3);
    }, "expected 'asd' to not have a length of 3");
  },

  'test eql(val)': function(){
    'test'.should.eql('test');
    ({ foo: 'bar' }).should.eql({ foo: 'bar' });
    (1).should.eql(1);
    '4'.should.eql(4);

    err(function(){
      (4).should.eql(3);
    }, 'expected 4 to equal 3');
  },

  'test equal(val)': function(){
    'test'.should.equal('test');
    (1).should.equal(1);

    err(function(){
      (4).should.equal(3);
    }, 'expected 4 to equal 3');

    err(function(){
      '4'.should.equal(4);
    }, "expected '4' to equal 4");
  },

  'test empty': function(){
    ''.should.be.empty;
    [].should.be.empty;
    ({ length: 0 }).should.be.empty;

    err(function(){
      ({}).should.be.empty;
    }, 'expected {} to have a property \'length\'');

    err(function(){
      'asd'.should.be.empty;
    }, "expected 'asd' to be empty");

    err(function(){
      ''.should.not.be.empty;
    }, "expected '' not to be empty");
  },

  'test property(name)': function(){
    'test'.should.have.property('length');
    (4).should.not.have.property('length');

    err(function(){
      'asd'.should.have.property('foo');
    }, "expected 'asd' to have a property 'foo'");
  },

  'test property(name, val)': function(){
    'test'.should.have.property('length', 4);
    'asd'.should.have.property('constructor', String);

    err(function(){
      'asd'.should.have.property('length', 4);
    }, "expected 'asd' to have a property 'length' of 4, but got 3");

    err(function(){
      'asd'.should.not.have.property('length', 3);
    }, "expected 'asd' to not have a property 'length' of 3");

    err(function(){
      'asd'.should.not.have.property('foo', 3);
    }, "'asd' has no property 'foo'");

    err(function(){
      'asd'.should.have.property('constructor', Number);
    }, "expected 'asd' to have a property 'constructor' of [Function: Number], but got [Function: String]");
  },

  'test ownProperty(name)': function(){
    'test'.should.have.ownProperty('length');
    'test'.should.haveOwnProperty('length');
    ({ length: 12 }).should.have.ownProperty('length');

    err(function(){
      ({ length: 12 }).should.not.have.ownProperty('length');
    }, "expected { length: 12 } to not have own property 'length'");
  },

  'test string()': function(){
    'foobar'.should.include.string('bar');
    'foobar'.should.include.string('foo');
    'foobar'.should.not.include.string('baz');

    err(function(){
      (3).should.include.string('baz');
    }, "expected 3 to be a string");

    err(function(){
      'foobar'.should.include.string('baz');
    }, "expected 'foobar' to include 'baz'");

    err(function(){
      'foobar'.should.not.include.string('bar');
    }, "expected 'foobar' to not include 'bar'");
  },

  'test contain()': function(){
    ['foo', 'bar'].should.contain('foo');
    ['foo', 'bar'].should.contain('foo');
    ['foo', 'bar'].should.contain('bar');
    [1,2].should.contain(1);
    ['foo', 'bar'].should.not.contain('baz');
    ['foo', 'bar'].should.not.contain(1);

    err(function(){
      ['foo'].should.contain('bar');
    }, "expected [ 'foo' ] to contain 'bar'");

    err(function(){
      ['bar', 'foo'].should.not.contain('foo');
    }, "expected [ 'bar', 'foo' ] to not contain 'foo'");
  },

  'test keys(array)': function(){
    ({ foo: 1 }).should.have.keys(['foo']);
    ({ foo: 1, bar: 2 }).should.have.keys(['foo', 'bar']);
    ({ foo: 1, bar: 2 }).should.have.keys('foo', 'bar');
    ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('foo', 'bar');
    ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('bar', 'foo');
    ({ foo: 1, bar: 2, baz: 3 }).should.include.keys('baz');

    ({ foo: 1, bar: 2 }).should.include.keys('foo');
    ({ foo: 1, bar: 2 }).should.include.keys('bar', 'foo');
    ({ foo: 1, bar: 2 }).should.include.keys(['foo']);
    ({ foo: 1, bar: 2 }).should.include.keys(['bar']);
    ({ foo: 1, bar: 2 }).should.include.keys(['bar', 'foo']);

    ({ foo: 1, bar: 2 }).should.not.have.keys('baz');
    ({ foo: 1, bar: 2 }).should.not.have.keys('foo', 'baz');
    ({ foo: 1, bar: 2 }).should.not.include.keys('baz');
    ({ foo: 1, bar: 2 }).should.not.include.keys('foo', 'baz');
    ({ foo: 1, bar: 2 }).should.not.include.keys('baz', 'foo');

    err(function(){
      ({ foo: 1 }).should.have.keys();
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.have.keys([]);
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.not.have.keys([]);
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.include.keys([]);
    }, "keys required");

    err(function(){
      ({ foo: 1 }).should.have.keys(['bar']);
    }, "expected { foo: 1 } to have key 'bar'");

    err(function(){
      ({ foo: 1 }).should.have.keys(['bar', 'baz']);
    }, "expected { foo: 1 } to have keys 'bar', and 'baz'");

    err(function(){
      ({ foo: 1 }).should.have.keys(['foo', 'bar', 'baz']);
    }, "expected { foo: 1 } to have keys 'foo', 'bar', and 'baz'");

    err(function(){
      ({ foo: 1 }).should.not.have.keys(['foo']);
    }, "expected { foo: 1 } to not have key 'foo'");

    err(function(){
      ({ foo: 1 }).should.not.have.keys(['foo']);
    }, "expected { foo: 1 } to not have key 'foo'");

    err(function(){
      ({ foo: 1, bar: 2 }).should.not.have.keys(['foo', 'bar']);
    }, "expected { foo: 1, bar: 2 } to not have keys 'foo', and 'bar'");

    err(function(){
      ({ foo: 1 }).should.not.include.keys(['foo']);
    }, "expected { foo: 1 } to not include key 'foo'");

    err(function(){
      ({ foo: 1 }).should.include.keys('foo', 'bar');
    }, "expected { foo: 1 } to include keys 'foo', and 'bar'");
  },

  'test respondTo(method)': function(){
    'test'.should.respondTo('toString');
    'test'.should.not.respondTo('toBuffer');
  },

  'test chaining': function(){
    var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'] };
    user.should.have.property('pets').with.lengthOf(4);

    err(function(){
      user.should.have.property('pets').with.lengthOf(5);
    }, "expected [ 'tobi', 'loki', 'jane', 'bandit' ] to have a length of 5 but got 4");

    user.should.be.a('object').and.have.property('name', 'tj');
  }
};<|endoftext|>


<commit_before>module.exports = function( grunt ) {
  'use strict';
  //
  // Grunt configuration:
  //
  // https://github.com/cowboy/grunt/blob/master/docs/getting_started.md
  //
  grunt.initConfig({

    // store the path the theme used to make it a bit easier
    wordpress: {
      theme: 'app/wp-content/themes/twentyeleven'
    },

    // Project configuration
    // ---------------------

    // specify an alternate install location for Bower
    bower: {
      dir: 'app/scripts/vendor'
    },

    // Coffee to JS compilation
    coffee: {
      dist: {
        src: 'app/wp-content/themes/**/js/*.coffee',
        dest: 'app/wp-content/themes/**/js'
      }
    },

    // compile .scss/.sass to .css using Compass
    compass: {
      dist: {
        // http://compass-style.org/help/tutorials/configuration-reference/#configuration-properties
        options: {
          css_dir: '<config:wordpress.theme>',
          sass_dir: '<config:wordpress.theme>',
          images_dir: 'app/wp-content/themes/**/images',
          javascripts_dir: 'app/wp-content/themes/**/js',
          force: true
        }
      }
    },

    // generate application cache manifest
    manifest:{
      dest: ''
    },

    // headless testing through PhantomJS
    mocha: {
      all: ['test/**/*.html']
    },

    // default watch configuration
    watch: {
      coffee: {
        files: '<config:coffee.dist.src>',
        tasks: 'coffee reload'
      },
      compass: {
        files: [
          'app/wp-content/themes/**/*.{scss,sass}'
        ],
        tasks: 'compass reload'
      },
      reload: {
        files: [
          'app/wp-content/themes/**/*.php',
          'app/wp-content/themes/**/**/*.css',
          'app/wp-content/themes/**/js/*.js',
          'app/wp-content/themes/**/images/*',
          'app/wp-content/themes/**/images/**/*'
        ],
        tasks: 'reload'
      }
    },

    // default lint configuration, change this to match your setup:
    // https://github.com/cowboy/grunt/blob/master/docs/task_lint.md#lint-built-in-task
    lint: {
      files: [
        'Gruntfile.js',
        'app/wp-content/themes/**/js/*.js'
      ]
    },

    // specifying JSHint options and globals
    // https://github.com/cowboy/grunt/blob/master/docs/task_lint.md#specifying-jshint-options-and-globals
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },

    // Build configuration
    // -------------------

    // the staging directory used during the process
    staging: 'temp',
    // final build output
    output: 'dist',

    mkdirs: {
      staging: 'app/'
    },

    // Below, all paths are relative to the staging directory, which is a copy
    // of the app/ directory. Any .gitignore, .ignore and .buildignore file
    // that might appear in the app/ tree are used to ignore these values
    // during the copy process.

    // concat css/**/*.css files, inline @import, output a single minified css
    // TODO: find a way to use the config variable to avoid writing the name of the theme
    // to make it work with wordpress we need to keep the name 'style.css'
    css: {
      'wp-content/themes/twentyeleven/style.css': ['wp-content/themes/twentyeleven/*.css']
    },

    //'styles/main.css': ['styles/**/*.css']

    // renames JS/CSS to prepend a hash of their contents for easier
    // versioning
    // disabled to make it work with wordpress
    rev: {
//      js: 'wp-content/themes/**/js/*.js',
//      css: 'wp-content/themes/**/*.css',
      img: 'wp-content/themes/**/images/*.png' // avoid a crash - not sur if this is good https://github.com/yeoman/yeoman/issues/262
    },

    // usemin handler should point to the file containing
    // the usemin blocks to be parsed
    'usemin-handler': {
      html: 'index.html'
    },

    // update references in HTML/CSS to revved files
    usemin: {
      html: ['**/*.html'],
      css: ['**/*.css']
    },

    // HTML minification
    html: {
      files: ['**/*.html']
    },

    // Optimizes JPGs and PNGs (with jpegtran & optipng)
    img: {
      dist: '<config:rev.img>'
    },

    // rjs configuration. You don't necessarily need to specify the typical
    // `path` configuration, the rjs task will parse these values from your
    // main module, using http://requirejs.org/docs/optimization.html#mainConfigFile
    //
    // name / out / mainConfig file should be used. You can let it blank if
    // you're using usemin-handler to parse rjs config from markup (default
    // setup)
    rjs: {
      // no minification, is done by the min task
      optimize: 'none',
      baseUrl: './wp-content/themes/**/js',
      wrap: true
    },

    // While Yeoman handles concat/min when using
    // usemin blocks, you can still use them manually
    concat: {
      dist: ''
    },

    min: {
      dist: ''
    },

    // server port to match livereload browser extensions
    // https://github.com/yeoman/yeoman/issues/250#issuecomment-8024212
    server: {
      port: 35729
    }

  });

  // Alias the `test` task to run the `mocha` task instead
  grunt.registerTask('test', 'mocha');

};<commit_msg>Fixed a bug in build task<commit_after>module.exports = function( grunt ) {
  'use strict';
  //
  // Grunt configuration:
  //
  // https://github.com/cowboy/grunt/blob/master/docs/getting_started.md
  //
  grunt.initConfig({

    // store the path the theme used to make it a bit easier
    wordpress: {
      theme: 'app/wp-content/themes/twentyeleven'
    },

    // Project configuration
    // ---------------------

    // specify an alternate install location for Bower
    bower: {
      dir: 'app/scripts/vendor'
    },

    // Coffee to JS compilation
    coffee: {
      dist: {
        src: 'app/wp-content/themes/**/js/*.coffee',
        dest: 'app/wp-content/themes/**/js'
      }
    },

    // compile .scss/.sass to .css using Compass
    compass: {
      dist: {
        // http://compass-style.org/help/tutorials/configuration-reference/#configuration-properties
        options: {
          css_dir: '<config:wordpress.theme>',
          sass_dir: '<config:wordpress.theme>',
          images_dir: 'app/wp-content/themes/**/images',
          javascripts_dir: 'app/wp-content/themes/**/js',
          force: true
        }
      }
    },

    // generate application cache manifest
    manifest:{
      dest: ''
    },

    // headless testing through PhantomJS
    mocha: {
      all: ['test/**/*.html']
    },

    // default watch configuration
    watch: {
      coffee: {
        files: '<config:coffee.dist.src>',
        tasks: 'coffee reload'
      },
      compass: {
        files: [
          'app/wp-content/themes/**/*.{scss,sass}'
        ],
        tasks: 'compass reload'
      },
      reload: {
        files: [
          'app/wp-content/themes/**/*.php',
          'app/wp-content/themes/**/**/*.css',
          'app/wp-content/themes/**/js/*.js',
          'app/wp-content/themes/**/images/*',
          'app/wp-content/themes/**/images/**/*'
        ],
        tasks: 'reload'
      }
    },

    // default lint configuration, change this to match your setup:
    // https://github.com/cowboy/grunt/blob/master/docs/task_lint.md#lint-built-in-task
    lint: {
      files: [
        'Gruntfile.js',
        'app/wp-content/themes/**/js/*.js'
      ]
    },

    // specifying JSHint options and globals
    // https://github.com/cowboy/grunt/blob/master/docs/task_lint.md#specifying-jshint-options-and-globals
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },

    // Build configuration
    // -------------------

    // the staging directory used during the process
    staging: 'temp',
    // final build output
    output: 'dist',

    mkdirs: {
      staging: 'app/'
    },

    // Below, all paths are relative to the staging directory, which is a copy
    // of the app/ directory. Any .gitignore, .ignore and .buildignore file
    // that might appear in the app/ tree are used to ignore these values
    // during the copy process.

    // concat css/**/*.css files, inline @import, output a single minified css
    // TODO: find a way to use the config variable to avoid writing the name of the theme
    // to make it work with wordpress we need to keep the name 'style.css'
    css: {
      'wp-content/themes/twentyeleven/style.css': ['wp-content/themes/twentyeleven/*.css']
    },

    //'styles/main.css': ['styles/**/*.css']

    // renames JS/CSS to prepend a hash of their contents for easier
    // versioning
    // disabled to make it work with wordpress
    rev: {
//      js: 'wp-content/themes/**/js/*.js',
//      css: 'wp-content/themes/**/*.css',
      img: 'wp-content/themes/**/images/**'
    },

    // usemin handler should point to the file containing
    // the usemin blocks to be parsed
    'usemin-handler': {
      html: 'index.html'
    },

    // update references in HTML/CSS to revved files
    usemin: {
      html: ['**/*.html'],
      css: ['**/*.css']
    },

    // HTML minification
    html: {
      files: ['**/*.html']
    },

    // Optimizes JPGs and PNGs (with jpegtran & optipng)
    img: {
      dist: '<config:rev.img>'
    },

    // rjs configuration. You don't necessarily need to specify the typical
    // `path` configuration, the rjs task will parse these values from your
    // main module, using http://requirejs.org/docs/optimization.html#mainConfigFile
    //
    // name / out / mainConfig file should be used. You can let it blank if
    // you're using usemin-handler to parse rjs config from markup (default
    // setup)
    rjs: {
      // no minification, is done by the min task
      optimize: 'none',
      baseUrl: './wp-content/themes/**/js',
      wrap: true
    },

    // While Yeoman handles concat/min when using
    // usemin blocks, you can still use them manually
    concat: {
      dist: ''
    },

    min: {
      dist: ''
    },

    // server port to match livereload browser extensions
    // https://github.com/yeoman/yeoman/issues/250#issuecomment-8024212
    server: {
      port: 35729
    }

  });

  // Alias the `test` task to run the `mocha` task instead
  grunt.registerTask('test', 'mocha');

};<|endoftext|>


<commit_before>if (Meteor.isServer) {
    Meteor.methods({
        sleep: function(ms) {
            var start = Date.now();
            Meteor.sleep(ms);
            var end = Date.now();
            return end - start;
        }
    });

    Tinytest.add("typeof Meteor.sleep === \"function\"", function(test) {
        test.equal(typeof Meteor.sleep, "function");
    });

    Tinytest.addAsync("for (var i=0;i<5;i++)Meteor.sleep(200);", function(test, done) {
        var start = Date.now();
        for (var i = 0; i < 5; i++) {
            Meteor.sleep(200);
        }
        var end = Date.now();
        var elapsed = end - start;
        var variance = Math.abs(1000 - elapsed);
        test.isTrue(variance < 10);
        done();
    });
} else {
    Tinytest.add("typeof Meteor.sleep === \"undefined\"", function(test) {
        test.equal(typeof Meteor.sleep, "undefined");
    });

    Tinytest.addAsync("Meteor.sleep(0)", function(test, done) {
        if (!Meteor.isClient) {
            done();
            return;
        }

        Meteor.call("sleep", 0, function(err, elapsed) {
            test.isUndefined(err);

            var variance = Math.abs(elapsed - 0);
            test.isTrue(variance < 10);
            done();
        });
    });

    Tinytest.addAsync("Meteor.sleep(1000)", function(test, done) {
        if (!Meteor.isClient) {
            done();
            return;
        }

        Meteor.call("sleep", 1000, function(err, elapsed) {
            test.isUndefined(err);

            var variance = Math.abs(elapsed - 1000);
            test.isTrue(variance < 10);
            done();
        });
    });

    Tinytest.addAsync("Meteor.sleep()", function(test, done) {
        if (!Meteor.isClient) {
            done();
            return;
        }

        Meteor.call("sleep", undefined, function(err, elapsed) {
            test.isUndefined(err);

            var variance = Math.abs(elapsed - 0);
            test.isTrue(variance < 10);
            done();
        });
    });
}
<commit_msg>Remove unnecessary isClient checks in tests.<commit_after>if (Meteor.isServer) {
    Meteor.methods({
        sleep: function(ms) {
            var start = Date.now();
            Meteor.sleep(ms);
            var end = Date.now();
            return end - start;
        }
    });

    Tinytest.add("typeof Meteor.sleep === \"function\"", function(test) {
        test.equal(typeof Meteor.sleep, "function");
    });

    Tinytest.addAsync("for (var i=0;i<5;i++)Meteor.sleep(200);", function(test, done) {
        var start = Date.now();
        for (var i = 0; i < 5; i++) {
            Meteor.sleep(200);
        }
        var end = Date.now();
        var elapsed = end - start;
        var variance = Math.abs(1000 - elapsed);
        test.isTrue(variance < 10);
        done();
    });
} else {
    Tinytest.add("typeof Meteor.sleep === \"undefined\"", function(test) {
        test.equal(typeof Meteor.sleep, "undefined");
    });

    Tinytest.addAsync("Meteor.sleep(0)", function(test, done) {
        Meteor.call("sleep", 0, function(err, elapsed) {
            test.isUndefined(err);

            var variance = Math.abs(elapsed - 0);
            test.isTrue(variance < 10);
            done();
        });
    });

    Tinytest.addAsync("Meteor.sleep(1000)", function(test, done) {
        Meteor.call("sleep", 1000, function(err, elapsed) {
            test.isUndefined(err);

            var variance = Math.abs(elapsed - 1000);
            test.isTrue(variance < 10);
            done();
        });
    });

    Tinytest.addAsync("Meteor.sleep()", function(test, done) {
        Meteor.call("sleep", undefined, function(err, elapsed) {
            test.isUndefined(err);

            var variance = Math.abs(elapsed - 0);
            test.isTrue(variance < 10);
            done();
        });
    });
}
<|endoftext|>


<commit_before><commit_msg>Add typedefs<commit_after><|endoftext|>


<commit_before>var gulp = require("gulp");
var clean = require("del");

gulp.task("clean.perf", function(cb) {
    clean(["./performance/bin", "./performance/out"], cb);
});

gulp.task("clean.doc", function(cb) {
    clean(["./doc"], cb);
});

gulp.task("clean.bin", function(cb) {
    clean(["./bin"], cb);
});

gulp.task("clean.dist", function(cb) {
    clean(["./dist"], cb);
});

gulp.task("clean.coverage", function(cb) {
    clean(["./coverage"], cb);
});

gulp.task("clean", ["clean.doc", "clean.bin", "clean.coverage"]);
gulp.task("clean.dev", ["clean.bin"]);

<commit_msg>added clean.perf to the clean command.<commit_after>var gulp = require("gulp");
var clean = require("del");

gulp.task("clean.perf", function(cb) {
    clean(["./performance/bin", "./performance/out"], cb);
});

gulp.task("clean.doc", function(cb) {
    clean(["./doc"], cb);
});

gulp.task("clean.bin", function(cb) {
    clean(["./bin"], cb);
});

gulp.task("clean.dist", function(cb) {
    clean(["./dist"], cb);
});

gulp.task("clean.coverage", function(cb) {
    clean(["./coverage"], cb);
});

gulp.task("clean", ["clean.doc", "clean.bin", "clean.coverage", "clean.perf"]);
gulp.task("clean.dev", ["clean.bin"]);

<|endoftext|>


<commit_before>
module("About Regular Expressions (topics/about_regular_expressions.js)");

test("exec", function() {
    var numberFinder = /(\d).*(\d)/;
    var results = numberFinder.exec("what if 6 turned out to be 9?");
    ok(results.equalTo([__, __, __]), 'what is the value of results?');
});

test("test", function() {
    var containsSelect = /select/.test("  select * from users ");
    equal(__, containsSelect, 'does the string provided contain "select"?');
});

test("match", function() {
    var matches = "what if 6 turned out to be 9?".match(/(\d)/g);
    ok(matches.equalTo([__, __]), 'what is the value of matches?');
});

test("replace", function() {
    var pie = "apple pie".replace("apple", "strawberry");
    equal(__, pie, 'what is the value of pie?');

    pie = "what if 6 turned out to be 9?".replace(/\d/g, function(number) { // the second parameter can be a string or a function
        var map = {'6': 'six','9': 'nine'};
        return map[number];
    });
    equal(__, pie, 'what is the value of pie?');
});

// THE END
<commit_msg>Fix regular expressions' koans<commit_after>
module("About Regular Expressions (topics/about_regular_expressions.js)");

test("exec", function() {
    var numberFinder = /(\d).*(\d)/;
    var results = numberFinder.exec("what if 6 turned out to be 9?");

    // gambs pra passar
    console.log("results: "+ results);
    ok(results.equalTo(["6 turned out to be 9", "6", "9"]), 'what is the value of results?' + results);
});

test("test", function() {
    var containsSelect = /select/.test("  select * from users ");
    equal(true, containsSelect, 'does the string provided contain "select"?');
});

test("match", function() {
    var matches = "what if 6 turned out to be 9?".match(/(\d)/g);

    // seems that is not working properly
    ok(matches.equalTo(["6", "9"]), 'what is the value of matches?');
});

test("replace", function() {
    var pie = "apple pie".replace("apple", "strawberry");
    equal("strawberry pie", pie, 'what is the value of pie?');

    pie = "what if 6 turned out to be 9?".replace(/\d/g, function(number) { // the second parameter can be a string or a function
        var map = {'6': 'six','9': 'nine'};
        return map[number];
    });
    equal(["what if six turned out to be nine?"], pie, 'what is the value of pie?');
});

// THE END
<|endoftext|>


<commit_before>detailRowHeaderPopover.$inject = ['$templateRequest', '$compile', '$rootScope', '$document'];

export default function detailRowHeaderPopover($templateRequest, $compile, $rootScope, $document) {
    return {
        restrict: "A",
        scope: true,
        link: function(scope, element, attrs) {

            var templateUrl = scope.$eval(attrs.detailRowHeaderPopover);

            // load template
            var promise = $templateRequest(templateUrl);

            var popoverOpen = false;

            var popoverScope;

            // wait until promise is resolved
            promise.then(function(html) {

                // create scope with function to close popover
                popoverScope = $rootScope.$new(true);

                // add function to close popover to scope
                popoverScope.closePopover = closePopover;

                // add function to toggle filter icon to scope
                popoverScope.setFilterActive = setFilterActive;

                // compile template
                var template = $compile(html)(popoverScope);

                element.popover({
                    html: true,
                    template: '

',
                    content: template,
                    placement: 'bottom',
                    container: 'body',
                    animation: false
                });

            });

            element.on("shown.bs.popover", function() {
                popoverOpen = true;
                popoverScope.$broadcast("detailRowHeaderPopoverOpened");
            });

            element.on("hidden.bs.popover", function() {
                popoverOpen = false;
                popoverScope.$broadcast("detailRowHeaderPopoverClosed");
            });

            // Handler for clicks outside the popover, to close it
            $document.on("click.detailRowHeaderPopover", popoverDocumentClick);

            // watch for window resize events - we should dismiss to avoid popover misplacement
            window.addEventListener('resize', closePopover.bind(this));

            scope.$on("$destroy", function() {
                element.off("shown.bs.popover hidden.bs.popover");
                $document.off("click.detailRowHeaderPopover", popoverDocumentClick);
            });

            function closePopover() {
                element.popover('hide');
            }

            function setFilterActive(active) {
                var nativeElement = element[0];
                if (active) {
                    nativeElement.classList.remove("hpe-caret-down");
                    nativeElement.classList.add("hpe-caret-down-filled");
                } else {
                    nativeElement.classList.add("hpe-caret-down");
                    nativeElement.classList.remove("hpe-caret-down-filled");
                }
            }

            function popoverDocumentClick(event) {
                if (popoverOpen) {
                    var target = angular.element(event.target);
                    // Close unless target is the popover toggle or popover itself.
                    if (!element.is(target) && element.has(target).length === 0 &&
                        !target.hasClass("popover") && target.parents(".popover").length === 0) {
                        closePopover();
                    }
                }
            }
        }
    };
}<commit_msg>EL-2471 - Fixing detail row header popover issue (#105)<commit_after>detailRowHeaderPopover.$inject = ['$templateRequest', '$compile', '$rootScope', '$document'];

export default function detailRowHeaderPopover($templateRequest, $compile, $rootScope, $document) {
    return {
        restrict: "A",
        scope: true,
        link: function(scope, element, attrs) {

            var templateUrl = scope.$eval(attrs.detailRowHeaderPopover);

            // load template
            var promise = $templateRequest(templateUrl);

            var popoverOpen = false;

            var popoverScope;

            // wait until promise is resolved
            promise.then(function(html) {

                // create scope with function to close popover
                popoverScope = $rootScope.$new(true);

                // add function to close popover to scope
                popoverScope.closePopover = closePopover;

                // add function to toggle filter icon to scope
                popoverScope.setFilterActive = setFilterActive;

                // compile template
                var template = $compile(html)(popoverScope);

                element.popover({
                    html: true,
                    template: '

',
                    content: template,
                    placement: 'bottom',
                    container: 'body',
                    animation: false
                });

            });

            element.on("shown.bs.popover", function() {
                popoverOpen = true;
                popoverScope.$broadcast("detailRowHeaderPopoverOpened");
            });

            element.on("hidden.bs.popover", function(e) {
                popoverOpen = false;
                angular.element(e.target).data("bs.popover").inState.click = false;
                popoverScope.$broadcast("detailRowHeaderPopoverClosed");
            });

            // Handler for clicks outside the popover, to close it
            $document.on("click.detailRowHeaderPopover", popoverDocumentClick);

            // watch for window resize events - we should dismiss to avoid popover misplacement
            window.addEventListener('resize', closePopover.bind(this));

            scope.$on("$destroy", function() {
                element.off("shown.bs.popover hidden.bs.popover");
                $document.off("click.detailRowHeaderPopover", popoverDocumentClick);
            });

            function closePopover() {
                element.popover('hide');
            }

            function setFilterActive(active) {
                var nativeElement = element[0];
                if (active) {
                    nativeElement.classList.remove("hpe-caret-down");
                    nativeElement.classList.add("hpe-caret-down-filled");
                } else {
                    nativeElement.classList.add("hpe-caret-down");
                    nativeElement.classList.remove("hpe-caret-down-filled");
                }
            }

            function popoverDocumentClick(event) {
                if (popoverOpen) {
                    var target = angular.element(event.target);
                    // Close unless target is the popover toggle or popover itself.
                    if (!element.is(target) && element.has(target).length === 0 &&
                        !target.hasClass("popover") && target.parents(".popover").length === 0) {
                        closePopover();
                    }
                }
            }
        }
    };
}<|endoftext|>


<commit_before>export { Base };

import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as TwoTensors from "../../util/TwoTensors.js";
import * as ReturnOrClone_Activation from "../ReturnOrClone_Activation.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import { FiltersArray_BiasesArray } from "./Pointwise_FiltersArray_BiasesArray.js";

/**
 * Handle pointwise convolution (1x1 conv2d), bias and activation.
 *
 *
 * @member {boolean} bExisted
 *   If true, this pointwise convolution exists. The same as this.bPointwise.
 *
 * @member {boolean} bPointwise
 *   If true, this pointwise convolution exists. The same as this.bExisted.
 *
 * @member {boolean} bInitOk
 *   If true, the init() is successful.
 *
 * @member {function} pfnConv
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensor may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Conv_and_destroy(), Conv_and_keep() according to the parameters.
 *
 * @member {function} apply
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensors may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Conv_and_destroy_or_keep(), ConvBias_and_destroy_or_keep(),
 * ConvActivation_and_destroy_or_keep(), ConvBiasActivation_and_destroy_or_keep() according to the parameters.
 *
 * @see FiltersArray_BiasesArray
 */
class Base extends FiltersArray_BiasesArray( TwoTensors.filtersTensor4d_biasesTensor3d( ReturnOrClone_Activation.Base ) ) {

  /**
   */
  constructor(
    inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount ) {

    super(
      inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
      nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount );
  }

  /**
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @param {Array} arrayTemp_forInterleave_asGrouptTwo
   *   A temporary array for placing the original elements temporarily. Providing this array could reduce memory re-allocation
   * and improve performance when doing Interleave_asGrouptTwo.
   *
   * @return {boolean} Return true, if succeeded.
   */
  init( inputFloat32Array, byteOffsetBegin, inputScaleBoundsArray, arrayTemp_forInterleave_asGrouptTwo ) {

    // Q1: Why is the inputFloat32Array not a parameter of constructor?
    // A1: The reason is to avoid keeping it as this.inputFloat32Array so that it could be released by memory garbage collector.
    //
    // Q2: Why not keep filtersWeights and biasesWeights in data members of this?
    // A2: Their underlying ArrayBuffer is inputFloat32Array.buffer. If this.filtersWeights and this.biasesWeights are kept,
    //     the inputFloat32Array.buffer could not be released by memory garbage collector.

    this.disposeTensors();

    // 1. Determine operation functions.
    Base.setup_bPointwise_pfn.call( this );

    let bExtractOk;
    if ( !this.bPointwise ) {
      bExtractOk = true; // 2. no operation at all.

      this.byteOffsetBegin = this.byteOffsetEnd = byteOffsetBegin;
      this.tensorWeightCountExtracted = this.tensorWeightCountTotal = 0;

      this.boundsArraySet = new BoundsArraySet.Pointwise( inputScaleBoundsArray, inputScaleBoundsArray.channelCount );
      this.boundsArraySet.output0.set_all_byScaleBoundsArray( inputScaleBoundsArray ); // Bypass previous to next.

    } else { // 3.

      bExtractOk = super.init( inputFloat32Array, byteOffsetBegin, inputScaleBoundsArray, arrayTemp_forInterleave_asGrouptTwo );
      if ( bExtractOk ) {
        try {
          if ( this.filtersShape && this.filtersArray ) {
            this.filtersTensor4d = tf.tensor( this.filtersArray, this.filtersShape );
            this.filtersShape = this.filtersArray = null; // Release for reducing memory usage.
          }

          if ( this.biasesShape && this.biasesArray ) {
            this.biasesTensor3d = tf.tensor( this.biasesArray, this.biasesShape );
            this.biasesShape = this.biasesArray = null; // Release for reducing memory usage.
          }

        } catch ( e ) {  // If failed (e.g. memory not enough), return false.
          bExtractOk = false;
        }
      }

    }

    this.bInitOk = bExtractOk;
    return this.bInitOk;
  }

  disposeTensors() {
    super.disposeTensors(); // Release filtersTensor4d and biasesTensor3d.

    this.apply = this.pfnConv = this.pfnActivation = null;

    this.bPointwise = false;
    this.byteOffsetBegin = this.byteOffsetEnd = -1;
    this.bKeepInputTensor = false;  // Default will dispose input tensor.
    this.bInitOk = false;
  }

  /**
   * Adjust this.pfnConv (and this.apply if need) so that this.pfnConv() and this.apply() will or will not
   * dispose its inputTensor.
   */
  setKeepInputTensor( bKeepInputTensor ) {
    if ( bKeepInputTensor == this.bKeepInputTensor )
      return;

    this.bKeepInputTensor = bKeepInputTensor;

    if ( this.bExisted ) {
      if ( bKeepInputTensor ) {
        this.pfnConv = Base.Conv_and_keep;
      } else {
        this.pfnConv = Base.Conv_and_destroy;
      }
    } else {
      // Since there is no operation at all, let apply ignore pfnConv completely.
      if ( bKeepInputTensor ) {
        this.apply = this.pfnConv = Base.keep_input_return_copy;
      } else {
        this.apply = this.pfnConv = Base.return_input_directly;
      }
    }
  }

  get bExisted() {
    return this.bPointwise;
  }

  /** Determine this.bPointwise and this.pfnXxx data members.
   *
   * @param {Base} this
   *   The Base object to be determined and modified.
   */
  static setup_bPointwise_pfn() {

    // 0. Determine whether pointwise operation should exist.
    if ( this.outputChannelCount > 0 ) {
      this.bPointwise = true;

    } else {  // ( outputChannelCount <= 0 )
      if ( this.channelShuffler_outputGroupCount > 0 ) {

//!!! ...unfinished... (2022/05/20)
        // Perhaps, deprecate this special case. Since pointwise2 always exists now.
        // So assert if executed here.
        tf.util.assert( false,
          `Pointwise.Base.setup_bPointwise_pfn(): `
            + `When outputChannelCount ( ${this.outputChannelCount} ) is not positive, `
            + `channelShuffler_outputGroupCount ( ${this.channelShuffler_outputGroupCount} ) should not be positive.`
        );

        this.bPointwise = true; // all-pass-through-and-channel-shuffling mode. (Otherwise, no way to do channel shuffling.)
        this.bBias = false; // In this case, there is always no biases (no matter how original bBias is).

//!!! ...unfinished... (2022/05/20) What about nActivationId?

      } else {
        this.bPointwise = false;
      }
    }

    // 1.
    this.pfnConv = Base.Conv_and_destroy; // will dispose inputTensor.

    // 2.
    this.pfnActivation = Base.ActivationFunction_getById( this.nActivationId );

    // 3.
    if ( this.bPointwise ) {
      if ( this.bBias ) {
        if ( this.pfnActivation )
          this.apply = Base.ConvBiasActivation_and_destroy_or_keep;
        else
          this.apply = Base.ConvBias_and_destroy_or_keep;
      } else {
        if ( this.pfnActivation )
          this.apply = Base.ConvActivation_and_destroy_or_keep;
         else
          this.apply = Base.Conv_and_destroy_or_keep;
      }
    } else {
      // Since there is no operation at all, let apply ignore pfnConv completely.
      this.apply = this.pfnConv = Base.return_input_directly;
    }
  }

  /** Pointwise Convolution (1x1). (The inputTensor will not be disposed so that it can be used for achieving skip connection.) */
  static Conv_and_keep( inputTensor ) {
    return tf.conv2d( inputTensor, this.filtersTensor4d, 1, "valid" ); // 1x1, Stride = 1
  }

  static Conv_and_destroy( inputTensor ) {
    let t = tf.conv2d( inputTensor, this.filtersTensor4d, 1, "valid" );
    inputTensor.dispose();
    return t;
  }

  /** Pointwise Convolution, Bias and Activation. */
  static Conv_and_destroy_or_keep( inputTensor ) {
    return this.pfnConv( inputTensor );
  }

  static ConvBias_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnConv( inputTensor );

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    return t1;
  }

  static ConvActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnConv( inputTensor );

    let t1 = this.pfnActivation( t0 );
    t0.dispose();

    return t1;
  }

  static ConvBiasActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnConv( inputTensor );

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    t0 = this.pfnActivation( t1 );
    t1.dispose();

    return t0;
  }

}
<commit_msg>Update Pointwise_Base.js<commit_after>export { Base };

import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as TwoTensors from "../../util/TwoTensors.js";

//!!! (2022/05/31 Remarked)
//import * as ReturnOrClone_Activation from "../ReturnOrClone_Activation.js";

//import * as TensorPlaceholder from "../TensorPlaceholder.js";
import * as Operation from "../Operation.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import { FiltersArray_BiasesArray } from "./Pointwise_FiltersArray_BiasesArray.js";

/**
 * Handle pointwise convolution (1x1 conv2d), bias and activation.
 *
 *
 * @member {boolean} bExisted
 *   If true, this pointwise convolution exists. The same as this.bPointwise.
 *
 * @member {boolean} bPointwise
 *   If true, this pointwise convolution exists. The same as this.bExisted.
 *
 * @member {boolean} bInitOk
 *   If true, the init() is successful.
 *
 * @member {function} pfnConv
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensor may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Conv_and_destroy(), Conv_and_keep() according to the parameters.
 *
 * @member {function} apply
 *   This is a method. It has one parameter inputTensor and return a outputTensor. The inputTensor (tf.tensor3d) represents the image
 * ( height x width x channel ) which will be processed. The outputTensor (tf.tensor3d) represents the result.
 * All intermediate tensors will be disposed. The inputTensors may or may not be disposed. In fact, this method calls one of
 * Base.return_input_directly(), Base.keep_input_return_copy(), Conv_and_destroy_or_keep(), ConvBias_and_destroy_or_keep(),
 * ConvActivation_and_destroy_or_keep(), ConvBiasActivation_and_destroy_or_keep() according to the parameters.
 *
 * @see FiltersArray_BiasesArray
 */
//!!! (2022/05/31 Remarked)
//class Base extends FiltersArray_BiasesArray( TwoTensors.filtersTensor4d_biasesTensor3d( ReturnOrClone_Activation.Base ) ) {
class Base extends FiltersArray_BiasesArray( TwoTensors.filtersTensor4d_biasesTensor3d( Operation.Base() ) ) {

  /**
   */
  constructor(
    inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount ) {

    super(
      inputChannelCount, outputChannelCount, bBias, nActivationId, nPassThroughStyleId,
      nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount );
  }

  /**
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @param {Array} arrayTemp_forInterleave_asGrouptTwo
   *   A temporary array for placing the original elements temporarily. Providing this array could reduce memory re-allocation
   * and improve performance when doing Interleave_asGrouptTwo.
   *
   * @return {boolean} Return true, if succeeded.
   */
  init( inputFloat32Array, byteOffsetBegin, inputScaleBoundsArray, arrayTemp_forInterleave_asGrouptTwo ) {

    // Q1: Why is the inputFloat32Array not a parameter of constructor?
    // A1: The reason is to avoid keeping it as this.inputFloat32Array so that it could be released by memory garbage collector.
    //
    // Q2: Why not keep filtersWeights and biasesWeights in data members of this?
    // A2: Their underlying ArrayBuffer is inputFloat32Array.buffer. If this.filtersWeights and this.biasesWeights are kept,
    //     the inputFloat32Array.buffer could not be released by memory garbage collector.

    this.disposeTensors();

    // 1. Determine operation functions.
    Base.setup_bPointwise_pfn.call( this );

    let bExtractOk;
    if ( !this.bPointwise ) {
      bExtractOk = true; // 2. no operation at all.

      this.byteOffsetBegin = this.byteOffsetEnd = byteOffsetBegin;
      this.tensorWeightCountExtracted = this.tensorWeightCountTotal = 0;

      this.boundsArraySet = new BoundsArraySet.Pointwise( inputScaleBoundsArray, inputScaleBoundsArray.channelCount );
      this.boundsArraySet.output0.set_all_byScaleBoundsArray( inputScaleBoundsArray ); // Bypass previous to next.

    } else { // 3.

      bExtractOk = super.init( inputFloat32Array, byteOffsetBegin, inputScaleBoundsArray, arrayTemp_forInterleave_asGrouptTwo );
      if ( bExtractOk ) {
        try {
          if ( this.filtersShape && this.filtersArray ) {
            this.filtersTensor4d = tf.tensor( this.filtersArray, this.filtersShape );
            this.filtersShape = this.filtersArray = null; // Release for reducing memory usage.
          }

          if ( this.biasesShape && this.biasesArray ) {
            this.biasesTensor3d = tf.tensor( this.biasesArray, this.biasesShape );
            this.biasesShape = this.biasesArray = null; // Release for reducing memory usage.
          }

        } catch ( e ) {  // If failed (e.g. memory not enough), return false.
          bExtractOk = false;
        }
      }

    }

    this.bInitOk = bExtractOk;
    return this.bInitOk;
  }

  disposeTensors() {
    super.disposeTensors(); // Release filtersTensor4d and biasesTensor3d.

    this.apply = this.pfnConv = this.pfnActivation = null;

    this.bPointwise = false;
    this.byteOffsetBegin = this.byteOffsetEnd = -1;
    this.bKeepInputTensor = false;  // Default will dispose input tensor.
    this.bInitOk = false;
  }

  /**
   * Adjust this.pfnConv (and this.apply if need) so that this.pfnConv() and this.apply() will or will not
   * dispose its inputTensor.
   */
  setKeepInputTensor( bKeepInputTensor ) {
    if ( bKeepInputTensor == this.bKeepInputTensor )
      return;

    this.bKeepInputTensor = bKeepInputTensor;

    if ( this.bExisted ) {
      if ( bKeepInputTensor ) {
        this.pfnConv = Base.Conv_and_keep;
      } else {
        this.pfnConv = Base.Conv_and_destroy;
      }
    } else {
      // Since there is no operation at all, let apply ignore pfnConv completely.
      if ( bKeepInputTensor ) {
        this.apply = this.pfnConv = Base.keep_input_return_copy;
      } else {
        this.apply = this.pfnConv = Base.return_input_directly;
      }
    }
  }

  get bExisted() {
    return this.bPointwise;
  }

  /** Determine this.bPointwise and this.pfnXxx data members.
   *
   * @param {Base} this
   *   The Base object to be determined and modified.
   */
  static setup_bPointwise_pfn() {

    // 0. Determine whether pointwise operation should exist.
    if ( this.outputChannelCount > 0 ) {
      this.bPointwise = true;

    } else {  // ( outputChannelCount <= 0 )
      if ( this.channelShuffler_outputGroupCount > 0 ) {

//!!! ...unfinished... (2022/05/20)
        // Perhaps, deprecate this special case. Since pointwise2 always exists now.
        // So assert if executed here.
        tf.util.assert( false,
          `Pointwise.Base.setup_bPointwise_pfn(): `
            + `When outputChannelCount ( ${this.outputChannelCount} ) is not positive, `
            + `channelShuffler_outputGroupCount ( ${this.channelShuffler_outputGroupCount} ) should not be positive.`
        );

        this.bPointwise = true; // all-pass-through-and-channel-shuffling mode. (Otherwise, no way to do channel shuffling.)
        this.bBias = false; // In this case, there is always no biases (no matter how original bBias is).

//!!! ...unfinished... (2022/05/20) What about nActivationId?

      } else {
        this.bPointwise = false;
      }
    }

    // 1.
    this.pfnConv = Base.Conv_and_destroy; // will dispose inputTensor.

    // 2.
    this.pfnActivation = ValueDesc.ActivationFunction.Singleton.getInfoById( this.nActivationId );

    // 3.
    if ( this.bPointwise ) {
      if ( this.bBias ) {
        if ( this.pfnActivation )
          this.apply = Base.ConvBiasActivation_and_destroy_or_keep;
        else
          this.apply = Base.ConvBias_and_destroy_or_keep;
      } else {
        if ( this.pfnActivation )
          this.apply = Base.ConvActivation_and_destroy_or_keep;
         else
          this.apply = Base.Conv_and_destroy_or_keep;
      }
    } else {
      // Since there is no operation at all, let apply ignore pfnConv completely.
      this.apply = this.pfnConv = Base.return_input_directly;
    }
  }

  /** Pointwise Convolution (1x1). (The inputTensor will not be disposed so that it can be used for achieving skip connection.) */
  static Conv_and_keep( inputTensor ) {
    return tf.conv2d( inputTensor, this.filtersTensor4d, 1, "valid" ); // 1x1, Stride = 1
  }

  static Conv_and_destroy( inputTensor ) {
    let t = tf.conv2d( inputTensor, this.filtersTensor4d, 1, "valid" );
    inputTensor.dispose();
    return t;
  }

  /** Pointwise Convolution, Bias and Activation. */
  static Conv_and_destroy_or_keep( inputTensor ) {
    return this.pfnConv( inputTensor );
  }

  static ConvBias_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnConv( inputTensor );

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    return t1;
  }

  static ConvActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnConv( inputTensor );

    let t1 = this.pfnActivation( t0 );
    t0.dispose();

    return t1;
  }

  static ConvBiasActivation_and_destroy_or_keep( inputTensor ) {
    let t0 = this.pfnConv( inputTensor );

    let t1 = tf.add( t0, this.biasesTensor3d );
    t0.dispose();

    t0 = this.pfnActivation( t1 );
    t1.dispose();

    return t0;
  }

}
<|endoftext|>


<commit_before>var ArticleAlbum = {
    init: function () {
        this._initControls();
    },

    _initControls: function () {
        var articleAlbum = $.templates("#articleAlbumTemplate");
        var articleAlbumHtml = articleAlbum.render({});
        $("#main_content").append(articleAlbumHtml);
        response = this._convertToJson();
        this._generateCarousel(response);
    },

    _convertToJson: function () {
        var jsonArray = [];
        var counter = 0;
        function imageSrc(item) {
            var src = $(item).find("img").attr('srcset');
            if (typeof src != 'undefined') {
                return src.split(',')[1];
            }
            return $(item).find("img").attr('data-src')|| $(item).find("img").attr('currentSrc') || $(item).find("img").attr('src');
        }
        $(".banner-container").each(function (index, item) {
           jsonArray.push({
               'srcset': $(item).find("img").attr('src'),
               'src': $(item).find("img").attr('src'),
               'description': '',
               'article_title': $('#article-gallery-title').text(),
               'id': counter++
           });
       });

        $(".article-content .rich-text-image-holder").each(function (index, item) {
            var description = $(item).find("img").next("i").text().trim();
            jsonArray.push({
                'src': imageSrc(item),
                'description': description.length < 0 ? description : $(item).next(".center.paragraph-holder").find("i").text().trim(),
                'article_title': $('#article-gallery-title').text(),
                'id': counter++
            });
        });
        return jsonArray;
    },

    // imageSrc: function(item) {
    //   var src = $(item).find("img").attr('srcset');
    //   if (typeof src != 'undefined') {
    //     return src.split(',')[1];
    //   }
    //   return $(item).find("img").attr('data-src')|| $(item).find("img").attr('currentSrc') || $(item).find("img").attr('src');
    // },
    _generateCarousel : function (data) {
        this.carouselData = data;
        data.forEach(function (slide, index) {
            slide.carouselPageClass = index === 0 ? "item image-container active" : "item image-container";
            var carouselPage = $.templates("#carouselPage");
            var carouselPageHtml = carouselPage.render(slide);
            $(".carousel-items").append(carouselPageHtml);
        });

        $("#carousel").carousel("pause");
        this.handleCarouselEvents(this.carouselData);
    },

    handleCarouselEvents : function (carouselData) {
    var totalItems = $('.carousel-items .item').length,
        currentIndex = 0;
    updateCurrentPageData();

    $('#showSlideInfo').click(function () {
        $(this).toggleClass("selected");
        $(this).removeClass("fa-info-circle").removeClass("fa-angle-right");
        $(this).addClass($(this).hasClass("selected") ? "fa-angle-right" : "fa-info-circle");
        $(".photo-album").toggleClass("show-slide-info");
    });

    $('.back-to-albums').click(function () {
        $(".carousel-container").removeClass("carousel");
        $(".photo-album-popup").addClass("hide");
    });

    $('#carousel').on('slid.bs.carousel', function () {
        updateIndexOnSlide();

    });

    $('.rich-text .gallery').click(function (event) {

        $(".photo-album-popup").removeClass("hide");
        $(".carousel-container").addClass("carousel");
        $(".carousel-container").attr("data-ride", "carousel");
        $("#carousel").carousel("pause");
        $("#carousel").carousel({
        interval: 0,
        pause: true
    });
        var index = $(event.currentTarget).attr('id');
        $("#carousel").carousel(parseInt(index)+1);

    });

    $('.preview').on('click', function () {
        $("#carousel").carousel(0);
        $(".photo-album-popup").removeClass("hide");
        $(".carousel-container").addClass("carousel");
        $("#carousel").carousel("pause");
        $(".carousel-container").attr("data-ride", "carousel");

    });

    function updateIndexOnSlide() {
        currentIndex = getSelectedCarouselIndex();
        updateCurrentPageData();
    }

    function getSelectedCarouselIndex() {
        return $('.photo-album .carousel-items li.active').index('.photo-album .carousel-items li.item');
    }

    function updateCurrentPageData() {
        totalItems = $('.carousel-items .item').length;
        $('.carousel-index').html((currentIndex + 1) + " / " + totalItems);

        var data = carouselData[currentIndex];
        $(".right-icons .open-in-new-tab").attr("href",data.src);

        if (currentIndex <= carouselData.length) {
            $(".slide-info .description").html(data.description);
            $(".slide-info .album-title").text(data.article_title);
        }
    }
}

};

$(function () {
    $(".lazyload").css("display", "initial");

    $(".scrollToTop").hide();

    $(".full-row .info a").on("click", function () {
        $("body").animate({
            scrollTop: $(".article-title").offset().top
        }, 1000);
        $(".full-row .info").animate({
            toggleClass: "hidden"
        }, 1000);
    });
    $(document).on("scroll", function () {
        if ($(window).scrollTop() < 10) {
            $(".full-row .info").removeClass("hidden");
            $(".scrollToTop").hide();
        } else {
            $(".full-row .info").addClass("hidden");
            $(".scrollToTop").show();
        }
    });

    $(".scrollToTop").on("click", function () {
        $("body").animate({
            scrollTop: 0
        }, 1000);
    });

    $('.rich-text p').each(function () {
        if ($(this).find('img').length > 0) {
            $(this).addClass("rich-text-image-holder");
        } else {
            $(this).addClass("paragraph-holder");
        }
    });

    $('.rich-text img').each(function (index) {
        $(this).wrap('');
        $(this).parents('a').first().prepend('').css("position", "relative");
    });

    ArticleAlbum.init();

    function _dummy() {
        return [{
            "srcset": '/static/img/stories-1.jpg',
            "description": "Currently, image is being stored along with alt tags as single content. While doing this feature, we need to separate html & content. Hence we get the ability to add alt tags to images for SEO purposes",
            "album_title": "Weavers of walagpet"
        },
            {
                "srcset": '/static/img/stories-1.jpg',
                "description": "Currently, image is being stored along with alt tags as single content. While doing this feature, we need to separate html & content. Hence we get the ability to add alt tags to images for SEO purposes",
                "album_title": "Weavers of walagpet"
            }];
    }
});
<commit_msg>#85 [Nimesh/ lOkesh] Photo viewer description defect<commit_after>var ArticleAlbum = {
    init: function () {
        this._initControls();
    },

    _initControls: function () {
        var articleAlbum = $.templates("#articleAlbumTemplate");
        var articleAlbumHtml = articleAlbum.render({});
        $("#main_content").append(articleAlbumHtml);
        response = this._convertToJson();
        this._generateCarousel(response);
    },

    _convertToJson: function () {
        var jsonArray = [];
        var counter = 0;
        function imageSrc(item) {
            var src = $(item).find("img").attr('srcset') || $(item).find("img").attr('data-srcset');
            if (typeof src != 'undefined') {
                return src.split(',')[1];
            }
            return $(item).find("img").attr('data-src')|| $(item).find("img").attr('currentSrc') || $(item).find("img").attr('src');
        }
        $(".banner-container").each(function (index, item) {
           jsonArray.push({
               'srcset': $(item).find("img").attr('src'),
               'src': $(item).find("img").attr('src'),
               'description': '',
               'article_title': $('#article-gallery-title').text(),
               'id': counter++
           });
       });

        $(".article-content .rich-text-image-holder").each(function (index, item) {
            var description = $(item).find("img").next("i").text().trim();
            if(description.length === 0) {
                description = $(item).children("i").text().trim();
            }
            jsonArray.push({
                'src': imageSrc(item),
                'description': description.length > 0 ? description : $(item).nextAll(".center.paragraph-holder").first().find("i").text().trim(),
                'article_title': $('#article-gallery-title').text(),
                'id': counter++
            });
        });
        return jsonArray;
    },

    // imageSrc: function(item) {
    //   var src = $(item).find("img").attr('srcset');
    //   if (typeof src != 'undefined') {
    //     return src.split(',')[1];
    //   }
    //   return $(item).find("img").attr('data-src')|| $(item).find("img").attr('currentSrc') || $(item).find("img").attr('src');
    // },
    _generateCarousel : function (data) {
        this.carouselData = data;
        data.forEach(function (slide, index) {
            slide.carouselPageClass = index === 0 ? "item image-container active" : "item image-container";
            var carouselPage = $.templates("#carouselPage");
            var carouselPageHtml = carouselPage.render(slide);
            $(".carousel-items").append(carouselPageHtml);
        });

        $("#carousel").carousel("pause");
        this.handleCarouselEvents(this.carouselData);
    },

    handleCarouselEvents : function (carouselData) {
    var totalItems = $('.carousel-items .item').length,
        currentIndex = 0;
    updateCurrentPageData();

    $('#showSlideInfo').click(function () {
        $(this).toggleClass("selected");
        $(this).removeClass("fa-info-circle").removeClass("fa-angle-right");
        $(this).addClass($(this).hasClass("selected") ? "fa-angle-right" : "fa-info-circle");
        $(".photo-album").toggleClass("show-slide-info");
    });

    $('.back-to-albums').click(function () {
        $(".carousel-container").removeClass("carousel");
        $(".photo-album-popup").addClass("hide");
    });

    $('#carousel').on('slid.bs.carousel', function () {
        updateIndexOnSlide();

    });

    $('.rich-text .gallery').click(function (event) {

        $(".photo-album-popup").removeClass("hide");
        $(".carousel-container").addClass("carousel");
        $(".carousel-container").attr("data-ride", "carousel");
        $("#carousel").carousel("pause");
        $("#carousel").carousel({
        interval: 0,
        pause: true
    });
        var index = $(event.currentTarget).attr('id');
        $("#carousel").carousel(parseInt(index)+1);

    });

    $('.preview').on('click', function () {
        $("#carousel").carousel(0);
        $(".photo-album-popup").removeClass("hide");
        $(".carousel-container").addClass("carousel");
        $("#carousel").carousel("pause");
        $(".carousel-container").attr("data-ride", "carousel");

    });

    function updateIndexOnSlide() {
        currentIndex = getSelectedCarouselIndex();
        updateCurrentPageData();
    }

    function getSelectedCarouselIndex() {
        return $('.photo-album .carousel-items li.active').index('.photo-album .carousel-items li.item');
    }

    function updateCurrentPageData() {
        totalItems = $('.carousel-items .item').length;
        $('.carousel-index').html((currentIndex + 1) + " / " + totalItems);

        var data = carouselData[currentIndex];
        $(".right-icons .open-in-new-tab").attr("href",data.src);

        if (currentIndex <= carouselData.length) {
            $(".slide-info .description").html(data.description);
            $(".slide-info .album-title").text(data.article_title);
        }
    }
}

};

$(function () {
    $(".lazyload").css("display", "initial");

    $(".scrollToTop").hide();

    $(".full-row .info a").on("click", function () {
        $("body").animate({
            scrollTop: $(".article-title").offset().top
        }, 1000);
        $(".full-row .info").animate({
            toggleClass: "hidden"
        }, 1000);
    });
    $(document).on("scroll", function () {
        if ($(window).scrollTop() < 10) {
            $(".full-row .info").removeClass("hidden");
            $(".scrollToTop").hide();
        } else {
            $(".full-row .info").addClass("hidden");
            $(".scrollToTop").show();
        }
    });

    $(".scrollToTop").on("click", function () {
        $("body").animate({
            scrollTop: 0
        }, 1000);
    });

    $('.rich-text p').each(function () {
        if ($(this).find('img').length > 0) {
            $(this).addClass("rich-text-image-holder");
        } else {
            $(this).addClass("paragraph-holder");
        }
    });

    $('.rich-text img').each(function (index) {
        $(this).wrap('');
        $(this).parents('a').first().prepend('').css("position", "relative");
    });

    ArticleAlbum.init();

    function _dummy() {
        return [{
            "srcset": '/static/img/stories-1.jpg',
            "description": "Currently, image is being stored along with alt tags as single content. While doing this feature, we need to separate html & content. Hence we get the ability to add alt tags to images for SEO purposes",
            "album_title": "Weavers of walagpet"
        },
            {
                "srcset": '/static/img/stories-1.jpg',
                "description": "Currently, image is being stored along with alt tags as single content. While doing this feature, we need to separate html & content. Hence we get the ability to add alt tags to images for SEO purposes",
                "album_title": "Weavers of walagpet"
            }];
    }
});
<|endoftext|>


<commit_before>import { resolveIfNotPlain } from 'es-module-loader/core/resolve.js';
import { baseURI, isBrowser, isWindows, addToError, global, createSymbol } from 'es-module-loader/core/common.js';
import RegisterLoader from 'es-module-loader/core/register-loader.js';
import { ModuleNamespace } from 'es-module-loader/core/loader-polyfill.js';

export { baseURI, isBrowser, isWindows, addToError, global, resolveIfNotPlain, ModuleNamespace }

export var resolvedPromise = Promise.resolve();
export function noop () {};

export var emptyModule = new ModuleNamespace({});

export function protectedCreateNamespace (bindings) {
  if (bindings instanceof ModuleNamespace)
    return bindings;

  if (bindings && bindings.__esModule)
    return new ModuleNamespace(bindings);

  return new ModuleNamespace({ default: bindings, __useDefault: bindings });
}

var hasStringTag;
export function isModule (m) {
  if (hasStringTag === undefined)
    hasStringTag = typeof Symbol !== 'undefined' && !!Symbol.toStringTag;
  return m instanceof ModuleNamespace || hasStringTag && Object.prototype.toString.call(m) == '[object Module]';
}

export var CONFIG = createSymbol('loader-config');
export var METADATA = createSymbol('metadata');
export var PLAIN_RESOLVE = createSymbol('plain-resolve');
export var PLAIN_RESOLVE_SYNC = createSymbol('plain-resolve-sync');

export var isWorker = typeof window === 'undefined' && typeof self !== 'undefined' && typeof importScripts !== 'undefined';

export function warn (msg, force) {
  if (force || this.warnings && typeof console !== 'undefined' && console.warn)
    console.warn(msg);
}

export function checkInstantiateWasm (loader, wasmBuffer, processAnonRegister) {
  var bytes = new Uint8Array(wasmBuffer);

  // detect by leading bytes
  // Can be (new Uint32Array(fetched))[0] === 0x6D736100 when working in Node
  if (bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115) {
    return WebAssembly.compile(wasmBuffer).then(function (m) {
      var deps = [];
      var setters = [];
      var importObj = {};

      // we can only set imports if supported (eg Safari doesnt support)
      if (WebAssembly.Module.imports)
        WebAssembly.Module.imports(m).forEach(function (i) {
          var key = i.module;
          setters.push(function (m) {
            importObj[key] = m;
          });
          if (deps.indexOf(key) === -1)
            deps.push(key);
        });
      loader.register(deps, function (_export) {
        return {
          setters: setters,
          execute: function () {
            _export(new WebAssembly.Instance(m, importObj).exports);
          }
        };
      });
      processAnonRegister();

      return true;
    });
  }

  return Promise.resolve(false);
}

var parentModuleContext;
export function loadNodeModule (key, baseURL) {
  if (key[0] === '.')
    throw new Error('Node module ' + key + ' can\'t be loaded as it is not a package require.');

  if (!parentModuleContext) {
    var Module = this._nodeRequire('module');
    var base = decodeURI(baseURL.substr(isWindows ? 8 : 7));
    parentModuleContext = new Module(base);
    parentModuleContext.paths = Module._nodeModulePaths(base);
  }
  return parentModuleContext.require(key);
}

export function extend (a, b) {
  for (var p in b) {
    if (!Object.hasOwnProperty.call(b, p))
      continue;
    a[p] = b[p];
  }
  return a;
}

export function prepend (a, b) {
  for (var p in b) {
    if (!Object.hasOwnProperty.call(b, p))
      continue;
    if (a[p] === undefined)
      a[p] = b[p];
  }
  return a;
}

// meta first-level extends where:
// array + array appends
// object + object extends
// other properties replace
export function extendMeta (a, b, _prepend) {
  for (var p in b) {
    if (!Object.hasOwnProperty.call(b, p))
      continue;
    var val = b[p];
    if (a[p] === undefined)
      a[p] = val;
    else if (val instanceof Array && a[p] instanceof Array)
      a[p] = [].concat(_prepend ? val : a[p]).concat(_prepend ? a[p] : val);
    else if (typeof val == 'object' && val !== null && typeof a[p] == 'object')
      a[p] = (_prepend ? prepend : extend)(extend({}, a[p]), val);
    else if (!_prepend)
      a[p] = val;
  }
}

var supportsPreload = false, supportsPrefetch = false;
if (isBrowser)
  (function () {
    var relList = document.createElement('link').relList;
    if (relList && relList.supports) {
      supportsPrefetch = true;
      try {
        supportsPreload = relList.supports('preload');
      }
      catch (e) {}
    }
  })();

export function preloadScript (url) {
  // fallback to old fashioned image technique which still works in safari
  if (!supportsPreload && !supportsPrefetch) {
    var preloadImage = new Image();
    preloadImage.src = url;
    return;
  }

  var link = document.createElement('link');
  if (supportsPreload) {
    link.rel = 'preload';
    link.as = 'script';
  }
  else {
    // this works for all except Safari (detected by relList.supports lacking)
    link.rel = 'prefetch';
  }
  link.href = url;
  document.head.appendChild(link);
  document.head.removeChild(link);
}

function workerImport (src, resolve, reject) {
  try {
    importScripts(src);
  }
  catch (e) {
    reject(e);
  }
  resolve();
}

if (isBrowser) {
  var loadingScripts = [];
  var onerror = window.onerror;
  window.onerror = function globalOnerror (msg, src) {
    for (var i = 0; i < loadingScripts.length; i++) {
      if (loadingScripts[i].src !== src)
        continue;
      loadingScripts[i].err(msg);
      return;
    }
    if (onerror)
      onerror.apply(this, arguments);
  };
}

export function scriptLoad (src, crossOrigin, integrity, resolve, reject) {
  // percent encode just "#" for HTTP requests
  src = src.replace(/#/g, '%23');

  // subresource integrity is not supported in web workers
  if (isWorker)
    return workerImport(src, resolve, reject);

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.charset = 'utf-8';
  script.async = true;

  if (crossOrigin)
    script.crossOrigin = crossOrigin;
  if (integrity)
    script.integrity = integrity;

  script.addEventListener('load', load, false);
  script.addEventListener('error', error, false);

  script.src = src;
  document.head.appendChild(script);

  function load () {
    resolve();
    cleanup();
  }

  // note this does not catch execution errors
  function error (err) {
    cleanup();
    reject(new Error('Fetching ' + src));
  }

  function cleanup () {
    for (var i = 0; i < loadingScripts.length; i++) {
      if (loadingScripts[i].err === error) {
        loadingScripts.splice(i, 1);
        break;
      }
    }
    script.removeEventListener('load', load, false);
    script.removeEventListener('error', error, false);
    document.head.removeChild(script);
  }
}

export function readMemberExpression (p, value) {
  var pParts = p.split('.');
  while (pParts.length)
    value = value[pParts.shift()];
  return value;
}

// separate out paths cache as a baseURL lock process
export function applyPaths (baseURL, paths, key) {
  var mapMatch = getMapMatch(paths, key);
  if (mapMatch) {
    var target = paths[mapMatch] + key.substr(mapMatch.length);

    var resolved = resolveIfNotPlain(target, baseURI);
    if (resolved !== undefined)
      return resolved;

    return baseURL + target;
  }
  else if (key.indexOf(':') !== -1) {
    return key;
  }
  else {
    return baseURL + key;
  }
}

function checkMap (p) {
  var name = this.name;
  // can add ':' here if we want paths to match the behaviour of map
  if (name.substr(0, p.length) === p && (name.length === p.length || name[p.length] === '/' || p[p.length - 1] === '/' || p[p.length - 1] === ':')) {
    var curLen = p.split('/').length;
    if (curLen > this.len) {
      this.match = p;
      this.len = curLen;
    }
  }
}

export function getMapMatch (map, name) {
  if (Object.hasOwnProperty.call(map, name))
    return name;

  var bestMatch = {
    name: name,
    match: undefined,
    len: 0
  };

  Object.keys(map).forEach(checkMap, bestMatch);

  return bestMatch.match;
}

// RegEx adjusted from https://github.com/jbrantly/yabble/blob/master/lib/yabble.js#L339
export var cjsRequireRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF."'])require\s*\(\s*("[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*'|`[^'\\]*(?:\\.[^'\\]*)*`)\s*\)/g
<commit_msg>ensure preload persistence, regex fix<commit_after>import { resolveIfNotPlain } from 'es-module-loader/core/resolve.js';
import { baseURI, isBrowser, isWindows, addToError, global, createSymbol } from 'es-module-loader/core/common.js';
import RegisterLoader from 'es-module-loader/core/register-loader.js';
import { ModuleNamespace } from 'es-module-loader/core/loader-polyfill.js';

export { baseURI, isBrowser, isWindows, addToError, global, resolveIfNotPlain, ModuleNamespace }

export var resolvedPromise = Promise.resolve();
export function noop () {};

export var emptyModule = new ModuleNamespace({});

export function protectedCreateNamespace (bindings) {
  if (bindings instanceof ModuleNamespace)
    return bindings;

  if (bindings && bindings.__esModule)
    return new ModuleNamespace(bindings);

  return new ModuleNamespace({ default: bindings, __useDefault: bindings });
}

var hasStringTag;
export function isModule (m) {
  if (hasStringTag === undefined)
    hasStringTag = typeof Symbol !== 'undefined' && !!Symbol.toStringTag;
  return m instanceof ModuleNamespace || hasStringTag && Object.prototype.toString.call(m) == '[object Module]';
}

export var CONFIG = createSymbol('loader-config');
export var METADATA = createSymbol('metadata');
export var PLAIN_RESOLVE = createSymbol('plain-resolve');
export var PLAIN_RESOLVE_SYNC = createSymbol('plain-resolve-sync');

export var isWorker = typeof window === 'undefined' && typeof self !== 'undefined' && typeof importScripts !== 'undefined';

export function warn (msg, force) {
  if (force || this.warnings && typeof console !== 'undefined' && console.warn)
    console.warn(msg);
}

export function checkInstantiateWasm (loader, wasmBuffer, processAnonRegister) {
  var bytes = new Uint8Array(wasmBuffer);

  // detect by leading bytes
  // Can be (new Uint32Array(fetched))[0] === 0x6D736100 when working in Node
  if (bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115) {
    return WebAssembly.compile(wasmBuffer).then(function (m) {
      var deps = [];
      var setters = [];
      var importObj = {};

      // we can only set imports if supported (eg Safari doesnt support)
      if (WebAssembly.Module.imports)
        WebAssembly.Module.imports(m).forEach(function (i) {
          var key = i.module;
          setters.push(function (m) {
            importObj[key] = m;
          });
          if (deps.indexOf(key) === -1)
            deps.push(key);
        });
      loader.register(deps, function (_export) {
        return {
          setters: setters,
          execute: function () {
            _export(new WebAssembly.Instance(m, importObj).exports);
          }
        };
      });
      processAnonRegister();

      return true;
    });
  }

  return Promise.resolve(false);
}

var parentModuleContext;
export function loadNodeModule (key, baseURL) {
  if (key[0] === '.')
    throw new Error('Node module ' + key + ' can\'t be loaded as it is not a package require.');

  if (!parentModuleContext) {
    var Module = this._nodeRequire('module');
    var base = decodeURI(baseURL.substr(isWindows ? 8 : 7));
    parentModuleContext = new Module(base);
    parentModuleContext.paths = Module._nodeModulePaths(base);
  }
  return parentModuleContext.require(key);
}

export function extend (a, b) {
  for (var p in b) {
    if (!Object.hasOwnProperty.call(b, p))
      continue;
    a[p] = b[p];
  }
  return a;
}

export function prepend (a, b) {
  for (var p in b) {
    if (!Object.hasOwnProperty.call(b, p))
      continue;
    if (a[p] === undefined)
      a[p] = b[p];
  }
  return a;
}

// meta first-level extends where:
// array + array appends
// object + object extends
// other properties replace
export function extendMeta (a, b, _prepend) {
  for (var p in b) {
    if (!Object.hasOwnProperty.call(b, p))
      continue;
    var val = b[p];
    if (a[p] === undefined)
      a[p] = val;
    else if (val instanceof Array && a[p] instanceof Array)
      a[p] = [].concat(_prepend ? val : a[p]).concat(_prepend ? a[p] : val);
    else if (typeof val == 'object' && val !== null && typeof a[p] == 'object')
      a[p] = (_prepend ? prepend : extend)(extend({}, a[p]), val);
    else if (!_prepend)
      a[p] = val;
  }
}

var supportsPreload = false, supportsPrefetch = false;
if (isBrowser)
  (function () {
    var relList = document.createElement('link').relList;
    if (relList && relList.supports) {
      supportsPrefetch = true;
      try {
        supportsPreload = relList.supports('preload');
      }
      catch (e) {}
    }
  })();

export function preloadScript (url) {
  // fallback to old fashioned image technique which still works in safari
  if (!supportsPreload && !supportsPrefetch) {
    var preloadImage = new Image();
    preloadImage.src = url;
    return;
  }

  var link = document.createElement('link');
  if (supportsPreload) {
    link.rel = 'preload';
    link.as = 'script';
  }
  else {
    // this works for all except Safari (detected by relList.supports lacking)
    link.rel = 'prefetch';
  }
  link.href = url;
  document.head.appendChild(link);
}

function workerImport (src, resolve, reject) {
  try {
    importScripts(src);
  }
  catch (e) {
    reject(e);
  }
  resolve();
}

if (isBrowser) {
  var loadingScripts = [];
  var onerror = window.onerror;
  window.onerror = function globalOnerror (msg, src) {
    for (var i = 0; i < loadingScripts.length; i++) {
      if (loadingScripts[i].src !== src)
        continue;
      loadingScripts[i].err(msg);
      return;
    }
    if (onerror)
      onerror.apply(this, arguments);
  };
}

export function scriptLoad (src, crossOrigin, integrity, resolve, reject) {
  // percent encode just "#" for HTTP requests
  src = src.replace(/#/g, '%23');

  // subresource integrity is not supported in web workers
  if (isWorker)
    return workerImport(src, resolve, reject);

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.charset = 'utf-8';
  script.async = true;

  if (crossOrigin)
    script.crossOrigin = crossOrigin;
  if (integrity)
    script.integrity = integrity;

  script.addEventListener('load', load, false);
  script.addEventListener('error', error, false);

  script.src = src;
  document.head.appendChild(script);

  function load () {
    resolve();
    cleanup();
  }

  // note this does not catch execution errors
  function error (err) {
    cleanup();
    reject(new Error('Fetching ' + src));
  }

  function cleanup () {
    for (var i = 0; i < loadingScripts.length; i++) {
      if (loadingScripts[i].err === error) {
        loadingScripts.splice(i, 1);
        break;
      }
    }
    script.removeEventListener('load', load, false);
    script.removeEventListener('error', error, false);
    document.head.removeChild(script);
  }
}

export function readMemberExpression (p, value) {
  var pParts = p.split('.');
  while (pParts.length)
    value = value[pParts.shift()];
  return value;
}

// separate out paths cache as a baseURL lock process
export function applyPaths (baseURL, paths, key) {
  var mapMatch = getMapMatch(paths, key);
  if (mapMatch) {
    var target = paths[mapMatch] + key.substr(mapMatch.length);

    var resolved = resolveIfNotPlain(target, baseURI);
    if (resolved !== undefined)
      return resolved;

    return baseURL + target;
  }
  else if (key.indexOf(':') !== -1) {
    return key;
  }
  else {
    return baseURL + key;
  }
}

function checkMap (p) {
  var name = this.name;
  // can add ':' here if we want paths to match the behaviour of map
  if (name.substr(0, p.length) === p && (name.length === p.length || name[p.length] === '/' || p[p.length - 1] === '/' || p[p.length - 1] === ':')) {
    var curLen = p.split('/').length;
    if (curLen > this.len) {
      this.match = p;
      this.len = curLen;
    }
  }
}

export function getMapMatch (map, name) {
  if (Object.hasOwnProperty.call(map, name))
    return name;

  var bestMatch = {
    name: name,
    match: undefined,
    len: 0
  };

  Object.keys(map).forEach(checkMap, bestMatch);

  return bestMatch.match;
}

// RegEx adjusted from https://github.com/jbrantly/yabble/blob/master/lib/yabble.js#L339
export var cjsRequireRegEx = /(?:^\uFEFF?|[^$_a-zA-Z\xA0-\uFFFF."'])require\s*\(\s*("[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*'|`[^`\\]*(?:\\.[^`\\]*)*`)\s*\)/g
<|endoftext|>