<commit_before>// ==UserScript==
// @name        pixivblocker
// @namespace   commies.pixivblocker
// @description nuke shit
// @include     /http://.*pixiv\.net/.*/
// @include     /https?://.*pixiv\.net/.*/
// @version     1.1.6
// @grant       none
// ==/UserScript==
function PB_CFG_CREATE() {
    return {
        'settings' : {
            'shitusers': [],
            'weaddedshitusers': false
        },
        getArray: function (myvar)
        {
            if ((localStorage.getItem(myvar) === null) || (localStorage.getItem(myvar) === ''))
            {
                console.log(myvar);
                return this.settings[myvar];
            }
            else
            {
                return localStorage.getItem(myvar).split(',');
            }
        },
        setArray: function (usersetting, settingvar)
        {
            try {
                return localStorage.setItem(usersetting, settingvar.toString());
            } catch (e) {
                console.log('Error: ' + e);
            }
        },
        nukeSetting: function(settvar){
            try {
                if(confirm('Really unblock all users??')){
                    localStorage.removeItem(settvar);
                }
            } catch (e) {
                console.log('Error: ' + e);
            }
        },
        exportSetting: function (settvar){
            alert("Copy the following:\r\n\r\n" + localStorage.getItem(settvar));
        },
        importSetting: function (settvar){
            try {
                var wef = prompt("Paste your blocked users separated by comma:");
                if(wef){
                   localStorage.setItem(settvar, wef);
                }
            } catch (e) {
                console.log('Error: ' + e);
            }
        },
        arrayContains: function (needle, arrhaystack)
        {
            return (arrhaystack.indexOf(needle) > - 1);
        },
        listManage: function(thelist, theuser){
            var realshitlist = this.getArray(thelist);
            if (!theuser) {
                theuser = prompt("Enter Username Here", "Type here");
            }
            var willyou = false;

            //check if user is already in the list
            for (var x=0; x<realshitlist.length; x++) {
                var thisblistitem = realshitlist[x];
                if ( theuser === thisblistitem ) {
                    willyou = confirm('Are you sure you want to unblock this user?');
                    if (willyou){
                        realshitlist.splice(x,1);
                        this.setArray(thelist, realshitlist );
                    }
                    return false;
                }
            }

            //user wasn't in list
            willyou = confirm('Add to Filterlist?');
            if (willyou){
                realshitlist[realshitlist.length] = theuser;
                this.setArray(thelist, realshitlist );

                return true;
            }
            return false;
        },
        nukeThumbs: function(username){
            var allElements = document.getElementsByClassName('image-item');
            for (var i = 0, n = allElements.length; i < n; i++)
            {
                if (this.sescape(allElements[i].childNodes[1].attributes['data-user_name'].value) === username)
                {
                    // Element exists with attribute. Add to array.
                    allElements[i].parentNode.removeChild(allElements[i--]);
                }
            }
        },
        sescape: function(v){
            return v.replace(/&/, "&").replace(/'/g, "'").replace(/"/g, """);
        },
        addShitUserList: function(){
            if(!this.settings['weaddedshitusers']){
                alert('Loading the list of shit users. This may take a while if you have a ton!\r\nKeep hovering over that area to show them after it\'s done.');
                var shitusers = PB_CFG.getArray('shitusers');
                var ourdiv = document.getElementsByClassName('pixivblocker_shitdiv')[0];
                var coollist = document.createElement('ul');
                coollist.className = "pixivblocker_shitusers";

                for(var v = 0; v < shitusers.length; v++){
                    var coolitem = document.createElement('li');

                    coolspan = document.createElement('span');
                    coolspan.className = "pixivblocker_minus";
                    coolspan.setAttribute("onclick", "PB_CFG.listManage('shitusers','"+shitusers[v]+"');");
                    coolspan.innerHTML = "❤";
                    coolspan.title = "Remove from pixivblocker";

                    coolitem.innerHTML = shitusers[v] + " " + coolspan.outerHTML;
                    coollist.innerHTML = coolitem.outerHTML + "\r\n" + coollist.innerHTML;
                }

                ourdiv.appendChild(coollist);
            }
            this.settings['weaddedshitusers'] = true;
        },
        init: function ()
        {
            var shitusers = PB_CFG.getArray('shitusers');
            var testElements = document.getElementsByClassName('image-item');
            var testDivs = Array.prototype.filter.call(testElements, function (testElement) {
                return testElement.nodeName === 'LI';
            });
            var coolspan;
            //go through list of thumbnails and add stuff to them
            for (var v = 0, u = null; v < testElements.length; v++, u = null) {
                u = testElements.item(v).childNodes[1].attributes['data-user_name'].value
                u = this.sescape(u);

                //add +/- next to names
                coolspan = document.createElement('span');

                //if shit users
                if (PB_CFG.arrayContains(u, shitusers)) {
                    testElements.item(v).parentNode.removeChild(testElements.item(v));
                    v--;
                    //testElements.item(v).childNodes[0].innerHTML = 'This user is shit
';

                    /*coolspan.className = "pixivblocker_minus";
                    coolspan.setAttribute("onclick", "PB_CFG.listManage('shitusers','"+u+"');");
                    coolspan.innerHTML = "❤";
                    coolspan.title = "Remove from pixivblocker";*/
                }
                else{
                    coolspan.className = "pixivblocker_plus";
                    coolspan.setAttribute("onclick", "if(PB_CFG.listManage('shitusers','"+u+"')) PB_CFG.nukeThumbs('"+u+"');");
                    coolspan.innerHTML = "🚫";
                    coolspan.title = "Add user to pixivblocker";
                    testElements.item(v).insertBefore(coolspan, testElements.item(v).childNodes[1].nextSibling);
                }
            }

            //add list of shitusers at bottom of page
            var cooldiv = document.createElement('div');
            cooldiv.className = "pixivblocker_shitdiv";
            cooldiv.id = "pixivblocker_shitdiv";

            var coolheader = document.createElement('h3');
            coolheader.innerHTML = "Shit users you've blocked: (click/hover me)";
            coolheader.setAttribute("onclick", "PB_CFG.addShitUserList();");
            cooldiv.innerHTML += coolheader.outerHTML;

            var coolbutton = document.createElement('button');
            coolbutton.type = "button";
            coolbutton.innerHTML += "!! Unblock all users !!";
            coolbutton.setAttribute("onclick", "PB_CFG.nukeSetting('shitusers');");
            cooldiv.innerHTML += coolbutton.outerHTML;

            coolbutton = document.createElement('button');
            coolbutton.type = "button";
            coolbutton.innerHTML += "EXPORT";
            coolbutton.setAttribute("onclick", "PB_CFG.exportSetting('shitusers');");
            cooldiv.innerHTML += coolbutton.outerHTML;

            coolbutton = document.createElement('button');
            coolbutton.type = "button";
            coolbutton.innerHTML += "IMPORT";
            coolbutton.setAttribute("onclick", "PB_CFG.importSetting('shitusers');");
            cooldiv.innerHTML += coolbutton.outerHTML;

            var targetcontainer = document.getElementsByClassName('layout-body')[0];
            var num = 0;
            if(!targetcontainer) {
               targetcontainer = document.getElementsByClassName('contents-main')[0];
               num = 2;
            }
            targetcontainer.childNodes[num].appendChild(cooldiv);
        }
    };
}

function populateCSS(){
    var ourcss = "";

    ourcss += ".image-item { height:auto !important; }"; //fixes heights being cut off
    ourcss += ".popular-introduction { position:relative !important; top: 0px !important; left: 0px !important; }"; //fixes popular thing being in the way terribly
    ourcss += ".pixivblocker_minus { padding:0px 4px; background: #77FF88; color:#FFF; cursor:pointer;}";
    ourcss += ".pixivblocker_plus { padding:0px 4px; background: #FF7788; color:#FFF; cursor:pointer; margin-left:5px;}";
    ourcss += ".pixivblocker_shitdiv {width:95%; margin:auto; margin-bottom: 15px; border-bottom: 2px dashed rgba(0,0,0,.2);}";
    ourcss += ".pixivblocker_shitdiv ul {max-height: 0; transition: max-height 1s ease-out .4s; overflow: hidden; list-style: none; display:block;}";
    ourcss += ".pixivblocker_shitdiv:hover ul {max-height:9999px; transition: max-height 1s ease-in .4s;}";
    ourcss += ".pixivblocker_shitdiv h3 { font-weight: bolder; font-size: 110%; margin-bottom: 5px;}";
    ourcss += ".pixivblocker_shitdiv h3 small { font-size: 70%;}";
    ourcss += ".pixivblocker_shitdiv ul li { padding-left:3px; display:inline-block; background: rgba(0,0,0,.1); margin:5px;}";
    //ourcss += ".pixivblocker_shitusers li:after { content: ', '}";
    //ourcss += ".pixivblocker_shitusers li:last-child:after {content: ''; }";

    //now we actually add our CSS to the page
    if (document.getElementById("PB_CSS") !== null){
        document.getElementById("PB_CSS").innerHTML = ourcss;
    } else {
        var head = document.getElementsByTagName('head')[0];
        if (!head) { return; }
        var style = document.createElement('style');
        style.type = 'text/css';
        style.id = "PB_CSS";
        style.innerHTML = ourcss;
        head.appendChild(style);
    }
}

function addJS (str){
    var head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    var style = document.createElement('script');
    style.innerHTML = str;
    head.appendChild(style);
}

var cooljs = ''+
PB_CFG_CREATE.toString()+
'var PB_CFG = new PB_CFG_CREATE();'+
'PB_CFG.init();';

    addJS(cooljs);
    populateCSS();
<commit_msg>Update pixivblocker.user.js<commit_after>// ==UserScript==
// @name        pixivblocker
// @namespace   commies.pixivblocker
// @description nuke shit
// @include     /http://.*pixiv\.net/.*/
// @include     /https?://.*pixiv\.net/.*/
// @version     1.1.6
// @grant       none
// ==/UserScript==
function PB_CFG_CREATE() {
    return {
        'settings' : {
            'shitusers': [],
            'weaddedshitusers': false
        },
        getArray: function (myvar)
        {
            if ((localStorage.getItem(myvar) === null) || (localStorage.getItem(myvar) === ''))
            {
                console.log(myvar);
                return this.settings[myvar];
            }
            else
            {
                return localStorage.getItem(myvar).split(',');
            }
        },
        setArray: function (usersetting, settingvar)
        {
            try {
                return localStorage.setItem(usersetting, settingvar.toString());
            } catch (e) {
                console.log('Error: ' + e);
            }
        },
        nukeSetting: function(settvar){
            try {
                if(confirm('Really unblock all users??')){
                    localStorage.removeItem(settvar);
                }
            } catch (e) {
                console.log('Error: ' + e);
            }
        },
        exportSetting: function (settvar){
            alert("Copy the following:\r\n\r\n" + localStorage.getItem(settvar));
        },
        importSetting: function (settvar){
            try {
                var wef = prompt("Paste your blocked users separated by comma:");
                if(wef){
                   localStorage.setItem(settvar, wef);
                }
            } catch (e) {
                console.log('Error: ' + e);
            }
        },
        arrayContains: function (needle, arrhaystack)
        {
            return (arrhaystack.indexOf(needle) > - 1);
        },
        listManage: function(thelist, theuser){
            var realshitlist = this.getArray(thelist);
            if (!theuser) {
                theuser = prompt("Enter Username Here", "Type here");
            }
            var willyou = false;

            //check if user is already in the list
            for (var x=0; x<realshitlist.length; x++) {
                var thisblistitem = realshitlist[x];
                if ( theuser === thisblistitem ) {
                    willyou = confirm('Are you sure you want to unblock this user?');
                    if (willyou){
                        realshitlist.splice(x,1);
                        this.setArray(thelist, realshitlist );
                    }
                    return false;
                }
            }

            //user wasn't in list
            willyou = confirm('Add to Filterlist?');
            if (willyou){
                realshitlist[realshitlist.length] = theuser;
                this.setArray(thelist, realshitlist );

                return true;
            }
            return false;
        },
        nukeThumbs: function(username){
            var allElements = document.getElementsByClassName('image-item');
            for (var i = 0, n = allElements.length; i < n; i++)
            {
                console.log(allElements[i].childNodes);
                if (this.sescape(allElements[i].childNodes[2].attributes['data-user_name'].value) === username)
                {
                    // Element exists with attribute. Add to array.
                    allElements[i].parentNode.removeChild(allElements[i--]);
                }
            }
        },
        sescape: function(v){
            return v.replace(/&/, "&").replace(/'/g, "'").replace(/"/g, """);
        },
        addShitUserList: function(){
            if(!this.settings['weaddedshitusers']){
                alert('Loading the list of shit users. This may take a while if you have a ton!\r\nKeep hovering over that area to show them after it\'s done.');
                var shitusers = PB_CFG.getArray('shitusers');
                var ourdiv = document.getElementsByClassName('pixivblocker_shitdiv')[0];
                var coollist = document.createElement('ul');
                coollist.className = "pixivblocker_shitusers";

                for(var v = 0; v < shitusers.length; v++){
                    var coolitem = document.createElement('li');

                    coolspan = document.createElement('span');
                    coolspan.className = "pixivblocker_minus";
                    coolspan.setAttribute("onclick", "PB_CFG.listManage('shitusers','"+shitusers[v]+"');");
                    coolspan.innerHTML = "❤";
                    coolspan.title = "Remove from pixivblocker";

                    coolitem.innerHTML = shitusers[v] + " " + coolspan.outerHTML;
                    coollist.innerHTML = coolitem.outerHTML + "\r\n" + coollist.innerHTML;
                }

                ourdiv.appendChild(coollist);
            }
            this.settings['weaddedshitusers'] = true;
        },
        init: function ()
        {
            var shitusers = PB_CFG.getArray('shitusers');
            console.log("[PixivBlocker] Currently blocking " + shitusers.length + " shit users.");
            var testElements = document.getElementsByClassName('image-item');
            var testDivs = Array.prototype.filter.call(testElements, function (testElement) {
                return testElement.nodeName === 'LI';
            });
            var coolspan;
            //go through list of thumbnails and add stuff to them
            for (var v = 0, u = null; v < testElements.length; v++, u = null) {
                if(testElements.item(v).childNodes[2].attributes['data-user_name'].value !== 'undefined'){
                    u = testElements.item(v).childNodes[2].attributes['data-user_name'].value;
                    u = this.sescape(u);

                    //add +/- next to names
                    coolspan = document.createElement('span');

                    //if shit users
                    if (PB_CFG.arrayContains(u, shitusers)) {
                        testElements.item(v).parentNode.removeChild(testElements.item(v));
                        v--;
                        //testElements.item(v).childNodes[0].innerHTML = 'This user is shit
';

                        /*coolspan.className = "pixivblocker_minus";
                        coolspan.setAttribute("onclick", "PB_CFG.listManage('shitusers','"+u+"');");
                        coolspan.innerHTML = "❤";
                        coolspan.title = "Remove from pixivblocker";*/
                    }
                    else{
                        coolspan.className = "pixivblocker_plus";
                        coolspan.setAttribute("onclick", "if(PB_CFG.listManage('shitusers','"+u+"')) PB_CFG.nukeThumbs('"+u+"');");
                        coolspan.innerHTML = "🚫";
                        coolspan.title = "Add user to pixivblocker";
                        testElements.item(v).insertBefore(coolspan, testElements.item(v).childNodes[2].nextSibling);
                    }
               }
            }

            //add list of shitusers at bottom of page
            var cooldiv = document.createElement('div');
            cooldiv.className = "pixivblocker_shitdiv";
            cooldiv.id = "pixivblocker_shitdiv";

            var coolheader = document.createElement('h3');
            coolheader.innerHTML = "Shit users you've blocked: (click/hover me)";
            coolheader.setAttribute("onclick", "PB_CFG.addShitUserList();");
            cooldiv.innerHTML += coolheader.outerHTML;

            var coolbutton = document.createElement('button');
            coolbutton.type = "button";
            coolbutton.innerHTML += "!! Unblock all users !!";
            coolbutton.setAttribute("onclick", "PB_CFG.nukeSetting('shitusers');");
            cooldiv.innerHTML += coolbutton.outerHTML;

            coolbutton = document.createElement('button');
            coolbutton.type = "button";
            coolbutton.innerHTML += "EXPORT";
            coolbutton.setAttribute("onclick", "PB_CFG.exportSetting('shitusers');");
            cooldiv.innerHTML += coolbutton.outerHTML;

            coolbutton = document.createElement('button');
            coolbutton.type = "button";
            coolbutton.innerHTML += "IMPORT";
            coolbutton.setAttribute("onclick", "PB_CFG.importSetting('shitusers');");
            cooldiv.innerHTML += coolbutton.outerHTML;

            var targetcontainer = document.getElementsByClassName('layout-body')[0];
            var num = 0;
            if(!targetcontainer) {
               targetcontainer = document.getElementsByClassName('contents-main')[0];
               num = 2;
            }
            targetcontainer.childNodes[num].appendChild(cooldiv);
        }
    };
}

function populateCSS(){
    var ourcss = "";

    ourcss += ".image-item { height:auto !important; }"; //fixes heights being cut off
    ourcss += ".popular-introduction { position:relative !important; top: 0px !important; left: 0px !important; }"; //fixes popular thing being in the way terribly
    ourcss += ".pixivblocker_minus { padding:0px 4px; background: #77FF88; color:#FFF; cursor:pointer;}";
    ourcss += ".pixivblocker_plus { padding:0px 4px; background: #FF7788; color:#FFF; cursor:pointer; margin-left:5px;}";
    ourcss += ".pixivblocker_shitdiv {width:95%; margin:auto; margin-bottom: 15px; border-bottom: 2px dashed rgba(0,0,0,.2);}";
    ourcss += ".pixivblocker_shitdiv ul {max-height: 0; transition: max-height 1s ease-out .4s; overflow: hidden; list-style: none; display:block;}";
    ourcss += ".pixivblocker_shitdiv:hover ul {max-height:9999px; transition: max-height 1s ease-in .4s;}";
    ourcss += ".pixivblocker_shitdiv h3 { font-weight: bolder; font-size: 110%; margin-bottom: 5px;}";
    ourcss += ".pixivblocker_shitdiv h3 small { font-size: 70%;}";
    ourcss += ".pixivblocker_shitdiv ul li { padding-left:3px; display:inline-block; background: rgba(0,0,0,.1); margin:5px;}";
    //ourcss += ".pixivblocker_shitusers li:after { content: ', '}";
    //ourcss += ".pixivblocker_shitusers li:last-child:after {content: ''; }";

    //now we actually add our CSS to the page
    if (document.getElementById("PB_CSS") !== null){
        document.getElementById("PB_CSS").innerHTML = ourcss;
    } else {
        var head = document.getElementsByTagName('head')[0];
        if (!head) { return; }
        var style = document.createElement('style');
        style.type = 'text/css';
        style.id = "PB_CSS";
        style.innerHTML = ourcss;
        head.appendChild(style);
    }
}

function addJS (str){
    if (document.getElementById("pixivblockerscript") !== null)
    {
        document.getElementById("pixivblockerscript").innerHTML = str;
    }
    else
    {
        var head = document.getElementsByTagName('head')[0];
        if (!head) { return; }
        var style = document.createElement('script');
        style.id = "pixivblockerscript";
        style.innerHTML = str;
        head.appendChild(style);
    }
}

var cooljs = ''+
PB_CFG_CREATE.toString()+
'var PB_CFG = new PB_CFG_CREATE();'+
'PB_CFG.init();';

    addJS(cooljs);
    populateCSS();
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

var testName = 'Bob Jr';
var testWork = 'Test Work';
var testYear = '2016-2017';
var testEmail = 'bob@example.com';
var testWebsite = 'http://www.example.com';
var testLicenses = [
  'CC-BY-4.0'
];
var testOutput = 'LICENSE';

var testHeaderFull =
  testWork + ' (c) ' + testYear + ' ' + testName + ' <' + testEmail + '> (' + testWebsite + ')';
var testHeaderNoContacts =
  testWork + ' (c) ' + testYear + ' ' + testName;
var testHeaderNoContactsWebsite =
  testWork + ' (c) ' + testYear + ' ' + testName + ' <' + testEmail + '>';
var testHeaderNoContactsEmail =
  testWork + ' (c) ' + testYear + ' ' + testName + ' (' + testWebsite + ')';

var testHeaderNoYear =
  testWork + ' (c)  ' + testName;

describe('generator-license-cc:app', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        year: testYear,
        email: testEmail,
        website: testWebsite,
        licensePrompt: 'Choose a License:',
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderFull);
  });
});

describe('generator-license-cc:app no contact details', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        year: testYear,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoContacts);
  });
});

describe('generator-license-cc:app no contact details - email', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        website: testWebsite,
        work: testWork,
        year: testYear,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoContactsEmail);
  });
});

describe('generator-license-cc:app no contact details - website', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        email: testEmail,
        work: testWork,
        year: testYear,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoContactsWebsite);
  });
});

describe('generator-license-cc:app no contact details + no year', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoYear);
  });
});

describe('generator-license-cc:app passnameas option', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        work: testWork,
        license: testLicenses[0],
        output: testOutput
      }).withOptions({
        name: testName
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoYear);
  });
});
<commit_msg>test: test passing email as an option<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

var testName = 'Bob Jr';
var testWork = 'Test Work';
var testYear = '2016-2017';
var testEmail = 'bob@example.com';
var testWebsite = 'http://www.example.com';
var testLicenses = [
  'CC-BY-4.0'
];
var testOutput = 'LICENSE';

var testHeaderFull =
  testWork + ' (c) ' + testYear + ' ' + testName + ' <' + testEmail + '> (' + testWebsite + ')';
var testHeaderNoContacts =
  testWork + ' (c) ' + testYear + ' ' + testName;
var testHeaderNoContactsWebsite =
  testWork + ' (c) ' + testYear + ' ' + testName + ' <' + testEmail + '>';
var testHeaderNoContactsEmail =
  testWork + ' (c) ' + testYear + ' ' + testName + ' (' + testWebsite + ')';

var testHeaderNoYear =
  testWork + ' (c)  ' + testName;

describe('generator-license-cc:app', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        year: testYear,
        email: testEmail,
        website: testWebsite,
        licensePrompt: 'Choose a License:',
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderFull);
  });
});

describe('generator-license-cc:app no contact details', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        year: testYear,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoContacts);
  });
});

describe('generator-license-cc:app no contact details - email', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        website: testWebsite,
        work: testWork,
        year: testYear,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoContactsEmail);
  });
});

describe('generator-license-cc:app no contact details - website', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        email: testEmail,
        work: testWork,
        year: testYear,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoContactsWebsite);
  });
});

describe('generator-license-cc:app no contact details + no year', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        license: testLicenses[0],
        output: testOutput
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoYear);
  });
});

describe('generator-license-cc:app pass name as option', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        work: testWork,
        license: testLicenses[0],
        output: testOutput
      }).withOptions({
        name: testName
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoYear);
  });
});

describe('generator-license-cc:app pass email as option', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: testName,
        work: testWork,
        license: testLicenses[0],
        output: testOutput
      }).withOptions({
        email: testEmail
      }).toPromise();
  });

  it('creates LICENSE file with correct data', function () {
    assert.fileContent(testOutput, testHeaderNoYear);
  });
});

<|endoftext|>


<commit_before>var should = require('should');

var Characteristic = require('../lib/characteristic');

describe('Characteristic', function() {
  var mockUuid = 'mock-uuid';
  var mockProperties = ['property1', 'property2', 'property3'];
  var mockValue = new Buffer('mock value');
  var mockDescriptors = [{}, {}, {}];

  var mockOnReadRequest = function() {};
  var mockOnWriteRequest = function() {};
  var mockOnSubscribe = function() {};
  var mockOnUnsubscribe = function() {};
  var mockOnNotify = function() {};

  var mockMaxValueSize = 20;
  var mockUpdateValueCallback = function() {};

  it('should create with uuid option', function() {
    var characteristic = new Characteristic({
      uuid: mockUuid
    });

    characteristic.uuid.should.equal(mockUuid);

    Array.isArray(characteristic.properties).should.equal(true);
    characteristic.properties.length.should.equal(0);

    should(characteristic.value).equal(null);

    Array.isArray(characteristic.descriptors).should.equal(true);
    characteristic.descriptors.length.should.equal(0);
  });

  it('should create with properties option', function() {
    var characteristic = new Characteristic({
      properties: mockProperties
    });

    characteristic.properties.should.equal(mockProperties);
  });

  it('should create with value option', function() {
    var characteristic = new Characteristic({
      value: mockValue
    });

    characteristic.value.should.equal(mockValue);
  });

  it('should create with descriptors option', function() {
    var characteristic = new Characteristic({
      descriptors: mockDescriptors
    });

    characteristic.descriptors.should.equal(mockDescriptors);
  });

  it('should create with onReadRequest option', function() {
    var characteristic = new Characteristic({
      onReadRequest: mockOnReadRequest
    });

    characteristic.onReadRequest.should.equal(mockOnReadRequest);
  });

  it('should create with onWriteRequest option', function() {
    var characteristic = new Characteristic({
      onWriteRequest: mockOnWriteRequest
    });

    characteristic.onWriteRequest.should.equal(mockOnWriteRequest);
  });

  it('should create with onSubscribe option', function() {
    var characteristic = new Characteristic({
      onSubscribe: mockOnSubscribe
    });

    characteristic.onSubscribe.should.equal(mockOnSubscribe);
  });

  it('should create with onUnsubscribe option', function() {
    var characteristic = new Characteristic({
      onUnsubscribe: mockOnUnsubscribe
    });

    characteristic.onUnsubscribe.should.equal(mockOnUnsubscribe);
  });

  it('should create with onNotify option', function() {
    var characteristic = new Characteristic({
      onNotify: mockOnNotify
    });

    characteristic.onNotify.should.equal(mockOnNotify);
  });

  it('should toString', function() {
    var characteristic = new Characteristic({
      uuid: mockUuid
    });

    characteristic.toString().should.equal('{"uuid":"mock-uuid","properties":[],"value":null,"descriptors":[]}');
  });

  it('should handle read request', function(done) {
    var characteristic = new Characteristic({});

    characteristic.emit('readRequest', 0, function(result, data) {
      result.should.equal(0x0e);
      should(data).equal(null);

      done();
    });
  });

  it('should handle write request', function(done) {
    var characteristic = new Characteristic({});

    characteristic.emit('writeRequest', new Buffer(0), 0, false, function(result) {
      result.should.equal(0x0e);

      done();
    });
  });

  it('should handle unsubscribe', function() {
    var characteristic = new Characteristic({});

    characteristic.maxValueSize = mockMaxValueSize;
    characteristic.updateValueCallback = mockUpdateValueCallback;

    characteristic.emit('unsubscribe');

    should(characteristic.maxValueSize).equal(null);
    should(characteristic.updateValueCallback).equal(null);
  });

  it('should handle unsubscribe', function() {
    var characteristic = new Characteristic({});

    characteristic.emit('notify');
  });
});<commit_msg>- update characteristic tests for new secure property<commit_after>var should = require('should');

var Characteristic = require('../lib/characteristic');

describe('Characteristic', function() {
  var mockUuid = 'mock-uuid';
  var mockProperties = ['property1', 'property2', 'property3'];
  var mockSecure = ['secure1', 'secure2', 'secure3'];
  var mockValue = new Buffer('mock value');
  var mockDescriptors = [{}, {}, {}];

  var mockOnReadRequest = function() {};
  var mockOnWriteRequest = function() {};
  var mockOnSubscribe = function() {};
  var mockOnUnsubscribe = function() {};
  var mockOnNotify = function() {};

  var mockMaxValueSize = 20;
  var mockUpdateValueCallback = function() {};

  it('should create with uuid option', function() {
    var characteristic = new Characteristic({
      uuid: mockUuid
    });

    characteristic.uuid.should.equal(mockUuid);

    Array.isArray(characteristic.properties).should.equal(true);
    characteristic.properties.length.should.equal(0);

    Array.isArray(characteristic.secure).should.equal(true);
    characteristic.secure.length.should.equal(0);

    should(characteristic.value).equal(null);

    Array.isArray(characteristic.descriptors).should.equal(true);
    characteristic.descriptors.length.should.equal(0);
  });

  it('should create with properties option', function() {
    var characteristic = new Characteristic({
      properties: mockProperties
    });

    characteristic.properties.should.equal(mockProperties);
  });

  it('should create with secure option', function() {
    var characteristic = new Characteristic({
      secure: mockSecure
    });

    characteristic.secure.should.equal(mockSecure);
  });

  it('should create with value option', function() {
    var characteristic = new Characteristic({
      value: mockValue
    });

    characteristic.value.should.equal(mockValue);
  });

  it('should create with descriptors option', function() {
    var characteristic = new Characteristic({
      descriptors: mockDescriptors
    });

    characteristic.descriptors.should.equal(mockDescriptors);
  });

  it('should create with onReadRequest option', function() {
    var characteristic = new Characteristic({
      onReadRequest: mockOnReadRequest
    });

    characteristic.onReadRequest.should.equal(mockOnReadRequest);
  });

  it('should create with onWriteRequest option', function() {
    var characteristic = new Characteristic({
      onWriteRequest: mockOnWriteRequest
    });

    characteristic.onWriteRequest.should.equal(mockOnWriteRequest);
  });

  it('should create with onSubscribe option', function() {
    var characteristic = new Characteristic({
      onSubscribe: mockOnSubscribe
    });

    characteristic.onSubscribe.should.equal(mockOnSubscribe);
  });

  it('should create with onUnsubscribe option', function() {
    var characteristic = new Characteristic({
      onUnsubscribe: mockOnUnsubscribe
    });

    characteristic.onUnsubscribe.should.equal(mockOnUnsubscribe);
  });

  it('should create with onNotify option', function() {
    var characteristic = new Characteristic({
      onNotify: mockOnNotify
    });

    characteristic.onNotify.should.equal(mockOnNotify);
  });

  it('should toString', function() {
    var characteristic = new Characteristic({
      uuid: mockUuid
    });

    characteristic.toString().should.equal('{"uuid":"mock-uuid","properties":[],"secure":[],"value":null,"descriptors":[]}');
  });

  it('should handle read request', function(done) {
    var characteristic = new Characteristic({});

    characteristic.emit('readRequest', 0, function(result, data) {
      result.should.equal(0x0e);
      should(data).equal(null);

      done();
    });
  });

  it('should handle write request', function(done) {
    var characteristic = new Characteristic({});

    characteristic.emit('writeRequest', new Buffer(0), 0, false, function(result) {
      result.should.equal(0x0e);

      done();
    });
  });

  it('should handle unsubscribe', function() {
    var characteristic = new Characteristic({});

    characteristic.maxValueSize = mockMaxValueSize;
    characteristic.updateValueCallback = mockUpdateValueCallback;

    characteristic.emit('unsubscribe');

    should(characteristic.maxValueSize).equal(null);
    should(characteristic.updateValueCallback).equal(null);
  });

  it('should handle unsubscribe', function() {
    var characteristic = new Characteristic({});

    characteristic.emit('notify');
  });
});<|endoftext|>


<commit_before>/*
waitMe - 1.15 [15.02.16]
Author: vadimsva
Github: https://github.com/vadimsva/waitMe
*/
(function($) {
  $.fn.waitMe = function(method) {
    return this.each(function() {

      var elem = $(this),
			elemClass = 'waitMe',
			waitMe_text,
			effectObj,
			effectElemCount,
			createSubElem = false,
			specificAttr = 'background-color',
			addStyle = '',
			effectElemHTML = '',
			waitMeObj,
			_options,
			currentID;

      var methods = {
        init : function() {
          var _defaults = {
            effect: 'bounce',
            text: '',
            bg: 'rgba(255,255,255,0.7)',
            color: '#000',
						maxSize: '',
            source: '',
						onClose: function() {}
          };
          _options = $.extend(_defaults, method);

          currentID = new Date().getMilliseconds();
          waitMeObj = $('

');

          switch (_options.effect) {
            case 'none':
              effectElemCount = 0;
              break;
            case 'bounce':
              effectElemCount = 3;
              break;
            case 'rotateplane':
              effectElemCount = 1;
              break;
            case 'stretch':
              effectElemCount = 5;
              break;
            case 'orbit':
              effectElemCount = 2;
              break;
            case 'roundBounce':
              effectElemCount = 12;
              break;
            case 'win8':
              effectElemCount = 5;
              createSubElem = true;
              break;
            case 'win8_linear':
              effectElemCount = 5;
              createSubElem = true;
              break;
            case 'ios':
              effectElemCount = 12;
              break;
            case 'facebook':
              effectElemCount = 3;
              break;
            case 'rotation':
              effectElemCount = 1;
              specificAttr = 'border-color';
              break;
            case 'timer':
              effectElemCount = 2;
							if ($.isArray(_options.color)) {
								var color = _options.color[0];
							} else {
								var color = _options.color;
							}
              addStyle = 'border-color:' + color;
              break;
            case 'pulse':
              effectElemCount = 1;
              specificAttr = 'border-color';
              break;
            case 'progressBar':
              effectElemCount = 1;
              break;
            case 'bouncePulse':
              effectElemCount = 3;
              break;
            case 'img':
              effectElemCount = 1;
              break;
          }

          if (addStyle !== '') {
            addStyle += ';';
          }

          if (effectElemCount > 0) {
            if(_options.effect === 'img') {
							effectElemHTML = '';
            } else {
              for (var i = 1; i <= effectElemCount; ++i) {
								if ($.isArray(_options.color)) {
									var color = _options.color[i];
									if (color == undefined) {
										color = '#000';
									}
								} else {
									var color = _options.color;
								}
                if (createSubElem) {
                  effectElemHTML += '

';
                } else {
                  effectElemHTML += '

';
                }
              }
            }
            effectObj = $('
' + effectElemHTML + '
');
          }

          if (_options.text && _options.maxSize === '') {
						if ($.isArray(_options.color)) {
							var color = _options.color[0];
						} else {
							var color = _options.color;
						}
            waitMe_text = $('
' + _options.text + '
');
          }
					var elemObj = elem.find('> .' + elemClass);

          if (elemObj) {
            elemObj.remove();
          }
          var waitMeDivObj = $('

');
          waitMeDivObj.append(effectObj, waitMe_text);
          waitMeObj.append(waitMeDivObj);
          if (elem[0].tagName == 'HTML') {
            elem = $('body');
          }
          elem.addClass(elemClass + '_container').attr('data-waitme_id', currentID).append(waitMeObj);
					elemObj = elem.find('> .' + elemClass);
					var elemContentObj = elem.find('.' + elemClass + '_content');
          elemObj.css({background: _options.bg});
					elemContentObj.css({marginTop: - elemContentObj.outerHeight() / 2 + 'px'});

					if (_options.maxSize !== '') {
						var elemH = effectObj.outerHeight();
						var elemW = effectObj.outerWidth();
						var elemMax = elemH;
						if (_options.effect === 'img') {
							effectObj.css({height: _options.maxSize + 'px'});
							effectObj.find('>img').css({maxHeight: '100%'});
							elemContentObj.css({marginTop: - elemContentObj.outerHeight() / 2 + 'px'});
						} else {
							if (_options.maxSize < elemMax) {
								waitMeDivObj.css({transform: 'scale(' + _options.maxSize / elemMax + ')'});
							}
						}
					}

					function setElTop(getTop) {
						elemContentObj.css({top: 'auto', transform: 'translateY(' + getTop + 'px) translateZ(0)'});
					}
          if (elem.outerHeight() > $(window).height()) {
            var sTop = $(window).scrollTop(),
            elH = elemContentObj.outerHeight(),
            elTop = elem.offset().top,
            cH = elem.outerHeight(),
						getTop = sTop - elTop + $(window).height()/2;
						if (getTop < 0) {
							getTop = Math.abs(getTop);
						}
						if (getTop - elH >= 0 && getTop + elH <= cH) {
							if (elTop - sTop > $(window).height()/2) {
								getTop = elH;
							}
							setElTop(getTop);
						} else {
							if (sTop > elTop + cH - elH) {
								getTop = sTop - elTop - elH;
							} else {
								getTop = sTop - elTop + elH;
							}
							setElTop(getTop);
						}
            $(document).scroll(function() {
              var sTop = $(window).scrollTop(),
              getTop = sTop - elTop + $(window).height()/2;
              if (getTop - elH >= 0 && getTop + elH <= cH) {
								setElTop(getTop);
              }
            });
          }

					elemObj.on('destroyed', function() {
						if (_options.onClose && $.isFunction(_options.onClose)) {
							_options.onClose();
						}
						elemObj.trigger('close');
					});

					$.event.special.destroyed = {
						remove: function(o) {
							if (o.handler) {
								o.handler();
							}
						}
					};

					return elemObj;
        },
        hide : function() {
          waitMeClose();
        }
      };

      function waitMeClose() {
        var currentID = elem.attr('data-waitme_id');
        elem.removeClass(elemClass + '_container').removeAttr('data-waitme_id');
        elem.find('.' + elemClass + '[data-waitme_id="' + currentID + '"]').remove();
      }

      if (methods[method]) {
        return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));
      } else if (typeof method === 'object' || ! method) {
        return methods.init.apply(this, arguments);
      }

    });

  };
  $(window).on('load', function(){
    $('body.waitMe_body').addClass('hideMe');
    setTimeout(function(){
      $('body.waitMe_body').find('.waitMe_container:not([data-waitme_id])').remove();
      $('body.waitMe_body').removeClass('waitMe_body hideMe');
    },200);
  });
})(jQuery);
<commit_msg>25.07.16<commit_after>/*
waitMe - 1.16 [25.07.16]
Author: vadimsva
Github: https://github.com/vadimsva/waitMe
*/
(function($) {
  $.fn.waitMe = function(method) {
    return this.each(function() {

      var elem = $(this),
			elemClass = 'waitMe',
			waitMe_text,
			effectObj,
			effectElemCount,
			createSubElem = false,
			specificAttr = 'background-color',
			addStyle = '',
			effectElemHTML = '',
			waitMeObj,
			_options,
			currentID;

      var methods = {
        init : function() {
          var _defaults = {
            effect: 'bounce',
            text: '',
            bg: 'rgba(255,255,255,0.7)',
            color: '#000',
						maxSize: '',
            source: '',
						onClose: function() {}
          };
          _options = $.extend(_defaults, method);

          currentID = new Date().getMilliseconds();
          waitMeObj = $('

');

          switch (_options.effect) {
            case 'none':
              effectElemCount = 0;
              break;
            case 'bounce':
              effectElemCount = 3;
              break;
            case 'rotateplane':
              effectElemCount = 1;
              break;
            case 'stretch':
              effectElemCount = 5;
              break;
            case 'orbit':
              effectElemCount = 2;
              break;
            case 'roundBounce':
              effectElemCount = 12;
              break;
            case 'win8':
              effectElemCount = 5;
              createSubElem = true;
              break;
            case 'win8_linear':
              effectElemCount = 5;
              createSubElem = true;
              break;
            case 'ios':
              effectElemCount = 12;
              break;
            case 'facebook':
              effectElemCount = 3;
              break;
            case 'rotation':
              effectElemCount = 1;
              specificAttr = 'border-color';
              break;
            case 'timer':
              effectElemCount = 2;
							if ($.isArray(_options.color)) {
								var color = _options.color[0];
							} else {
								var color = _options.color;
							}
              addStyle = 'border-color:' + color;
              break;
            case 'pulse':
              effectElemCount = 1;
              specificAttr = 'border-color';
              break;
            case 'progressBar':
              effectElemCount = 1;
              break;
            case 'bouncePulse':
              effectElemCount = 3;
              break;
            case 'img':
              effectElemCount = 1;
              break;
          }

          if (addStyle !== '') {
            addStyle += ';';
          }

          if (effectElemCount > 0) {
            if(_options.effect === 'img') {
							effectElemHTML = '';
            } else {
              for (var i = 1; i <= effectElemCount; ++i) {
								if ($.isArray(_options.color)) {
									var color = _options.color[i];
									if (color == undefined) {
										color = '#000';
									}
								} else {
									var color = _options.color;
								}
                if (createSubElem) {
                  effectElemHTML += '

';
                } else {
                  effectElemHTML += '

';
                }
              }
            }
            effectObj = $('
' + effectElemHTML + '
');
          }

          if (_options.text && _options.maxSize === '') {
						if ($.isArray(_options.color)) {
							var color = _options.color[0];
						} else {
							var color = _options.color;
						}
            waitMe_text = $('
' + _options.text + '
');
          }
					var elemObj = elem.find('> .' + elemClass);

          if (elemObj) {
            elemObj.remove();
          }
          var waitMeDivObj = $('

');
          waitMeDivObj.append(effectObj, waitMe_text);
          waitMeObj.append(waitMeDivObj);
          if (elem[0].tagName == 'HTML') {
            elem = $('body');
          }
          elem.addClass(elemClass + '_container').attr('data-waitme_id', currentID).append(waitMeObj);
					elemObj = elem.find('> .' + elemClass);
					var elemContentObj = elem.find('.' + elemClass + '_content');
          elemObj.css({background: _options.bg});

					if (_options.maxSize !== '') {
						var elemH = effectObj.outerHeight();
						var elemW = effectObj.outerWidth();
						var elemMax = elemH;
						if (_options.effect === 'img') {
							effectObj.css({height: _options.maxSize + 'px'});
							effectObj.find('>img').css({maxHeight: '100%'});
							elemContentObj.css({marginTop: - elemContentObj.outerHeight() / 2 + 'px'});
						} else {
							if (_options.maxSize < elemMax) {
								if (_options.effect == 'stretch') {
									effectObj.css({height:_options.maxSize + 'px'});
									effectObj.find('> div').css({margin: '0 5%'});
								} else {
									waitMeDivObj.css({zoom: _options.maxSize / elemMax - 0.2});
								}

							}
						}
					}
					elemContentObj.css({marginTop: - elemContentObj.outerHeight() / 2 + 'px'});

					function setElTop(getTop) {
						elemContentObj.css({top: 'auto', transform: 'translateY(' + getTop + 'px) translateZ(0)'});
					}
          if (elem.outerHeight() > $(window).height()) {
            var sTop = $(window).scrollTop(),
            elH = elemContentObj.outerHeight(),
            elTop = elem.offset().top,
            cH = elem.outerHeight(),
						getTop = sTop - elTop + $(window).height()/2;
						if (getTop < 0) {
							getTop = Math.abs(getTop);
						}
						if (getTop - elH >= 0 && getTop + elH <= cH) {
							if (elTop - sTop > $(window).height()/2) {
								getTop = elH;
							}
							setElTop(getTop);
						} else {
							if (sTop > elTop + cH - elH) {
								getTop = sTop - elTop - elH;
							} else {
								getTop = sTop - elTop + elH;
							}
							setElTop(getTop);
						}
            $(document).scroll(function() {
              var sTop = $(window).scrollTop(),
              getTop = sTop - elTop + $(window).height()/2;
              if (getTop - elH >= 0 && getTop + elH <= cH) {
								setElTop(getTop);
              }
            });
          }

					elemObj.on('destroyed', function() {
						if (_options.onClose && $.isFunction(_options.onClose)) {
							_options.onClose();
						}
						elemObj.trigger('close');
					});

					$.event.special.destroyed = {
						remove: function(o) {
							if (o.handler) {
								o.handler();
							}
						}
					};

					return elemObj;
        },
        hide : function() {
          waitMeClose();
        }
      };

      function waitMeClose() {
        var currentID = elem.attr('data-waitme_id');
        elem.removeClass(elemClass + '_container').removeAttr('data-waitme_id');
        elem.find('.' + elemClass + '[data-waitme_id="' + currentID + '"]').remove();
      }

      if (methods[method]) {
        return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));
      } else if (typeof method === 'object' || ! method) {
        return methods.init.apply(this, arguments);
      }

    });

  };
  $(window).on('load', function(){
    $('body.waitMe_body').addClass('hideMe');
    setTimeout(function(){
      $('body.waitMe_body').find('.waitMe_container:not([data-waitme_id])').remove();
      $('body.waitMe_body').removeClass('waitMe_body hideMe');
    },200);
  });
})(jQuery);
<|endoftext|>


<commit_before>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var assert = require('assert');

/**
 * Testing data
 */

var fixture = require('./fixture');

describe('wpcom.site.tag', function(){
  // Global instances
  var wpcom = WPCOM(fixture.site.token);
  var site = wpcom.site(fixture.site.url);
  var new_tag;

  // Create a testing_tag before to start tests
  var testing_tag;
  before(function(done){
    site.tag()
    .add(fixture.tag, function(err, tag) {
      if (err) throw err;

      testing_tag = tag;
      done();
    });
  });

  // Delete testing tag
  after(function(done){
    site.tag(testing_tag.slug)
    .delete(function(err, tag) {
      if (err) throw err;

      done();
    });
  });

  describe('wpcom.site.tag.get', function(){
    it('should get added tag', function(done){
      var cat = site.tag(testing_tag.slug);

      cat.get(function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');
        assert.equal(testing_tag.slug, data.slug);
        assert.equal(testing_tag.name, data.name);
        done();
      });
    });
  });

  describe('wpcom.site.tag.add', function(){
    it('should add a new tag', function(done){
      var tag = site.tag();
      fixture.tag.name += '-added';

      tag.add(fixture.tag, function(err, data){
        if (err) throw err;

        // checking some data date
        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');

        // store added catogory
        new_tag = data;

        done();
      });
    });
  });

  describe('wpcom.site.tag.update', function(){
    it('should edit the new added tag', function(done){
      var tag = site.tag(new_tag.slug);
      var edited_name = fixture.tag.name + '-updated';

      tag.update({ name: edited_name }, function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.equal(edited_name, data.name);

        // update added tag
        new_tag = data;

        done();
      });
    });
  });

  describe('wpcom.site.tag.delete', function() {
    it('should delete the new added tag', function(done) {
      var cat = site.tag(new_tag.slug);

      cat.delete(function(err, data) {
        if (err) throw err;

        assert.ok(data);
        assert.equal("true", data.success);
        assert.equal(new_tag.slug, data.slug);

        done();
      });
    });
  });

});<commit_msg>test: add random number to tag name<commit_after>
/**
 * WPCOM module
 */

var WPCOM = require('../');
var assert = require('assert');

/**
 * Testing data
 */

var fixture = require('./fixture');

describe('wpcom.site.tag', function(){
  // Global instances
  var wpcom = WPCOM(fixture.site.token);
  var site = wpcom.site(fixture.site.url);
  var new_tag;

  // Create a testing_tag before to start tests
  var testing_tag;
  before(function(done){
    fixture.tag.name += Math.random() * 1000000 | 0;
    site.tag()
    .add(fixture.tag, function(err, tag) {
      if (err) throw err;

      testing_tag = tag;
      done();
    });
  });

  // Delete testing tag
  after(function(done){
    site.tag(testing_tag.slug)
    .delete(function(err, tag) {
      if (err) throw err;

      done();
    });
  });

  describe('wpcom.site.tag.get', function(){
    it('should get added tag', function(done){
      var cat = site.tag(testing_tag.slug);

      cat.get(function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');
        assert.equal(testing_tag.slug, data.slug);
        assert.equal(testing_tag.name, data.name);
        done();
      });
    });
  });

  describe('wpcom.site.tag.add', function(){
    it('should add a new tag', function(done){
      var tag = site.tag();
      fixture.tag.name += '-added';

      tag.add(fixture.tag, function(err, data){
        if (err) throw err;

        // checking some data date
        assert.ok(data);
        assert.ok(data instanceof Object, 'data is not an object');

        // store added catogory
        new_tag = data;

        done();
      });
    });
  });

  describe('wpcom.site.tag.update', function(){
    it('should edit the new added tag', function(done){
      var tag = site.tag(new_tag.slug);
      var edited_name = fixture.tag.name + '-updated';

      tag.update({ name: edited_name }, function(err, data){
        if (err) throw err;

        assert.ok(data);
        assert.equal(edited_name, data.name);

        // update added tag
        new_tag = data;

        done();
      });
    });
  });

  describe('wpcom.site.tag.delete', function() {
    it('should delete the new added tag', function(done) {
      var cat = site.tag(new_tag.slug);

      cat.delete(function(err, data) {
        if (err) throw err;

        assert.ok(data);
        assert.equal("true", data.success);
        assert.equal(new_tag.slug, data.slug);

        done();
      });
    });
  });

});<|endoftext|>


<commit_before>(function(){

  var angularJsUrl;
  var scripts = document.getElementsByTagName("script");
  var angularJsRegex = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/;
  for(var j = 0; j < scripts.length; j++) {
    var src = scripts[j].src;
    if (src && src.match(angularJsRegex)) {
      angularJsUrl = src.replace('docs.angularjs.org', 'code.angularjs.org');
      continue;
    }
  }

  var HTML_TEMPLATE =
  '<!doctype html>\n' +
  '\n' +
  ' \n' +
  ' \n' +
  '_HTML_SOURCE_\n' +
  ' \n' +
  '';

  angular.widget('doc:example', function(element){
    this.descend(true); //compile the example code
    element.hide();

    var example = element.find('pre.doc-source').eq(0),
        exampleSrc = example.text(),
        scenario = element.find('pre.doc-scenario').eq(0);

    var code = indent(exampleSrc);
    var tabHtml =
      '
' +
        '

Source

' +
        '
' +
          '

' +
        '

Live Preview

' +
        '
' + exampleSrc +'
';
    if (scenario.text()) {
      tabHtml +=
        '

Scenario Test

' +
        '

' + scenario.text() + '

';
    }
    tabHtml +=
      '
';
    var tabs = angular.element(tabHtml);

    tabs.find('li.doc-example-source > pre').text(HTML_TEMPLATE.replace('_HTML_SOURCE_', code.html));

    element.html('');
    element.append(tabs);
    element.show();

    var script = (exampleSrc.match(/\n' +
  ' \n' +
  '_HTML_SOURCE_\n' +
  ' \n' +
  '';

  angular.widget('doc:example', function(element){
    this.descend(true); //compile the example code
    element.hide();

    var example = element.find('pre.doc-source').eq(0),
        exampleSrc = example.text(),
        scenario = element.find('pre.doc-scenario').eq(0);

    var code = indent(exampleSrc);
    var tabHtml =
      '
' +
        '

Source

' +
        '
' +
          '

' +
        '

Live Preview

' +
        '
' + exampleSrc +'
';
    if (scenario.text()) {
      tabHtml +=
        '

Scenario Test

' +
        '

' + scenario.text() + '

';
    }
    tabHtml +=
      '
';
    var tabs = angular.element(tabHtml);

    tabs.find('li.doc-example-source > pre').text(HTML_TEMPLATE.replace('_HTML_SOURCE_', code.html));

    element.html('');
    element.append(tabs);
    element.show();

    var script = (exampleSrc.match(/


<commit_before>'use strict';

const path                    = require('path');
const webpack                 = require('webpack');
const MiniCssExtractPlugin    = require("mini-css-extract-plugin");
const TSConfigPathsPlugin     = require('tsconfig-paths-webpack-plugin');
const TSLintPlugin            = require('tslint-webpack-plugin');
const { CleanWebpackPlugin }  = require('clean-webpack-plugin');

const SOURCE_ROOT = __dirname + '/src/main/webpack';

module.exports = {
        resolve: {
            extensions: ['js', '.ts'],
            plugins: [new TSConfigPathsPlugin({
                configFile: "./tsconfig.json"
            })]
        },
        entry: {
            site: SOURCE_ROOT + '/site/main.ts',
            dependencies: SOURCE_ROOT + '/site/vendors.js'
        },
        output: {
            filename: (chunkData) => {
                return chunkData.chunk.name === 'dependencies' ? 'clientlib-dependencies/[name].js' : 'clientlib-site/[name].js';
            },
            path: path.resolve(__dirname, 'dist')
        },
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    exclude: [
                        /(node_modules)/
                    ],
                    use: [
                        {
                            loader: "ts-loader"
                        },
                        {
                            loader: "webpack-import-glob-loader",
                            options: {
                                url: false
                            }
                        }
                    ]
                },
                {
                    test: /\.scss$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: "css-loader",
                            options: {
                                url: false
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins() {
                                    return [
                                        require('autoprefixer')
                                    ];
                                }
                            }
                        },
                        {
                            loader: "sass-loader",
                            options: {
                                url: false
                            }
                        },
                        {
                            loader: "webpack-import-glob-loader",
                            options: {
                                url: false
                            }
                        }
                    ]
                }
            ]
        },
        plugins: [
            new CleanWebpackPlugin(),
            new webpack.NoEmitOnErrorsPlugin(),
            new MiniCssExtractPlugin({
                filename: 'clientlib-[name]/[name].css'
            }),
            new TSLintPlugin({
                files: ['./**/components/**/*.ts', './**/components/**/*.tsx']
            })
        ],
        stats: {
            assetsSort: "chunks",
            builtAt: true,
            children: false,
            chunkGroups: true,
            chunkOrigins: true,
            colors: false,
            errors: true,
            errorDetails: true,
            env: true,
            modules: false,
            performance: true,
            providedExports: false,
            source: false,
            warnings: true
        }
};
<commit_msg>changed 'js' to '.js' in resolve (#227)<commit_after>'use strict';

const path                    = require('path');
const webpack                 = require('webpack');
const MiniCssExtractPlugin    = require("mini-css-extract-plugin");
const TSConfigPathsPlugin     = require('tsconfig-paths-webpack-plugin');
const TSLintPlugin            = require('tslint-webpack-plugin');
const { CleanWebpackPlugin }  = require('clean-webpack-plugin');

const SOURCE_ROOT = __dirname + '/src/main/webpack';

module.exports = {
        resolve: {
            extensions: ['.js', '.ts'],
            plugins: [new TSConfigPathsPlugin({
                configFile: "./tsconfig.json"
            })]
        },
        entry: {
            site: SOURCE_ROOT + '/site/main.ts',
            dependencies: SOURCE_ROOT + '/site/vendors.js'
        },
        output: {
            filename: (chunkData) => {
                return chunkData.chunk.name === 'dependencies' ? 'clientlib-dependencies/[name].js' : 'clientlib-site/[name].js';
            },
            path: path.resolve(__dirname, 'dist')
        },
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    exclude: [
                        /(node_modules)/
                    ],
                    use: [
                        {
                            loader: "ts-loader"
                        },
                        {
                            loader: "webpack-import-glob-loader",
                            options: {
                                url: false
                            }
                        }
                    ]
                },
                {
                    test: /\.scss$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: "css-loader",
                            options: {
                                url: false
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins() {
                                    return [
                                        require('autoprefixer')
                                    ];
                                }
                            }
                        },
                        {
                            loader: "sass-loader",
                            options: {
                                url: false
                            }
                        },
                        {
                            loader: "webpack-import-glob-loader",
                            options: {
                                url: false
                            }
                        }
                    ]
                }
            ]
        },
        plugins: [
            new CleanWebpackPlugin(),
            new webpack.NoEmitOnErrorsPlugin(),
            new MiniCssExtractPlugin({
                filename: 'clientlib-[name]/[name].css'
            }),
            new TSLintPlugin({
                files: ['./**/components/**/*.ts', './**/components/**/*.tsx']
            })
        ],
        stats: {
            assetsSort: "chunks",
            builtAt: true,
            children: false,
            chunkGroups: true,
            chunkOrigins: true,
            colors: false,
            errors: true,
            errorDetails: true,
            env: true,
            modules: false,
            performance: true,
            providedExports: false,
            source: false,
            warnings: true
        }
};
<|endoftext|>


<commit_before>require([
    './dist/akqa-core/utils'
],
function (CoreUtils) {

    var Utils = function (options) {
        return this;
    };

    Utils.prototype = {

        addClass: function  (el, className) {

        },

        removeClass: function (el, className) {

        },

        isIE8: function () {
            var rv = -1;
            var ua = navigator.userAgent;
            var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null) {
                rv = parseFloat(RegExp.$1);
            }
            return (rv == 4);
        }

    };

    return Utils;
});
<commit_msg>Updated build folder to latest<commit_after>define([
    'core-modules/core/utils'
],
function (CoreUtils) {

    var Utils = {

        /**
         * Adds a CSS class to an element.
         * @param {HTMLElement} el - The element to add a class to.
         * @param {string} className - The css class value to add
         */
        addClass: function  (el, className) {
            if (!this.hasClass(el, className)) {
                el.className = el.className + ' ' + className;
            }
        },

        /**
         * Remvoes a CSS class from an element.
         * @param {HTMLElement} el - The element to remove class from.
         * @param {string} className - The css class value to remove
         */
        removeClass: function (el, className) {
            if (this.hasClass(el, className)) {
                el.className = el.className.replace(className, '');
            }
        },

        /**
         * Checks if an element has a class.
         * @param {HTMLElement} el - The element to check.
         * @param {string} className - The css class value to check
         */
        hasClass: function (el, className) {
            return el.className.indexOf(className) !== -1;
        },

        /**
         * Creates an HTML Element from an html string.
         * @param {string} html - String of html
         * @returns {HTMLElement} - Returns and html element node
         */
        createHtmlElement: function (html) {
            var tempParentEl;
            if (html) {
                tempParentEl = document.createElement('div');
                tempParentEl.innerHTML = html;
                return tempParentEl.childNodes[1];
            }
        },

        /**
         * Gets a simplified mapping of all attributes of an element.
         * @param {HTMLElement} el - The element containing attributes
         * @returns {object} - Returns an object containing all attribute mappings
         */
        getElementAttrMap: function (el) {
            var attrs = el.attributes,
                map = {};
            if (attrs.length) {
                for (var i = 0; i < attrs.length; i++) {
                    map[attrs[i].name] = attrs[i].value;
                }
            }
            return map;
        },

        /**
         * Checks if browser is IE 8.
         * @returns {boolean} Returns true if the current browser is IE 8.
         */
        isIE8: function () {
            var rv = -1;
            var ua = navigator.userAgent;
            var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null) {
                rv = parseFloat(RegExp.$1);
            }
            return (rv == 4);
        }

    };

    return Utils;
});
<|endoftext|>


<commit_before>var Handlebars = {
  compile: function(string) {
    var fnBody = Handlebars.compileFunctionBody(string);
    var fn = new Function("context", "fallback", "Handlebars", fnBody);
    return function(context, fallback) { return fn(context, fallback, Handlebars); };
  },

  compileToString: function(string) {
    var fnBody = Handlebars.compileFunctionBody(string);
    return "function(context, fallback) { " + fnBody + "}";
  },

  compileFunctionBody: function(string) {
    var compiler = new Handlebars.Compiler(string);
    compiler.compile();

    return "fallback = fallback || {}; var stack = [];" + compiler.fn;
  },

  isFunction: function(fn) {
    return Object.prototype.toString.call(fn) == "[object Function]";
  },

  escapeText: function(string) {
    string = string.replace(/'/g, "\\'");
    string = string.replace(/\"/g, "\\\"");
    if (string.slice(-1) == "\\") {
      string = string + "\\";
    }

    return string;
  },

  escapeExpression: function(string) {
    // don't escape SafeStrings, since they're already safe
    if (string instanceof Handlebars.SafeString) {
      return string.toString();
    }
    else if (string === null) {
      string = "";
    }

    return string.toString().replace(/&(?!\w+;)|["\\<>]/g, function(str) {
      switch(str) {
        case "&":
          return "&";
          break;
        case '"':
          return "\"";
        case "\\":
          return "\\\\";
          break;
        case "<":
          return "<";
          break;
        case ">":
          return ">";
          break;
        default:
          return str;
      }
    });
  },

  compiledPartials: {},
  compilePartial: function(partial) {
    var compiled = Handlebars.compiledPartials[partial];

    if (compiled == null) {
      if (Handlebars.isFunction(partial)) {
        compiled = partial;
      } else {
        compiled = Handlebars.compile(partial);
      }
      Handlebars.compiledPartials[partial] = compiled;
    }

    return compiled;
  },

  buildContext: function(context, stack) {
    var contextWrapper = function(stack) {
      this.__stack__ = stack;
      this.__get__ = function(path) {
        var context = this;
        var parsedPath = Handlebars.parsePath(path);
        var depth = parsedPath[0];
        var parts = parsedPath[1];
        if (depth > 0) {
          context = this.__stack__[stack.length - depth];
        }

        for (var i = 0; i < parts.length; i++) {
          context = context[parts[i]];
        }

        return context;
      };
    };

    contextWrapper.prototype = context;
    return new contextWrapper(stack);
  },

  // Returns a two element array containing the numbers of contexts to back up the stack and
  // the properties to dig into on the current context
  //
  // For example, if the path is "../../alan/name", the result will be [2, ["alan", "name"]].
  parsePath: function(path) {
    if (path == null) {
      return [0, []];
    }

    var parts = path.split("/");
    var readDepth = false;
    var depth = 0;
    var dig = [];
    for (var i = 0, j = parts.length; i < j; i++) {
      switch(parts[i]) {
        case "..":
          if (readDepth) {
            throw new Handlebars.Exception("Cannot jump out of context after moving into a context.");
          } else {
            depth += 1;
          }
          break;
        case ".":
          // do nothing - using .'s is pretty dumb, but it's also basically free for us to support
        case "this":
          // if we do nothing you'll end up sticking in the same context
          break;
        default:
          readDepth = true;
          dig.push(parts[i]);
      }
    }

    return [depth, dig];
  },

  isEmpty: function(value) {
    if (typeof value === "undefined") {
      return true;
    } else if (!value) {
      return true;
    } else if(Object.prototype.toString.call(value) === "[object Array]" && value.length == 0) {
      return true;
    } else {
      return false;
    }
  },

  // Escapes output and converts empty values to empty strings
  filterOutput: function(value, escape) {

    if (Handlebars.isEmpty(value)) {
      return "";
    } else if (escape) {
      return Handlebars.escapeExpression(value);
    } else {
      return value;
    }
  }
}

Handlebars.Compiler = function(string) {
  this.string   = string;
  this.pointer  = -1;
  this.mustache = false;
  this.text     = "";
  this.fn       = "var out = ''; var lookup; ";
  this.newlines = "";
  this.comment  = false;
  this.escaped = true;
  this.partial = false;
  this.inverted = false;
  this.endCondition = null;
  this.continueInverted = false;
};

Handlebars.Exception = function(message) {
  this.message = message;
};

// Build out our basic SafeString type
Handlebars.SafeString = function(string) {
  this.string = string;
}
Handlebars.SafeString.prototype.toString = function() {
  return this.string.toString();
}

Handlebars.helperMissing = function(object, fn) {
  var ret = "";

  if(object === true) {
    return fn(this);
  } else if(object === false) {
    return "";
  } else if(Object.prototype.toString.call(object) === "[object Array]") {
    for(var i=0, j=object.length; i<j; i++) {
      ret = ret + fn(object[i]);
    }
    return ret;
  } else {
		return fn(object);
	}
};

Handlebars.Compiler.prototype = {
  getChar: function(n) {
    var ret = this.peek(n);
    this.pointer = this.pointer + (n || 1);
    return ret;
  },

  peek: function(n) {
    n = n || 1;
    var start = this.pointer + 1;
    return this.string.slice(start, start + n);
  },

  compile: function(endCondition) {
    var chr;
    while(chr = this.getChar()) {
      if(chr === "{" && this.peek() === "{" && !this.mustache) {
        this.getChar();
        this.parseMustache();

      } else {
        if(chr === "\n") {
          this.newlines = this.newlines + "\n";
          chr = "\\n";
        } else if (chr === "\r") {
          this.newlines = this.newlines + "\r";
          chr = "\\r";
        }
        this.text = this.text + chr;
      }

      if (endCondition && this.peek(5) == "{{^}}") {
        this.continueInverted = true;
        this.getChar(5);
        break;
      }
      else if(endCondition && endCondition(this)) { break };
    }

    this.addText();
    this.fn += "return out;";

    return;
  },

  addText: function() {
    if(this.text) {
      this.fn       = this.fn + "out = out + \"" + Handlebars.escapeText(this.text) + "\"; ";
      this.fn       = this.fn + this.newlines;
      this.newlines = "";
      this.text     = "";
    }
  },

  addExpression: function(mustache, param) {
    var expr = this.lookupFor(mustache);
    this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + Handlebars.filterOutput(" + expr + ".call(Handlebars.buildContext(context, stack), " + param + "), " + this.escaped + "); ";
    this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + Handlebars.filterOutput(" + expr + ", " + this.escaped + "); ";
  },

  addInvertedSection: function(mustache) {
    var compiler = this.compileToEndOfBlock(mustache);
    var result = compiler.fn;

    // each function made internally needs a unique IDs. These are locals, so they
    // don't need to be globally unique, just per compiler
    var fnId = "fn" + this.pointer.toString();
    this.fn += "var " + fnId + " = function(context) {" + result + "}; ";
    this.fn += "lookup = " + this.lookupFor(mustache) + "; ";
    this.fn += "if(Handlebars.isFunction(lookup) && Handlebars.isEmpty(lookup())) out = out + " + fnId + "(context);";
    this.fn += "else if (Handlebars.isEmpty(lookup)) out = out + " + fnId + "(context);";

    this.openBlock = false;
    this.inverted = false;
  },

  lookupFor: function(param) {
    var parsed = Handlebars.parsePath(param);
    var depth = parsed[0];
    var parts = parsed[1];

    var paramExpr = "";
    for(var i = 0; i < parts.length; i++) {
      paramExpr += "['" + parts[i] + "']";
    }

    if (depth > 0) {
      return "( stack[stack.length - " + depth + "]" + paramExpr + ")";
    } else {
      return "( context" + paramExpr + " || fallback" + paramExpr + " )";
    }
  },

  compileToEndOfBlock: function(mustache) {
    var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1));

    // sub-compile with a custom EOF instruction
    compiler.compile(function(compiler) {
      if(compiler.peek(mustache.length + 5) === "{{/" + mustache + "}}") {
        compiler.getChar(mustache.length + 5);
        return true;
      }
    });

    // move the pointer forward the amount of characters handled by the sub-compiler
    this.pointer += compiler.pointer + 1;

    return compiler;
  },

  addBlock: function(mustache, param, parts) {
    // set up the stack before the new compiler starts
    this.fn += "stack.push(context);";
    var compiler = this.compileToEndOfBlock(mustache);
    var result = compiler.fn;

    // each function made internally needs a unique IDs. These are locals, so they
    // don't need to be globally unique, just per compiler
    var fnId = "fn" + this.pointer.toString();
    this.fn += "var proxy = Handlebars.buildContext(" + param + ", stack);";
    this.fn += "var wrappedContext = Handlebars.buildContext(context);";
    this.fn += "var " + fnId + " = function(context) {" + result + "}; ";
    this.fn += "lookup = " + this.lookupFor(mustache) + "; ";
    this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(wrappedContext, proxy, " + fnId + "); ";
    this.fn += "else if(typeof lookup !== 'undefined') { out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); }";

    if (compiler.continueInverted) {
      var invertedCompiler = this.compileToEndOfBlock(mustache);
      this.fn += "if (Handlebars.isFunction(lookup.not)) {";
      this.fn += "  var " + fnId + "Not = function(context) { " + invertedCompiler.fn + " };";
      this.fn += "  out = out + lookup.not.call(wrappedContext, proxy, " + fnId + "Not);";
      this.fn += "}";
    }

    this.fn += "stack.pop();";
    this.openBlock = false;
  },

  addPartial: function(mustache, param) {
    // either used a cached copy of the partial or compile a new one
    this.fn += "if (typeof fallback['partials'] === 'undefined' || typeof fallback['partials']['" + mustache + "'] === 'undefined') throw new Handlebars.Exception('Attempted to render undefined partial: " + mustache + "');";
    this.fn += "out = out + Handlebars.compilePartial(fallback['partials']['" + mustache + "'])(" + param + ", fallback);";
  },

  parseMustache: function() {
    var chr, part, mustache, param;

    var next = this.peek();

    if(next === "!") {
      this.comment = true;
      this.getChar();
    } else if(next === "#") {
      this.openBlock = true;
      this.getChar();
    } else if (next === ">") {
      this.partial = true;
      this.getChar();
    } else if (next === "^") {
      this.inverted = true;
      this.openBlock = true;
      this.getChar();
    } else if(next === "{" || next === "&") {
      this.escaped = false;
      this.getChar();
    }

    this.addText();
    this.mustache = " ";

    while(chr = this.getChar()) {
      if(this.mustache && chr === "}" && this.peek() === "}") {
        var parts = this.mustache.trim().split(/\s+/);
        mustache  = parts[0];
        param     = this.lookupFor(parts[1]);

        this.mustache = false;

        // finish reading off the close of the handlebars
        this.getChar();
        // {{{expression}} is techically valid, but if we started with {{{ we'll try to read
        // }}} off of the close of the handlebars
        if (!this.escaped && this.peek() === "}") {
          this.getChar();
        }

        if(this.comment) {
          this.comment = false;
          return;
        } else if (this.partial) {
          this.addPartial(mustache, param)
          return;
        } else if (this.inverted) {
          this.addInvertedSection(mustache);
          return;
        } else if(this.openBlock) {
          this.addBlock(mustache, param, parts)
          return;
        } else {
          return this.addExpression(mustache, param);
        }

        this.escaped = true;
      } else if(this.comment) {
        ;
      } else {
        this.mustache = this.mustache + chr;
      }
    }
  }
};

// CommonJS Exports
var exports = exports || {};
exports['compile'] = Handlebars.compile;
exports['compileToString'] = Handlebars.compileToString;
<commit_msg>Added Handlebars.trim for IE compatibility.<commit_after>var Handlebars = {
  compile: function(string) {
    var fnBody = Handlebars.compileFunctionBody(string);
    var fn = new Function("context", "fallback", "Handlebars", fnBody);
    return function(context, fallback) { return fn(context, fallback, Handlebars); };
  },

  compileToString: function(string) {
    var fnBody = Handlebars.compileFunctionBody(string);
    return "function(context, fallback) { " + fnBody + "}";
  },

  compileFunctionBody: function(string) {
    var compiler = new Handlebars.Compiler(string);
    compiler.compile();

    return "fallback = fallback || {}; var stack = [];" + compiler.fn;
  },

  isFunction: function(fn) {
    return Object.prototype.toString.call(fn) == "[object Function]";
  },

  trim: function(str) {
    return str.replace(/^\s+|\s+$/g, '');
  },

  escapeText: function(string) {
    string = string.replace(/'/g, "\\'");
    string = string.replace(/\"/g, "\\\"");
    if (string.slice(-1) == "\\") {
      string = string + "\\";
    }

    return string;
  },

  escapeExpression: function(string) {
    // don't escape SafeStrings, since they're already safe
    if (string instanceof Handlebars.SafeString) {
      return string.toString();
    }
    else if (string === null) {
      string = "";
    }

    return string.toString().replace(/&(?!\w+;)|["\\<>]/g, function(str) {
      switch(str) {
        case "&":
          return "&";
          break;
        case '"':
          return "\"";
        case "\\":
          return "\\\\";
          break;
        case "<":
          return "<";
          break;
        case ">":
          return ">";
          break;
        default:
          return str;
      }
    });
  },

  compiledPartials: {},
  compilePartial: function(partial) {
    var compiled = Handlebars.compiledPartials[partial];

    if (compiled == null) {
      if (Handlebars.isFunction(partial)) {
        compiled = partial;
      } else {
        compiled = Handlebars.compile(partial);
      }
      Handlebars.compiledPartials[partial] = compiled;
    }

    return compiled;
  },

  buildContext: function(context, stack) {
    var contextWrapper = function(stack) {
      this.__stack__ = stack;
      this.__get__ = function(path) {
        var context = this;
        var parsedPath = Handlebars.parsePath(path);
        var depth = parsedPath[0];
        var parts = parsedPath[1];
        if (depth > 0) {
          context = this.__stack__[stack.length - depth];
        }

        for (var i = 0; i < parts.length; i++) {
          context = context[parts[i]];
        }

        return context;
      };
    };

    contextWrapper.prototype = context;
    return new contextWrapper(stack);
  },

  // Returns a two element array containing the numbers of contexts to back up the stack and
  // the properties to dig into on the current context
  //
  // For example, if the path is "../../alan/name", the result will be [2, ["alan", "name"]].
  parsePath: function(path) {
    if (path == null) {
      return [0, []];
    }

    var parts = path.split("/");
    var readDepth = false;
    var depth = 0;
    var dig = [];
    for (var i = 0, j = parts.length; i < j; i++) {
      switch(parts[i]) {
        case "..":
          if (readDepth) {
            throw new Handlebars.Exception("Cannot jump out of context after moving into a context.");
          } else {
            depth += 1;
          }
          break;
        case ".":
          // do nothing - using .'s is pretty dumb, but it's also basically free for us to support
        case "this":
          // if we do nothing you'll end up sticking in the same context
          break;
        default:
          readDepth = true;
          dig.push(parts[i]);
      }
    }

    return [depth, dig];
  },

  isEmpty: function(value) {
    if (typeof value === "undefined") {
      return true;
    } else if (!value) {
      return true;
    } else if(Object.prototype.toString.call(value) === "[object Array]" && value.length == 0) {
      return true;
    } else {
      return false;
    }
  },

  // Escapes output and converts empty values to empty strings
  filterOutput: function(value, escape) {

    if (Handlebars.isEmpty(value)) {
      return "";
    } else if (escape) {
      return Handlebars.escapeExpression(value);
    } else {
      return value;
    }
  }
}

Handlebars.Compiler = function(string) {
  this.string   = string;
  this.pointer  = -1;
  this.mustache = false;
  this.text     = "";
  this.fn       = "var out = ''; var lookup; ";
  this.newlines = "";
  this.comment  = false;
  this.escaped = true;
  this.partial = false;
  this.inverted = false;
  this.endCondition = null;
  this.continueInverted = false;
};

Handlebars.Exception = function(message) {
  this.message = message;
};

// Build out our basic SafeString type
Handlebars.SafeString = function(string) {
  this.string = string;
}
Handlebars.SafeString.prototype.toString = function() {
  return this.string.toString();
}

Handlebars.helperMissing = function(object, fn) {
  var ret = "";

  if(object === true) {
    return fn(this);
  } else if(object === false) {
    return "";
  } else if(Object.prototype.toString.call(object) === "[object Array]") {
    for(var i=0, j=object.length; i<j; i++) {
      ret = ret + fn(object[i]);
    }
    return ret;
  } else {
		return fn(object);
	}
};

Handlebars.Compiler.prototype = {
  getChar: function(n) {
    var ret = this.peek(n);
    this.pointer = this.pointer + (n || 1);
    return ret;
  },

  peek: function(n) {
    n = n || 1;
    var start = this.pointer + 1;
    return this.string.slice(start, start + n);
  },

  compile: function(endCondition) {
    var chr;
    while(chr = this.getChar()) {
      if(chr === "{" && this.peek() === "{" && !this.mustache) {
        this.getChar();
        this.parseMustache();

      } else {
        if(chr === "\n") {
          this.newlines = this.newlines + "\n";
          chr = "\\n";
        } else if (chr === "\r") {
          this.newlines = this.newlines + "\r";
          chr = "\\r";
        }
        this.text = this.text + chr;
      }

      if (endCondition && this.peek(5) == "{{^}}") {
        this.continueInverted = true;
        this.getChar(5);
        break;
      }
      else if(endCondition && endCondition(this)) { break };
    }

    this.addText();
    this.fn += "return out;";

    return;
  },

  addText: function() {
    if(this.text) {
      this.fn       = this.fn + "out = out + \"" + Handlebars.escapeText(this.text) + "\"; ";
      this.fn       = this.fn + this.newlines;
      this.newlines = "";
      this.text     = "";
    }
  },

  addExpression: function(mustache, param) {
    var expr = this.lookupFor(mustache);
    this.fn += "if (Handlebars.isFunction(" + expr + ")) out = out + Handlebars.filterOutput(" + expr + ".call(Handlebars.buildContext(context, stack), " + param + "), " + this.escaped + "); ";
    this.fn += "else if(typeof " + expr + "!== 'undefined') out = out + Handlebars.filterOutput(" + expr + ", " + this.escaped + "); ";
  },

  addInvertedSection: function(mustache) {
    var compiler = this.compileToEndOfBlock(mustache);
    var result = compiler.fn;

    // each function made internally needs a unique IDs. These are locals, so they
    // don't need to be globally unique, just per compiler
    var fnId = "fn" + this.pointer.toString();
    this.fn += "var " + fnId + " = function(context) {" + result + "}; ";
    this.fn += "lookup = " + this.lookupFor(mustache) + "; ";
    this.fn += "if(Handlebars.isFunction(lookup) && Handlebars.isEmpty(lookup())) out = out + " + fnId + "(context);";
    this.fn += "else if (Handlebars.isEmpty(lookup)) out = out + " + fnId + "(context);";

    this.openBlock = false;
    this.inverted = false;
  },

  lookupFor: function(param) {
    var parsed = Handlebars.parsePath(param);
    var depth = parsed[0];
    var parts = parsed[1];

    var paramExpr = "";
    for(var i = 0; i < parts.length; i++) {
      paramExpr += "['" + parts[i] + "']";
    }

    if (depth > 0) {
      return "( stack[stack.length - " + depth + "]" + paramExpr + ")";
    } else {
      return "( context" + paramExpr + " || fallback" + paramExpr + " )";
    }
  },

  compileToEndOfBlock: function(mustache) {
    var compiler = new Handlebars.Compiler(this.string.slice(this.pointer + 1, -1));

    // sub-compile with a custom EOF instruction
    compiler.compile(function(compiler) {
      if(compiler.peek(mustache.length + 5) === "{{/" + mustache + "}}") {
        compiler.getChar(mustache.length + 5);
        return true;
      }
    });

    // move the pointer forward the amount of characters handled by the sub-compiler
    this.pointer += compiler.pointer + 1;

    return compiler;
  },

  addBlock: function(mustache, param, parts) {
    // set up the stack before the new compiler starts
    this.fn += "stack.push(context);";
    var compiler = this.compileToEndOfBlock(mustache);
    var result = compiler.fn;

    // each function made internally needs a unique IDs. These are locals, so they
    // don't need to be globally unique, just per compiler
    var fnId = "fn" + this.pointer.toString();
    this.fn += "var proxy = Handlebars.buildContext(" + param + ", stack);";
    this.fn += "var wrappedContext = Handlebars.buildContext(context);";
    this.fn += "var " + fnId + " = function(context) {" + result + "}; ";
    this.fn += "lookup = " + this.lookupFor(mustache) + "; ";
    this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(wrappedContext, proxy, " + fnId + "); ";
    this.fn += "else if(typeof lookup !== 'undefined') { out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); }";

    if (compiler.continueInverted) {
      var invertedCompiler = this.compileToEndOfBlock(mustache);
      this.fn += "if (Handlebars.isFunction(lookup.not)) {";
      this.fn += "  var " + fnId + "Not = function(context) { " + invertedCompiler.fn + " };";
      this.fn += "  out = out + lookup.not.call(wrappedContext, proxy, " + fnId + "Not);";
      this.fn += "}";
    }

    this.fn += "stack.pop();";
    this.openBlock = false;
  },

  addPartial: function(mustache, param) {
    // either used a cached copy of the partial or compile a new one
    this.fn += "if (typeof fallback['partials'] === 'undefined' || typeof fallback['partials']['" + mustache + "'] === 'undefined') throw new Handlebars.Exception('Attempted to render undefined partial: " + mustache + "');";
    this.fn += "out = out + Handlebars.compilePartial(fallback['partials']['" + mustache + "'])(" + param + ", fallback);";
  },

  parseMustache: function() {
    var chr, part, mustache, param;

    var next = this.peek();

    if(next === "!") {
      this.comment = true;
      this.getChar();
    } else if(next === "#") {
      this.openBlock = true;
      this.getChar();
    } else if (next === ">") {
      this.partial = true;
      this.getChar();
    } else if (next === "^") {
      this.inverted = true;
      this.openBlock = true;
      this.getChar();
    } else if(next === "{" || next === "&") {
      this.escaped = false;
      this.getChar();
    }

    this.addText();
    this.mustache = " ";

    while(chr = this.getChar()) {
      if(this.mustache && chr === "}" && this.peek() === "}") {
        var parts = Handlebars.trim(this.mustache).split(/\s+/);
        mustache  = parts[0];
        param     = this.lookupFor(parts[1]);

        this.mustache = false;

        // finish reading off the close of the handlebars
        this.getChar();
        // {{{expression}} is techically valid, but if we started with {{{ we'll try to read
        // }}} off of the close of the handlebars
        if (!this.escaped && this.peek() === "}") {
          this.getChar();
        }

        if(this.comment) {
          this.comment = false;
          return;
        } else if (this.partial) {
          this.addPartial(mustache, param)
          return;
        } else if (this.inverted) {
          this.addInvertedSection(mustache);
          return;
        } else if(this.openBlock) {
          this.addBlock(mustache, param, parts)
          return;
        } else {
          return this.addExpression(mustache, param);
        }

        this.escaped = true;
      } else if(this.comment) {
        ;
      } else {
        this.mustache = this.mustache + chr;
      }
    }
  }
};

// CommonJS Exports
var exports = exports || {};
exports['compile'] = Handlebars.compile;
exports['compileToString'] = Handlebars.compileToString;
<|endoftext|>