<commit_before>//
//     nodemavens
//     Copyright(c) 2014 Matt Hernandez <matt@modulus.io>
//     MIT Licensed
//

module.exports = function(app, controller) {
  var blacklist = JSON.parse(process.env.BLACKLIST || '[]');

  //
  // Disallow blacklisted IPs and verify the session count.
  //
  app.all('/*', function(req, res, next) {
    if ('POST' === req.method) {

      if (!req.headers['x-forwarded-for']) {
        res.statusCode = 500;
        return res.json();
      }

      var ips = req.headers['x-forwarded-for'].split(',')
        , ua  = req.headers['user-agent'];

      console.log(new Date().toString(), ips);

      var blocked = blacklist.some(function(ip) {
        return ips.indexOf(ip) >= 0;
      });

      if (blocked || !ua || ua.indexOf('curl') >= 0) {
        res.statusCode = 403;
        return res.json();
      }

      if (req.session.count) {
        if (req.session.count === 5) {
          return res.json({
            error: 'Whoa! That\'s a little too much love... you\'re making people uncomfortable...'
          });
        } else {
          req.session.count++;
        }
      } else {
        req.session.count = 1;
      }
    }

    next();
  });

  //
  // GET index.
  //
  app.get('/', function(req, res) {
    res.sendfile('./server/views/index.html');
  });

  //
  // API routes.
  // ===========
  //

  //
  // GET the most recent mavens.
  //
  app.get('/api/mavens/recent', function(req, res) {
    controller.getRecent()
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // GET mavens.
  //
  app.get('/api/mavens/:username?', function(req, res) {
    controller.get(req.params.username)
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Create/POST a maven.
  //
  app.post('/api/mavens', function(req, res) {
    controller.create(req.body.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Vote for a maven.
  //
  app.post('/api/mavens/:username/love', function(req, res) {
    controller.love(req.params.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });
};
<commit_msg>Do not block local requests.<commit_after>//
//     nodemavens
//     Copyright(c) 2014 Matt Hernandez <matt@modulus.io>
//     MIT Licensed
//

module.exports = function(app, controller) {
  var blacklist = JSON.parse(process.env.BLACKLIST || '[]');

  //
  // Disallow blacklisted IPs and verify the session count.
  //
  app.all('/*', function(req, res, next) {
    if ('POST' === req.method) {

      if (!req.headers['x-forwarded-for']) {
        // This occurs when running locally.
        return next();
      }

      var ips = req.headers['x-forwarded-for'].split(',')
        , ua  = req.headers['user-agent'];

      console.log(new Date().toString(), ips);

      var blocked = blacklist.some(function(ip) {
        return ips.indexOf(ip) >= 0;
      });

      if (blocked || !ua || ua.indexOf('curl') >= 0) {
        res.statusCode = 403;
        return res.json();
      }

      if (req.session.count) {
        if (req.session.count === 5) {
          return res.json({
            error: 'Whoa! That\'s a little too much love... you\'re making people uncomfortable...'
          });
        } else {
          req.session.count++;
        }
      } else {
        req.session.count = 1;
      }
    }

    next();
  });

  //
  // GET index.
  //
  app.get('/', function(req, res) {
    res.sendfile('./server/views/index.html');
  });

  //
  // API routes.
  // ===========
  //

  //
  // GET the most recent mavens.
  //
  app.get('/api/mavens/recent', function(req, res) {
    controller.getRecent()
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // GET mavens.
  //
  app.get('/api/mavens/:username?', function(req, res) {
    controller.get(req.params.username)
      .then(function(mavens) {
        res.json(mavens);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Create/POST a maven.
  //
  app.post('/api/mavens', function(req, res) {
    controller.create(req.body.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });

  //
  // Vote for a maven.
  //
  app.post('/api/mavens/:username/love', function(req, res) {
    controller.love(req.params.username)
      .then(function(maven) {
        res.json(maven);
      })
      .fail(function(err) {
        res.json({ error: err.message });
      })
      .done();
  });
};
<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
            automatedWeightCalculation(this.subcompetences());
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
            automatedWeightCalculation(this.subcompetences());
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {

        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
            automatedWeightCalculation(this.indicators());
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);

        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            var self = this;

            if(indicator.id() == undefined) // User deletes an indicator that hasn't been saved to the database yet
            {
                self.indicators.remove(indicator);
                automatedWeightCalculation(this.indicators());
            }
            else
            {
                $.getJSON(
                    "/api/project/indicator/delete/" + indicator.id(),
                    function(result)
                    {
                        if(result.success)
                        {
                            self.indicators.remove(indicator);
                            automatedWeightCalculation(self.indicators());
                        }
                        else
                        {
                            alert("Failed processing your request: " + result.error);
                        }
                    }
                );
            }
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, description, locked) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        description : ko.observable(description),
        locked: false,

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));
        automatedWeightCalculation(this.competences());

        // Update automated weight calculation
        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
        automatedWeightCalculation(this.competences());
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

function fetchProjectStructure() {
    viewModel.clearStructure();
    console.log(projectid);
    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.weight, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        if(allValidationChecks()) {
            saveProjectStructure();
            console.log("Saved");
        }
        else
        {
            window.scrollTo(0,0);
            console.log("Not saved");
        }
    });
}

function saveProjectStructure() {
    $.ajax({
        type: "POST",
        url: "/api/projectstructure/" + projectid,
        data: ko.toJSON(viewModel.competences),
        success: function(){
            // TODO make multilangual and with modals
            alert("Saved projectstructure to server");

            fetchProjectStructure();
        }
    });
}

function allValidationChecks()
{
    return totalPercentCheck() && validationCheck();
}

function validationCheck()
{
    var allCompetencesValid = true;
    var allSubcompetencesValid = true;
    var allIndicatorsValid = true;

    for(var indexCompetences =0; indexCompetences < viewModel.competences().length; indexCompetences++)
    {
        if(!viewModel.competences()[indexCompetences].code() && !viewModel.competences()[indexCompetences].name())
        {
            if(allCompetencesValid)
            {
                $(".validationSummary ul").append("
Code or name in competences is empty
");
                $(".validationSummary").removeClass("hide");
            }
            allCompetencesValid = false;
        }
        for(var indexSubcompetence = 0; indexSubcompetence < viewModel.competences()[indexCompetences].subcompetences().length; indexSubcompetence++)
        {
            if(!viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].name() && !viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].code())
            {
                if(allSubcompetencesValid)
                {
                    $(".validationSummary ul").append("
Code or name in subcompetences is empty
");
                    $(".validationSummary").removeClass("hide");
                }
                allSubcompetencesValid = false;
            }
            for(var indexIndicators = 0; indexIndicators < viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators().length; indexIndicators++)
            {
                if(!viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators()[indexIndicators].name() && !viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators()[indexIndicators].description())
                {
                    if(allIndicatorsValid)
                    {
                        $(".validationSummary ul").append("
Description or name in indicators is empty
");
                        $(".validationSummary").removeClass("hide");
                    }
                    allIndicatorsValid = false;
                }
            }
        }
    }
    return allCompetencesValid && allSubcompetencesValid && allIndicatorsValid;
}

function totalPercentCheck()
{
    var totalPercentCompetences = 0;
    var totalPercentSubcompetences = new Array();
    var totalPercentIndicators = new Array();
    var nrOfSubcompetences = 0;
    var nrOfIndicators = 0;

    var checkSubcompetences = true;
    var checkIndicators = true;

    for(var indexCompetences =0; indexCompetences < viewModel.competences().length; indexCompetences++)
    {
        totalPercentCompetences = totalPercentCompetences + parseInt(viewModel.competences()[indexCompetences].weight());
        totalPercentSubcompetences.push(0);
        for(var indexSubcompetence = 0; indexSubcompetence < viewModel.competences()[indexCompetences].subcompetences().length; indexSubcompetence++)
        {
            totalPercentSubcompetences[nrOfSubcompetences] = totalPercentSubcompetences[nrOfSubcompetences] + parseInt(viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].weight());
            totalPercentIndicators.push(0);
            for(var indexIndicators = 0; indexIndicators < viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators().length; indexIndicators++)
            {
                totalPercentIndicators[nrOfIndicators] = totalPercentIndicators[nrOfIndicators] + parseInt(viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators()[indexIndicators].weight());
            }
            nrOfIndicators++;
        }
        nrOfSubcompetences++;
    }

    for(var i = 0; i < nrOfSubcompetences - 1; i++)
    {
        if(totalPercentSubcompetences[i] != 100)
        {
            checkSubcompetences = false;
        }
    }

    for(var index = 0; index < nrOfIndicators - 1; index++)
    {
        if(totalPercentIndicators[index] != 100)
        {
            checkIndicators = false;
        }
    }

    if(totalPercentCompetences == 100 && checkSubcompetences && checkIndicators )
    {
        $(".validationSummary ul").html("");
        $(".validationSummary").addClass("hide");
        return true;
    }
    else
    {
        $(".validationSummary ul").append("
Not all percentages are 100%
");
        $(".validationSummary").removeClass("hide");
        return false;
    }
}

function automatedWeightCalculation(data)
{
    var lockedPercent = 0;
    var nrOfUnlocked = 0;

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == true)
        {
            lockedPercent = lockedPercent + parseInt(data[index].weight());
        }
        else
        {
            nrOfUnlocked++;
        }
    }

    var remainingPercent = 100 - lockedPercent;

    var percentPerCompetence = remainingPercent / nrOfUnlocked;

    percentPerCompetence = percentPerCompetence.toFixed(2);

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == false)
        {
            data[index].weight(percentPerCompetence);
        }
    }
}
<commit_msg>Only remove indicators from database when clicking save<commit_after>var workQueue = [];
/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
            automatedWeightCalculation(this.subcompetences());
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
            automatedWeightCalculation(this.subcompetences());
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {

        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
            automatedWeightCalculation(this.indicators());
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);

        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            var self = this;

            if(indicator.id() != undefined) // User deletes an indicator that hasn't been saved to the database yet
            {
                workQueue.push("/api/project/indicator/delete/" + indicator.id())
            }

            self.indicators.remove(indicator);
            automatedWeightCalculation(this.indicators());
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, description, locked) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        description : ko.observable(description),
        locked: false,

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));
        automatedWeightCalculation(this.competences());

        // Update automated weight calculation
        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
        automatedWeightCalculation(this.competences());
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

function fetchProjectStructure() {
    viewModel.clearStructure();
    console.log(projectid);
    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.weight, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        if(allValidationChecks()) {
            saveProjectStructure();
            console.log("Saved");
        }
        else
        {
            window.scrollTo(0,0);
            console.log("Not saved");
        }
    });
}

function saveProjectStructure() {
    var self = this;

    this.doTheRest = function()
    {
        $.ajax({
            type: "POST",
            url: "/api/projectstructure/" + projectid,
            data: ko.toJSON(viewModel.competences),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved projectstructure to server");

                fetchProjectStructure();
            }
        });
    }

    if(workQueue.length == 0)
    {
        this.doTheRest();
    }

    for(i = 0; i < workQueue.length; ++i)
    {
        $.getJSON(
            workQueue[i],
            function(result)
            {
                if(!result.success)
                {
                    alert("Failed processing your request: " + result.error);
                }

                if(i == workQueue.length)
                {
                    self.doTheRest();
                }
            }
        );
    }

}

function allValidationChecks()
{
    return totalPercentCheck() && validationCheck();
}

function validationCheck()
{
    var allCompetencesValid = true;
    var allSubcompetencesValid = true;
    var allIndicatorsValid = true;

    for(var indexCompetences =0; indexCompetences < viewModel.competences().length; indexCompetences++)
    {
        if(!viewModel.competences()[indexCompetences].code() && !viewModel.competences()[indexCompetences].name())
        {
            if(allCompetencesValid)
            {
                $(".validationSummary ul").append("
Code or name in competences is empty
");
                $(".validationSummary").removeClass("hide");
            }
            allCompetencesValid = false;
        }
        for(var indexSubcompetence = 0; indexSubcompetence < viewModel.competences()[indexCompetences].subcompetences().length; indexSubcompetence++)
        {
            if(!viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].name() && !viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].code())
            {
                if(allSubcompetencesValid)
                {
                    $(".validationSummary ul").append("
Code or name in subcompetences is empty
");
                    $(".validationSummary").removeClass("hide");
                }
                allSubcompetencesValid = false;
            }
            for(var indexIndicators = 0; indexIndicators < viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators().length; indexIndicators++)
            {
                if(!viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators()[indexIndicators].name() && !viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators()[indexIndicators].description())
                {
                    if(allIndicatorsValid)
                    {
                        $(".validationSummary ul").append("
Description or name in indicators is empty
");
                        $(".validationSummary").removeClass("hide");
                    }
                    allIndicatorsValid = false;
                }
            }
        }
    }
    return allCompetencesValid && allSubcompetencesValid && allIndicatorsValid;
}

function totalPercentCheck()
{
    var totalPercentCompetences = 0;
    var totalPercentSubcompetences = new Array();
    var totalPercentIndicators = new Array();
    var nrOfSubcompetences = 0;
    var nrOfIndicators = 0;

    var checkSubcompetences = true;
    var checkIndicators = true;

    for(var indexCompetences =0; indexCompetences < viewModel.competences().length; indexCompetences++)
    {
        totalPercentCompetences = totalPercentCompetences + parseInt(viewModel.competences()[indexCompetences].weight());
        totalPercentSubcompetences.push(0);
        for(var indexSubcompetence = 0; indexSubcompetence < viewModel.competences()[indexCompetences].subcompetences().length; indexSubcompetence++)
        {
            totalPercentSubcompetences[nrOfSubcompetences] = totalPercentSubcompetences[nrOfSubcompetences] + parseInt(viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].weight());
            totalPercentIndicators.push(0);
            for(var indexIndicators = 0; indexIndicators < viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators().length; indexIndicators++)
            {
                totalPercentIndicators[nrOfIndicators] = totalPercentIndicators[nrOfIndicators] + parseInt(viewModel.competences()[indexCompetences].subcompetences()[indexSubcompetence].indicators()[indexIndicators].weight());
            }
            nrOfIndicators++;
        }
        nrOfSubcompetences++;
    }

    for(var i = 0; i < nrOfSubcompetences - 1; i++)
    {
        if(totalPercentSubcompetences[i] != 100)
        {
            checkSubcompetences = false;
        }
    }

    for(var index = 0; index < nrOfIndicators - 1; index++)
    {
        if(totalPercentIndicators[index] != 100)
        {
            checkIndicators = false;
        }
    }

    if(totalPercentCompetences == 100 && checkSubcompetences && checkIndicators )
    {
        $(".validationSummary ul").html("");
        $(".validationSummary").addClass("hide");
        return true;
    }
    else
    {
        $(".validationSummary ul").append("
Not all percentages are 100%
");
        $(".validationSummary").removeClass("hide");
        return false;
    }
}

function automatedWeightCalculation(data)
{
    var lockedPercent = 0;
    var nrOfUnlocked = 0;

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == true)
        {
            lockedPercent = lockedPercent + parseInt(data[index].weight());
        }
        else
        {
            nrOfUnlocked++;
        }
    }

    var remainingPercent = 100 - lockedPercent;

    var percentPerCompetence = remainingPercent / nrOfUnlocked;

    percentPerCompetence = percentPerCompetence.toFixed(2);

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == false)
        {
            data[index].weight(percentPerCompetence);
        }
    }
}
<|endoftext|>


<commit_before>/*!
 * -----------
 * SCGDB®-Data
 * -----------
 * Data of SCGDB — A manually curated dedicated schizosaccharomyces comparative genome database.
 * ______________________________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ______________________________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ______________________________________________________________________________________________
 *
 * @date      : 18-Dec-2016
 * @license   : Apache, version 2.0
 * @require   : Node.js®
 * @require   : NPM
 * @require   : package.json
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ______________________________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "SCGDB®-Data".
 * ______________________________________________________________________________________________
 */

// To load required Node module.
// -----------------------------
var fs    = require('fs');
<commit_msg>Initial commit<commit_after>/*!
 * -----------
 * SCGDB®-Data
 * -----------
 * Data of SCGDB — A manually curated dedicated schizosaccharomyces comparative genome database.
 * ______________________________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ______________________________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ______________________________________________________________________________________________
 *
 * @date      : 18-Dec-2016
 * @license   : Apache, version 2.0
 * @require   : Node.js®
 * @require   : NPM
 * @require   : package.json
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ______________________________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "SCGDB®-Data".
 * ______________________________________________________________________________________________
 */

// To load required Node module.
// -----------------------------
var fs    = require('fs');

///--------------------------
// A smart stripBOM function.
///----------- 01 -----------
function stripBOM(content) {
  // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  // because the buffer-to-string conversion in `fs.readFileSync()`
  // translates it to FEFF, the UTF-16 BOM.
  if (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1);
  }
  return content;
}
<|endoftext|>


<commit_before>var express = require('express');
var app =express();
var router = express.Router();

var User = require('../model/User');
var Article = require('../model/Article');

var config = {
    development: {
        title: '一起离职吧！',
        link: '/stylesheets/style.css',
        src: '/javascripts/all.js'
    },
    production: {
        title: 'zwhu',
        link: '/stylesheets/style.min.css',
        src: '/javascripts/all.min.js'
    }
};

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', config[app.get('env') || 'development']);
});

//TODO: 1.登录成功后输出cookie的token
router.post('/login', function(req, res, next) {
    var user = new User();

    user.get(req.body.name, function(e, v) {
        if (!e &&  v && v.password === req.body.password) {
            //TODO: 使用token登陆的时候需要判断ip地址是否发生变化，如果发生变化，token登陆失败
            // 每次登录都要更新新的token
            res.cookie('token', Math.random().toString(36).substring(7), { maxAge: 24 * 60 * 60 * 10000 });
            return res.status(200).end();
        }
        //TODO: 以后要对HTTP的请求返回错误做出规范
        return res.status(404).end();
    });
});

router.param('id', function(req, res, next, id) {
    req.id = id;
    next();
});

//TODO: 获取所有帖子的缩略信息
//TODO： 根据id获取帖子的详细信息
//TODO: 对错误统一处理

router.get('/articles/:id', function(req, res, next) {
    var article = new Article();
    article.get(req.id, function(e, v) {
        if (!e) {
            return res.json(v);
        }
        //TODO: 以后要对HTTP的请求返回错误做出规范
        return res.status(404).end();
    });
});

//TODO: 根据 Cookie 验证是否为本人， 和 database 对比，验证还是要做的，走心。
router.post('/posts', function(req, res, next) {

    // 从数据库中取出token
    if(!req.cookie.token) {
        return res.status(404).end();
    }

    var user = new User();

    user.get(req.cookie.token, function(e, v) {
        if(v.token !== req.cookie.token) {
            return res.status(404).end();
        }

        if(!req.article)
            return res.status(404).end();

        var article = new Article(req.article);

        article.post(function(e) {
            if (!e) {
                return res.status(200).end();
            }
            //TODO: 以后要对HTTP的请求返回错误做出规范
            return res.status(404).end();
        });

    });
});

module.exports = router;
<commit_msg>获取所有文章的请求<commit_after>var express = require('express');
var app =express();
var router = express.Router();

var User = require('../model/User');
var Article = require('../model/Article');

var config = {
    development: {
        title: '一起离职吧！',
        link: '/stylesheets/style.css',
        src: '/javascripts/all.js'
    },
    production: {
        title: 'zwhu',
        link: '/stylesheets/style.min.css',
        src: '/javascripts/all.min.js'
    }
};

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', config[app.get('env') || 'development']);
});

//TODO: 1.登录成功后输出cookie的token
router.post('/login', function(req, res, next) {
    var user = new User();

    user.get(req.body.name, function(e, v) {
        if (!e &&  v && v.password === req.body.password) {
            //TODO: 使用token登陆的时候需要判断ip地址是否发生变化，如果发生变化，token登陆失败
            // 每次登录都要更新新的token
            res.cookie('token', Math.random().toString(36).substring(7), { maxAge: 24 * 60 * 60 * 10000 });
            return res.status(200).end();
        }
        //TODO: 以后要对HTTP的请求返回错误做出规范
        return res.status(404).end();
    });
});

router.param('id', function(req, res, next, id) {
    req.id = id;
    next();
});

//TODO: 获取所有帖子的缩略信息
//TODO： 根据id获取帖子的详细信息
//TODO: 对错误统一处理

router.get('/articles/:id', function(req, res, next) {
    var article = new Article();
    article.get(req.id, function(e, v) {
        if (!e) {
            return res.json(v);
        }
        //TODO: 以后要对HTTP的请求返回错误做出规范
        return res.status(404).end();
    });
});

router.get('/posts', function(req, res, next) {
    var article = new Article(req.article);

    // 取所有
    article.get(null, function(e, v) {
        if (!e) {
            return res.json(v);
        }
        //TODO: 以后要对HTTP的请求返回错误做出规范
        return res.status(404).end();
    });
});

//TODO: 根据 Cookie 验证是否为本人， 和 database 对比，验证还是要做的，走心。
router.post('/posts', function(req, res, next) {

    // 从数据库中取出token
    if(!req.cookie.token) {
        return res.status(404).end();
    }

    var user = new User();

    user.get(req.cookie.token, function(e, v) {
        if(v.token !== req.cookie.token) {
            return res.status(404).end();
        }

        if(!req.article)
            return res.status(404).end();

        var article = new Article(req.article);

        article.post(function(e) {
            if (!e) {
                return res.status(200).end();
            }
            //TODO: 以后要对HTTP的请求返回错误做出规范
            return res.status(404).end();
        });
    });
});

module.exports = router;
<|endoftext|>


<commit_before>game.SpendExp = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('exp-screen')), -10);
		//the -10 is the z-axis for putting our title screen in the back
		//the above line of code adds an image to the title screen

		me.game.world.addChild(new (me.Renderable.extend({
			init: function(){
				this._super(me.Renderable, 'init', [10, 10, 300, 50]);
				this.font = new me.Font("Arial", 54, "black");
			},

			draw: function(renderer){
				this.font.draw(renderer.getContext(), "Press F1-F4 to buy, F5 to skip", this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "CURRENT EXP: " + game.data.exp.toString(), this.pos.x + 100, this.pos.y + 50);
				this.font.draw(renderer.getContext(), "F1: INCREASE GOLD PRODUCTION " + game.data.exp.toString(), this.pos.x + 100, this.pos.y + 100);
				this.font.draw(renderer.getContext(), "F2: ADD STARTING GOLD " + game.data.exp.toString(), this.pos.x + 100, this.pos.y + 150);
				this.font.draw(renderer.getContext(), "F3: INCREASE ATTACK DAMAGE " + game.data.exp.toString(), this.pos.x + 100, this.pos.y + 200);
				this.font.draw(renderer.getContext(), "F4: INCREASE HEALTH" + game.data.exp.toString(), this.pos.x + 100, this.pos.y + 250);
				//adds text to the screen
				//the numbers added to the x and y positions move the text down as to not overlap
			},
		})));

	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function(renderer) {

	}
});
//this new file is run when you select "continue" and is proceeded by the option to spend experience or play the game<commit_msg>Video 44 (finishing spendEXP screen) completed<commit_after>game.SpendExp = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('exp-screen')), -10);
		//the -10 is the z-axis for putting our title screen in the back
		//the above line of code adds an image to the title screen

		me.input.bindKey(me.input.KEY.F1, "F1");
		me.input.bindKey(me.input.KEY.F2, "F2");
		me.input.bindKey(me.input.KEY.F3, "F3");
		me.input.bindKey(me.input.KEY.F4, "F4");
		me.input.bindKey(me.input.KEY.F5, "F5");

		me.game.world.addChild(new (me.Renderable.extend({
			init: function(){
				this._super(me.Renderable, 'init', [10, 10, 300, 50]);
				this.font = new me.Font("Arial", 45, "black");
			},

			draw: function(renderer){
				this.font.draw(renderer.getContext(), "Press F1-F4 to buy, F5 to skip", this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "CURRENT EXP: " + game.data.exp.toString(), this.pos.x + 100, this.pos.y + 50);
				this.font.draw(renderer.getContext(), "F1: INCREASE GOLD PRODUCTION " + game.data.exp1.toString() + " ; cost: " + ((game.data.exp1 + 1) * 10), this.pos.x, this.pos.y + 100);
				this.font.draw(renderer.getContext(), "F2: ADD STARTING GOLD ", this.pos.x, this.pos.y + 150);
				this.font.draw(renderer.getContext(), "F3: INCREASE ATTACK DAMAGE ", this.pos.x, this.pos.y + 200);
				this.font.draw(renderer.getContext(), "F4: INCREASE HEALTH ", this.pos.x, this.pos.y + 250);
				//adds text to the screen
				//the numbers added to the x and y positions move the text down as to not overlap
			},
		})));

		this.handler = me.event.subscribe(me.event.KEYDOWN, function(action, keyCode, edge){
			if(action === "F1"){

			}
			else if(action === "F2"){

			}
			else if(action === "F3"){

			}
			else if(action === "F4"){

			}
			else if(action === "F5"){
				me.state.change(me.state.PLAY);
			}
		});
	},

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function(renderer) {
		me.input.unbindKey(me.input.KEY.F1, "F1");
		me.input.unbindKey(me.input.KEY.F2, "F2");
		me.input.unbindKey(me.input.KEY.F3, "F3");
		me.input.unbindKey(me.input.KEY.F4, "F4");
		me.input.unbindKey(me.input.KEY.F5, "F5");
		me.event.unsubscribe(this.handler);
	}
});
//this new file is run when you select "continue" and is proceeded by the option to spend experience or play the game<|endoftext|>


<commit_before>/*
 * This module defines a replacement navigator.geolocation.* which
 * invokes emscripten to do a lookup.
 */

self.port.on("offline_fix_found", function(message) {
    console.log("DEBUG: geo-script.js received a message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_location'] = 1;
    var json_msg = JSON.stringify(message);
    window.postMessage(json_msg, "*");
});

self.port.on("offline_fix_unavailable", function(message) {
    console.log("DEBUG: geo-script.js received a unavailable location message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_unavailable_location'] = 1;
    var json_msg = JSON.stringify(message);
    window.postMessage(json_msg, "*");
});

if (self.options.showOptions) {
    function injectedCode() {

        /* None of this code will work within the regular javascript
         * debugger if you put a breakpoint inside of it.  ALl the
         * code here is clobbered into each HTML page and injected at
         * the top so the only way to set a break point is to go into
         * the individual page HTML and set a breakpoint there.
         *
         * You also can't even view the code within the HTML page as
         * injected code in a content script doesn't exist within
         * the regular Javascript runtime.
         *
         * So debugging this relies on console.log messages as you can
         * never actually see the code running within the page.
         *
         * Generally - debugging content scripts is awful.
         *
         * https://bugzilla.mozilla.org/show_bug.cgi?id=1016046
         *
         * I've managed to make things even *worse* by injecting code
         * dynamically into the actual content of the page with the
         * content script.
         *
         */

        navigator.geolocation.getCurrentPosition = function(callBack,
                                                            errBack,
                                                            options) {

            function MockGeoPositionObject(lat, lng, acc) {
              this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);
              this.address = null;
              this.timestamp = Date.now();
            }

            function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {
              this.latitude = lat;
              this.longitude = lon;
              this.accuracy = acc;
              this.altitude = alt;
              this.altitudeAccuracy = altacc;
            }

            window.startOfflineScan();

            navigator.geolocation.captured_callBack = callBack;
            navigator.geolocation.captured_errBack = errBack;

            console.log("Callback function: " + navigator.geolocation.captured_callBack);
            console.log("^^ Bound callback to navigator.geolocation.captured_callBack");

            // TODO: this callback needs to be invoked after a lookup
            // in the marisa trie
            //callBack(new MockGeoPositionObject(44.033639,-79.490813, 50));
        };

        navigator.geolocation.watchPosition = function(cb1, cb2, options) {
            alert("watchPosition was called");
        };

        navigator.geolocation.clearWatch = function () {
            alert("clearWatch was called");
        };

        // Remove script
        // Ok - this is a bit wacky and probably unnecessary.
        // Once we're finished clobbering the navigator.geolocation
        // namespace - we actually *delete* the clobbering code from
        // the page content.  Just to be sneaky.

        /*
        var s = document.getElementById('__offline_clobber');
        if (s) {
            s.remove();	// DEMO: in demo injectCode is run directly so there's no script
        }
        */
    }

    if (document.documentElement.tagName.toLowerCase() == 'html') { // only for html
        // Step 1- Clobber the navigator.geolocation namespace
        var inject = "(function(){"
            + injectedCode +
            " injectedCode();" +
            "})()";

        var script = document.createElement('script');
        script.setAttribute('id', '__offline_clobber');
        script.appendChild(document.createTextNode(inject));

        // FF: there is already another variable in the scope named
        // 'parent', this causes a very hard to catch bug so we'll
        // just call this '_parent'
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }

        // Step 2 - add a listener for offline fixes
        // Now inject a listener for when the content script passes
        // a message with the offline fix.
        var script = document.createElement('script');
        var inject = "window.addEventListener('message', function(event) {  \
            console.log('Page got a message: ' + event.data);  \
            if (event.data.substring('__fx_elm_location' > -1)) {  \
                var json_obj = JSON.parse(event.data);  \
                function MockGeoPositionObject(lat, lng, acc) {  \
                  this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);  \
                  this.address = null;  \
                  this.timestamp = Date.now();  \
                }  \
                function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {  \
                  this.latitude = lat;  \
                  this.longitude = lon;  \
                  this.accuracy = acc;  \
                  this.altitude = alt;  \
                  this.altitudeAccuracy = altacc;  \
                }  \
                navigator.geolocation.captured_callBack(new MockGeoPositionObject(json_obj['lat'], json_obj['lon'], 100));  \
            }  \
         }, false);";

        // TODO: add the errback callback code above to return
        // PositionError to the errBack

        script.setAttribute('id', '__offline_receiver');
        script.appendChild(document.createTextNode(inject));
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }
    }
}
<commit_msg>added page script injection code to handle invoking the errorBack when a position fix is not possible<commit_after>/*
 * This module defines a replacement navigator.geolocation.* which
 * invokes emscripten to do a lookup.
 */

self.port.on("offline_fix_found", function(message) {
    console.log("DEBUG: geo-script.js received a message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_location'] = 1;
    var json_msg = JSON.stringify(message);
    window.postMessage(json_msg, "*");
});

self.port.on("offline_fix_unavailable", function(message) {
    console.log("DEBUG: geo-script.js received an unavailable location message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_unavailable_location'] = 1;
    var json_msg = JSON.stringify(message);
    console.log("Sending page unavailable JSON: " + json_msg);
    window.postMessage(json_msg, "*");
});

if (self.options.showOptions) {
    function injectedCode() {

        /* None of this code will work within the regular javascript
         * debugger if you put a breakpoint inside of it.  ALl the
         * code here is clobbered into each HTML page and injected at
         * the top so the only way to set a break point is to go into
         * the individual page HTML and set a breakpoint there.
         *
         * You also can't even view the code within the HTML page as
         * injected code in a content script doesn't exist within
         * the regular Javascript runtime.
         *
         * So debugging this relies on console.log messages as you can
         * never actually see the code running within the page.
         *
         * Generally - debugging content scripts is awful.
         *
         * https://bugzilla.mozilla.org/show_bug.cgi?id=1016046
         *
         * I've managed to make things even *worse* by injecting code
         * dynamically into the actual content of the page with the
         * content script.
         *
         */

        navigator.geolocation.getCurrentPosition = function(callBack,
                                                            errBack,
                                                            options) {

            function MockGeoPositionObject(lat, lng, acc) {
              this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);
              this.address = null;
              this.timestamp = Date.now();
            }

            function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {
              this.latitude = lat;
              this.longitude = lon;
              this.accuracy = acc;
              this.altitude = alt;
              this.altitudeAccuracy = altacc;
            }

            window.startOfflineScan();

            navigator.geolocation.captured_callBack = callBack;
            navigator.geolocation.captured_errBack = errBack;

            console.log("Callback function: " + navigator.geolocation.captured_callBack);
            console.log("^^ Bound callback to navigator.geolocation.captured_callBack");

            // TODO: this callback needs to be invoked after a lookup
            // in the marisa trie
            //callBack(new MockGeoPositionObject(44.033639,-79.490813, 50));
        };

        navigator.geolocation.watchPosition = function(cb1, cb2, options) {
            alert("watchPosition was called");
        };

        navigator.geolocation.clearWatch = function () {
            alert("clearWatch was called");
        };

        // Remove script
        // Ok - this is a bit wacky and probably unnecessary.
        // Once we're finished clobbering the navigator.geolocation
        // namespace - we actually *delete* the clobbering code from
        // the page content.  Just to be sneaky.

        /*
        var s = document.getElementById('__offline_clobber');
        if (s) {
            s.remove();	// DEMO: in demo injectCode is run directly so there's no script
        }
        */
    }

    if (document.documentElement.tagName.toLowerCase() == 'html') { // only for html
        // Step 1- Clobber the navigator.geolocation namespace
        var inject = "(function(){"
            + injectedCode +
            " injectedCode();" +
            "})()";

        var script = document.createElement('script');
        script.setAttribute('id', '__offline_clobber');
        script.appendChild(document.createTextNode(inject));

        // FF: there is already another variable in the scope named
        // 'parent', this causes a very hard to catch bug so we'll
        // just call this '_parent'
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }

        // Step 2 - add a listener for offline fixes
        // Now inject a listener for when the content script passes
        // a message with the offline fix.
        var script = document.createElement('script');
        var inject = "window.addEventListener('message', function(event) {  \
            console.log('Page got a message: ' + event.data);  \
            if (event.data.indexOf('__fx_elm_location')  > -1) {  \
                console.log('Available position received in page'); \
                var json_obj = JSON.parse(event.data);  \
                function MockGeoPositionObject(lat, lng, acc) {  \
                  this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);  \
                  this.address = null;  \
                  this.timestamp = Date.now();  \
                }  \
                function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {  \
                  this.latitude = lat;  \
                  this.longitude = lon;  \
                  this.accuracy = acc;  \
                  this.altitude = alt;  \
                  this.altitudeAccuracy = altacc;  \
                }  \
                var mockLocation = new MockGeoPositionObject(json_obj['lat'], json_obj['lon'], 100); \
                navigator.geolocation.captured_callBack(mockLocation);  \
            }  \
            if (event.data.indexOf('__fx_elm_unavailable_location') > -1) {  \
                console.log('Unavailable position received in page'); \
                function MockPositionError() {  \
                  this.code = 2;  \
                  this.message = 'Offline position is unavailable'; \
                }  \
                var posError = new MockPositionError(); \
                console.log('ErrBack: ' + navigator.geolocation.captured_errBack);\
                console.log('PositionError: ' + posError); \
                var mockLocation = new MockGeoPositionObject(0, 0, 100); \
                navigator.geolocation.captured_errBack(posError); \
                navigator.geolocation.captured_callBack(mockLocation);  \
            }  \
         }, false);";

        script.setAttribute('id', '__offline_receiver');
        script.appendChild(document.createTextNode(inject));
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }
    }
}
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.spotlight = "2.5.1-pre.9";
}
<commit_msg>Update version string to 2.5.2-pre.1<commit_after>if (enyo && enyo.version) {
	enyo.version.spotlight = "2.5.2-pre.1";
}
<|endoftext|>


<commit_before>/**
 * Schema Utilities
 */

// Generate a field graph
// Leaf nodes are empty objects
// Use info.fieldASTs as a starting point
export function getFieldGraph (fields = []): Object {
  return fields
    .filter(field => field.kind === 'Field')
    .reduce((result, field) => {
      result[field.name.value] = field.selectionSet
        ? getFieldGraph(field.selectionSet.selections)
        : {}
      return result
    }, {})
}

// Get the fields for a type
export function getFields (info: Object): Array<string> {
  const fieldGraph = getFieldGraph(info.fieldASTs)
  return Object.keys(fieldGraph[info.fieldName])
}

// Get the fields for an edge node
export function getEdgeNodeFields (info: Object): Array<string> {
  const fieldGraph = getFieldGraph(info.fieldASTs)
  return Object.keys(fieldGraph[info.fieldName].node)
}

// Get the fields for a connection
export function getConnectionFields (info: Object): Array<string> {
  const fieldGraph = getFieldGraph(info.fieldASTs)
  return Object.keys(fieldGraph[info.fieldName].edges.node)
}

// Get an empty connection
export function getEmptyConnection () {
  return {
    edges: [],
    pageInfo: {
      startCursor: null,
      endCursor: null,
      hasPreviousPage: false,
      hasNextPage: false
    }
  }
}
<commit_msg>Add graphql model utils<commit_after>/**
 * Schema Utilities
 */
import { globalIdField } from 'graphql-relay'

// Generate a field graph
// Leaf nodes are empty objects
// Use info.fieldASTs as a starting point
export function getFieldGraph (fields = []): Object {
  return fields
    .filter(field => field.kind === 'Field')
    .reduce((result, field) => {
      result[field.name.value] = field.selectionSet
        ? getFieldGraph(field.selectionSet.selections)
        : {}
      return result
    }, {})
}

// Get the fields for a type
export function getFields (info: Object): Array<string> {
  const fieldGraph = getFieldGraph(info.fieldASTs)
  return Object.keys(fieldGraph[info.fieldName])
}

// Get the fields for an edge node
export function getEdgeNodeFields (info: Object): Array<string> {
  const fieldGraph = getFieldGraph(info.fieldASTs)
  return Object.keys(fieldGraph[info.fieldName].node)
}

// Get the fields for a connection
export function getConnectionFields (info: Object): Array<string> {
  const fieldGraph = getFieldGraph(info.fieldASTs)
  return Object.keys(fieldGraph[info.fieldName].edges.node)
}

// Get an empty connection
export function getEmptyConnection () {
  return {
    edges: [],
    pageInfo: {
      startCursor: null,
      endCursor: null,
      hasPreviousPage: false,
      hasNextPage: false
    }
  }
}

export function modelField (field) {
  field.resolve = function resolve (model, args, { fieldName }) {
    return model.get(fieldName)
  }
  return field
}

export function modelGlobalIdField (name) {
  return globalIdField(name, model => model.get('id'))
}

export function modelIsTypeOf (modelName) {
  return function isTypeOf (model, { rootValue }) {
    return model instanceof rootValue.models[modelName]
  }
}
<|endoftext|>


<commit_before>import React, {
  StyleSheet,
} from 'react-native';

const styles = StyleSheet.create({
  description: {
    marginBottom: 20,
    fontSize: 18,
    textAlign: 'center',
    color: '#656565'
  },
  container: {
    padding: 30,
    marginTop: 65,
    alignItems: 'center'
  },
  flowRight: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'stretch'
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 36,
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#48BBEC',
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  buttonInactive: {
    height: 36,
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#AAAAAA',
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  searchInput: {
    height: 36,
    padding: 4,
    flex: 4,
    fontSize: 18,
    borderWidth: 1,
    borderColor: '#48BBEC',
    color: '#48BBEC'
  }
});

module.exports = styles;<commit_msg>added the styling<commit_after>import React, {
  StyleSheet,
} from 'react-native';

const styles = StyleSheet.create({
  navBar: {
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderBottomColor: '#CCCCCC'
  },
  nav: {
    flex: 1,
  },
  description: {
    marginBottom: 20,
    fontSize: 18,
    textAlign: 'center',
    color: '#656565'
  },
  container: {
    padding: 30,
    marginTop: 65,
    alignItems: 'center'
  },
  flowRight: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'stretch'
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 36,
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#AAAAAA',
    marginBottom: 10,
    padding: 3,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  buttonActive: {
    backgroundColor: '#48BBEC',
  },
  searchInput: {
    alignSelf: 'stretch',
    height: 36,
    padding: 4,
    marginBottom: 10,
    borderBottomWidth: 2,
    borderBottomColor: '#CCCCCC',
  },
  searchInputText: {
    color: '#CCCCCC',
    fontSize: 18,
  },
  searchInputActive: {
    color: '#48BBEC'
  },
  list: {
    alignSelf: 'stretch',
    flex: 1,
    flexDirection: 'row',
  },
  searchListRow: {
    alignSelf: 'stretch',
    height: 36,
  },
  searchListRowText: {
    fontSize: 18
  }
});

module.exports = styles;<|endoftext|>


<commit_before>$( document ).ready(function() {
	// create the audio context (chrome only for now)
    if (! window.AudioContext) {
        if (! window.webkitAudioContext) {
            alert('no audiocontext found');
        }
        window.AudioContext = window.webkitAudioContext;
    }

	//audio context variables
	var context = new AudioContext();
    var audioBuffer;
    var sourceNode;
    var splitter;
    var analyser, analyser2;
    var javascriptNode;

	var averageVolume = averageVolume2 = 0;

	var ctx;
	var WIDTH;
	var HEIGHT;
	var intervalId = 0;
	var frame = 0;

	var increment = 1;

	var volumeCenter = 87;

	var audioPlayer;
	var playerMuted = false;

	var catBody = new Image();
	catBody.src = 'img/body.png';
	var bx = bx0 = 245;
	var by = by0 = 750-543;
	var bw;
	var bh;
	//set natural width and natural height once the image is loaded
	if (catBody.addEventListener){
		catBody.addEventListener('load', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		}, false);
	} else if (catBody.attachEvent){
		catBody.attachEvent('onload', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		});
	}

	var catHead = new Image();
	catHead.src = 'img/head.png';
	var hx = hx0 = 486;
	var hy = hy0 = 750-524;
	var hw;
	var hh;
	//set natural width and natural height once the image is loaded
	if (catHead.addEventListener){
		catHead.addEventListener('load', function(){
			hw = catHead.naturalWidth;
			hh = catHead.naturalHeight;
		}, false);
	} else if (catHead.attachEvent){
		catHead.attachEvent('onload', function(){
			hw = catHead.naturalWidth;
			hh = catHead.naturalHeight;
		});
	}

	var catTail = new Image();
	catTail.src = 'img/tail.png';
	var tx = tx0 = 320;
	var ty = ty0 = 750-642;
	var tw;
	var th;
	//set natural width and natural height once the image is loaded
	if (catTail.addEventListener){
		catTail.addEventListener('load', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		}, false);
	} else if (catTail.attachEvent){
		catTail.attachEvent('onload', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		});
	}

	function init(){

		//set canvas context
		var canvas = (typeof(G_vmlCanvasManager) != 'undefined') ? G_vmlCanvasManager.initElement($("canvas#card")[0]) : $("canvas#card")[0];
		ctx = canvas.getContext('2d');
	    ctx.font = "20.0px Arial, Helvetica, sans-serif";
		WIDTH = $("canvas#card").width();
		HEIGHT = $("canvas#card").height();

		audioPlayer = $('.audio audio')[0];
	}

	function toggleMute(){
		if(playerMuted == false){
			//variable to force iOS to know that the icon is supposed to be shown in the muted state, even though it doesn't respect actually muting
			playerMuted = true;

			$('button#mute').addClass('muted');

			//actually mutes the audio
			audioPlayer.muted = true;
		}
		else{
			playerMuted = false;
			$('button#mute').removeClass('muted');
			audioPlayer.muted = false;
		}
	}

	function startDrawing(){
		$('button#play').hide();
		intervalId = setInterval(draw, 10);

		//only play audio if the browser supports it. Thanks, Microsoft
		if(typeof audioPlayer != 'undefined'){
			//audioPlayer.play();
		}
		loadSound("audio/bird.mp3");
	}

	function draw(){
		frame ++;
		clear();

		//draw cat body and rotate
		/*
		if(averageVolume > 0){
			ctx.translate(bx, by);
			ctx.rotate((averageVolume-volumeCenter)*Math.PI/180);
			drawCharacter(catBody, bx, by, bw, bh);
			ctx.rotate(-(averageVolume-volumeCenter)*Math.PI/180);
			ctx.translate(-bx, -by);
		} else {
			drawCharacter(catBody, bx, by, bw, bh);
		}
		*/

		//draw tail
		if(averageVolume > 0){
			ctx.save();
			ctx.translate(tx, (ty+th));
			ctx.rotate((averageVolume - volumeCenter)*Math.PI/180);
			ctx.translate(0, -th);
			drawCharacter(catTail, 0, 0, tw, th);
			ctx.restore();
		} else {
			drawCharacter(catTail, tx, ty, tw, th);
		}

		//draw head
		if(averageVolume - volumeCenter > 0){
			ctx.save();
			ctx.translate( (hx+(hw/2)), (hy+(hh/2)) );
			drawCharacter(catHead, -(hw/2), -(hh/2), hw, hh);
			ctx.restore();
		} else {
			drawCharacter(catHead, hx, hy, hw, hh);
		}

		//draw body
		drawCharacter(catBody, bx, by, bw, bh);

		// create the meters
        /*
		ctx.fillRect(0,130-averageVolume,25,130);
        ctx.fillRect(30,130-averageVolume2,25,130);
		*/

		//show audio levels
		/*
		console.log(averageVolume);
		console.log(averageVolume2);
		*/

		/*
		//create a new random emflake
		emflakew = getRandomInt(50, ew);
		emflakeh = (emflakew * eh / ew);
		emflakex = getRandomInt(0 - (emflakew/2), WIDTH - (emflakew/2));

		//move all emflakes

		if (value.thisy <= HEIGHT){
			drawCharacter(emflake, value.thisx, value.thisy, value.thisw, value.thish);
			value.thisy += value.increment;
		}
		else {
			//remove the emflake from the array if it is off screen
			emflakes.splice(index, 1);
			return false;
		}
		*/

	} //end draw

	function drawCharacter(name, x, y, w, h){
		ctx.drawImage(name, x, y, w, h);
	}

	function clear() {
	  ctx.clearRect(0, 0, WIDTH, HEIGHT);
	}

	function getRandomInt (min, max) {
	    return Math.floor(Math.random() * (max - min + 1)) + min;
	}

	function drawRect(){
		/* draw a rectangle just for debugging purposes */
		ctx.fillRect(100, 100, 10, 10);
	}

	function setupAudioNodes() {

        // setup a javascript node
        javascriptNode = context.createScriptProcessor(2048, 1, 1);
        // connect to destination, else it isn't called
        javascriptNode.connect(context.destination);

        // setup a analyzer
        analyser = context.createAnalyser();
        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 1024;

        analyser2 = context.createAnalyser();
        analyser2.smoothingTimeConstant = 0.0;
        analyser2.fftSize = 1024;

        // create a buffer source node
        sourceNode = context.createBufferSource();
        splitter = context.createChannelSplitter();

        // connect the source to the analyser and the splitter
        sourceNode.connect(splitter);

        // connect one of the outputs from the splitter to
        // the analyser
        splitter.connect(analyser,0,0);
        splitter.connect(analyser2,1,0);

        // connect the splitter to the javascriptnode
        // we use the javascript node to draw at a
        // specific interval.
        analyser.connect(javascriptNode);

//        splitter.connect(context.destination,0,0);
//        splitter.connect(context.destination,0,1);

        // and connect to destination
        sourceNode.connect(context.destination);
    }

    // load the specified sound
    function loadSound(url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';

        // When loaded decode the data
        request.onload = function() {

            // decode the data
            context.decodeAudioData(request.response, function(buffer) {
                // when the audio is decoded play the sound
                playSound(buffer);
            }, onError);
        }
        request.send();
    }

    function playSound(buffer) {
        sourceNode.buffer = buffer;
        sourceNode.start(0);
    }

	// log if an error occurs
    function onError(e) {
        console.log(e);
    }

	init();

	// load the sound
    setupAudioNodes();
    //loadSound("../audio/bird.mp3");

	// when the javascript node is called
    // we use information from the analyzer node
    // to draw the volume
    javascriptNode.onaudioprocess = function() {

        // get the average for the first channel
        var array =  new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(array);
        averageVolume = getAverageVolume(array);

        // get the average for the second channel
        var array2 =  new Uint8Array(analyser2.frequencyBinCount);
        analyser2.getByteFrequencyData(array2);
        averageVolume2 = getAverageVolume(array2);

        // clear the current state
        //ctx.clearRect(0, 0, 60, 130);
    }

    function getAverageVolume(array) {
        var values = 0;
        var average;

        var length = array.length;

        // get all the frequency amplitudes
        for (var i = 0; i < length; i++) {
            values += array[i];
        }

        average = values / length;
        return average;
    }

	$('button#play').on('click', startDrawing );
	$('button#mute').on('click', toggleMute );
//end document ready
});<commit_msg>pulsing head from center<commit_after>$( document ).ready(function() {
	// create the audio context (chrome only for now)
    if (! window.AudioContext) {
        if (! window.webkitAudioContext) {
            alert('no audiocontext found');
        }
        window.AudioContext = window.webkitAudioContext;
    }

	//audio context variables
	var context = new AudioContext();
    var audioBuffer;
    var sourceNode;
    var splitter;
    var analyser, analyser2;
    var javascriptNode;

	var averageVolume = averageVolume2 = 0;

	var ctx;
	var WIDTH;
	var HEIGHT;
	var intervalId = 0;
	var frame = 0;

	var increment = 1;

	var volumeCenter = 87;

	var audioPlayer;
	var playerMuted = false;

	var catBody = new Image();
	catBody.src = 'img/body.png';
	var bx = bx0 = 245;
	var by = by0 = 750-543;
	var bw;
	var bh;
	//set natural width and natural height once the image is loaded
	if (catBody.addEventListener){
		catBody.addEventListener('load', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		}, false);
	} else if (catBody.attachEvent){
		catBody.attachEvent('onload', function(){
			bw = catBody.naturalWidth;
			bh = catBody.naturalHeight;
		});
	}

	var catHead = new Image();
	catHead.src = 'img/head.png';
	var hx = 486;
	var hy = 750-524;
	var hw;
	var hh;
	var hw0;
	var hh0;
	//set natural width and natural height once the image is loaded
	if (catHead.addEventListener){
		catHead.addEventListener('load', function(){
			hw = hw0 = catHead.naturalWidth;
			hh = hh0 = catHead.naturalHeight;
		}, false);
	} else if (catHead.attachEvent){
		catHead.attachEvent('onload', function(){
			hw = hw0 = catHead.naturalWidth;
			hh = hh0 = catHead.naturalHeight;
		});
	}

	var catTail = new Image();
	catTail.src = 'img/tail.png';
	var tx = tx0 = 320;
	var ty = ty0 = 750-642;
	var tw;
	var th;
	//set natural width and natural height once the image is loaded
	if (catTail.addEventListener){
		catTail.addEventListener('load', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		}, false);
	} else if (catTail.attachEvent){
		catTail.attachEvent('onload', function(){
			tw = catTail.naturalWidth;
			th = catTail.naturalHeight;
		});
	}

	function init(){

		//set canvas context
		var canvas = (typeof(G_vmlCanvasManager) != 'undefined') ? G_vmlCanvasManager.initElement($("canvas#card")[0]) : $("canvas#card")[0];
		ctx = canvas.getContext('2d');
	    ctx.font = "20.0px Arial, Helvetica, sans-serif";
		WIDTH = $("canvas#card").width();
		HEIGHT = $("canvas#card").height();

		audioPlayer = $('.audio audio')[0];
	}

	function toggleMute(){
		if(playerMuted == false){
			//variable to force iOS to know that the icon is supposed to be shown in the muted state, even though it doesn't respect actually muting
			playerMuted = true;

			$('button#mute').addClass('muted');

			//actually mutes the audio
			audioPlayer.muted = true;
		}
		else{
			playerMuted = false;
			$('button#mute').removeClass('muted');
			audioPlayer.muted = false;
		}
	}

	function startDrawing(){
		$('button#play').hide();
		intervalId = setInterval(draw, 10);

		//only play audio if the browser supports it. Thanks, Microsoft
		if(typeof audioPlayer != 'undefined'){
			//audioPlayer.play();
		}
		loadSound("audio/bird.mp3");
	}

	function draw(){
		frame ++;
		clear();

		//draw cat body and rotate
		/*
		if(averageVolume > 0){
			ctx.translate(bx, by);
			ctx.rotate((averageVolume-volumeCenter)*Math.PI/180);
			drawCharacter(catBody, bx, by, bw, bh);
			ctx.rotate(-(averageVolume-volumeCenter)*Math.PI/180);
			ctx.translate(-bx, -by);
		} else {
			drawCharacter(catBody, bx, by, bw, bh);
		}
		*/

		//draw tail
		if(averageVolume > 0){
			ctx.save();
			ctx.translate(tx, (ty+th));
			ctx.rotate((averageVolume - volumeCenter)*Math.PI/180);
			ctx.translate(0, -th);
			drawCharacter(catTail, 0, 0, tw, th);
			ctx.restore();
		} else {
			drawCharacter(catTail, tx, ty, tw, th);
		}

		//draw head
		if(averageVolume - volumeCenter > 0){
			//increase head width based on volume
			hw = hw0 + (averageVolume - volumeCenter);
			//set head height proportionally to head width
			hh = (hw * (hh0 / hw0) );

			/*
			var headRatio = (hh0 / hw0);
			console.log('headRatio = '+headRatio);
			console.log('hw = '+hw);
			console.log('hh = '+hh);
			*/

			//pulse head size
			ctx.save();
			ctx.translate( (hx+(hw/2)), (hy+(hh/2)) );
			drawCharacter(catHead, -(hw/2), -(hh/2), hw, hh);
			ctx.restore();
		} else {
			//reset width and height to natural size
			hw = hw0;
			hh = hh0;
			drawCharacter(catHead, hx, hy, hw, hh);
		}

		//draw body
		drawCharacter(catBody, bx, by, bw, bh);

		// create the meters
        /*
		ctx.fillRect(0,130-averageVolume,25,130);
        ctx.fillRect(30,130-averageVolume2,25,130);
		*/

		//show audio levels
		/*
		console.log(averageVolume);
		console.log(averageVolume2);
		*/

		/*
		//create a new random emflake
		emflakew = getRandomInt(50, ew);
		emflakeh = (emflakew * eh / ew);
		emflakex = getRandomInt(0 - (emflakew/2), WIDTH - (emflakew/2));

		//move all emflakes

		if (value.thisy <= HEIGHT){
			drawCharacter(emflake, value.thisx, value.thisy, value.thisw, value.thish);
			value.thisy += value.increment;
		}
		else {
			//remove the emflake from the array if it is off screen
			emflakes.splice(index, 1);
			return false;
		}
		*/

	} //end draw

	function drawCharacter(name, x, y, w, h){
		ctx.drawImage(name, x, y, w, h);
	}

	function clear() {
	  ctx.clearRect(0, 0, WIDTH, HEIGHT);
	}

	function getRandomInt (min, max) {
	    return Math.floor(Math.random() * (max - min + 1)) + min;
	}

	function drawRect(){
		/* draw a rectangle just for debugging purposes */
		ctx.fillRect(100, 100, 10, 10);
	}

	function setupAudioNodes() {

        // setup a javascript node
        javascriptNode = context.createScriptProcessor(2048, 1, 1);
        // connect to destination, else it isn't called
        javascriptNode.connect(context.destination);

        // setup a analyzer
        analyser = context.createAnalyser();
        analyser.smoothingTimeConstant = 0.3;
        analyser.fftSize = 1024;

        analyser2 = context.createAnalyser();
        analyser2.smoothingTimeConstant = 0.0;
        analyser2.fftSize = 1024;

        // create a buffer source node
        sourceNode = context.createBufferSource();
        splitter = context.createChannelSplitter();

        // connect the source to the analyser and the splitter
        sourceNode.connect(splitter);

        // connect one of the outputs from the splitter to
        // the analyser
        splitter.connect(analyser,0,0);
        splitter.connect(analyser2,1,0);

        // connect the splitter to the javascriptnode
        // we use the javascript node to draw at a
        // specific interval.
        analyser.connect(javascriptNode);

//        splitter.connect(context.destination,0,0);
//        splitter.connect(context.destination,0,1);

        // and connect to destination
        sourceNode.connect(context.destination);
    }

    // load the specified sound
    function loadSound(url) {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';

        // When loaded decode the data
        request.onload = function() {

            // decode the data
            context.decodeAudioData(request.response, function(buffer) {
                // when the audio is decoded play the sound
                playSound(buffer);
            }, onError);
        }
        request.send();
    }

    function playSound(buffer) {
        sourceNode.buffer = buffer;
        sourceNode.start(0);
    }

	// log if an error occurs
    function onError(e) {
        console.log(e);
    }

	init();

	// load the sound
    setupAudioNodes();
    //loadSound("../audio/bird.mp3");

	// when the javascript node is called
    // we use information from the analyzer node
    // to draw the volume
    javascriptNode.onaudioprocess = function() {

        // get the average for the first channel
        var array =  new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(array);
        averageVolume = getAverageVolume(array);

        // get the average for the second channel
        var array2 =  new Uint8Array(analyser2.frequencyBinCount);
        analyser2.getByteFrequencyData(array2);
        averageVolume2 = getAverageVolume(array2);

        // clear the current state
        //ctx.clearRect(0, 0, 60, 130);
    }

    function getAverageVolume(array) {
        var values = 0;
        var average;

        var length = array.length;

        // get all the frequency amplitudes
        for (var i = 0; i < length; i++) {
            values += array[i];
        }

        average = values / length;
        return average;
    }

	$('button#play').on('click', startDrawing );
	$('button#mute').on('click', toggleMute );
//end document ready
});<|endoftext|>


<commit_before>/* Modernizr 2.5.3 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-borderradius-boxshadow-opacity-rgba-textshadow-cssgradients-csstransitions-history-websockets-shiv-cssclasses-testprop-testallprops-prefixes-domprefixes-load
 */
;window.Modernizr=function(a,b,c){function y(a){j.cssText=a}function z(a,b){return y(m.join(a+";")+(b||""))}function A(a,b){return typeof a===b}function B(a,b){return!!~(""+a).indexOf(b)}function C(a,b){for(var d in a)if(j[a[d]]!==c)return b=="pfx"?a[d]:!0;return!1}function D(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:A(f,"function")?f.bind(d||b):f}return!1}function E(a,b,c){var d=a.charAt(0).toUpperCase()+a.substr(1),e=(a+" "+o.join(d+" ")+d).split(" ");return A(b,"string")||A(b,"undefined")?C(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),D(e,b,c))}var d="2.5.3",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w={}.hasOwnProperty,x;!A(w,"undefined")&&!A(w.call,"undefined")?x=function(a,b){return w.call(a,b)}:x=function(a,b){return b in a&&A(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e}),q.history=function(){return!!a.history&&!!history.pushState},q.websockets=function(){for(var b=-1,c=o.length;++b<c;)if(a[o[b]+"WebSocket"])return!0;return"WebSocket"in a},q.rgba=function(){return y("background-color:rgba(150,255,150,.5)"),B(j.backgroundColor,"rgba")},q.borderradius=function(){return E("borderRadius")},q.boxshadow=function(){return E("boxShadow")},q.textshadow=function(){return b.createElement("div").style.textShadow===""},q.opacity=function(){return z("opacity:.55"),/^0.55$/.test(j.opacity)},q.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return y((a+"-webkit- ".split(" ").join(b+a)+m.join(c+a)).slice(0,-a.length)),B(j.backgroundImage,"gradient")},q.csstransitions=function(){return E("transition")};for(var F in q)x(q,F)&&(v=F.toLowerCase(),e[v]=q[F](),t.push((e[v]?"":"no-")+v));return y(""),i=k=null,function(a,b){function g(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function h(){var a=k.elements;return typeof a=="string"?a.split(" "):a}function i(a){var b={},c=a.createElement,e=a.createDocumentFragment,f=e();a.createElement=function(a){var e=(b[a]||(b[a]=c(a))).cloneNode();return k.shivMethods&&e.canHaveChildren&&!d.test(a)?f.appendChild(e):e},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+h().join().replace(/\w+/g,function(a){return b[a]=c(a),f.createElement(a),'c("'+a+'")'})+");return n}")(k,f)}function j(a){var b;return a.documentShived?a:(k.shivCSS&&!e&&(b=!!g(a,"article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio{display:none}canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}mark{background:#FF0;color:#000}")),f||(b=!i(a)),b&&(a.documentShived=b),a)}var c=a.html5||{},d=/^<|^(?:button|form|map|select|textarea)$/i,e,f;(function(){var a=b.createElement("a");a.innerHTML="<xyz></xyz>",e="hidden"in a,f=a.childNodes.length==1||function(){try{b.createElement("a")}catch(a){return!0}var c=b.createDocumentFragment();return typeof c.cloneNode=="undefined"||typeof c.createDocumentFragment=="undefined"||typeof c.createElement=="undefined"}()})();var k={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:j};a.html5=k,j(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.testProp=function(a){return C([a])},e.testAllProps=E,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return o.call(a)=="[object Function]"}function e(a){return typeof a=="string"}function f(){}function g(a){return!a||a=="loaded"||a=="complete"||a=="uninitialized"}function h(){var a=p.shift();q=1,a?a.t?m(function(){(a.t=="c"?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){a!="img"&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l={},o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};y[c]===1&&(r=1,y[c]=[],l=b.createElement(a)),a=="object"?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),a!="img"&&(r||y[c]===2?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i(b=="c"?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),p.length==1&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&o.call(a.opera)=="[object Opera]",l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return o.call(a)=="[object Array]"},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,i){var j=b(a),l=j.autoCallback;j.url.split(".").pop().split("?").shift(),j.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]||h),j.instead?j.instead(a,e,f,g,i):(y[j.url]?j.noexec=!0:y[j.url]=1,f.load(j.url,j.forceCSS||!j.forceJS&&"css"==j.url.split(".").pop().split("?").shift()?"c":c,j.noexec,j.attrs,j.timeout),(d(e)||d(l))&&f.load(function(){k(),e&&e(j.origUrl,i,g),l&&l(j.origUrl,i,g),y[j.url]=2})))}function i(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var j,l,m=this.yepnope.loader;if(e(a))g(a,0,m,0);else if(w(a))for(j=0;j<a.length;j++)l=a[j],e(l)?g(l,0,m,0):w(l)?B(l):Object(l)===l&&i(l,m);else Object(a)===a&&i(a,m)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,b.readyState==null&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};<commit_msg>Removido dectecção do border-radius e box-shadow do Modernizr.<commit_after>/* Modernizr 2.6.2 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-textshadow-cssgradients-csstransitions-history-websockets-shiv-cssclasses-testprop-testallprops-prefixes-domprefixes-load
 */
;window.Modernizr=function(a,b,c){function y(a){j.cssText=a}function z(a,b){return y(m.join(a+";")+(b||""))}function A(a,b){return typeof a===b}function B(a,b){return!!~(""+a).indexOf(b)}function C(a,b){for(var d in a){var e=a[d];if(!B(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function D(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:A(f,"function")?f.bind(d||b):f}return!1}function E(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+o.join(d+" ")+d).split(" ");return A(b,"string")||A(b,"undefined")?C(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),D(e,b,c))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w={}.hasOwnProperty,x;!A(w,"undefined")&&!A(w.call,"undefined")?x=function(a,b){return w.call(a,b)}:x=function(a,b){return b in a&&A(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e}),q.history=function(){return!!a.history&&!!history.pushState},q.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},q.textshadow=function(){return b.createElement("div").style.textShadow===""},q.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return y((a+"-webkit- ".split(" ").join(b+a)+m.join(c+a)).slice(0,-a.length)),B(j.backgroundImage,"gradient")},q.csstransitions=function(){return E("transition")};for(var F in q)x(q,F)&&(v=F.toLowerCase(),e[v]=q[F](),t.push((e[v]?"":"no-")+v));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)x(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},y(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.testProp=function(a){return C([a])},e.testAllProps=E,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
<|endoftext|>