<commit_before>/*global app, client*/
"use strict";

var async = require('async');
var BaseCollection = require('./baseCollection');
var MUC = require('./muc');

module.exports = BaseCollection.extend({
    type: 'mucs',
    model: MUC,
    comparator: function (model1, model2) {
        var name1 = model1.displayName.toLowerCase();
        var name2 = model2.displayName.toLowerCase();
        if (name1 === name2) {
            return 0;
        }
        if (name1 < name2) {
            return -1;
        }
        return 1;
    },
    initialize: function (model, options) {
        this.bind('change', this.sort, this);
    },
    loadBookmarks: function () {
        var self = this;
        app.whenConnected(function () {
            client.getBookmarks(function (err, res) {
                if (err) return;

                var mucs = res.privateStorage.bookmarks.conferences;
                mucs.forEach(function (muc) {
                    self.add(muc);
                    if (muc.autoJoin) {
                        self.get(muc.jid).join();
                    }
                });
            });
        });
    },
    init: function () {
        var self = this;
        app.whenConnected(function () {

            function _fetch(init) {
                self.fetch(function() {
                    self.update();
                    if (init) self.trigger('loaded');
                    setTimeout(_fetch, 30000);
                });
            }
            _fetch(true);

        });
    },
    fetch: function(cb) {
        var self = this;
        while(app.mucInfos.length > 0) {
            app.mucInfos.pop();
        }

        if (SERVER_CONFIG.muc) {
            if (client.sessionStarted) {

                var rooms = [];
                client.getDiscoItems(SERVER_CONFIG.muc, '', function (err, res) {
                    if (err) return;

                    rooms = res.discoItems.items;
                    if (rooms === undefined)
                        rooms = [];
                    var roomNum = 0;

                    rooms.forEach (function (room) {
                      client.getDiscoInfo(room.jid, '', function (err, res) {

                        roomNum++;
                        if (err) return;

                        var features = res.discoInfo.features;

                        var persistent = features.indexOf("muc_persistent") > -1;
                        var membersOnly = features.indexOf("muc_membersonly") > -1;

                        var mucInfo = {
                          id: room.jid.full,
                          name: room.name,
                          jid: room.jid,
                          nick: me.nick,
                          autoJoin: persistent,
                          persistent: persistent
                        };

                        if(membersOnly)
                        {
                            async.parallel([
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'member' } ] }, function (err, res) {
                                        if(err) {
                                            console.log(err);
                                            callback(null, false);
                                        }
                                        console.log(res);
                                        var members = res.mucAdmin.items.map(function (item) {
                                            return item.jid.bare;
                                        });
                                        var amMember = members.indexOf(client.jid.bare) > -1;
                                        callback(null, amMember);
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'admin' } ] }, function (err, res) {
                                        if(err) {
                                            console.log(err);
                                            callback(null, false);
                                        }
                                        console.log(res);
                                        var members = res.mucAdmin.items.map(function (item) {
                                            return item.jid.bare;
                                        });
                                        var amMember = members.indexOf(client.jid.bare) > -1;
                                        callback(null, amMember);
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'owner' } ] }, function (err, res) {
                                        if(err) {
                                            console.log(err);
                                            callback(null, false);
                                        }
                                        console.log(res);
                                        var members = res.mucAdmin.items.map(function (item) {
                                            return item.jid.bare;
                                        });
                                        var amMember = members.indexOf(client.jid.bare) > -1;
                                        callback(null, amMember);
                                    })
                                }
                            ],
                            function(err, results){
                                if(results.indexOf('true') > -1)
                                {
                                    app.mucInfos.push(mucInfo);
                                }
                            });
                        }
                        else
                        {
                            app.mucInfos.push(mucInfo);
                        }

                      }).then(function() {
                        if (cb && roomNum == rooms.length) cb();
                      });
                    });
                }).then(function() {
                    if (cb && !rooms.length) cb();
                });

            } else {
                app.whenConnected(function () {
                    self.fetch(cb);
                });
            }
            return;
        }

        if (cb) cb();

    },
    update: function () {
        if (SERVER_CONFIG.muc) {
            var toRemove = [];
            for ( var i = 0; i < this.models.length; i++) {
                toRemove.push(this.models[i]);
            }

            for (var i = 0; i < app.mucInfos.length; i++) {

                var mucInfo = app.mucInfos[i];
                var muc = this.get(mucInfo.jid);
                if (muc) {
                    muc.name = mucInfo.name;
                    muc.autoJoin =  mucInfo.autoJoin;
                    muc.persistent = mucInfo.persistent;

                    var index = toRemove.indexOf(muc);
                    if (index > -1) {
                        toRemove.splice(index, 1);
                    }
                }
                else {
                    this.add(mucInfo);
                    muc = this.get(mucInfo.jid);
                }

                if (muc.autoJoin && !muc.joined) {
                    muc.join();
                }

            }

            this.remove(toRemove);

            while(app.mucInfos.length > 0) {
                app.mucInfos.pop();
            }
        }
    },
    save: function (cb) {
        var self = this;
        app.whenConnected(function () {
            var models = [];
            self.models.forEach(function (model) {
                models.push({
                    name: model.name,
                    jid: model.jid,
                    nick: model.nick,
                    autoJoin: model.autoJoin
                });
            });
            client.setBookmarks({conferences: models}, cb);
        });
    }
});
<commit_msg>Nullchecks<commit_after>/*global app, client*/
"use strict";

var async = require('async');
var BaseCollection = require('./baseCollection');
var MUC = require('./muc');

module.exports = BaseCollection.extend({
    type: 'mucs',
    model: MUC,
    comparator: function (model1, model2) {
        var name1 = model1.displayName.toLowerCase();
        var name2 = model2.displayName.toLowerCase();
        if (name1 === name2) {
            return 0;
        }
        if (name1 < name2) {
            return -1;
        }
        return 1;
    },
    initialize: function (model, options) {
        this.bind('change', this.sort, this);
    },
    loadBookmarks: function () {
        var self = this;
        app.whenConnected(function () {
            client.getBookmarks(function (err, res) {
                if (err) return;

                var mucs = res.privateStorage.bookmarks.conferences;
                mucs.forEach(function (muc) {
                    self.add(muc);
                    if (muc.autoJoin) {
                        self.get(muc.jid).join();
                    }
                });
            });
        });
    },
    init: function () {
        var self = this;
        app.whenConnected(function () {

            function _fetch(init) {
                self.fetch(function() {
                    self.update();
                    if (init) self.trigger('loaded');
                    setTimeout(_fetch, 30000);
                });
            }
            _fetch(true);

        });
    },
    fetch: function(cb) {
        var self = this;
        while(app.mucInfos.length > 0) {
            app.mucInfos.pop();
        }

        if (SERVER_CONFIG.muc) {
            if (client.sessionStarted) {

                var rooms = [];
                client.getDiscoItems(SERVER_CONFIG.muc, '', function (err, res) {
                    if (err) return;

                    rooms = res.discoItems.items;
                    if (rooms === undefined)
                        rooms = [];
                    var roomNum = 0;

                    rooms.forEach (function (room) {
                      client.getDiscoInfo(room.jid, '', function (err, res) {

                        roomNum++;
                        if (err) return;

                        var features = res.discoInfo.features;

                        var persistent = features.indexOf("muc_persistent") > -1;
                        var membersOnly = features.indexOf("muc_membersonly") > -1;

                        var mucInfo = {
                          id: room.jid.full,
                          name: room.name,
                          jid: room.jid,
                          nick: me.nick,
                          autoJoin: persistent,
                          persistent: persistent
                        };

                        if(membersOnly)
                        {
                            async.parallel([
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'member' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, false);
                                        }
                                        if(res.mucAdmin.items)
                                        {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember);
                                        }
                                        else
                                        {
                                            callback(null, false);
                                        }
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'admin' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, false);
                                        }
                                        if(res.mucAdmin.items)
                                        {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember);
                                        }
                                        else
                                        {
                                            callback(null, false);
                                        }
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'owner' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, false);
                                        }
                                        if(res.mucAdmin.items)
                                        {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember);
                                        }
                                        else
                                        {
                                            callback(null, false);
                                        }
                                    })
                                }
                            ],
                            function(err, results){
                                if(results.indexOf('true') > -1)
                                {
                                    app.mucInfos.push(mucInfo);
                                }
                            });
                        }
                        else
                        {
                            app.mucInfos.push(mucInfo);
                        }

                      }).then(function() {
                        if (cb && roomNum == rooms.length) cb();
                      });
                    });
                }).then(function() {
                    if (cb && !rooms.length) cb();
                });

            } else {
                app.whenConnected(function () {
                    self.fetch(cb);
                });
            }
            return;
        }

        if (cb) cb();

    },
    update: function () {
        if (SERVER_CONFIG.muc) {
            var toRemove = [];
            for ( var i = 0; i < this.models.length; i++) {
                toRemove.push(this.models[i]);
            }

            for (var i = 0; i < app.mucInfos.length; i++) {

                var mucInfo = app.mucInfos[i];
                var muc = this.get(mucInfo.jid);
                if (muc) {
                    muc.name = mucInfo.name;
                    muc.autoJoin =  mucInfo.autoJoin;
                    muc.persistent = mucInfo.persistent;

                    var index = toRemove.indexOf(muc);
                    if (index > -1) {
                        toRemove.splice(index, 1);
                    }
                }
                else {
                    this.add(mucInfo);
                    muc = this.get(mucInfo.jid);
                }

                if (muc.autoJoin && !muc.joined) {
                    muc.join();
                }

            }

            this.remove(toRemove);

            while(app.mucInfos.length > 0) {
                app.mucInfos.pop();
            }
        }
    },
    save: function (cb) {
        var self = this;
        app.whenConnected(function () {
            var models = [];
            self.models.forEach(function (model) {
                models.push({
                    name: model.name,
                    jid: model.jid,
                    nick: model.nick,
                    autoJoin: model.autoJoin
                });
            });
            client.setBookmarks({conferences: models}, cb);
        });
    }
});
<|endoftext|>


<commit_before>//based loosely on bostock's example and
//http://bl.ocks.org/d3noob/5141278

var nodes = data.nodes
var links = data.links
var count = 0
for (i in links) {
   if (count<links[i].value) count = links[i].value
}

var ele = document.getElementById("vis"),
    //width = ele.offsetWidth+1200
    //height = ele.offsetHeight+1200
    width = ele.clientWidth - 25,
    height= ele.clientHeight - 25;

var force = d3.layout.force()
    .charge([-250])
    .linkDistance([75])
    .size([width, height])
    .nodes(nodes)
    .links(links)
    .start();

var drag = force.drag();
drag.on("dragstart",dragstart)
	.on("dragend",dragend);

var defaultColors = d3.scale.category20(); //10 or 20

var svg = d3.select("#vis").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(d3.behavior.zoom().center([width/2, height/2]).scaleExtent([0.1,5]).on("zoom",zoomHandler)).on("dblclick.zoom",null).on("mousedown.zoom",null);

var isSelected = false;
var isDragging = false;

var svgGroup = svg.append("g");

//var outer_box = svg.append("rect")
 //   .attr("width", width*2)
  //  .attr("height", height*2)
  //  .attr("x", 0)
  //  .attr("y", 0)
  //  .attr("id","outer_box")    //.attr("fill","none")
  //  	.attr("fill", "grey")
  //  	.attr("opacity", 0.1)
  //  .attr("pointer-events","all")
  //  .on("mousemove", manualZoom);

//console.log(outer_box);

svg.append("svg:defs").selectAll("marker")
    .data(["end"])// Different path types defined here
    .enter().append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", 0)
    .attr("markerUnits", "userSpaceOnUse")
    .style("fill", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .attr("markerWidth", 10)
    .attr("markerHeight", 10)
    .attr("orient", "auto")
    .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var link = svgGroup.append("svg:g").selectAll("path")
    .data(links)
    .enter().append("svg:path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)")
    .style("stroke-width", function (d) {
        return d.width || "1.5"
    })
    .style("stroke", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .style("stroke-dasharray", function(d) {
        return d.dasharray || ""
    })
    .style("fill", "none")

//scale values between 1 and 100 to a reasonable range
var scaleSize = d3.scale.linear()
    .domain([1,100])
    .range([80,4000]);

//outer node
var node = svgGroup.selectAll(".node")
    .data(nodes)
    .enter().append("g")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("dblclick", dblclick)
    .call(force.drag)

//inner nodes
node
    .append('path')
    .attr("class", "node")
    .attr("d", d3.svg.symbol()
        .type(function(d) { return d.shape || "circle"; })
        .size(function(d) {return scaleSize(d.size || 1); })
    )
    .style("fill", function(d, i) {
        return d.color || defaultColors(i);
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })

//inner nodes
node
    .append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .style("color",'black')
    .style("display", "none")
    .text(function(d) {
        return d.name;
    });

// Function to add line breaks to node labels/names
var insertLineBreaks = function(d) {
	var el = d3.select(this);
	var words = d3.select(this).text().split('\n');
	el.text('');

	for (var i = 0; i < words.length; i++) {
	    var tspan = el.append('tspan').text(words[i]);
	    if (i > 0)
		tspan.attr('x',0).attr('dy','15');
	}
}

// Add line breaks to node labels
svgGroup.selectAll('text').each(insertLineBreaks);

force.on("tick", function() {
    link
        .attr("d", function(d) {
            var dx = d.target.x - d.source.x,
                dy = d.target.y - d.source.y,
                dr = Math.sqrt(dx * dx + dy * dy);
            return "M" +
                d.source.x + "," +
                d.source.y + "A" +
                dr + "," + dr + " 0 0,1 " +
                d.target.x + "," +
                d.target.y;
        });

    node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
})

function mouseover() {
    //isSelected = true;
    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","block")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(40))()
        })
}
function mouseup(){
    isSelected = false;
    d3.event.translate([0,0]);
}

function mouseout() {
    //if(!isDragging)
   // {
    //  isSelected = false;
    //  var zm = d3.behavior.zoom();
    //  zm.translate([0,0]);
   // }
    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","none")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(d.size||1))()
        })

}

// zoom function
function zoomHandler() {
    //if(!isSelected)
	svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
	//svgGroup.attr("transform", "scale(" + d3.event.scale + ")");
}

// Handle doubleclick on node path (shape)
function dblclick(d) {
    d3.select(this).classed("fixed", d.fixed = false);
}

// Handle dragstart on force.drag()
function dragstart(d) {
    //console.log(this, d);
    //isDragging = true;
    d3.select(this).classed("fixed", d.fixed = true);
}

function dragend(d){
	//isDragging = false;
}
<commit_msg>fixing zoom<commit_after>//based loosely on bostock's example and
//http://bl.ocks.org/d3noob/5141278

var nodes = data.nodes
var links = data.links
var count = 0
for (i in links) {
   if (count<links[i].value) count = links[i].value
}

var ele = document.getElementById("vis"),
    //width = ele.offsetWidth+1200
    //height = ele.offsetHeight+1200
    width = ele.clientWidth - 15,
    height= ele.clientHeight - 15;

var force = d3.layout.force()
    .charge([-250])
    .linkDistance([50])
    .size([width, height])
    .nodes(nodes)
    .links(links)
    .gravity(0.001)
    .start();

var drag = force.drag();
drag.on("dragstart",dragstart)
	.on("dragend",dragend);

var defaultColors = d3.scale.category20(); //10 or 20

var svg = d3.select("#vis").append("svg")
    .attr("width", width)
    .attr("height", height)
    .call(d3.behavior.zoom().center([width/2, height/2]).scaleExtent([0.1,5]).on("zoom",zoomHandler)).on("dblclick.zoom",null).on("mousedown.zoom",null);

var isSelected = false;
var isDragging = false;

var svgGroup = svg.append("g");

//var outer_box = svg.append("rect")
 //   .attr("width", width*2)
  //  .attr("height", height*2)
  //  .attr("x", 0)
  //  .attr("y", 0)
  //  .attr("id","outer_box")    //.attr("fill","none")
  //  	.attr("fill", "grey")
  //  	.attr("opacity", 0.1)
  //  .attr("pointer-events","all")
  //  .on("mousemove", manualZoom);

//console.log(outer_box);

svg.append("svg:defs").selectAll("marker")
    .data(["end"])// Different path types defined here
    .enter().append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", 0)
    .attr("markerUnits", "userSpaceOnUse")
    .style("fill", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .attr("markerWidth", 10)
    .attr("markerHeight", 10)
    .attr("orient", "auto")
    .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var link = svgGroup.append("svg:g").selectAll("path")
    .data(links)
    .enter().append("svg:path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)")
    .style("stroke-width", function (d) {
        return d.width || "1.5"
    })
    .style("stroke", function (d) {
        return d.color || "black"
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })
    .style("stroke-dasharray", function(d) {
        return d.dasharray || ""
    })
    .style("fill", "none")

//scale values between 1 and 100 to a reasonable range
var scaleSize = d3.scale.linear()
    .domain([1,100])
    .range([80,4000]);

//outer node
var node = svgGroup.selectAll(".node")
    .data(nodes)
    .enter().append("g")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("dblclick", dblclick)
    .call(force.drag)

//inner nodes
node
    .append('path')
    .attr("class", "node")
    .attr("d", d3.svg.symbol()
        .type(function(d) { return d.shape || "circle"; })
        .size(function(d) {return scaleSize(d.size || 1); })
    )
    .style("fill", function(d, i) {
        return d.color || defaultColors(i);
    })
    .style("opacity", function(d) {
        return d.opacity || 1
    })

//inner nodes
node
    .append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .style("color",'black')
    .style("display", "none")
    .text(function(d) {
        return d.name;
    });

// Function to add line breaks to node labels/names
var insertLineBreaks = function(d) {
	var el = d3.select(this);
	var words = d3.select(this).text().split('\n');
	el.text('');

	for (var i = 0; i < words.length; i++) {
	    var tspan = el.append('tspan').text(words[i]);
	    if (i > 0)
		tspan.attr('x',0).attr('dy','15');
	}
}

// Add line breaks to node labels
svgGroup.selectAll('text').each(insertLineBreaks);

force.on("tick", function() {
    link
        .attr("d", function(d) {
            var dx = d.target.x - d.source.x,
                dy = d.target.y - d.source.y,
                dr = Math.sqrt(dx * dx + dy * dy);
            return "M" +
                d.source.x + "," +
                d.source.y + "A" +
                dr + "," + dr + " 0 0,1 " +
                d.target.x + "," +
                d.target.y;
        });

    node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
})

function mouseover() {
    //isSelected = true;
    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","block")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(40))()
        })
}
function mouseup(){
    isSelected = false;
    d3.event.translate([0,0]);
}

function mouseout() {
    //if(!isDragging)
   // {
    //  isSelected = false;
    //  var zm = d3.behavior.zoom();
    //  zm.translate([0,0]);
   // }
    d3.select(this).select("text").transition()
        .duration(750)
        .style("display","none")
    d3.select(this).select("path").transition()
        .duration(750)
        .attr('d', function (d) {
            return d3.svg.symbol().type(d.shape||"circle")
                    .size(scaleSize(d.size||1))()
        })

}

// zoom function
function zoomHandler() {
    //if(!isSelected)
	svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
	//svgGroup.attr("transform", "scale(" + d3.event.scale + ")");
}

// Handle doubleclick on node path (shape)
function dblclick(d) {
    d3.select(this).classed("fixed", d.fixed = false);
}

// Handle dragstart on force.drag()
function dragstart(d) {
    //console.log(this, d);
    //isDragging = true;
    d3.select(this).classed("fixed", d.fixed = true);
}

function dragend(d){
	//isDragging = false;
}
<|endoftext|>


<commit_before>"use strict";

angular.module('app', [])
  .config(($stateProvider, $urlRouterProvider, $httpProvider, $urlRouterProvider) => {
    $urlRouterProvider.otherwise('/dashbaord');
    $stateProvider
      .state('dashboard', {
        url: '/dashboard',
        templateUrl: 'app/dashbaord/dashbaord.html',
        controller: 'DashboardCtrl'
      })
      .state('signin', {
        url: '/signin',
        templateUrl: 'app/auth/signin.html',
        controller: 'AuthCtrl'
      })
      .state('signup', {
        url: '/signup',
        templateUrl: 'app/auth/signup.html',
        controller: 'AuthCtrl'
      })
      .state('medications', {
        url: '/medications',
        templateUrl: 'app/auth/medications.html',
        controller: 'MedicationCtrl'
      });
      $httpProvider.interceptors.push('AttachTokens');
    })
    .factory('AttachTokens', ($window) => {

      let attach = {
        request: (object) => {

          let jwt = $window.localStorage.getItem('com.pillMeNow');

          if (jwt) {
            object.headers['x-access-token'] = jwt;
          }

          object.headers['Allow-Control-Allow-Origin'] = '*';

          return object;

        }
      };

      return attach;

    })
    .run(($rootScope, $state, Auth) => {
      $rootScope.on('$stateChangeStart', (evt, toState) => {

        if (toState.name === 'signin') return;

        if (!Auth.isAuth() && toState.name !== 'signup') {
          evt.preventDefault();
          $state.go('signin');
        }

      });
    });
<commit_msg>refactor<commit_after>(() => {
  "use strict";

  angular.module('app', [])
    .config(($stateProvider, $urlRouterProvider, $httpProvider, $urlRouterProvider) => {
      $urlRouterProvider.otherwise('/dashbaord');
      $stateProvider
        .state('dashboard', {
          url: '/dashboard',
          templateUrl: 'app/dashbaord/dashbaord.html',
          controller: 'DashboardCtrl'
        })
        .state('signin', {
          url: '/signin',
          templateUrl: 'app/auth/signin.html',
          controller: 'AuthCtrl'
        })
        .state('signup', {
          url: '/signup',
          templateUrl: 'app/auth/signup.html',
          controller: 'AuthCtrl'
        })
        .state('medications', {
          url: '/medications',
          templateUrl: 'app/auth/medications.html',
          controller: 'MedicationCtrl'
        });
        $httpProvider.interceptors.push('AttachTokens');
      })
      .factory('AttachTokens', attachTokens)
      .run(appRun);
}();

function attachTokens = ($window) => {

  let attach = {
    request: (object) => {

      let jwt = $window.localStorage.getItem('com.pillMeNow');

      if (jwt) {
        object.headers['x-access-token'] = jwt;
      }

      object.headers['Allow-Control-Allow-Origin'] = '*';

      return object;

    }
  };

  return attach;

}

function appRun = ($rootScope, $state, Auth) => {
  $rootScope.on('$stateChangeStart', (evt, toState) => {

    if (toState.name === 'signin') return;

    if (!Auth.isAuth() && toState.name !== 'signup') {
      evt.preventDefault();
      $state.go('signin');
    }

  });
}
<|endoftext|>


<commit_before>// models a cart item
var CartItem = function(description, sku, price, shippingType, weight, quantity){

	var self = this;
	self.description = ko.observable(description);
	self.sku = ko.observable(sku);
	self.price = ko.observable(price);
	self.shippingType = ko.observable(shippingType);
	self.weight = ko.observable(weight);
	self.quantity = ko.observable(quantity);

	self.priceFriendly = ko.computed(function(){
		var p = self.price() + ' ' + cartModel.currency;

		if(cartModel.currency == 'USD'){
			p = '$' + p;
		}

    	return p;
	});

	// total weight for line item
	self.totalWeight = ko.computed(function(){

		var weight = parseFloat(self.weight()) * parseInt(self.quantity());

		return Number(weight);
	});

	// total price for line item
	self.total = ko.computed(function(){

		var total = parseFloat(self.price()) * parseInt(self.quantity());

		return Number(total);
	});

	// total price for line item (formatted)
	self.totalFriendly = ko.computed(function(){

		var total = parseFloat(self.price()) * parseInt(self.quantity());

		var p = Number(total).toFixed(2) + ' ' + cartModel.currency;

		if(cartModel.currency == 'USD'){
			p = '$' + p;
		}

		return p;
	});
}

// models the cart
var cartModel = {

   	payPalId: '',
   	currency: 'USD',
   	weightUnit: 'kgs',
   	taxRate: 0,
   	returnUrl: 'return',
   	calculation: 'free',
   	flatRate: 0,
   	tiers: [],

    items: ko.observableArray([]),

    init:function(){

    	cartModel.payPalId = $('#cart').attr('data-currency');
    	cartModel.currency = $('#cart').attr('data-currency');
    	cartModel.weightUnit = $('#cart').attr('data-weightunit');
    	cartModel.calculation = $('#cart').attr('data-shippingcalculation');
		cartModel.flatRate = Number($('#cart').attr('data-shippingrate'));
		cartModel.tiers = $('#cart').attr('data-shippingtiers');

		// validate flatrate
		if(isNaN(cartModel.flatRate)){
			cartModel.flatRate = 0;
		}

		// parse tiers if not empty
		if(cartModel.tiers != ''){
	    	cartModel.tiers = JSON.parse(decodeURI(tiers));
	    }
	    else{
		    cartModel.tiers = [];
	    }

    	// get taxrate
    	var taxRate = Number($('#cart').attr('data-taxrate').replace(/[^0-9\.]+/g, ''));

    	if(!isNaN(taxRate)){
    		cartModel.taxRate = taxRate;
    	}

    	var url = 'http://' + $('body').attr('data-domain') + '/return';
    	cartModel.returnUrl = url;

    	// setup events used by the cart
    	cartModel.setupEvents();

    	// grab cart from localStorage
    	cartModel.updateCart();

        // apply bindings
        ko.applyBindings(cartModel, $('#cart').get(0));

	},

	// setup events
	setupEvents:function(){

		// toggles the cart
		$('.cart-toggle').on('click', function(){

			$('#cart').toggleClass('active');

		});

		// handle add to cart
		$('.shelf-add button').on('click', function(){

			var shelfItem = $(this).parents('.shelf-item');

			var description = $(shelfItem).find('.shelf-description').text();
			var sku = $(shelfItem).find('.shelf-sku').text();

			// get price
			var price = Number($(shelfItem).find('.shelf-price').attr('data-price'));

			// handle error
	    	if(isNaN(price)){
	    		throw('cartModel.js: pricing error');
	    	}

			var type = $(shelfItem).find('.shelf-shipping').attr('data-type');

			// get weight
			var weight = Number($(shelfItem).find('.shelf-shipping').attr('data-weight'));

	    	// handle error (set default weight to 0)
	    	if(isNaN(weight)){
	    		weight = 0;
	    	}

			// get quantity
			var quantity = Number($(shelfItem).find('.shelf-quantity input').val());

	    	// handle error (set default quantity to 1)
	    	if(isNaN(quantity)){
	    		quantity = 1;
	    	}

			// create new cart item
			var item = new CartItem(description, sku, price, type, weight, quantity);

			// check for match
			var match = false;
			match = ko.utils.arrayFirst(cartModel.items(), function (curr) {
                            if(curr.sku().toUpperCase() == item.sku().toUpperCase()){
                            	// get new quantity
                            	var q = parseInt(curr.quantity()) + parseInt(quantity);

                            	// update quantity
                            	curr.quantity(q);

                            	return true;
                            }
                        });

            // if match is not found, push item to the cart, or else +1 to quantity of existing item
            if(!match){
                cartModel.items.push(item);
            }

            // update external references and save the cart
			cartModel.updateExternal();
			cartModel.saveCart();

		});

	},

	// updates cart from local storage
	updateCart:function(){

		if(localStorage['respond-cart']){

			var str = localStorage['respond-cart'];

			var storedItems = eval(str);

			for(x=0; x<storedItems.length; x++){
				// #debug console.log(storedItems[x]);

				var description = storedItems[x].description;
				var sku = storedItems[x].sku;
				var price = Number(storedItems[x].price);
				var type = storedItems[x].shippingType;
				var weight = Number(storedItems[x].weight);
				var quantity = Number(storedItems[x].quantity);

				// create new cart item
				var item = new CartItem(description, sku, price, type, weight, quantity);

				// push item to model
				cartModel.items.push(item);
			}

		}

		// update external elements
		cartModel.updateExternal();

	},

	// save cart
	saveCart:function(){

		var json = ko.toJSON(cartModel.items());

		localStorage['respond-cart'] = json;

	},

	// updates external references to the cart
	updateExternal:function(){

		$('.cart-count').text(cartModel.count());
		$('.cart-total').text(cartModel.subtotalFriendly());

	},

	// updates the cart quantity
	updateQuantity:function(o, e){
		var q = parseInt($(e.target).val());

		if(q<=0){
			cartModel.items.remove(o);
		}
		else{
			o.quantity(q);
		}

		// update external references and save the cart
		cartModel.updateExternal();
		cartModel.saveCart();

	},

	// removes an item from a cart
	removeFromCart:function(o, e){
		cartModel.items.remove(o);

		// update external references and save the cart
		cartModel.updateExternal();
		cartModel.saveCart();
	},

	// checkout using PayPal
	checkoutWithPayPal:function(o, e){

		var email = $(e.target).attr('data-email');

		// data setup
		// #ref tutorial: https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/cart_upload/
		// #ref: form: https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/#id08A6HF00TZS
		var data = {
			'email':			email,
			'cmd':				'_cart',
			'upload':			'1',
			'currency_code': 	cartModel.currency,
			'business':			email,
			'rm':				'0',
			'charset':			'utf-8',
			'return':			cartModel.returnUrl + '?processor=paypal&action=success',
			'cancel_return':	cartModel.returnUrl + '?processor=paypal&action=cancel',
			'notify_url':		cartModel.returnUrl + '?processor=paypal&action=notify'
		};

		var noshipping = 1;

		// add cart items
		for (x=0; x<cartModel.items().length; x++){

			var c = x+1;

			var item = cartModel.items()[x];

			data['item_name_'+c] = item.description();
			data['quantity_'+c] = item.quantity();
			data['amount_'+c] = item.price().toFixed(2);
			data['item_number_'+c] = item.sku();

			if(item.shippingType == 'shipped'){
				noshipping = 2;
			}

		}

		data['no_shipping'] = noshipping; // 1 = do not prompt, 2 = prompt for address and require it
		data['weight_unit'] = cartModel.weightUnit;
		data['handling_cart'] = cartModel.shipping().toFixed(2);
		data['tax_cart'] = cartModel.tax().toFixed(2);

		//var url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; // sandbox
		var url = 'https://www.paypal.com/cgi-bin/webscr'; // live

		// create form with data values
		var form = $('<form id="paypal-form" action="' + url + '" method="POST"></form');

		for(x in data){
			form.append('<input type="hidden" name="'+x+'" value="'+data[x]+'" />');
		}

		// append form
		$('body').append(form);

		// submit form
		$('#paypal-form').submit();

	}
}

// total count calculation
cartModel.count = ko.computed(function() {
    var count = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
        count += item.quantity();
    });

    return count;
}, cartModel);

// total count of shipped items
cartModel.countShipped = ko.computed(function() {
    var count = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
    	if(item.shippingType() == 'shipped'){
        	count += item.quantity();
        }
    });

    return count;
}, cartModel);

// subtotal calculation (line item total)
cartModel.subtotal = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
        total += item.total();
    });

    return total;
}, cartModel);

// subtotal calculation for shipped items (line item total)
cartModel.subtotalShipped = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
        if(item.shippingType() == 'shipped'){
        	total += item.total();
        }
    });

    return total;
}, cartModel);

// subtotal display
cartModel.subtotalFriendly = ko.computed(function() {
    var p = cartModel.subtotal().toFixed(2) + ' ' + cartModel.currency;

    if(cartModel.currency == 'USD'){
		p = '$' + p;
	}

    return p;
}, cartModel);

// tax calculation (subtotal * rate)
cartModel.tax = ko.computed(function() {
	return cartModel.subtotal() * cartModel.taxRate;
}, cartModel);

// tax display
cartModel.taxFriendly = ko.computed(function() {
    var p = cartModel.tax().toFixed(2) + ' ' + cartModel.currency;

    if(cartModel.currency == 'USD'){
		p = '$' + p;
	}

	p = '(' + cartModel.taxRate + '%) ' + p;

    return p;
}, cartModel);

// total weight calculation
cartModel.totalWeight = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
    	if(item.shippingType() == 'shipped'){
        	total += item.totalWeight();
        }
    });

    return total;
}, cartModel);

// total weight display
cartModel.totalWeightFriendly = ko.computed(function() {
   return cartModel.totalWeight() + ' ' + this.weightUnit;
}, cartModel);

// shipping calculation (based on settings)
cartModel.shipping = ko.computed(function() {

    var stop = 0;

    // get totals (this also makes sure the model is up-to-date)
    var subtotal = cartModel.subtotalShipped();
	var totalWeight = cartModel.totalWeight();

	// get params
	var calculation = cartModel.calculation;
	var flatRate = cartModel.flatRate;
	var tiers = cartModel.tiers;

    if(calculation == 'free'){
	    return 0;
    }
    else if(calculation == 'flat-rate'){
    	if(cartModel.countShipped() > 0){
			return flatRate;
		}
		else{
			return 0;
		}
    }
    else if(calculation == 'amount'){
	    stop = subtotal;
    }
    else if(calculation == 'weight'){
	    stop = totalWeight;
    }
    else{
	    return 0;
    }

    // walk through tiers
    for(x=0; x<tiers.length; x++){
	    var from = tiers[x].from;
	    var to = tiers[x].to;

	    // determine if rate falls between to and from
	    if(stop > from && stop <= to){
		    var rate = Number(tiers[x].rate);

		    console.log('rate='+rate);

		    // return rate
		    if(!isNaN(rate)){
			    return rate;
		    }
	    }

    }

    // easy default
    return 0;

}, cartModel);

// shipping display
cartModel.shippingFriendly = ko.computed(function() {

    var p = cartModel.shipping().toFixed(2) + ' ' + this.currency;

    if(this.currency == 'USD'){
		p = '$' + p;
	}

    return p;
}, cartModel);

// total calculation (subtotal + shipping + tax)
cartModel.total = ko.computed(function() {

    var total = cartModel.subtotal() + cartModel.shipping() + cartModel.tax();
	return total;

}, cartModel);

// total display
cartModel.totalFriendly = ko.computed(function() {

    var p = cartModel.total().toFixed(2) + ' ' + this.currency;

    if(this.currency == 'USD'){
		p = '$' + p;
	}

    return p;
}, cartModel);

// init model
$(document).ready(function(){cartModel.init();});
<commit_msg>fix paypal integration<commit_after>// models a cart item
var CartItem = function(description, sku, price, shippingType, weight, quantity){

	var self = this;
	self.description = ko.observable(description);
	self.sku = ko.observable(sku);
	self.price = ko.observable(price);
	self.shippingType = ko.observable(shippingType);
	self.weight = ko.observable(weight);
	self.quantity = ko.observable(quantity);

	self.priceFriendly = ko.computed(function(){
		var p = self.price() + ' ' + cartModel.currency;

		if(cartModel.currency == 'USD'){
			p = '$' + p;
		}

    	return p;
	});

	// total weight for line item
	self.totalWeight = ko.computed(function(){

		var weight = parseFloat(self.weight()) * parseInt(self.quantity());

		return Number(weight);
	});

	// total price for line item
	self.total = ko.computed(function(){

		var total = parseFloat(self.price()) * parseInt(self.quantity());

		return Number(total);
	});

	// total price for line item (formatted)
	self.totalFriendly = ko.computed(function(){

		var total = parseFloat(self.price()) * parseInt(self.quantity());

		var p = Number(total).toFixed(2) + ' ' + cartModel.currency;

		if(cartModel.currency == 'USD'){
			p = '$' + p;
		}

		return p;
	});
}

// models the cart
var cartModel = {

   	payPalId: '',
   	currency: 'USD',
   	weightUnit: 'kgs',
   	taxRate: 0,
   	returnUrl: 'return',
   	calculation: 'free',
   	flatRate: 0,
   	tiers: [],

    items: ko.observableArray([]),

    init:function(){

    	cartModel.payPalId = $('#cart').attr('data-paypalid');
    	cartModel.currency = $('#cart').attr('data-currency');
    	cartModel.weightUnit = $('#cart').attr('data-weightunit');
    	cartModel.calculation = $('#cart').attr('data-shippingcalculation');
		cartModel.flatRate = Number($('#cart').attr('data-shippingrate'));
		cartModel.tiers = $('#cart').attr('data-shippingtiers');

		// validate flatrate
		if(isNaN(cartModel.flatRate)){
			cartModel.flatRate = 0;
		}

		// parse tiers if not empty
		if(cartModel.tiers != ''){
	    	cartModel.tiers = JSON.parse(decodeURI(tiers));
	    }
	    else{
		    cartModel.tiers = [];
	    }

    	// get taxrate
    	var taxRate = Number($('#cart').attr('data-taxrate').replace(/[^0-9\.]+/g, ''));

    	if(!isNaN(taxRate)){
    		cartModel.taxRate = taxRate;
    	}

    	var url = 'http://' + $('body').attr('data-domain') + '/';
    	cartModel.returnUrl = url;

    	// setup events used by the cart
    	cartModel.setupEvents();

    	// grab cart from localStorage
    	cartModel.updateCart();

        // apply bindings
        ko.applyBindings(cartModel, $('#cart').get(0));

	},

	// setup events
	setupEvents:function(){

		// toggles the cart
		$('.cart-toggle').on('click', function(){

			$('#cart').toggleClass('active');

		});

		// handle add to cart
		$('.shelf-add button').on('click', function(){

			var shelfItem = $(this).parents('.shelf-item');

			var description = $(shelfItem).find('.shelf-description').text();
			var sku = $(shelfItem).find('.shelf-sku').text();

			// get price
			var price = Number($(shelfItem).find('.shelf-price').attr('data-price'));

			// handle error
	    	if(isNaN(price)){
	    		throw('cartModel.js: pricing error');
	    	}

			var type = $(shelfItem).find('.shelf-shipping').attr('data-type');

			// get weight
			var weight = Number($(shelfItem).find('.shelf-shipping').attr('data-weight'));

	    	// handle error (set default weight to 0)
	    	if(isNaN(weight)){
	    		weight = 0;
	    	}

			// get quantity
			var quantity = Number($(shelfItem).find('.shelf-quantity input').val());

	    	// handle error (set default quantity to 1)
	    	if(isNaN(quantity)){
	    		quantity = 1;
	    	}

			// create new cart item
			var item = new CartItem(description, sku, price, type, weight, quantity);

			// check for match
			var match = false;
			match = ko.utils.arrayFirst(cartModel.items(), function (curr) {
                            if(curr.sku().toUpperCase() == item.sku().toUpperCase()){
                            	// get new quantity
                            	var q = parseInt(curr.quantity()) + parseInt(quantity);

                            	// update quantity
                            	curr.quantity(q);

                            	return true;
                            }
                        });

            // if match is not found, push item to the cart, or else +1 to quantity of existing item
            if(!match){
                cartModel.items.push(item);
            }

            // update external references and save the cart
			cartModel.updateExternal();
			cartModel.saveCart();

		});

	},

	// updates cart from local storage
	updateCart:function(){

		if(localStorage['respond-cart']){

			var str = localStorage['respond-cart'];

			var storedItems = eval(str);

			for(x=0; x<storedItems.length; x++){
				// #debug console.log(storedItems[x]);

				var description = storedItems[x].description;
				var sku = storedItems[x].sku;
				var price = Number(storedItems[x].price);
				var type = storedItems[x].shippingType;
				var weight = Number(storedItems[x].weight);
				var quantity = Number(storedItems[x].quantity);

				// create new cart item
				var item = new CartItem(description, sku, price, type, weight, quantity);

				// push item to model
				cartModel.items.push(item);
			}

		}

		// update external elements
		cartModel.updateExternal();

	},

	// save cart
	saveCart:function(){

		var json = ko.toJSON(cartModel.items());

		localStorage['respond-cart'] = json;

	},

	// updates external references to the cart
	updateExternal:function(){

		$('.cart-count').text(cartModel.count());
		$('.cart-total').text(cartModel.subtotalFriendly());

	},

	// updates the cart quantity
	updateQuantity:function(o, e){
		var q = parseInt($(e.target).val());

		if(q<=0){
			cartModel.items.remove(o);
		}
		else{
			o.quantity(q);
		}

		// update external references and save the cart
		cartModel.updateExternal();
		cartModel.saveCart();

	},

	// removes an item from a cart
	removeFromCart:function(o, e){
		cartModel.items.remove(o);

		// update external references and save the cart
		cartModel.updateExternal();
		cartModel.saveCart();
	},

	// checkout using PayPal
	checkoutWithPayPal:function(o, e){

		var email = cartModel.payPalId;

		// data setup
		// #ref tutorial: https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/cart_upload/
		// #ref: form: https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/#id08A6HF00TZS
		// #ref: notify: https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNIntro/
		var data = {
			'email':			email,
			'cmd':				'_cart',
			'upload':			'1',
			'currency_code': 	cartModel.currency,
			'business':			email,
			'rm':				'0',
			'charset':			'utf-8',
			'return':			cartModel.returnUrl + 'thankyou?p=paypal',
			'cancel_return':	cartModel.returnUrl + 'cancel?p=paypal',
			'notify_url':		cartModel.returnUrl + 'notify?p=paypal'
		};

		var noshipping = 1;

		// add cart items
		for (x=0; x<cartModel.items().length; x++){

			var c = x+1;

			var item = cartModel.items()[x];

			data['item_name_'+c] = item.description();
			data['quantity_'+c] = item.quantity();
			data['amount_'+c] = item.price().toFixed(2);
			data['item_number_'+c] = item.sku();

			if(item.shippingType() == 'shipped'){
				noshipping = 2;
			}

		}

		data['no_shipping'] = noshipping; // 1 = do not prompt, 2 = prompt for address and require it
		data['weight_unit'] = cartModel.weightUnit;
		data['handling_cart'] = cartModel.shipping().toFixed(2);
		data['tax_cart'] = cartModel.tax().toFixed(2);

		//var url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; // sandbox
		var url = 'https://www.paypal.com/cgi-bin/webscr'; // live

		// create form with data values
		var form = $('<form id="paypal-form" action="' + url + '" method="POST"></form');

		for(x in data){
			form.append('<input type="hidden" name="'+x+'" value="'+data[x]+'" />');
		}

		// append form
		$('body').append(form);

		// submit form
		$('#paypal-form').submit();

	}
}

// total count calculation
cartModel.count = ko.computed(function() {
    var count = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
        count += item.quantity();
    });

    return count;
}, cartModel);

// total count of shipped items
cartModel.countShipped = ko.computed(function() {
    var count = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
    	if(item.shippingType() == 'shipped'){
        	count += item.quantity();
        }
    });

    return count;
}, cartModel);

// subtotal calculation (line item total)
cartModel.subtotal = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
        total += item.total();
    });

    return total;
}, cartModel);

// subtotal calculation for shipped items (line item total)
cartModel.subtotalShipped = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
        if(item.shippingType() == 'shipped'){
        	total += item.total();
        }
    });

    return total;
}, cartModel);

// subtotal display
cartModel.subtotalFriendly = ko.computed(function() {
    var p = cartModel.subtotal().toFixed(2) + ' ' + cartModel.currency;

    if(cartModel.currency == 'USD'){
		p = '$' + p;
	}

    return p;
}, cartModel);

// tax calculation (subtotal * rate)
cartModel.tax = ko.computed(function() {
	return cartModel.subtotal() * cartModel.taxRate;
}, cartModel);

// tax display
cartModel.taxFriendly = ko.computed(function() {
    var p = cartModel.tax().toFixed(2) + ' ' + cartModel.currency;

    if(cartModel.currency == 'USD'){
		p = '$' + p;
	}

	p = '(' + cartModel.taxRate + '%) ' + p;

    return p;
}, cartModel);

// total weight calculation
cartModel.totalWeight = ko.computed(function() {
    var total = 0;
    ko.utils.arrayForEach(this.items(), function(item) {
    	if(item.shippingType() == 'shipped'){
        	total += item.totalWeight();
        }
    });

    return total;
}, cartModel);

// total weight display
cartModel.totalWeightFriendly = ko.computed(function() {
   return cartModel.totalWeight() + ' ' + this.weightUnit;
}, cartModel);

// shipping calculation (based on settings)
cartModel.shipping = ko.computed(function() {

    var stop = 0;

    // get totals (this also makes sure the model is up-to-date)
    var subtotal = cartModel.subtotalShipped();
	var totalWeight = cartModel.totalWeight();

	// get params
	var calculation = cartModel.calculation;
	var flatRate = cartModel.flatRate;
	var tiers = cartModel.tiers;

    if(calculation == 'free'){
	    return 0;
    }
    else if(calculation == 'flat-rate'){
    	if(cartModel.countShipped() > 0){
			return flatRate;
		}
		else{
			return 0;
		}
    }
    else if(calculation == 'amount'){
	    stop = subtotal;
    }
    else if(calculation == 'weight'){
	    stop = totalWeight;
    }
    else{
	    return 0;
    }

    // walk through tiers
    for(x=0; x<tiers.length; x++){
	    var from = tiers[x].from;
	    var to = tiers[x].to;

	    // determine if rate falls between to and from
	    if(stop > from && stop <= to){
		    var rate = Number(tiers[x].rate);

		    console.log('rate='+rate);

		    // return rate
		    if(!isNaN(rate)){
			    return rate;
		    }
	    }

    }

    // easy default
    return 0;

}, cartModel);

// shipping display
cartModel.shippingFriendly = ko.computed(function() {

    var p = cartModel.shipping().toFixed(2) + ' ' + this.currency;

    if(this.currency == 'USD'){
		p = '$' + p;
	}

    return p;
}, cartModel);

// total calculation (subtotal + shipping + tax)
cartModel.total = ko.computed(function() {

    var total = cartModel.subtotal() + cartModel.shipping() + cartModel.tax();
	return total;

}, cartModel);

// total display
cartModel.totalFriendly = ko.computed(function() {

    var p = cartModel.total().toFixed(2) + ' ' + this.currency;

    if(this.currency == 'USD'){
		p = '$' + p;
	}

    return p;
}, cartModel);

// init model
$(document).ready(function(){cartModel.init();});
<|endoftext|>


<commit_before>var run = require("gulp-run");
var gulp = require("gulp");

gulp.task("cleanjsdocs", function(cb){
	    return require("del")(["docs/jsdoc"], cb);
});

gulp.task("jsdoc", ["cleanjsdocs"], function(){
    return run("./node_modules/.bin/jsdoc  -r -d docs/jsdocs **/*.js").exec(function(){
    	    console.log(arguments);
    });
});

gulp.task("watchJsdoc", function(){
    return gulp.watch(["./!(docs|node_modules)/**/*.js", "!Gulpfile.js"], ["jsdoc"]);
});
<commit_msg>fixing gulpfile based on eslint<commit_after>var run = require("gulp-run");
var gulp = require("gulp");
var debug = require("debug")("koala-puree:gulp");
gulp.task("cleanjsdocs", function(cb){
    return require("del")(["docs/jsdoc"], cb);
});

gulp.task("jsdoc", ["cleanjsdocs"], function(){
    return run("./node_modules/.bin/jsdoc  -r -d docs/jsdocs **/*.js").exec(function(){
        debug(arguments);
    });
});

gulp.task("watchJsdoc", function(){
    return gulp.watch(["./!(docs|node_modules)/**/*.js", "!Gulpfile.js"], ["jsdoc"]);
});
<|endoftext|>


<commit_before>'use strict'

const ChatServiceError = require('./ChatServiceError')
const CommandBinder = require('./CommandBinder')
const DirectMessaging = require('./DirectMessaging')
const Promise = require('bluebird')
const UserAssociations = require('./UserAssociations')
const _ = require('lodash')
const { asyncLimit, checkNameSymbols, run } = require('./utils')
const { mixin } = require('es6-mixin')

// Client commands implementation.
class User {

  constructor (server, userName) {
    this.server = server
    this.userName = userName
    this.echoChannel = `echo:${this.userName}`
    this.state = this.server.state
    this.transport = this.server.transport
    this.enableRoomsManagement = this.server.enableRoomsManagement
    this.enableDirectMessages = this.server.enableDirectMessages
    this.directMessaging = new DirectMessaging(server, userName)
    let State = this.server.state.UserState
    this.userState = new State(this.server, this.userName)
    this.commandBinder =
      new CommandBinder(this.server, this.transport, this.userName)
    let opts = {
      server,
      echoChannel: this.echoChannel,
      state: this.state,
      transport: this.transport,
      userName: this.userName,
      userState: this.userState
    }
    mixin(this, UserAssociations, opts)
  }

  initState (state) {
    return this.directMessaging.initState(state)
  }

  removeState () {
    return this.directMessaging.removeState()
  }

  checkOnline () {
    return this.userState.getAllSockets().then(sockets => {
      if (!sockets || !sockets.length) {
        let error = new ChatServiceError('noUserOnline', this.userName)
        return Promise.reject(error)
      }
    })
  }

  processMessage (msg, setTimestamp = false) {
    delete msg.id
    delete msg.timestamp
    if (setTimestamp) {
      msg.timestamp = _.now()
    }
    msg.author = this.userName || msg.author
    return msg
  }

  socketConnectEcho (id, nconnected) {
    this.transport.sendToChannel(
      id, this.echoChannel, 'socketConnectEcho', id, nconnected)
  }

  exec (command, options, args) {
    let { id } = options
    let requestsNames = this.server.rpcRequestsNames
    if (!_.includes(requestsNames, command)) {
      let error = new ChatServiceError('noCommand', command)
      return Promise.reject(error)
    }
    let requiresSocket = command === 'roomJoin' || command === 'roomLeave'
    if (!id && requiresSocket) {
      let error = new ChatServiceError('noSocket', command)
      return Promise.reject(error)
    }
    let fn = this[command].bind(this)
    let cmd = this.commandBinder.makeCommand(command, fn)
    return cmd(args, options)
  }

  registerSocket (id) {
    return run(this, function * () {
      let nconnected = yield this.addUserSocket(id, this.userName)
      let commands = this.server.rpcRequestsNames
      for (let cmd of commands) {
        this.commandBinder.bindCommand(id, cmd, this[cmd].bind(this))
      }
      this.commandBinder.bindDisconnect(id, this.removeSocket.bind(this))
      yield this.transport.joinChannel(id, this.echoChannel)
      return this.socketConnectEcho(id, nconnected)
    })
  }

  removeSocket (id) {
    return this.removeUserSocket(id)
  }

  disconnectInstanceSockets () {
    return this.userState.getAllSockets().then(sockets => {
      return Promise.map(
        sockets,
        sid => this.transport.disconnectSocket(sid),
        { concurrency: asyncLimit })
    })
  }

  directAddToList (listName, values) {
    return this.directMessaging.addToList(this.userName, listName, values)
      .return()
  }

  directGetAccessList (listName) {
    return this.directMessaging.getList(this.userName, listName)
  }

  directGetWhitelistMode () {
    return this.directMessaging.getMode(this.userName)
  }

  directMessage (recipientName, msg, {id, bypassPermissions}) {
    if (!this.enableDirectMessages) {
      let error = new ChatServiceError('notAllowed')
      return Promise.reject(error)
    }
    this.processMessage(msg, true)
    return this.server.state.getUser(recipientName).then(recipient => {
      let channel = recipient.echoChannel
      return recipient.directMessaging
        .message(this.userName, msg, bypassPermissions)
        .then(() => recipient.checkOnline())
        .then(() => {
          this.transport.emitToChannel(channel, 'directMessage', msg)
          this.transport.sendToChannel(
            id, this.echoChannel, 'directMessageEcho', recipientName, msg)
          return msg
        })
    })
  }

  directRemoveFromList (listName, values) {
    return this.directMessaging.removeFromList(this.userName, listName, values)
      .return()
  }

  directSetWhitelistMode (mode) {
    return this.directMessaging.changeMode(this.userName, mode).return()
  }

  listOwnSockets () {
    return this.userState.getSocketsToRooms()
  }

  roomAddToList (roomName, listName, values, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      return Promise.join(
        room.addToList(this.userName, listName, values, bypassPermissions),
        room.roomState.accessListsUpdatesGet(),
        (userNames, update) => {
          if (update) {
            this.transport.emitToChannel(
              roomName, 'roomAccessListAdded', roomName, listName, values)
          }
          return this.removeRoomUsers(roomName, userNames)
        })
    }).return()
  }

  roomCreate (roomName, whitelistOnly, {bypassPermissions}) {
    if (!this.enableRoomsManagement && !bypassPermissions) {
      let error = new ChatServiceError('notAllowed')
      return Promise.reject(error)
    }
    let owner = this.userName
    return checkNameSymbols(roomName)
      .then(() => this.state.addRoom(roomName, {owner, whitelistOnly}))
      .return()
  }

  roomDelete (roomName, {bypassPermissions}) {
    if (!this.enableRoomsManagement && !bypassPermissions) {
      let error = new ChatServiceError('notAllowed')
      return Promise.reject(error)
    }
    return this.state.getRoom(roomName).then(room => {
      return room.checkIsOwner(this.userName, bypassPermissions)
        .then(() => room.startRemoving())
        .then(() => room.getUsers())
        .then(userNames => this.removeRoomUsers(roomName, userNames))
        .then(() => this.state.removeRoom(roomName))
        .then(() => room.removeState())
        .return()
    })
  }

  roomGetAccessList (roomName, listName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getList(this.userName, listName, bypassPermissions))
  }

  roomGetOwner (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getOwner(this.userName, bypassPermissions))
  }

  roomGetWhitelistMode (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getMode(this.userName, bypassPermissions))
  }

  roomRecentHistory (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getRecentMessages(this.userName, bypassPermissions))
  }

  roomHistoryGet (roomName, msgid, limit, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getMessages(
        this.userName, msgid, limit, bypassPermissions))
  }

  roomHistoryInfo (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getHistoryInfo(this.userName, bypassPermissions))
  }

  roomJoin (roomName, {id, isLocalCall}) {
    return this.state.getRoom(roomName)
      .then(room => this.joinSocketToRoom(id, roomName, isLocalCall))
  }

  roomLeave (roomName, {id, isLocalCall}) {
    return this.state.getRoom(roomName)
      .then(room => this.leaveSocketFromRoom(id, room.roomName, isLocalCall))
  }

  roomMessage (roomName, msg, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      this.processMessage(msg)
      return room.message(this.userName, msg, bypassPermissions)
    }).then(pmsg => {
      this.transport.emitToChannel(roomName, 'roomMessage', roomName, pmsg)
      return pmsg.id
    })
  }

  roomNotificationsInfo (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getNotificationsInfo(this.userName, bypassPermissions))
  }

  roomRemoveFromList (roomName, listName, values, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      return Promise.join(
        room.removeFromList(this.userName, listName, values, bypassPermissions),
        room.roomState.accessListsUpdatesGet(),
        (userNames, update) => {
          if (update) {
            this.transport.emitToChannel(
              roomName, 'roomAccessListRemoved', roomName, listName, values)
          }
          return this.removeRoomUsers(roomName, userNames)
        })
    }).return()
  }

  roomSetWhitelistMode (roomName, mode, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      return Promise.join(
        room.changeMode(this.userName, mode, bypassPermissions),
        room.roomState.accessListsUpdatesGet(),
        ([userNames, mode], update) => {
          if (update) {
            this.transport.emitToChannel(
              roomName, 'roomModeChanged', roomName, mode)
          }
          return this.removeRoomUsers(roomName, userNames)
        })
    }).return()
  }

  roomUserSeen (roomName, userName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.userSeen(this.userName, userName, bypassPermissions))
  }

  systemMessage (data, {id}) {
    this.transport.sendToChannel(id, this.echoChannel, 'systemMessage', data)
    return Promise.resolve()
  }

}

module.exports = User
<commit_msg>refactor: remove method<commit_after>'use strict'

const ChatServiceError = require('./ChatServiceError')
const CommandBinder = require('./CommandBinder')
const DirectMessaging = require('./DirectMessaging')
const Promise = require('bluebird')
const UserAssociations = require('./UserAssociations')
const _ = require('lodash')
const { asyncLimit, checkNameSymbols, run } = require('./utils')
const { mixin } = require('es6-mixin')

// Client commands implementation.
class User {

  constructor (server, userName) {
    this.server = server
    this.userName = userName
    this.echoChannel = `echo:${this.userName}`
    this.state = this.server.state
    this.transport = this.server.transport
    this.enableRoomsManagement = this.server.enableRoomsManagement
    this.enableDirectMessages = this.server.enableDirectMessages
    this.directMessaging = new DirectMessaging(server, userName)
    let State = this.server.state.UserState
    this.userState = new State(this.server, this.userName)
    this.commandBinder =
      new CommandBinder(this.server, this.transport, this.userName)
    let opts = {
      server,
      echoChannel: this.echoChannel,
      state: this.state,
      transport: this.transport,
      userName: this.userName,
      userState: this.userState
    }
    mixin(this, UserAssociations, opts)
  }

  // utils

  initState (state) {
    return this.directMessaging.initState(state)
  }

  removeState () {
    return this.directMessaging.removeState()
  }

  checkOnline () {
    return this.userState.getAllSockets().then(sockets => {
      if (!sockets || !sockets.length) {
        let error = new ChatServiceError('noUserOnline', this.userName)
        return Promise.reject(error)
      }
    })
  }

  processMessage (msg, setTimestamp = false) {
    delete msg.id
    delete msg.timestamp
    if (setTimestamp) {
      msg.timestamp = _.now()
    }
    msg.author = this.userName || msg.author
    return msg
  }

  exec (command, options, args) {
    let { id } = options
    let requestsNames = this.server.rpcRequestsNames
    if (!_.includes(requestsNames, command)) {
      let error = new ChatServiceError('noCommand', command)
      return Promise.reject(error)
    }
    let requiresSocket = command === 'roomJoin' || command === 'roomLeave'
    if (!id && requiresSocket) {
      let error = new ChatServiceError('noSocket', command)
      return Promise.reject(error)
    }
    let fn = this[command].bind(this)
    let cmd = this.commandBinder.makeCommand(command, fn)
    return cmd(args, options)
  }

  registerSocket (id) {
    return run(this, function * () {
      let nconnected = yield this.addUserSocket(id, this.userName)
      let commands = this.server.rpcRequestsNames
      for (let cmd of commands) {
        this.commandBinder.bindCommand(id, cmd, this[cmd].bind(this))
      }
      this.commandBinder.bindDisconnect(id, this.removeSocket.bind(this))
      yield this.transport.joinChannel(id, this.echoChannel)
      this.transport.sendToChannel(
        id, this.echoChannel, 'socketConnectEcho', id, nconnected)
    })
  }

  removeSocket (id) {
    return this.removeUserSocket(id)
  }

  // RPC handlers

  disconnectInstanceSockets () {
    return this.userState.getAllSockets().then(sockets => {
      return Promise.map(
        sockets,
        sid => this.transport.disconnectSocket(sid),
        { concurrency: asyncLimit })
    })
  }

  directAddToList (listName, values) {
    return this.directMessaging.addToList(this.userName, listName, values)
      .return()
  }

  directGetAccessList (listName) {
    return this.directMessaging.getList(this.userName, listName)
  }

  directGetWhitelistMode () {
    return this.directMessaging.getMode(this.userName)
  }

  directMessage (recipientName, msg, {id, bypassPermissions}) {
    if (!this.enableDirectMessages) {
      let error = new ChatServiceError('notAllowed')
      return Promise.reject(error)
    }
    this.processMessage(msg, true)
    return this.server.state.getUser(recipientName).then(recipient => {
      let channel = recipient.echoChannel
      return recipient.directMessaging
        .message(this.userName, msg, bypassPermissions)
        .then(() => recipient.checkOnline())
        .then(() => {
          this.transport.emitToChannel(channel, 'directMessage', msg)
          this.transport.sendToChannel(
            id, this.echoChannel, 'directMessageEcho', recipientName, msg)
          return msg
        })
    })
  }

  directRemoveFromList (listName, values) {
    return this.directMessaging.removeFromList(this.userName, listName, values)
      .return()
  }

  directSetWhitelistMode (mode) {
    return this.directMessaging.changeMode(this.userName, mode).return()
  }

  listOwnSockets () {
    return this.userState.getSocketsToRooms()
  }

  roomAddToList (roomName, listName, values, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      return Promise.join(
        room.addToList(this.userName, listName, values, bypassPermissions),
        room.roomState.accessListsUpdatesGet(),
        (userNames, update) => {
          if (update) {
            this.transport.emitToChannel(
              roomName, 'roomAccessListAdded', roomName, listName, values)
          }
          return this.removeRoomUsers(roomName, userNames)
        })
    }).return()
  }

  roomCreate (roomName, whitelistOnly, {bypassPermissions}) {
    if (!this.enableRoomsManagement && !bypassPermissions) {
      let error = new ChatServiceError('notAllowed')
      return Promise.reject(error)
    }
    let owner = this.userName
    return checkNameSymbols(roomName)
      .then(() => this.state.addRoom(roomName, {owner, whitelistOnly}))
      .return()
  }

  roomDelete (roomName, {bypassPermissions}) {
    if (!this.enableRoomsManagement && !bypassPermissions) {
      let error = new ChatServiceError('notAllowed')
      return Promise.reject(error)
    }
    return this.state.getRoom(roomName).then(room => {
      return room.checkIsOwner(this.userName, bypassPermissions)
        .then(() => room.startRemoving())
        .then(() => room.getUsers())
        .then(userNames => this.removeRoomUsers(roomName, userNames))
        .then(() => this.state.removeRoom(roomName))
        .then(() => room.removeState())
        .return()
    })
  }

  roomGetAccessList (roomName, listName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getList(this.userName, listName, bypassPermissions))
  }

  roomGetOwner (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getOwner(this.userName, bypassPermissions))
  }

  roomGetWhitelistMode (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getMode(this.userName, bypassPermissions))
  }

  roomRecentHistory (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getRecentMessages(this.userName, bypassPermissions))
  }

  roomHistoryGet (roomName, msgid, limit, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getMessages(
        this.userName, msgid, limit, bypassPermissions))
  }

  roomHistoryInfo (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getHistoryInfo(this.userName, bypassPermissions))
  }

  roomJoin (roomName, {id, isLocalCall}) {
    return this.state.getRoom(roomName)
      .then(room => this.joinSocketToRoom(id, roomName, isLocalCall))
  }

  roomLeave (roomName, {id, isLocalCall}) {
    return this.state.getRoom(roomName)
      .then(room => this.leaveSocketFromRoom(id, room.roomName, isLocalCall))
  }

  roomMessage (roomName, msg, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      this.processMessage(msg)
      return room.message(this.userName, msg, bypassPermissions)
    }).then(pmsg => {
      this.transport.emitToChannel(roomName, 'roomMessage', roomName, pmsg)
      return pmsg.id
    })
  }

  roomNotificationsInfo (roomName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.getNotificationsInfo(this.userName, bypassPermissions))
  }

  roomRemoveFromList (roomName, listName, values, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      return Promise.join(
        room.removeFromList(this.userName, listName, values, bypassPermissions),
        room.roomState.accessListsUpdatesGet(),
        (userNames, update) => {
          if (update) {
            this.transport.emitToChannel(
              roomName, 'roomAccessListRemoved', roomName, listName, values)
          }
          return this.removeRoomUsers(roomName, userNames)
        })
    }).return()
  }

  roomSetWhitelistMode (roomName, mode, {bypassPermissions}) {
    return this.state.getRoom(roomName).then(room => {
      return Promise.join(
        room.changeMode(this.userName, mode, bypassPermissions),
        room.roomState.accessListsUpdatesGet(),
        ([userNames, mode], update) => {
          if (update) {
            this.transport.emitToChannel(
              roomName, 'roomModeChanged', roomName, mode)
          }
          return this.removeRoomUsers(roomName, userNames)
        })
    }).return()
  }

  roomUserSeen (roomName, userName, {bypassPermissions}) {
    return this.state.getRoom(roomName)
      .then(room => room.userSeen(this.userName, userName, bypassPermissions))
  }

  systemMessage (data, {id}) {
    this.transport.sendToChannel(id, this.echoChannel, 'systemMessage', data)
    return Promise.resolve()
  }

}

module.exports = User
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var path = require('path');
var jade = require('jade');
var Table = require('cli-table');
var numeral = require('numeral');
var program = require('commander');
var json2csv = require('json2csv');

var _ = require('underscore');
_.str = require('underscore.string');
_.mixin(_.str.exports());
_.str.include('Underscore.string', 'string');

var StyleStats = require('../lib/stylestats');

/**
 * Prettify StyleStats data.
 * @param {object} [result] StyleStats parse data. Required.
 * @return {array} prettified data.
 */
function prettify(result) {
    var collections = [];
    Object.keys(result).forEach(function(key) {
        var stats = {};
        var prop = _(_(key).humanize()).titleize();
        if (key === 'propertiesCount') {
            var array = [];
            result[key].forEach(function(item) {
                array.push([item.property, item.count]);
            });
            stats[prop] = array.join('\n').replace(/\,/g, ': ');
        } else if (key === 'size' || key === 'gzippedSize' || key === 'dataUriSize') {
            stats[prop] = numeral(result[key]).format('0.0b').replace(/\.0B/, 'B').replace(/0\.0/, '0');
        } else if (key === 'simplicity' || key === 'ratioOfDataUriSize') {
            stats[prop] = numeral(result[key]).format('0.00%');
        } else if (key === 'published' || key === 'paths') {
            return true;
        } else {
            stats[prop] = Array.isArray(result[key]) ? result[key].join('\n') : result[key];
            if (stats[prop] === '') {
                stats[prop] = 'N/A';
            }
        }
        collections.push(stats);
    });
    return collections;
}

program
    .version(require('../package.json').version)
    .usage('[options] <file ...>')
    .option('-c, --config [path]', 'Path and name of the incoming JSON file.')
    .option('-t, --type [format]', 'Specify the output format. <json|html|csv>')
    .option('-s, --simple', 'Show compact style\'s log.')
    .parse(process.argv);

if (!program.args.length) {
    console.log('\n No input file specified.');
    program.help();
}

var stats = new StyleStats(program.args, program.config);
stats.parse(function(result) {
    switch (program.type) {
        case 'json':
            var json = JSON.stringify(result, null, 2);
            console.log(json);
            break;
        case 'csv':
            json2csv({
                data: result,
                fields: Object.keys(result)
            }, function(err, csv) {
                console.log(csv);
            });
            break;
        case 'html':
            var template = path.join(__dirname, '../assets/stats.jade');
            var html = jade.renderFile(template, {
                pretty: true,
                stats: prettify(result),
                published: result.published,
                paths: result.paths
            });
            console.log(html);
            break;
        default:
            var table = new Table({
                style: {
                    head: ['cyan'],
                    compact: program.simple
                }
            });
            prettify(result).forEach(function(data) {
                table.push(data);
            });
            console.log(' StyleStats!\n' + table.toString());
            break;
    }
});<commit_msg>Fix CSV format<commit_after>#!/usr/bin/env node

'use strict';

var path = require('path');
var jade = require('jade');
var Table = require('cli-table');
var numeral = require('numeral');
var program = require('commander');
var json2csv = require('json2csv');

var _ = require('underscore');
_.str = require('underscore.string');
_.mixin(_.str.exports());
_.str.include('Underscore.string', 'string');

var StyleStats = require('../lib/stylestats');

/**
 * Prettify StyleStats data.
 * @param {object} [result] StyleStats parse data. Required.
 * @return {array} prettified data.
 */
function prettify(result) {
    var collections = [];
    Object.keys(result).forEach(function(key) {
        var stats = {};
        var prop = _(_(key).humanize()).titleize();
        if (key === 'propertiesCount') {
            var array = [];
            result[key].forEach(function(item) {
                array.push([item.property, item.count]);
            });
            stats[prop] = array.join('\n').replace(/\,/g, ': ');
        } else if (key === 'size' || key === 'gzippedSize' || key === 'dataUriSize') {
            stats[prop] = numeral(result[key]).format('0.0b').replace(/\.0B/, 'B').replace(/0\.0/, '0');
        } else if (key === 'simplicity' || key === 'ratioOfDataUriSize') {
            stats[prop] = numeral(result[key]).format('0.00%');
        } else if (key === 'published' || key === 'paths') {
            return true;
        } else {
            stats[prop] = Array.isArray(result[key]) ? result[key].join('\n') : result[key];
            if (stats[prop] === '') {
                stats[prop] = 'N/A';
            }
        }
        collections.push(stats);
    });
    return collections;
}

program
    .version(require('../package.json').version)
    .usage('[options] <file ...>')
    .option('-c, --config [path]', 'Path and name of the incoming JSON file.')
    .option('-t, --type [format]', 'Specify the output format. <json|html|csv>')
    .option('-s, --simple', 'Show compact style\'s log.')
    .parse(process.argv);

if (!program.args.length) {
    console.log('\n No input file specified.');
    program.help();
}

var stats = new StyleStats(program.args, program.config);
stats.parse(function(result) {
    switch (program.type) {
        case 'json':
            var json = JSON.stringify(result, null, 2);
            console.log(json);
            break;
        case 'csv':
            Object.keys(result).forEach(function(key) {
                result[key] = Array.isArray(result[key]) ? result[key].join(' ') : result[key];
            });
            json2csv({
                data: result,
                fields: Object.keys(result)
            }, function(err, csv) {
                console.log(csv);
            });
            break;
        case 'html':
            var template = path.join(__dirname, '../assets/stats.jade');
            var html = jade.renderFile(template, {
                pretty: true,
                stats: prettify(result),
                published: result.published,
                paths: result.paths
            });
            console.log(html);
            break;
        default:
            var table = new Table({
                style: {
                    head: ['cyan'],
                    compact: program.simple
                }
            });
            prettify(result).forEach(function(data) {
                table.push(data);
            });
            console.log(' StyleStats!\n' + table.toString());
            break;
    }
});<|endoftext|>


<commit_before>/*! @license
 * Shaka Player
 * Copyright 2016 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

(function() {
  // This is "window" in browsers and "global" in nodejs.
  // See https://github.com/google/shaka-player/issues/1445
  var innerGlobal = typeof window != 'undefined' ? window : global;

  // This is where our library exports things to.  It is "this" in the wrapped
  // code.  With this, we can decide later what module loader we are in, if any,
  // and put these exports in the appropriate place for that loader.
  var exportTo = {};

  // According to the Closure team, their polyfills will be written to
  // $jscomp.global, which will be "window", or "global", or "this", depending
  // on circumstances.
  // See https://github.com/google/closure-compiler/issues/2957 and
  // https://github.com/google/shaka-player/issues/1455#issuecomment-393250035

  // We provide "global" for use by Closure, and "window" for use by the Shaka
  // library itself.  Both point to "innerGlobal" above.
  // We also provide "module", which is always undefined, to prevent compiled-in
  // code from doing its own exports that conflict with ours.
  (function(window, global, module) {

%output%

  }).call(/* this= */ exportTo,
          /* window= */ innerGlobal,
          /* global= */ innerGlobal,
          /* module= */ undefined);

  if (typeof exports != 'undefined') {
    // CommonJS module loader.  Use "exports" instead of "module.exports" to
    // avoid triggering inappropriately in Electron.
    for (var k in exportTo.shaka) {
      exports[k] = exportTo.shaka[k];
    }
  } else if (typeof define != 'undefined' && define.amd) {
    // AMD module loader.
    define(function(){
      return exportTo.shaka;
    });
  } else {
    // Loaded as an ES module or directly in a <script> tag.
    // Export directly to the global scope.
    innerGlobal.shaka = exportTo.shaka;
  }
})();
<commit_msg>fix: Fix loading with global "define" set to null<commit_after>/*! @license
 * Shaka Player
 * Copyright 2016 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

(function() {
  // This is "window" in browsers and "global" in nodejs.
  // See https://github.com/google/shaka-player/issues/1445
  var innerGlobal = typeof window != 'undefined' ? window : global;

  // This is where our library exports things to.  It is "this" in the wrapped
  // code.  With this, we can decide later what module loader we are in, if any,
  // and put these exports in the appropriate place for that loader.
  var exportTo = {};

  // According to the Closure team, their polyfills will be written to
  // $jscomp.global, which will be "window", or "global", or "this", depending
  // on circumstances.
  // See https://github.com/google/closure-compiler/issues/2957 and
  // https://github.com/google/shaka-player/issues/1455#issuecomment-393250035

  // We provide "global" for use by Closure, and "window" for use by the Shaka
  // library itself.  Both point to "innerGlobal" above.
  // We also provide "module", which is always undefined, to prevent compiled-in
  // code from doing its own exports that conflict with ours.
  (function(window, global, module) {

%output%

  }).call(/* this= */ exportTo,
          /* window= */ innerGlobal,
          /* global= */ innerGlobal,
          /* module= */ undefined);

  if (typeof exports != 'undefined') {
    // CommonJS module loader.  Use "exports" instead of "module.exports" to
    // avoid triggering inappropriately in Electron.
    for (var k in exportTo.shaka) {
      exports[k] = exportTo.shaka[k];
    }
  } else if (typeof define == 'function' && define.amd) {
    // AMD module loader.
    define(function(){
      return exportTo.shaka;
    });
  } else {
    // Loaded as an ES module or directly in a <script> tag.
    // Export directly to the global scope.
    innerGlobal.shaka = exportTo.shaka;
  }
})();
<|endoftext|>