<commit_before>describe("Nodiak Riak Client Test Suite", function() {
    var riak = require('../../nodiak').getClient('localhost', '8091', 'http');
    var riaks = require('../../nodiak').getClient('localhost', '8071', 'https');

    var async = require('async');
    var should = require('should');

    before(function(pass){ // bootstrap settings and data for tests.
        riak.ping(function(err, response) {
            if(err) throw new Error(err.toString());
            else {
                riak.buckets.save('test', {"precommit":[{"mod":"riak_search_kv_hook","fun":"precommit"}]}, function(err, result) {
                    if(err) throw new Error(err.toString());
                    else {
                        var data = { field1: "has been set" };
                        var metadata = {
                            index: {
                                strings: { bin: ['this', 'that', 'the', 'other'] },
                                numbers: { int: [1000,250,37,4234,5] }
                            },
                            meta: { extra_details: "you might want to know"}
                        };
                        var created = [];
                        for(var i = 1; i <= 5; i++) {
                            riak.objects.save('test', null, data, metadata, function(err, obj) {
                                if(err) throw new Error(err.toString());
                                else {
                                    created.push(obj);
                                }

                                if(created.length == 5) {
                                    pass();
                                }
                            });
                        }
                    }
                });
            }
        });
    });

    describe("Basic HTTP & HTTPS functionality", function() {
        it("should be able to ping the cluster via HTTP", function(pass) {
            riak.ping(function(err, response) {
                should.not.exist(err);
                response.data.should.equal("OK");
                pass();
            });
        });

        it("should be able to ping the cluster via HTTPS", function(pass) {
            riaks.ping(function(err, response) {
                should.not.exist(err);
                response.data.should.equal("OK");
                pass();
            });
        });

        it("should be able to get stats via HTTP", function(pass) {
            riak.stats(function(err, response) {
                should.not.exist(err);
                response.data.should.be.a('object');
                pass();
            });
        });

        it("should be able to get stats via HTTPS", function(pass) {
            riaks.stats(function(err, response) {
                should.not.exist(err);
                response.data.should.be.a('object');
                pass();
            });
        });
    });

    describe("Using the base client to interact with buckets", function() {
        it("should be able to read bucket properties", function(pass) {
            riak.buckets.props('random_bucket', function(err, props) {
                should.not.exist(err);
                props.should.be.a('object').and.have.property('name', 'random_bucket');
                pass();
            });
        });

        it("should be able to save properties to a bucket", function(pass) {
            riak.buckets.props('random_bucket', function(err, props) {
                should.not.exist(err);

                var toggled = props.allow_mult ? false : true;
                props.allow_mult = toggled;

                riak.buckets.save('random_bucket', props, function(err, response) {
                    should.not.exist(err);

                    riak.buckets.props('random_bucket', function(err, props) {
                        should.not.exist(err);
                        props.allow_mult.should.equal(toggled);
                        pass();
                    });
                });
            });
        });

        it("should be able to list all buckets", function(pass) {
            riak.buckets.list(function(err, buckets) {
                should.not.exist(err);
                buckets.should.be.an.instanceOf(Array);
                pass();
            });
        });

        it("should be able to list all keys in a bucket", function(pass) {
            riak.buckets.keys('test', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array);
                pass();
            });
        });

        it("should be able to perform ranged integer 2i searches", function(pass) {
            riak.buckets.search('test', [0,10000], 'numbers_int', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(25);
                pass();
            });
        });

        it("should be able to perform exact match integer 2i searches", function(pass) {
            riak.buckets.search('test', 1000, 'numbers_int', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(5);
                pass();
            });
        });

        it("should be able to perform ranged binary 2i searches", function(pass) {
            riak.buckets.search('test', ['a','zzzzzzzzzzz'], 'strings_bin', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(20);
                pass();
            });
        });

        it("should be able to perform exact match binary 2i searches", function(pass) {
            riak.buckets.search('test', 'that', 'strings_bin', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(5);
                pass();
            });
        });
    });

    describe("Using the base client to interact with objects", function() {
        it("should be able to check existence of object", function(pass) {
            riak.objects.save('test', 'this_ol_key', { "pointless": "data" }, null, function(err, obj) {
                should.not.exist(err);

                riak.objects.exists('test', 'this_ol_key', function(err, exists) {
                    should.not.exist(err);
                    exists.should.be.true;

                    riak.objects.exists('test', 'no_key_here', function(err, exists) {
                        should.not.exist(err);
                        exists.should.be.false;
                        pass();
                    });
                });
            });
        });

        it("should be able to save an object", function(pass) {
            riak.objects.save('test', 'this_ol_key', { "pointless": "data" }, null, function(err, obj) {
                should.not.exist(err);
                obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                obj.should.be.a('object').and.have.property('data');
                obj.data.should.eql({ "pointless": "data" });
                pass();
            });
        });

        it("should be able to get an object", function(pass) {
            riak.objects.get('test', 'this_ol_key', function(err, obj) {
                should.not.exist(err);
                obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                obj.should.be.a('object').and.have.property('data');
                obj.data.should.eql({ "pointless": "data" });
                obj.metadata.should.be.a('object').and.have.property('vclock');
                pass();
            });
        });

        it("should be able to delete an object", function(pass) {
            riak.objects.delete('test', 'this_ol_key', function(err, obj) {
                should.not.exist(err);
                obj.metadata.status_code.should.equal(204);
                pass();
            });
        });

        it("should be able to get sibling vtags when siblings exist", function(pass) {
            riak.buckets.save('siblings_test', { allow_mult: true }, function(err, response) {
                should.not.exist(err);

                riak.objects.save('siblings_test', 'this_ol_key', { "pointless": "data" }, null, function(err, obj) {
                    should.not.exist(err);
                    obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                    obj.should.be.a('object').and.have.property('data');
                    obj.data.should.eql({ "pointless": "data" });

                    riak.objects.save('siblings_test', 'this_ol_key', { "pointless": "sibling" }, null, function(err, obj) {
                        should.not.exist(err);
                        obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                        obj.should.be.a('object').and.have.property('data');
                        obj.data.should.eql({ "pointless": "sibling" });

                        riak.objects.get('siblings_test', 'this_ol_key', function(err, obj) {
                            should.not.exist(err);
                            obj.should.be.a('object').and.have.property('siblings');
                            obj.siblings.should.be.an.instanceof(Array);
                            obj.metadata.should.be.a('object').and.have.property('vclock');
                            pass();
                        });
                    });
                });

            });
        });
    });

    after(function(pass) { // teardown pre-test setup.
        riak.buckets.list(function(err, buckets) {
            async.map(buckets,
                function(bucket_name, _intermediate) {
                    var bucket = riak.buckets.get(bucket_name);
                    bucket.objects.all(function(err, r_objs){
                        bucket.objects.delete(r_objs, function(err, result) {
                            _intermediate(err, result);
                        });
                    });
                },
                function(err, results) {
                    if(err) throw new Error(err.toString());
                    else pass();
                }
            );
        });
    });
});
    // describe('Test Riak 2i\'s and Riak Search', function(){

    //     describe('Riak Search w/ core client', function(){
    //         it("riak.objects.search('test', { q: 'field:been' }, null, function(err, obj))", function(pass) {
    //             var solr_q = {
    //                 q: 'field1:been'
    //             };

    //             riak.objects.search('test', { q: 'field:been' }, null, function(err, obj) {
    //                 should.not.exist(null);
    //                 obj.data.should.have.property('response');
    //                 obj.data.response.should.have.property('docs').with.lengthOf(5);
    //                 pass();
    //             });
    //         });

    //         it("riak.objects.search('test', { q: 'not_a_field:whatever' }, null, function(err, obj))", function(pass) {
    //             var solr_q = {
    //                 q: 'not_a_field:whatever'
    //             };

    //             riak.objects.search('test', solr_q, null, function(err, obj) {
    //                 should.not.exist(null);
    //                 obj.data.should.have.property('response');
    //                 obj.data.response.should.have.property('docs').with.lengthOf(0);
    //                 pass();
    //             });
    //         });
    //     });

    //     describe('Riak Search w/ Bucket instance', function(){
    //         it('"q=value:been" should return 5 RObjects', function(pass) {
    //             pass();
    //         });

    //         it('"q=not_a_field:whatever" should return 0 RObjects', function(pass) {
    //             pass();
    //         });
    //     });

    //     describe('2i\'s w/ core client', function() {
    //         it('should find 5 results for an exact match of 37 in the numbers_int index', function(pass) {

    //         });

    //         it('should find 5 results for a range match of 35 to 38 in the numbers_int index', function(pass) {

    //         });

    //         it('should find 0 results for an exact match of 1001 in the numbers_int index', function(pass) {

    //         });

    //         it('should find 0 results for an range match of 1001 to 1500 in the numbers_int index', function(pass) {

    //         });

    //         it('should find 5 results for an exact match of "that" in the strings_bin index', function(pass) {

    //         });

    //         it('should find 5 results for a range match of "r" to "z" in the strings_bin index', function(pass) {

    //         });

    //         it('should find 0 results for an exact match of 1001 in the numbers_int index', function(pass) {

    //         });

    //         it('should find 0 results for an range match of 1001 to 1500 in the numbers_int index', function(pass) {

    //         });
    //     });

    //     // after(function(pass) { // teardown pre-test setup.
    //     //     riak.buckets.list(function(err, buckets) {
    //     //         async.map(buckets,
    //     //             function(bucket, _intermediate) {
    //     //                 bucket.objects.all(function(err, r_objs){
    //     //                     bucket.objects.delete(r_objs, function(err, result) {
    //     //                         _intermediate(err, result);
    //     //                     });
    //     //                 });
    //     //             },
    //     //             function(err, results) {
    //     //                 if(err) throw new Error(err.toString());
    //     //                 else pass();
    //     //             }
    //     //         );
    //     //     });
    //     // });
    // });

<commit_msg>Updated tests to include search functionality.<commit_after>describe("Nodiak Riak Client Test Suite", function() {
    var riak = require('../../nodiak').getClient('localhost', '8091', 'http');
    var riaks = require('../../nodiak').getClient('localhost', '8071', 'https');

    var async = require('async');
    var should = require('should');

    before(function(pass){ // bootstrap settings and data for tests.
        riak.ping(function(err, response) {
            if(err) throw new Error(err.toString());
            else {
                riak.bucket.save('test', {"precommit":[{"mod":"riak_search_kv_hook","fun":"precommit"}]}, function(err, result) {
                    if(err) throw new Error(err.toString());
                    else {
                        var data = { field1: "has been set" };
                        var metadata = {
                            index: {
                                strings: { bin: ['this', 'that', 'the', 'other'] },
                                numbers: { int: [1000,250,37,4234,5] }
                            },
                            meta: { extra_details: "you might want to know"}
                        };
                        var created = [];
                        for(var i = 1; i <= 5; i++) {
                            riak.object.save('test', null, data, metadata, function(err, obj) {
                                if(err) throw new Error(err.toString());
                                else {
                                    created.push(obj);
                                }

                                if(created.length == 5) {
                                    pass();
                                }
                            });
                        }
                    }
                });
            }
        });
    });

    describe("Basic HTTP & HTTPS functionality", function() {
        it("should be able to ping the cluster via HTTP", function(pass) {
            riak.ping(function(err, response) {
                should.not.exist(err);
                response.data.should.equal("OK");
                pass();
            });
        });

        it("should be able to ping the cluster via HTTPS", function(pass) {
            riaks.ping(function(err, response) {
                should.not.exist(err);
                response.data.should.equal("OK");
                pass();
            });
        });

        it("should be able to get stats via HTTP", function(pass) {
            riak.stats(function(err, response) {
                should.not.exist(err);
                response.data.should.be.a('object');
                pass();
            });
        });

        it("should be able to get stats via HTTPS", function(pass) {
            riaks.stats(function(err, response) {
                should.not.exist(err);
                response.data.should.be.a('object');
                pass();
            });
        });
    });

    describe("Using the base client to interact with buckets", function() {
        it("should be able to read bucket properties", function(pass) {
            riak.bucket.props('random_bucket', function(err, props) {
                should.not.exist(err);
                props.should.be.a('object').and.have.property('name', 'random_bucket');
                pass();
            });
        });

        it("should be able to save properties to a bucket", function(pass) {
            riak.bucket.props('random_bucket', function(err, props) {
                should.not.exist(err);

                var toggled = props.allow_mult ? false : true;
                props.allow_mult = toggled;

                riak.bucket.save('random_bucket', props, function(err, response) {
                    should.not.exist(err);

                    riak.bucket.props('random_bucket', function(err, props) {
                        should.not.exist(err);
                        props.allow_mult.should.equal(toggled);
                        pass();
                    });
                });
            });
        });

        it("should be able to list all buckets", function(pass) {
            riak.buckets.list(function(err, buckets) {
                should.not.exist(err);
                buckets.should.be.an.instanceOf(Array);
                pass();
            });
        });

        it("should be able to list all keys in a bucket", function(pass) {
            riak.bucket.keys('test', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array);
                pass();
            });
        });
    });

    describe("Using the 'Bucket' class to interact with buckets and objects", function() {

    });

    describe("Using the 'RObject' class to interact with objects", function() {

    });

    describe("Using the base client to interact with objects", function() {
        it("should be able to check existence of object", function(pass) {
            riak.object.save('test', 'this_ol_key', { "pointless": "data" }, null, function(err, obj) {
                should.not.exist(err);

                riak.object.exists('test', 'this_ol_key', function(err, exists) {
                    should.not.exist(err);
                    exists.should.be.true;

                    riak.object.exists('test', 'no_key_here', function(err, exists) {
                        should.not.exist(err);
                        exists.should.be.false;
                        pass();
                    });
                });
            });
        });

        it("should be able to save an object", function(pass) {
            riak.object.save('test', 'this_ol_key', { "pointless": "data" }, null, function(err, obj) {
                should.not.exist(err);
                obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                obj.should.be.a('object').and.have.property('data');
                obj.data.should.eql({ "pointless": "data" });
                pass();
            });
        });

        it("should be able to get an object", function(pass) {
            riak.object.get('test', 'this_ol_key', function(err, obj) {
                should.not.exist(err);
                obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                obj.should.be.a('object').and.have.property('data');
                obj.data.should.eql({ "pointless": "data" });
                obj.metadata.should.be.a('object').and.have.property('vclock');
                pass();
            });
        });

        it("should be able to delete an object", function(pass) {
            riak.object.delete('test', 'this_ol_key', function(err, obj) {
                should.not.exist(err);
                obj.metadata.status_code.should.equal(204);
                pass();
            });
        });

        it("should be able to get sibling vtags when siblings exist", function(pass) {
            riak.bucket.save('siblings_test', { allow_mult: true }, function(err, response) {
                should.not.exist(err);

                riak.object.save('siblings_test', 'this_ol_key', { "pointless": "data" }, null, function(err, obj) {
                    should.not.exist(err);
                    obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                    obj.should.be.a('object').and.have.property('data');
                    obj.data.should.eql({ "pointless": "data" });

                    riak.object.save('siblings_test', 'this_ol_key', { "pointless": "sibling" }, null, function(err, obj) {
                        should.not.exist(err);
                        obj.should.be.a('object').and.have.property('key', 'this_ol_key');
                        obj.should.be.a('object').and.have.property('data');
                        obj.data.should.eql({ "pointless": "sibling" });

                        riak.object.get('siblings_test', 'this_ol_key', function(err, obj) {
                            should.not.exist(err);
                            obj.should.be.a('object').and.have.property('siblings');
                            obj.siblings.should.be.an.instanceof(Array);
                            obj.metadata.should.be.a('object').and.have.property('vclock');
                            pass();
                        });
                    });
                });

            });
        });
    });

    describe("Using the core client to perform searches", function() {
        it("should be able to perform ranged integer 2i searches", function(pass) {
            riak.bucket.search('test', [0,10000], 'numbers_int', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(25);
                pass();
            });
        });

        it("should be able to perform exact match integer 2i searches", function(pass) {
            riak.bucket.search('test', 1000, 'numbers_int', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(5);
                pass();
            });
        });

        it("should be able to perform ranged binary 2i searches", function(pass) {
            riak.bucket.search('test', ['a','zzzzzzzzzzz'], 'strings_bin', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(20);
                pass();
            });
        });

        it("should be able to perform exact match binary 2i searches", function(pass) {
            riak.bucket.search('test', 'that', 'strings_bin', function(err, keys) {
                should.not.exist(err);
                keys.should.be.an.instanceOf(Array).with.lengthOf(5);
                pass();
            });
        });

        it("should be able to perform solr search on indexed bucket", function(pass) {
            riak.bucket.search('test', { q: 'field:been' }, null, function(err, obj) {
                should.not.exist(null);
                obj.data.should.have.property('response');
                obj.data.response.should.have.property('numFound', 5);
                obj.data.response.should.have.property('docs').with.lengthOf(5);
                pass();
            });
        });
    });

    after(function(pass) { // teardown pre-test setup.
        riak.buckets.list(function(err, buckets) {
            async.map(buckets,
                function(bucket_name, _intermediate) {
                    var bucket = riak.bucket.get(bucket_name);
                    bucket.objects.all(function(err, r_objs){
                        bucket.objects.delete(r_objs, function(err, result) {
                            _intermediate(err, result);
                        });
                    });
                },
                function(err, results) {
                    if(err) throw new Error(err.toString());
                    else pass();
                }
            );
        });
    });
});
<|endoftext|>


<commit_before>
/**	Creates a callback that proxies node callback style arguments to an Express Response object.
 *	@param {express.Response} res	Express HTTP Response
 *	@param {number} [status=200]	Status code to send on success
 *
 *	@example
 *		list(req, res) {
 *			collection.find({}, toRes(res));
 *		}
 */
export function toRes(res, status=200) {
	return (err, thing) => {
		if (err) return res.status(500).send(err);

		if (thing && typeof thing.toObject==='function') {
			thing = thing.toObject();
		}
		res.status(status).json(thing);
	};
}
<commit_msg>(feat) Adds Review and Dentist utility functions<commit_after>import Xray from 'x-ray';
// import Osmosis from 'osmosis';

export function findAndParseReviews (url) {
	return new Promise((resolve, reject) => {
		let x  = Xray();
		x(url, '#copyreviews', [{
			'text' : '@text'
		}])
		.paginate('#copyheade11:last-child@href')
		.limit(10)
		((err, results) => {
			if (err) {
				reject(err)
			} else {
				let comments = results.filter((review) => {
						review.text = review.text.replace(/\s\s+/g, ' ');
						return review.text.length > 35 && review.text.match(/Review/);
				})
				resolve(parseReviews(comments))
			}
		})
	})
}

function parseReviews (reviews) {
	let name = reviews[0].text.match(/Dr.(.*?):/)[1].trim();
	reviews = reviews.map((review) => {
	 let dateRegex = /[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/;
	 let comment = {
		  date   : review.text.match(dateRegex)[0],
		  author : review.text.match(/by\s(.*?)[0-9]/)[1].trim(),
		  rating : review.text.match(/\s[[0-9].[0-9]\sstars|\s[0-9]\sstars/)[0].match(/[0-9].[0-9]|([0-9]{1})/)[0],
			comment : review.text.slice((review.text.search(dateRegex)+11))
		}
		return comment;
	})
	return { name : name, reviews : reviews };
}
<|endoftext|>


<commit_before>ds.charts = ds.charts || {}

/**
 * Chart provider for rendering dashboard chart with flot, which
 * provides Canvas-based interactivity.
 */
ds.charts.flot =
  (function() {

    var self = {}

    self.CHART_IMPL_TYPE = 'flot'

    function get_default_options() {
      var theme_colors = ds.charts.util.get_colors()
      var default_options = {
        colors: ds.charts.util.get_palette(),
        series: {
          lines: {
            show: true,
            lineWidth: 1,
            steps: false,
            fill: false
          },
          valueLabels: {
            show: false,
            showAsHtml: true,
            labelFormatter: d3.format(',.3s'),
            yoffset: -20
          },
          stack: null,
          points: { show: false },
          bars: { show: false }
        },
        xaxis: {
          mode: "time",
          tickFormatter: function(value, axis) {
            // Take care of time series axis
            if (axis.tickSize && axis.tickSize.length === 2) {
              if (axis.tickSize[1] === 'year' && axis.tickSize[0] >= 1)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('YYYY')
              if (axis.tickSize[1] === 'month' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'year')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM-\'YY')
              if (axis.tickSize[1] === 'day' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'month')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD')
              if (axis.tickSize[1] === 'hour' && axis.tickSize[0] >= 12)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD hA')
            }
            return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('h:mm A')
          },
          tickColor: theme_colors.minorGridLineColor,
          font: {
            color: theme_colors.fgcolor,
            size: 12
          }
        },
        yaxes: [
          {
            position: 'left',
            tickFormatter: d3.format(',.3s'),
            reserveSpace: 30,
            labelWidth: 30,
            tickColor: theme_colors.minorGridLineColor,
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          },
          {
            position: 'right',
            tickFormatter: d3.format(',.3s'),
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          }
        ],
        points: {
          show: false,
          radius: 2,
          symbol: "circle"
        },
        shadowSize: 0,
        legend: {
          container: null,
          noColumns: 2,
          position: 'sw',
          backgroundColor: 'transparent',
          labelBoxBorderColor: 'transparent'
        },
        grid: {
          borderWidth: 1,
          hoverable: true,
          clickable: true,
          autoHighlight: false,
          /* grid.color actually sets the color of the legend
           * text. WTH? */
          color: theme_colors.fgcolor,
          borderColor: theme_colors.minorGridLineColor
        },
        selection: {
          mode: "x",
          color: "red"
        },
        multihighlight: {
          mode: "x"
        },
        crosshair: {
          mode: "x",
          color: "#BBB",
          lineWidth: 1
        }
      }
      return default_options
    }

    function get_flot_options(item, base) {
      var options      = item.options || {}
      var flot_options = ds.extend(get_default_options(), base)

      flot_options.colors = ds.charts.util.get_palette(options.palette)

      if (options.y1 && options.y1.min)
        flot_options.yaxes[0].min = options.y1.min
      if (options.y2 && options.y2.min)
        flot_options.yaxes[1].min = options.y2.min

      if (options.y1 && options.y1.max)
        flot_options.yaxes[0].max = options.y1.max
      if (options.y2 && options.y2.max)
        flot_options.yaxes[1].max = options.y2.max

      if (options.y1 && options.y1.label)
        flot_options.yaxes[0].axisLabel = options.y1.label
      if (options.y2 && options.y2.label)
        flot_options.yaxes[1].axisLabel = options.y2.label

      return flot_options
    }

    function show_tooltip(x, y, contents) {
      $('
' + contents + '
').css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5
      }).appendTo("body").show()
    }

    function setup_plugins(container, context) {
      $(container).bind("multihighlighted", function(event, pos, items) {
        if ( !items )
          return
        var series = context.plot.getData()
        var item   = items[0]
        var point  = series[item.serieIndex].data[item.dataIndex]
        var format = d3.format(',.3s')
        var is_percent = context.item.stack_mode && (context.item.stack_mode === ds.charts.StackMode.PERCENT)

        var contents = ds.templates.flot.tooltip({
          time: point[0],
          items: items.map(function(item) {
                   var s = series[item.serieIndex]
                   var value = is_percent
                             ? s.percents[item.dataIndex]
                             : s.data[item.dataIndex][1]
                   return {
                     series: s,
                     value: is_percent ? format(value) + '%' : format(value)
                   }
                 })
        })

        $("#ds-tooltip").remove()
        show_tooltip(pos.pageX, pos.pageY, contents)
      })

      $(container).bind("unmultihighlighted", function(event) {
        $("#ds-tooltip").remove()
      })
    }

    function render_legend(item, query, flot_options) {
      var legend_id = '#ds-legend-' + item.item_id
      var legend = ''
      var data = query.chart_data('flot')
      for (var i = 0; i < data.length; i++) {
        var series = data[i]
        var label = series.label
        var color = flot_options.colors[i % flot_options.colors.length]

        var cell = '
'
                 + ''
                 + '' + label + ''
                 + '
'
        legend += cell
      }
      var elt = $(legend_id)
      elt.html(legend)
      elt.equalize({equalize: 'outerWidth', reset: true })
    }

    function set_value_label_options(item, flot_options) {
      if (item.show_max_value || item.show_min_value || item.show_last_value) {
        flot_options.series.valueLabels.show = true
      }
      flot_options.series.valueLabels.showMaxValue = item.show_max_value
      flot_options.series.valueLabels.showMinValue = item.show_min_value
      flot_options.series.valueLabels.showLastValue = item.show_last_value
    }

    self.simple_line_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      setup_plugins(e, context)

      var flot_options = get_flot_options(item, {
        grid: {
          show: false,
          hoverable: true
        },
        legend: {
          show: false
        }
      })

      set_value_label_options(item, flot_options)

      var series = query.chart_data('flot')[0]
      context.plot = $.plot($(e), [series], flot_options)

      return self
    }

    self.standard_line_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      setup_plugins(e, context)
      var flot_options = get_flot_options(item, {
        grid: ds.extend(get_default_options().grid, {
          hoverable: true,
          clickable: true,
          autoHighlight: false
        }),
        legend: {
          show: false
        }
      })

      context.plot = $.plot($(e), query.chart_data('flot'), flot_options)
      render_legend(item, query, flot_options)

      return self
    }

    self.simple_area_chart = function(e, item, query) {
      var options = item.options || {}
      var context = {
          plot: null,
          item: item
      }
      setup_plugins(e, context)
      var flot_options = ds.extend(get_default_options(), {
        colors: ds.charts.util.get_palette(options.palette),
        grid: {
          show: false,
          hoverable: true
        },
        legend: {
          show: false
        }
      })

      flot_options.series.lines.show = true
      flot_options.series.lines.fill = 1

      set_value_label_options(item, flot_options)

      context.plot = $.plot($(e), [query.chart_data('flot')[0]],
                            flot_options)
      return self
    }

    self.stacked_area_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      var legend_id = '#ds-legend-' + item.item_id
      var flot_options = get_flot_options(item, {
        legend: {
          container: legend_id,
          labelBoxBorderColor: 'transparent',
          show: true,
          noColumns: 4
        },
        series: {
          lines: { show: true, lineWidth: 1, fill: 1},
          stack: true,
          points: { show: false },
          bars: { show: false }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        flot_options.series.stack = false
        flot_options.series.stackpercent = true
        flot_options.yaxes[0].max = 100
        flot_options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        flot_options.series.stack = false
        flot_options.series.stackpercent = false
        flot_options.series.lines.fill = false
      }

      setup_plugins(e, context)
      context.plot = $.plot($(e), query.chart_data('flot'), flot_options)

      render_legend(item, query, flot_options)

      return self
    }

    self.donut_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      var options = get_flot_options(item, {
        legend: {
          show: false
        },
        crosshair: {
          mode: null
        },
        multihighlight: {
          mode: null
        },
        series: {
          lines: { show: false },
          points: { show: false },
          pie: {
            show: true,
            radius: 'auto',
            innerRadius: 0.35,
            label: {
              show: false
            }
          }
        },
        grid: {
          show: false,
          hoverable: true,
          clickable: true
        }
      })

      if (item.labels) {
        options.series.pie.label.show = true
      }
      if (item.is_pie) {
        options.series.pie.innerRadius = 0
      }

      var transform = item.transform || 'sum'
      var data = query.chart_data('flot').map(function(series) {
                   return {
                     label: series.label,
                     summation: series.summation,
                     data: [ series.label, series.summation[transform] ]
                   }
                 })

      setup_plugins(e, context)
      context.plot = $.plot($(e), data, options)

      if (item.legend) {
        render_legend(item, query, options)
      }
      return self
    }

    self.bar_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      var options = get_flot_options(item, {
        legend: {
          show: false
        },
        series: {
          lines: { show: false },
          stack: true,
          bars: {
            show: true,
            lineWidth: 1,
            barWidth: 30000 // TODO - figure this out from the data
          }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        options.series.stack = false
        options.series.stackpercent = true
        options.yaxes[0].max = 100
        options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        options.series.stack = false
        options.series.stackpercent = false
      }

      setup_plugins(e, context)
      context.plot = $.plot($(e), query.chart_data('flot'), options)

      render_legend(item, query, options)

      return self
    }

    self.discrete_bar_chart = function(e, item, query) {
      console.log('ds.charts.flot.discrete_bar_chart()')
      var is_horizontal = item.orientation === 'horizontal'
      var context = {
          plot: null,
          item: item
      }
      var options = get_flot_options(item, {
        legend: {
          show: false
        },
        xaxis: {
        },
        grid: {
          hoverable: true,
          show: true,
          borderWidth: 0,
          color: 'transparent',
          labelMargin: 10,
        },
        multihighlight: {
          mode: null
        },
        crosshair: {
          mode: null
        },
        series: {
          lines: { show: false },
          bars: {
            horizontal: is_horizontal,
            show: true,
            barWidth: 0.8,
            align: "center",
            fill: 0.75
          }
        }
      })

      var transform = item.transform || 'sum'
      var index = 0
      var data = query.chart_data('flot').map(function(series) {
                   return {
                     label: series.label,
                     data: [
                       is_horizontal
                            ? [ series.summation[transform], index]
                            : [index, series.summation[transform]]
                     ],
                     color: options.colors[options.colors % index++]
                   }
                 })
      index = 0
      var ticks = data.map(function(series) {
                              return [index++, series.label]
                            })
      if (is_horizontal) {
        options.yaxes[0].ticks = ticks
        options.xaxis.axisLabel = options.yaxes[0].axisLabel
        options.yaxes[0].axisLabel = null
      } else {
        options.xaxis.ticks = ticks
        options.xaxis.axisLabel = null
      }

      setup_plugins(e, context)
      context.plot = $.plot($(e), data, options)

      return self
    }

    self.process_series = function(series) {
      var result = {}
      if (series.summation) {
        result.summation = series.summation
      }
      result.label = series.target
      result.data = series.datapoints.map(function(point) {
                      return [point[1] * 1000, point[0]]
                    })
      return result
    }

    return self
  })()

/**
 * Set flot as the default interactive chart provider.
 */
ds.charts.provider = ds.charts.flot
<commit_msg>Remove console.log<commit_after>ds.charts = ds.charts || {}

/**
 * Chart provider for rendering dashboard chart with flot, which
 * provides Canvas-based interactivity.
 */
ds.charts.flot =
  (function() {

    var self = {}

    self.CHART_IMPL_TYPE = 'flot'

    function get_default_options() {
      var theme_colors = ds.charts.util.get_colors()
      var default_options = {
        colors: ds.charts.util.get_palette(),
        series: {
          lines: {
            show: true,
            lineWidth: 1,
            steps: false,
            fill: false
          },
          valueLabels: {
            show: false,
            showAsHtml: true,
            labelFormatter: d3.format(',.3s'),
            yoffset: -20
          },
          stack: null,
          points: { show: false },
          bars: { show: false }
        },
        xaxis: {
          mode: "time",
          tickFormatter: function(value, axis) {
            // Take care of time series axis
            if (axis.tickSize && axis.tickSize.length === 2) {
              if (axis.tickSize[1] === 'year' && axis.tickSize[0] >= 1)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('YYYY')
              if (axis.tickSize[1] === 'month' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'year')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM-\'YY')
              if (axis.tickSize[1] === 'day' && axis.tickSize[0] >= 1 || axis.tickSize[1] === 'month')
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD')
              if (axis.tickSize[1] === 'hour' && axis.tickSize[0] >= 12)
                return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('MM/DD hA')
            }
            return moment(value).tz(ds.config.DISPLAY_TIMEZONE).format('h:mm A')
          },
          tickColor: theme_colors.minorGridLineColor,
          font: {
            color: theme_colors.fgcolor,
            size: 12
          }
        },
        yaxes: [
          {
            position: 'left',
            tickFormatter: d3.format(',.3s'),
            reserveSpace: 30,
            labelWidth: 30,
            tickColor: theme_colors.minorGridLineColor,
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          },
          {
            position: 'right',
            tickFormatter: d3.format(',.3s'),
            font: {
              color: theme_colors.fgcolor,
              size: 12
            }
          }
        ],
        points: {
          show: false,
          radius: 2,
          symbol: "circle"
        },
        shadowSize: 0,
        legend: {
          container: null,
          noColumns: 2,
          position: 'sw',
          backgroundColor: 'transparent',
          labelBoxBorderColor: 'transparent'
        },
        grid: {
          borderWidth: 1,
          hoverable: true,
          clickable: true,
          autoHighlight: false,
          /* grid.color actually sets the color of the legend
           * text. WTH? */
          color: theme_colors.fgcolor,
          borderColor: theme_colors.minorGridLineColor
        },
        selection: {
          mode: "x",
          color: "red"
        },
        multihighlight: {
          mode: "x"
        },
        crosshair: {
          mode: "x",
          color: "#BBB",
          lineWidth: 1
        }
      }
      return default_options
    }

    function get_flot_options(item, base) {
      var options      = item.options || {}
      var flot_options = ds.extend(get_default_options(), base)

      flot_options.colors = ds.charts.util.get_palette(options.palette)

      if (options.y1 && options.y1.min)
        flot_options.yaxes[0].min = options.y1.min
      if (options.y2 && options.y2.min)
        flot_options.yaxes[1].min = options.y2.min

      if (options.y1 && options.y1.max)
        flot_options.yaxes[0].max = options.y1.max
      if (options.y2 && options.y2.max)
        flot_options.yaxes[1].max = options.y2.max

      if (options.y1 && options.y1.label)
        flot_options.yaxes[0].axisLabel = options.y1.label
      if (options.y2 && options.y2.label)
        flot_options.yaxes[1].axisLabel = options.y2.label

      return flot_options
    }

    function show_tooltip(x, y, contents) {
      $('
' + contents + '
').css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5
      }).appendTo("body").show()
    }

    function setup_plugins(container, context) {
      $(container).bind("multihighlighted", function(event, pos, items) {
        if ( !items )
          return
        var series = context.plot.getData()
        var item   = items[0]
        var point  = series[item.serieIndex].data[item.dataIndex]
        var format = d3.format(',.3s')
        var is_percent = context.item.stack_mode && (context.item.stack_mode === ds.charts.StackMode.PERCENT)

        var contents = ds.templates.flot.tooltip({
          time: point[0],
          items: items.map(function(item) {
                   var s = series[item.serieIndex]
                   var value = is_percent
                             ? s.percents[item.dataIndex]
                             : s.data[item.dataIndex][1]
                   return {
                     series: s,
                     value: is_percent ? format(value) + '%' : format(value)
                   }
                 })
        })

        $("#ds-tooltip").remove()
        show_tooltip(pos.pageX, pos.pageY, contents)
      })

      $(container).bind("unmultihighlighted", function(event) {
        $("#ds-tooltip").remove()
      })
    }

    function render_legend(item, query, flot_options) {
      var legend_id = '#ds-legend-' + item.item_id
      var legend = ''
      var data = query.chart_data('flot')
      for (var i = 0; i < data.length; i++) {
        var series = data[i]
        var label = series.label
        var color = flot_options.colors[i % flot_options.colors.length]

        var cell = '
'
                 + ''
                 + '' + label + ''
                 + '
'
        legend += cell
      }
      var elt = $(legend_id)
      elt.html(legend)
      elt.equalize({equalize: 'outerWidth', reset: true })
    }

    function set_value_label_options(item, flot_options) {
      if (item.show_max_value || item.show_min_value || item.show_last_value) {
        flot_options.series.valueLabels.show = true
      }
      flot_options.series.valueLabels.showMaxValue = item.show_max_value
      flot_options.series.valueLabels.showMinValue = item.show_min_value
      flot_options.series.valueLabels.showLastValue = item.show_last_value
    }

    self.simple_line_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      setup_plugins(e, context)

      var flot_options = get_flot_options(item, {
        grid: {
          show: false,
          hoverable: true
        },
        legend: {
          show: false
        }
      })

      set_value_label_options(item, flot_options)

      var series = query.chart_data('flot')[0]
      context.plot = $.plot($(e), [series], flot_options)

      return self
    }

    self.standard_line_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      setup_plugins(e, context)
      var flot_options = get_flot_options(item, {
        grid: ds.extend(get_default_options().grid, {
          hoverable: true,
          clickable: true,
          autoHighlight: false
        }),
        legend: {
          show: false
        }
      })

      context.plot = $.plot($(e), query.chart_data('flot'), flot_options)
      render_legend(item, query, flot_options)

      return self
    }

    self.simple_area_chart = function(e, item, query) {
      var options = item.options || {}
      var context = {
          plot: null,
          item: item
      }
      setup_plugins(e, context)
      var flot_options = ds.extend(get_default_options(), {
        colors: ds.charts.util.get_palette(options.palette),
        grid: {
          show: false,
          hoverable: true
        },
        legend: {
          show: false
        }
      })

      flot_options.series.lines.show = true
      flot_options.series.lines.fill = 1

      set_value_label_options(item, flot_options)

      context.plot = $.plot($(e), [query.chart_data('flot')[0]],
                            flot_options)
      return self
    }

    self.stacked_area_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      var legend_id = '#ds-legend-' + item.item_id
      var flot_options = get_flot_options(item, {
        legend: {
          container: legend_id,
          labelBoxBorderColor: 'transparent',
          show: true,
          noColumns: 4
        },
        series: {
          lines: { show: true, lineWidth: 1, fill: 1},
          stack: true,
          points: { show: false },
          bars: { show: false }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        flot_options.series.stack = false
        flot_options.series.stackpercent = true
        flot_options.yaxes[0].max = 100
        flot_options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        flot_options.series.stack = false
        flot_options.series.stackpercent = false
        flot_options.series.lines.fill = false
      }

      setup_plugins(e, context)
      context.plot = $.plot($(e), query.chart_data('flot'), flot_options)

      render_legend(item, query, flot_options)

      return self
    }

    self.donut_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      var options = get_flot_options(item, {
        legend: {
          show: false
        },
        crosshair: {
          mode: null
        },
        multihighlight: {
          mode: null
        },
        series: {
          lines: { show: false },
          points: { show: false },
          pie: {
            show: true,
            radius: 'auto',
            innerRadius: 0.35,
            label: {
              show: false
            }
          }
        },
        grid: {
          show: false,
          hoverable: true,
          clickable: true
        }
      })

      if (item.labels) {
        options.series.pie.label.show = true
      }
      if (item.is_pie) {
        options.series.pie.innerRadius = 0
      }

      var transform = item.transform || 'sum'
      var data = query.chart_data('flot').map(function(series) {
                   return {
                     label: series.label,
                     summation: series.summation,
                     data: [ series.label, series.summation[transform] ]
                   }
                 })

      setup_plugins(e, context)
      context.plot = $.plot($(e), data, options)

      if (item.legend) {
        render_legend(item, query, options)
      }
      return self
    }

    self.bar_chart = function(e, item, query) {
      var context = {
          plot: null,
          item: item
      }
      var options = get_flot_options(item, {
        legend: {
          show: false
        },
        series: {
          lines: { show: false },
          stack: true,
          bars: {
            show: true,
            lineWidth: 1,
            barWidth: 30000 // TODO - figure this out from the data
          }
        }
      })

      if (item.stack_mode === ds.charts.StackMode.PERCENT) {
        options.series.stack = false
        options.series.stackpercent = true
        options.yaxes[0].max = 100
        options.yaxes[0].min = 0
      } else if (item.stack_mode == ds.charts.StackMode.NONE) {
        options.series.stack = false
        options.series.stackpercent = false
      }

      setup_plugins(e, context)
      context.plot = $.plot($(e), query.chart_data('flot'), options)

      render_legend(item, query, options)

      return self
    }

    self.discrete_bar_chart = function(e, item, query) {
      var is_horizontal = item.orientation === 'horizontal'
      var context = {
          plot: null,
          item: item
      }
      var options = get_flot_options(item, {
        legend: {
          show: false
        },
        xaxis: {
        },
        grid: {
          hoverable: true,
          show: true,
          borderWidth: 0,
          color: 'transparent',
          labelMargin: 10,
        },
        multihighlight: {
          mode: null
        },
        crosshair: {
          mode: null
        },
        series: {
          lines: { show: false },
          bars: {
            horizontal: is_horizontal,
            show: true,
            barWidth: 0.8,
            align: "center",
            fill: 0.75
          }
        }
      })

      var transform = item.transform || 'sum'
      var index = 0
      var data = query.chart_data('flot').map(function(series) {
                   return {
                     label: series.label,
                     data: [
                       is_horizontal
                            ? [ series.summation[transform], index]
                            : [index, series.summation[transform]]
                     ],
                     color: options.colors[options.colors % index++]
                   }
                 })
      index = 0
      var ticks = data.map(function(series) {
                              return [index++, series.label]
                            })
      if (is_horizontal) {
        options.yaxes[0].ticks = ticks
        options.xaxis.axisLabel = options.yaxes[0].axisLabel
        options.yaxes[0].axisLabel = null
      } else {
        options.xaxis.ticks = ticks
        options.xaxis.axisLabel = null
      }

      setup_plugins(e, context)
      context.plot = $.plot($(e), data, options)

      return self
    }

    self.process_series = function(series) {
      var result = {}
      if (series.summation) {
        result.summation = series.summation
      }
      result.label = series.target
      result.data = series.datapoints.map(function(point) {
                      return [point[1] * 1000, point[0]]
                    })
      return result
    }

    return self
  })()

/**
 * Set flot as the default interactive chart provider.
 */
ds.charts.provider = ds.charts.flot
<|endoftext|>


<commit_before>var hours = ['10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm'];
var locations = ['PikePlace', 'SeaTac', 'SouthCenter', 'Bellevue', 'Alki'];
function CookieStand(minCust, maxCust, avgCookiesPerCust, store) {
  this.minCust = minCust;
  this.maxCust = maxCust;
  this.avgCookiesPerCust = avgCookiesPerCust;
  this.cHours = [];
  this.total = 0;
  this.store = store;
}

CookieStand.prototype.randCustomer = function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
};

CookieStand.prototype.generateHourly = function() {
    for (var i = 0; i < hours.length; i++) {
    // console.log('Inside FOR loop');
    var numCust = this.randCustomer();
    console.log(numCust + ' is the random number of customers per hour');
    var cookies = Math.floor(numCust * this.avgCookiesPerCust);
    // console.log('before total ' + cookies);
    this.cHours.push(cookies);
    this.total += cookies;
  }

};

  var sectEl = document.getElementById('storeData');

  var tableEl = document.createElement('table');
  // Create a table element.
  var trEl = document.createElement('tr');
  // Create a table header element.
  var thEl = document.createElement('th');
  thEl.textContent = 'Location';
  trEl.appendChild(thEl);

  var thEl = document.createElement('th');
  thEl.textContent = 'Total';
  trEl.appendChild(thEl);

  for (var i = 0; i < hours.length; i++) {
    var thEl = document.createElement('th');
    thEl.textContent = hours[i];
    trEl.appendChild(thEl);
  };
  tableEl.appendChild(trEl);

CookieStand.prototype.render = function() {

    this.generateHourly();

  // for (var x = 0; x < locations.length; x++) {
    // console.log('looking for ' + locations.length);
    var trEl = document.createElement('tr');
    var thEl = document.createElement('th');
    thEl.textContent = this.store;
    trEl.appendChild(thEl);
    // console.log('Give me the location ' + locations[x]);

    var tdEl = document.createElement('td');
    tdEl.textContent = this.total;
    // console.log('after this total ' + this.total);
    trEl.appendChild(tdEl);
      for (var i = 0; i < hours.length; i++) {
        var tdEl = document.createElement('td');
        tdEl.textContent = this.cHours[i];
        trEl.appendChild(tdEl);
      }
    tableEl.appendChild(trEl);
    // tbodyEl.appendChild(trEl);

}
  sectEl.appendChild(tableEl);

var PikePlace = new CookieStand(17, 88, 5.2, "Pike Place Market");
var SeaTac = new CookieStand(6, 44, 1.2, "SeaTac Airport");
var SouthCenter = new CookieStand(11, 38, 1.9, "SouthCenter Mall");
var Bellevue = new CookieStand(20, 48, 3.3, "Bellevue Square");
var Alki = new CookieStand(3, 24, 2.6, "Alki");

PikePlace.render();
SeaTac.render();
SouthCenter.render();
Bellevue.render();
Alki.render();

var userForm = document.getElementById('user-form');

var handleUserSubmit = function(event) {
    // console.log(event);
    event.preventDefault();

     if (!event.target.locName.value || !event.target.minCustHour.value || !event.target.maxCustHour.value || !event.target.avgCookieHour.value) {
      return alert('Fill the fields!');
     }

     var locName = event.target.locName.value;
     console.log('location name is ' + locName);
     var minCustHour = parseInt(event.target.minCustHour.value);
     console.log('min is ' + minCustHour);
     var maxCustHour = parseInt(event.target.maxCustHour.value);
     console.log('max is ' + maxCustHour);
     var avgCookieHour = parseFloat(event.target.avgCookieHour.value);
     console.log('average number of cookie ' + avgCookieHour);

     var newStore = new CookieStand(minCustHour, maxCustHour, avgCookieHour,locName);
     newStore.render();
    //  console.log('calling render');
};

// Event listener for submission button
userForm.addEventListener('submit', handleUserSubmit);
<commit_msg>Drying code little bit<commit_after>var hours = ['10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm'];
var locations = ['PikePlace', 'SeaTac', 'SouthCenter', 'Bellevue', 'Alki'];
function CookieStand(minCust, maxCust, avgCookiesPerCust, store) {
  this.minCust = minCust;
  this.maxCust = maxCust;
  this.avgCookiesPerCust = avgCookiesPerCust;
  this.cHours = [];
  this.total = 0;
  this.store = store;
}

CookieStand.prototype.randCustomer = function() {
    return Math.floor(Math.random() * (this.maxCust - this.minCust + 1) + this.minCust);
};

CookieStand.prototype.generateHourly = function() {
    for (var i = 0; i < hours.length; i++) {
    // console.log('Inside FOR loop');
    var numCust = this.randCustomer();
    console.log(numCust + ' is the random number of customers per hour');
    var cookies = Math.floor(numCust * this.avgCookiesPerCust);
    // console.log('before total ' + cookies);
    this.cHours.push(cookies);
    this.total += cookies;
  }

};

  var sectEl = document.getElementById('storeData');

  var tableEl = document.createElement('table');
  // Create a table element.
  var trEl = document.createElement('tr');
  // Create a table header element.
  var thEl = document.createElement('th');
  thEl.textContent = 'Location';
  trEl.appendChild(thEl);

  var thEl = document.createElement('th');
  thEl.textContent = 'Total';
  trEl.appendChild(thEl);

  for (var i = 0; i < hours.length; i++) {
    var thEl = document.createElement('th');
    thEl.textContent = hours[i];
    trEl.appendChild(thEl);
  };
  tableEl.appendChild(trEl);

CookieStand.prototype.render = function() {

    this.generateHourly();

  // for (var x = 0; x < locations.length; x++) {
    // console.log('looking for ' + locations.length);
    var trEl = document.createElement('tr');
    var thEl = document.createElement('th');
    thEl.textContent = this.store;
    trEl.appendChild(thEl);
    // console.log('Give me the location ' + locations[x]);

    var tdEl = document.createElement('td');
    tdEl.textContent = this.total;
    // console.log('after this total ' + this.total);
    trEl.appendChild(tdEl);
      for (var i = 0; i < hours.length; i++) {
        var tdEl = document.createElement('td');
        tdEl.textContent = this.cHours[i];
        trEl.appendChild(tdEl);
      }
    tableEl.appendChild(trEl);
    // tbodyEl.appendChild(trEl);

}
  sectEl.appendChild(tableEl);

var PikePlace = new CookieStand(17, 88, 5.2, "Pike Place Market");
var SeaTac = new CookieStand(6, 44, 1.2, "SeaTac Airport");
var SouthCenter = new CookieStand(11, 38, 1.9, "SouthCenter Mall");
var Bellevue = new CookieStand(20, 48, 3.3, "Bellevue Square");
var Alki = new CookieStand(3, 24, 2.6, "Alki");

PikePlace.render();
SeaTac.render();
SouthCenter.render();
Bellevue.render();
Alki.render();

var userForm = document.getElementById('user-form');

var handleUserSubmit = function(event) {
    // console.log(event);
    event.preventDefault();

     if (!event.target.locName.value || !event.target.minCustHour.value || !event.target.maxCustHour.value || !event.target.avgCookieHour.value) {
      return alert('Fill the fields!');
     }

     var locName = event.target.locName.value;
     console.log('location name is ' + locName);
     var minCustHour = parseInt(event.target.minCustHour.value);
     console.log('min is ' + minCustHour);
     var maxCustHour = parseInt(event.target.maxCustHour.value);
     console.log('max is ' + maxCustHour);
     var avgCookieHour = parseFloat(event.target.avgCookieHour.value);
     console.log('average number of cookie ' + avgCookieHour);

     var newStore = new CookieStand(minCustHour, maxCustHour, avgCookieHour,locName);
     newStore.render();
    //  new CookieStand(minCustHour, maxCustHour, avgCookieHour,locName).render(); you can call it like this!
    //  console.log('calling render');
};

// Event listener for submission button
userForm.addEventListener('submit', handleUserSubmit);

// if you have paramaters
// userForm.addEventListener('submit', handleUserSubmit, param1, param2);
<|endoftext|>


<commit_before>'use strict'

// Initialization
import { initAnimate } from 'animate'
import { initPointerEvents } from 'pointer-events'
import { initView } from 'view'
import { initMorphs } from 'morphs'
import { initTitleBar } from 'titlebar'
import { initResizeEvents } from 'resize-events'
import { initFastClick } from 'fast-click'

// Include the version
export { version } from '../package.json'

// Utils
export { Set } from 'set'
export { Map } from 'map'
export { List } from 'list'
export {
  hash,
  transpose,
  supports,
  debounce,
  clamp,
  clampUnit,
  randomId,
  min,
  minBy,
  argmin,
  max,
  maxBy,
  argmax,
  range,
  sum,
  flatten,
  cycle,
  hashList,
  find,
  isNumber,
  isString,
  isFunction,
  isArray,
  isObject,
  isBoolean,
  isPlainObject,
  groupBy,
  unique,
  endsWith,
  startsWith,
  tween,
  defined,
  zip,
  extend,
  mergeImpl,
  merge,
  mergeDefined,
  shallowMerge,
  shallowMergeDefined,
  clone,
  shallowClone,
  vendor,
  identity
} from 'utils'
export { EventEmitter } from 'event-emitter'
export { color, isColor, isColorString } from 'color'
export {
  select,
  selectAll,
  isSelection,
  detached,
  div,
  span,
  input,
  button,
  checkbox,
  i
} from 'selection'
export { loop, transition, ease } from 'transition'
export { interpolate } from 'interpolate'
export { animate, morph } from 'animate'
export { sort, sortBy, compare, compareNullsLast, localeCompare } from 'sort'
export { ClickDetector } from 'click-detector'
export {
  notify,
  notifyInfo,
  notifyPositive,
  notifyWarning,
  notifyNegative,
  notifyLoading,
  notifyDefaultTimeout,
  NotificationManager
} from 'notify'
export {
  filterExact,
  filterStartsWith,
  filterContains,
  filterExcludes,
  filterGreater,
  filterLess,
  filterFuzzy,
  filterRegex,
  filterStringTypes,
  filterNumberTypes,
  filterTypes
} from 'filter'
export { userFacingText } from 'user-facing-text'
export { palette } from 'palette'
export { format } from 'format'
export { preferences } from 'preferences'
export { dateTimeLocalizer } from 'date-localizer'
export { ColorScale } from 'color-scale'

// Components

export { spinner, spinnerWide } from 'spinner'
export { Modal, modalDialog, modalInput } from 'modal'
export { Dropdown } from 'dropdown'
export { Collapsible, initializeCollapsibles } from 'collapsible'
export { titleBar, TitleBar } from 'titlebar'
export { Menu } from 'menu'
export { autocomplete, Autocomplete } from 'autocomplete'
export { numberPicker, NumberPicker } from 'number-picker'
export { buttonGroup, ButtonGroup } from 'button-group'
export { picker, Picker } from 'picker'
export { inputGroup } from 'input-group'
export { group, section } from 'layout'
export { dragContainer, DragContainer } from 'drag-container'
export { progressBar, ProgressBar } from 'progress-bar'
export { toggle, Toggle } from 'toggle'
export { crumbtrail, Crumbtrail } from 'crumbtrail'
export { notice, noticeHead, noticeBody } from 'notice'
export { autocompletePicker, AutocompletePicker } from 'autocomplete-picker'
export { StickyTableHeaders } from 'sticky-table-headers'
export {
  graph,
  Graph,
  Axis,
  pieChart,
  PieChart,
  sparkline,
  Sparkline,
  LineSeries,
  BandSeries,
  ScatterSeries,
  BarSeries,
  StraightLineSeries,
  plotLabelStandard,
  plotLabelBasic
} from 'plot'
export { theme } from 'theme'
export { label } from 'label'
export { colorPicker, ColorPicker } from 'color-picker'
export { slider, Slider } from 'slider'
export { timeSlider, TimeSlider } from 'time-slider'
export { card } from 'card'
export { paginator, Paginator } from 'paginator'
export { SideCollapsible } from 'side-collapsible'
export { DatePicker, datePicker } from 'date-picker'
export { pivotTable, PivotTable } from 'pivot-table'
export { timePicker, TimePicker } from 'time-picker'
export { tabs, Tabs } from 'tabs'
export {
  tree,
  Tree,
  initializeTrees // XXX: Remove this?
} from 'tree'
export {
  dataTable,
  DataTable,
  objectFeed,
  getAdvancedSearchFilter
} from 'data-table'
export { Sidebar } from 'sidebar'
export { tagInput, TagInput } from 'tag-input'
export { dateTimePicker, DateTimePicker } from 'date-time-picker'
export { validateForm, Form } from 'form'
export { fileInput, FileInput } from 'file-input'

// XXX: these apis should be opt-in
initAnimate()       // XXX: remove
initPointerEvents() // XXX: make into a selection middleware
initResizeEvents()  // XXX: make into a selection middleware
initFastClick()     // XXX: make into a selection middleware
initView()          // XXX: remove view and replace with reactive lists and reactive objects?
initMorphs()        // XXX: remove

initTitleBar()
<commit_msg>Port the doctype detection to the javascript<commit_after>'use strict'

// Initialization
import { initAnimate } from 'animate'
import { initPointerEvents } from 'pointer-events'
import { initView } from 'view'
import { initMorphs } from 'morphs'
import { initTitleBar } from 'titlebar'
import { initResizeEvents } from 'resize-events'
import { initFastClick } from 'fast-click'
import logger from 'logger'

// Include the version
export { version } from '../package.json'

// Utils
export { Set } from 'set'
export { Map } from 'map'
export { List } from 'list'
export {
  hash,
  transpose,
  supports,
  debounce,
  clamp,
  clampUnit,
  randomId,
  min,
  minBy,
  argmin,
  max,
  maxBy,
  argmax,
  range,
  sum,
  flatten,
  cycle,
  hashList,
  find,
  isNumber,
  isString,
  isFunction,
  isArray,
  isObject,
  isBoolean,
  isPlainObject,
  groupBy,
  unique,
  endsWith,
  startsWith,
  tween,
  defined,
  zip,
  extend,
  mergeImpl,
  merge,
  mergeDefined,
  shallowMerge,
  shallowMergeDefined,
  clone,
  shallowClone,
  vendor,
  identity
} from 'utils'
export { EventEmitter } from 'event-emitter'
export { color, isColor, isColorString } from 'color'
export {
  select,
  selectAll,
  isSelection,
  detached,
  div,
  span,
  input,
  button,
  checkbox,
  i
} from 'selection'
export { loop, transition, ease } from 'transition'
export { interpolate } from 'interpolate'
export { animate, morph } from 'animate'
export { sort, sortBy, compare, compareNullsLast, localeCompare } from 'sort'
export { ClickDetector } from 'click-detector'
export {
  notify,
  notifyInfo,
  notifyPositive,
  notifyWarning,
  notifyNegative,
  notifyLoading,
  notifyDefaultTimeout,
  NotificationManager
} from 'notify'
export {
  filterExact,
  filterStartsWith,
  filterContains,
  filterExcludes,
  filterGreater,
  filterLess,
  filterFuzzy,
  filterRegex,
  filterStringTypes,
  filterNumberTypes,
  filterTypes
} from 'filter'
export { userFacingText } from 'user-facing-text'
export { palette } from 'palette'
export { format } from 'format'
export { preferences } from 'preferences'
export { dateTimeLocalizer } from 'date-localizer'
export { ColorScale } from 'color-scale'

// Components

export { spinner, spinnerWide } from 'spinner'
export { Modal, modalDialog, modalInput } from 'modal'
export { Dropdown } from 'dropdown'
export { Collapsible, initializeCollapsibles } from 'collapsible'
export { titleBar, TitleBar } from 'titlebar'
export { Menu } from 'menu'
export { autocomplete, Autocomplete } from 'autocomplete'
export { numberPicker, NumberPicker } from 'number-picker'
export { buttonGroup, ButtonGroup } from 'button-group'
export { picker, Picker } from 'picker'
export { inputGroup } from 'input-group'
export { group, section } from 'layout'
export { dragContainer, DragContainer } from 'drag-container'
export { progressBar, ProgressBar } from 'progress-bar'
export { toggle, Toggle } from 'toggle'
export { crumbtrail, Crumbtrail } from 'crumbtrail'
export { notice, noticeHead, noticeBody } from 'notice'
export { autocompletePicker, AutocompletePicker } from 'autocomplete-picker'
export { StickyTableHeaders } from 'sticky-table-headers'
export {
  graph,
  Graph,
  Axis,
  pieChart,
  PieChart,
  sparkline,
  Sparkline,
  LineSeries,
  BandSeries,
  ScatterSeries,
  BarSeries,
  StraightLineSeries,
  plotLabelStandard,
  plotLabelBasic
} from 'plot'
export { theme } from 'theme'
export { label } from 'label'
export { colorPicker, ColorPicker } from 'color-picker'
export { slider, Slider } from 'slider'
export { timeSlider, TimeSlider } from 'time-slider'
export { card } from 'card'
export { paginator, Paginator } from 'paginator'
export { SideCollapsible } from 'side-collapsible'
export { DatePicker, datePicker } from 'date-picker'
export { pivotTable, PivotTable } from 'pivot-table'
export { timePicker, TimePicker } from 'time-picker'
export { tabs, Tabs } from 'tabs'
export {
  tree,
  Tree,
  initializeTrees // XXX: Remove this?
} from 'tree'
export {
  dataTable,
  DataTable,
  objectFeed,
  getAdvancedSearchFilter
} from 'data-table'
export { Sidebar } from 'sidebar'
export { tagInput, TagInput } from 'tag-input'
export { dateTimePicker, DateTimePicker } from 'date-time-picker'
export { validateForm, Form } from 'form'
export { fileInput, FileInput } from 'file-input'

// XXX: these apis should be opt-in
initAnimate()       // XXX: remove
initPointerEvents() // XXX: make into a selection middleware
initResizeEvents()  // XXX: make into a selection middleware
initFastClick()     // XXX: make into a selection middleware
initView()          // XXX: remove view and replace with reactive lists and reactive objects?
initMorphs()        // XXX: remove

initTitleBar()

const doctypeIsValid = document.doctype &&
  document.doctype.name === 'html' &&
  !(document.doctype.publicId || document.doctype.systemId)

if (!doctypeIsValid) {
  logger.warn('Missing <!DOCTYPE html> tag - you may have CSS problems without this tag. To fix this add <!DOCTYPE html> to the top of your html file. Detected doctype:', document.doctype)
}
<|endoftext|>


<commit_before>module.exports = {
  parserOptions: {
    parser: "@typescript-eslint/parser", // allows ESLint to understand TypeScript syntax
  },
  plugins: ["prettier", "vue", "@typescript-eslint"],
  extends: [
    // small set of rules which lint for well-known best-practices
    "eslint:recommended",
    // 'recommended' set of rules only from TypeScript-specific plugin (optional)
    "plugin:@typescript-eslint/recommended",
    //
    "plugin:compat/recommended",
    // parse Single File Components + Vue specific rules
    "plugin:vue/vue3-recommended",
    //
    "prettier",
  ],
  env: {
    browser: true,
    es6: true,
    node: true,
  },
  rules: {
    // we're stripping console.* calls in production build
    "no-console": "off",

    // this check is already covered by TS (Vetur), complains about types
    // declared in globals.d.ts
    "no-undef": "off",

    "no-unused-vars": "off",
    "vue/max-attributes-per-line": "off",
    "vue/no-v-html": "off",
    // legacy js
    "no-this-alias": "off",
    //"no-var": "",
    "prefer-rest-params": "off",
    // don't care / don't like
    "prefer-const": "off",

    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/no-inferrable-types": "off",
    "@typescript-eslint/no-non-null-assertion": "off",
  },
};
<commit_msg>(eslintrc): no-empty, no-unused-vars<commit_after>module.exports = {
  parserOptions: {
    parser: "@typescript-eslint/parser", // allows ESLint to understand TypeScript syntax
  },
  plugins: ["prettier", "vue", "@typescript-eslint"],
  extends: [
    // small set of rules which lint for well-known best-practices
    "eslint:recommended",
    // 'recommended' set of rules only from TypeScript-specific plugin (optional)
    "plugin:@typescript-eslint/recommended",
    //
    "plugin:compat/recommended",
    // parse Single File Components + Vue specific rules
    "plugin:vue/vue3-recommended",
    //
    "prettier",
  ],
  env: {
    browser: true,
    es6: true,
    node: true,
  },
  rules: {
    // we're stripping console.* calls in production build
    "no-console": "off",

    // reduce distractions when editing code
    "no-empty": "warn",
    "@typescript-eslint/no-empty-function": "warn",
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": "warn",

    // this check is already covered by TS (Vetur), complains about types
    // declared in globals.d.ts
    "no-undef": "off",

    "vue/max-attributes-per-line": "off",
    "vue/no-v-html": "off",
    // legacy js
    "no-this-alias": "off",
    //"no-var": "",
    "prefer-rest-params": "off",
    // don't care / don't like
    "prefer-const": "off",

    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/explicit-module-boundary-types": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/no-inferrable-types": "off",
    "@typescript-eslint/no-non-null-assertion": "off",
  },
};
<|endoftext|>


<commit_before>'use babel';

import GodsDjsView from './godsdjs-view';
import { CompositeDisposable } from 'atom';

export default {

  godsdjsView: null,
  subscriptions: null,

  activate(state) {
    this.godsdjsView = new GodsDjsView(state.godsdjsViewState);

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'godsdjs:toggle': () => this.toggle()
    }));
  },

  consumeStatusBar(statusBar) {
	this.icon = statusBar.addRightTile({
		item: this.godsdjsView.getElement(),
		priority:
	});
  },

  deactivate() {
	this.icon.destroy();
	this.icon = null;
	this.subscriptions.dispose();
    this.godsdjsView.destroy();
  },

  serialize() {
    return {
      godsdjsViewState: this.godsdjsView.serialize()
    };
  },

  toggle() {
	this.godsdjsView.toggle();
  }

};
<commit_msg>hrmpf<commit_after>'use babel';

import GodsDjsView from './godsdjs-view';
import { CompositeDisposable } from 'atom';

export default {

  godsdjsView: null,
  subscriptions: null,

  activate(state) {
    this.godsdjsView = new GodsDjsView(state.godsdjsViewState);

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'godsdjs:toggle': () => this.toggle()
    }));
  },

  consumeStatusBar(statusBar) {
	this.icon = statusBar.addRightTile({
		item: this.godsdjsView.getElement(),
		priority: -1
	});
  },

  deactivate() {
	this.icon.destroy();
	this.icon = null;
	this.subscriptions.dispose();
    this.godsdjsView.destroy();
  },

  serialize() {
    return {
      godsdjsViewState: this.godsdjsView.serialize()
    };
  },

  toggle() {
	this.godsdjsView.toggle();
  }

};
<|endoftext|>