<commit_before>'use strict';

var url = require('url');
var path = require('path');
var request = require('request');
var debug = require('debug')('rdl-rest');
var os = require('os');
var clone = require('lodash.clone');

// Normalize the method name from the rdl name
// getFoo putBar deleteBaz, etc
// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _normalizeMethod = function(route, proto) {
    var name = route.type.charAt(0).toUpperCase() + route.type.substr(1);
    var method = route.method.toLowerCase();
    if (proto[method + name]) {
        var item = route.inputs.filter(function(o) {
            return (o.name === 'detail');
        })[0];
        // ignore from istanbul coverage because rdl-rest is external library
        /*istanbul ignore next*/
        if (item) {
            name = item.type.charAt(0).toUpperCase() + item.type.substr(1);
            debug('name collision', item.type, route);
        }
    }
    debug('method', method + name);
    return method + name;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var forwardHeaders = ['authorization', 'cookie', 'user-agent', 'client-ip', 'x-forwarded-for', 'bucket'];

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _isSuccessResponseCode = function(responseCode) {
  return responseCode && responseCode >= 200 && responseCode < 300;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _isJsonResponse = function(response) {
  return typeof response === 'object';
};

// Set the headers on the request
// Defaults to content-type unless scoped to a request
// then it forwards the defined headers across
// then it adds the referer as the host calling it
// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _setHeaders = function(headers) {
    headers = headers || {};
    if (this.request) {
        //Forward the headers from the request
        forwardHeaders.forEach(function(name) {
            if (this.request.headers[name]) {
                headers[name] = this.request.headers[name];
            }
        }.bind(this));
        headers.referer = url.format({
            protocol: this.request.protocol,
            host: os.hostname(),
            pathname: url.parse(this.request.originalUrl, true).pathname,
            path: this.request.originalUrl,
            query: this.request.query
        });
    }

    headers['content-type'] = 'application/json';

    if (this.headers) {
        if (typeof this.headers === 'function') {
            headers = this.headers(headers);
        } else {
            Object.keys(this.headers).forEach(function(name) {
                var value = this.headers[name];
                if (typeof value === 'function') {
                    value = value(this.request);
                }
                headers[name] = value;
            }.bind(this));
        }
    }
    return headers;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _normalizeParts = function(route, data) {
    var parts = url.parse(this.apiHost, true);

    var options = clone(this.requestOpts);

    //Cloning to avoid data corruption from the caller
    debug('data start', data);
    data = JSON.parse(JSON.stringify(data));

    options.method = route.method;

    options.headers = this._setHeaders(data.headers);
    delete data.headers;

    parts.pathname = path.join(parts.pathname, route.path);
    if (this.request && this.request.requestId) {
        parts.query.requestId = this.request.requestId;
    }
    route.inputs.forEach(function(item) {
        var name = item.name;
        var value = data[name];
        if (value) {
            if (item.header) {
                options.headers[item.header.toLowerCase()] = value;
                delete data[name];
            }
            if (item.queryParam) {
                parts.query[item.queryParam] = value;
                delete data[name];
            }
            if (item.pathParam) {
                parts.pathname = parts.pathname.replace('{' + name + '}', value);
                delete data[name];
            }
        }
    });
    delete parts.href;
    delete parts.path;
    options.json = true;
    options.uri = url.format(parts);
    data = this._normalizeData(route, data);
    if (data) {
        options.body = data;
    } else {
      delete options.body;
    }
    debug('parts', options);
    return options;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _normalizeData = function(route, data) {
    var out = {}, extra;
    var bodyItem = route.inputs.filter(function(item) {
        if (!item.pathParam && !item.header && !item.queryParam) {
            return true;
        }
        return false;
    });

    if (bodyItem.length) {
        out = data[bodyItem[0].name];
        delete data[bodyItem[0].name];
    }

    extra = Object.keys(data).length;
    if (extra) {
        debug('Found ' + extra + ' items in payload:', data);
    }
    if (!Object.keys(out).length) {
        out = null;
    }
    debug('payload', out);
    return out;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var generate = function(rdl, apiHost, mHeaders, requestOpts) {

    var RDLRest = function (req, headers) {
        if (!(this instanceof RDLRest)) {
            return new RDLRest(req, headers);
        }
        this.apiHost = apiHost;
        this.request = req;
        this.headers = headers || mHeaders;
        this.requestOpts = requestOpts || {
            timeout: 4000
        };
    };

    RDLRest.prototype._normalizeParts = _normalizeParts;
    RDLRest.prototype._normalizeData = _normalizeData;
    RDLRest.prototype._setHeaders = _setHeaders;

    rdl.resources.forEach(function(route) {
        var method = _normalizeMethod(route, RDLRest.prototype);
        RDLRest.prototype[method] = function(data, callback) {
            if (typeof data === 'function') {
                callback = data;
                data = {};
            }
            if (!data || !callback) {
                throw(new Error('Invalid number of arguments passed while calling: ' + method));
            }
            var parts = this._normalizeParts(route, data);
            var start = Date.now();
            var req = this.request;
            var done = function(err, json, res) {
                var time = Date.now() - start + 'ms';
                if (req && req.log && req.error) {
                    if (err) {
                        req.error('rdl-rest', time, err);
                    } else {
                        req.log('rdl-rest', time, json);
                    }
                }
                callback(err, json, res);
            };
            return request(parts, function(err, res, json) {
                var isJson = _isJsonResponse(json);
                var isSuccessResponse = _isSuccessResponseCode(res && res.statusCode);

                if (isSuccessResponse && !isJson) {
                  if (res && res.statusCode !== 200) {
                    json = {};
                    isJson = true;
                  }
                }

                if (err || !isSuccessResponse || !isJson) {
                    err = {
                        status: res && res.statusCode,
                        message: json,
                        error: err
                    };
                    if (!isJson) {
                        json = null;
                    }
                }

                done(err, json, res);
            });
        };
    });

    return RDLRest;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
module.exports = function(config) {
    config = config || {};
    if (!config.rdl) {
        throw(new Error('RDL spec not provided'));
    }
    if (!config.apiHost) {
        throw(new Error('apiHost is required'));
    }
    //Create the base client from the RDL
    var Client = generate(config.rdl, config.apiHost, config.headers, config.requestOpts);

    var factory = function(req, headers, cb) {
        var client =  new Client(req, headers);
        if (cb) {
            cb(client);
        }
        return client;
    };

    factory.Client = Client;

    //Return a factory to create a new client with scoped to a request
    return factory;
};

<commit_msg>source license<commit_after>/**
 * Copyright 2016 Yahoo Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var url = require('url');
var path = require('path');
var request = require('request');
var debug = require('debug')('rdl-rest');
var os = require('os');
var clone = require('lodash.clone');

// Normalize the method name from the rdl name
// getFoo putBar deleteBaz, etc
// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _normalizeMethod = function(route, proto) {
    var name = route.type.charAt(0).toUpperCase() + route.type.substr(1);
    var method = route.method.toLowerCase();
    if (proto[method + name]) {
        var item = route.inputs.filter(function(o) {
            return (o.name === 'detail');
        })[0];
        // ignore from istanbul coverage because rdl-rest is external library
        /*istanbul ignore next*/
        if (item) {
            name = item.type.charAt(0).toUpperCase() + item.type.substr(1);
            debug('name collision', item.type, route);
        }
    }
    debug('method', method + name);
    return method + name;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var forwardHeaders = ['authorization', 'cookie', 'user-agent', 'client-ip', 'x-forwarded-for', 'bucket'];

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _isSuccessResponseCode = function(responseCode) {
  return responseCode && responseCode >= 200 && responseCode < 300;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _isJsonResponse = function(response) {
  return typeof response === 'object';
};

// Set the headers on the request
// Defaults to content-type unless scoped to a request
// then it forwards the defined headers across
// then it adds the referer as the host calling it
// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _setHeaders = function(headers) {
    headers = headers || {};
    if (this.request) {
        //Forward the headers from the request
        forwardHeaders.forEach(function(name) {
            if (this.request.headers[name]) {
                headers[name] = this.request.headers[name];
            }
        }.bind(this));
        headers.referer = url.format({
            protocol: this.request.protocol,
            host: os.hostname(),
            pathname: url.parse(this.request.originalUrl, true).pathname,
            path: this.request.originalUrl,
            query: this.request.query
        });
    }

    headers['content-type'] = 'application/json';

    if (this.headers) {
        if (typeof this.headers === 'function') {
            headers = this.headers(headers);
        } else {
            Object.keys(this.headers).forEach(function(name) {
                var value = this.headers[name];
                if (typeof value === 'function') {
                    value = value(this.request);
                }
                headers[name] = value;
            }.bind(this));
        }
    }
    return headers;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _normalizeParts = function(route, data) {
    var parts = url.parse(this.apiHost, true);

    var options = clone(this.requestOpts);

    //Cloning to avoid data corruption from the caller
    debug('data start', data);
    data = JSON.parse(JSON.stringify(data));

    options.method = route.method;

    options.headers = this._setHeaders(data.headers);
    delete data.headers;

    parts.pathname = path.join(parts.pathname, route.path);
    if (this.request && this.request.requestId) {
        parts.query.requestId = this.request.requestId;
    }
    route.inputs.forEach(function(item) {
        var name = item.name;
        var value = data[name];
        if (value) {
            if (item.header) {
                options.headers[item.header.toLowerCase()] = value;
                delete data[name];
            }
            if (item.queryParam) {
                parts.query[item.queryParam] = value;
                delete data[name];
            }
            if (item.pathParam) {
                parts.pathname = parts.pathname.replace('{' + name + '}', value);
                delete data[name];
            }
        }
    });
    delete parts.href;
    delete parts.path;
    options.json = true;
    options.uri = url.format(parts);
    data = this._normalizeData(route, data);
    if (data) {
        options.body = data;
    } else {
      delete options.body;
    }
    debug('parts', options);
    return options;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var _normalizeData = function(route, data) {
    var out = {}, extra;
    var bodyItem = route.inputs.filter(function(item) {
        if (!item.pathParam && !item.header && !item.queryParam) {
            return true;
        }
        return false;
    });

    if (bodyItem.length) {
        out = data[bodyItem[0].name];
        delete data[bodyItem[0].name];
    }

    extra = Object.keys(data).length;
    if (extra) {
        debug('Found ' + extra + ' items in payload:', data);
    }
    if (!Object.keys(out).length) {
        out = null;
    }
    debug('payload', out);
    return out;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
var generate = function(rdl, apiHost, mHeaders, requestOpts) {

    var RDLRest = function (req, headers) {
        if (!(this instanceof RDLRest)) {
            return new RDLRest(req, headers);
        }
        this.apiHost = apiHost;
        this.request = req;
        this.headers = headers || mHeaders;
        this.requestOpts = requestOpts || {
            timeout: 4000
        };
    };

    RDLRest.prototype._normalizeParts = _normalizeParts;
    RDLRest.prototype._normalizeData = _normalizeData;
    RDLRest.prototype._setHeaders = _setHeaders;

    rdl.resources.forEach(function(route) {
        var method = _normalizeMethod(route, RDLRest.prototype);
        RDLRest.prototype[method] = function(data, callback) {
            if (typeof data === 'function') {
                callback = data;
                data = {};
            }
            if (!data || !callback) {
                throw(new Error('Invalid number of arguments passed while calling: ' + method));
            }
            var parts = this._normalizeParts(route, data);
            var start = Date.now();
            var req = this.request;
            var done = function(err, json, res) {
                var time = Date.now() - start + 'ms';
                if (req && req.log && req.error) {
                    if (err) {
                        req.error('rdl-rest', time, err);
                    } else {
                        req.log('rdl-rest', time, json);
                    }
                }
                callback(err, json, res);
            };
            return request(parts, function(err, res, json) {
                var isJson = _isJsonResponse(json);
                var isSuccessResponse = _isSuccessResponseCode(res && res.statusCode);

                if (isSuccessResponse && !isJson) {
                  if (res && res.statusCode !== 200) {
                    json = {};
                    isJson = true;
                  }
                }

                if (err || !isSuccessResponse || !isJson) {
                    err = {
                        status: res && res.statusCode,
                        message: json,
                        error: err
                    };
                    if (!isJson) {
                        json = null;
                    }
                }

                done(err, json, res);
            });
        };
    });

    return RDLRest;
};

// ignore from istanbul coverage because rdl-rest is external library
/*istanbul ignore next*/
module.exports = function(config) {
    config = config || {};
    if (!config.rdl) {
        throw(new Error('RDL spec not provided'));
    }
    if (!config.apiHost) {
        throw(new Error('apiHost is required'));
    }
    //Create the base client from the RDL
    var Client = generate(config.rdl, config.apiHost, config.headers, config.requestOpts);

    var factory = function(req, headers, cb) {
        var client =  new Client(req, headers);
        if (cb) {
            cb(client);
        }
        return client;
    };

    factory.Client = Client;

    //Return a factory to create a new client with scoped to a request
    return factory;
};

<|endoftext|>


<commit_before><commit_msg>start converting watches panel<commit_after><|endoftext|>


<commit_before>var chaisePage = require('../../../../utils/chaise.page.js'), IGNORE = "tag:isrd.isi.edu,2016:ignore", HIDDEN = "tag:misd.isi.edu,2015:hidden";
var recordEditHelpers = require('../../helpers.js');

describe('Edit existing record,', function() {

	var params, testConfiguration = browser.params.configuration.tests, testParams = testConfiguration.params;

    for (var i=0; i< testParams.tables.length; i++) {

    	(function(tableParams, index) {

    		describe("For table " + table.table_name + ",", function() {

    			var table, record;

				beforeAll(function () {
					var keys = [];
					tableParams.keys.forEach(function(key) {
						keys.push(key.name + key.operator + key.value);
					});
					browser.ignoreSynchronization=true;
					browser.get(browser.params.url + ":" + tableParams.table_name + "/" + keys.join("&"));
					table = browser.params.defaultSchema.content.tables[tableParams.table_name];

					browser.sleep(3000);
			        chaisePage.recordEditPage.getRecordModelRows().then(function(records) {
			        	browser.params.record = record = records[0];
			        	table.column_definitions.forEach(function(c) {
			        		if (record[c.name]) {
			        			if (c.type.typename !== "date" && c.type.typename !== "timestamptz") {
				        		 	c._value =  record[c.name] + "";
				        		}
			        		}
			        	});
			        });
			        browser.sleep(100);
			    });

				describe("Presentation and validation,", function() {
                    var params = recordEditHelpers.testPresentationAndBasicValidation(tableParams);
				});

				describe("Submit existing record", function() {
					beforeAll(function() {
						// Submit the form
						chaisePage.recordEditPage.submitForm();
					});

					var hasErrors = false;

					it("should have no errors, and should be redirected", function() {
						chaisePage.recordEditPage.getAlertError().then(function(err) {
							if (err) {
								expect("Page has errors").toBe("No errors");
								hasErrors = true;
							} else {
								expect(true).toBe(true);
							}
						});
					});

					xit("should be redirected to record page", function() {
						if (!hasErrors) {
							browser.sleep(3000);
							browser.driver.getCurrentUrl().then(function(url) {
						        expect(url.startsWith(process.env.CHAISE_BASE_URL + "/record/")).toBe(true);
						        console.log(url);
						    });
						}
					}).pend("Postpone test until foreign key UI is updated for the new reference apis");

				});

    		});

    	})(testParams.tables[i], i);

    }

});
<commit_msg>changed a spec to pend while foreign key implementation is worked on<commit_after>var chaisePage = require('../../../../utils/chaise.page.js'), IGNORE = "tag:isrd.isi.edu,2016:ignore", HIDDEN = "tag:misd.isi.edu,2015:hidden";
var recordEditHelpers = require('../../helpers.js');

describe('Edit existing record,', function() {

	var params, testConfiguration = browser.params.configuration.tests, testParams = testConfiguration.params;

    for (var i=0; i< testParams.tables.length; i++) {

    	(function(tableParams, index) {

    		describe("For table " + table.table_name + ",", function() {

    			var table, record;

				beforeAll(function () {
					var keys = [];
					tableParams.keys.forEach(function(key) {
						keys.push(key.name + key.operator + key.value);
					});
					browser.ignoreSynchronization=true;
					browser.get(browser.params.url + ":" + tableParams.table_name + "/" + keys.join("&"));
					table = browser.params.defaultSchema.content.tables[tableParams.table_name];

					browser.sleep(3000);
			        chaisePage.recordEditPage.getRecordModelRows().then(function(records) {
			        	browser.params.record = record = records[0];
			        	table.column_definitions.forEach(function(c) {
			        		if (record[c.name]) {
			        			if (c.type.typename !== "date" && c.type.typename !== "timestamptz") {
				        		 	c._value =  record[c.name] + "";
				        		}
			        		}
			        	});
			        });
			        browser.sleep(100);
			    });

				describe("Presentation and validation,", function() {
                    var params = recordEditHelpers.testPresentationAndBasicValidation(tableParams);
				});

				describe("Submit existing record", function() {
					beforeAll(function() {
						// Submit the form
						chaisePage.recordEditPage.submitForm();
					});

					var hasErrors = false;

					xit("should have no errors, and should be redirected", function() {
						chaisePage.recordEditPage.getAlertError().then(function(err) {
							if (err) {
								expect("Page has errors").toBe("No errors");
								hasErrors = true;
							} else {
								expect(true).toBe(true);
							}
						});
					}).pend("Postpone test until foreign key UI is updated for the new reference apis");

					xit("should be redirected to record page", function() {
						if (!hasErrors) {
							browser.sleep(3000);
							browser.driver.getCurrentUrl().then(function(url) {
						        expect(url.startsWith(process.env.CHAISE_BASE_URL + "/record/")).toBe(true);
						        console.log(url);
						    });
						}
					}).pend("Postpone test until foreign key UI is updated for the new reference apis");

				});

    		});

    	})(testParams.tables[i], i);

    }

});
<|endoftext|>


<commit_before>// jscs:disable validateQuoteMarks
export default {
    "categories": [],
    "crate": {
        "badges": [],
        "categories": [],
        "created_at": "2014-12-08T02:08:06Z",
        "description": "A high-level, Rust idiomatic wrapper around nanomsg.",
        "documentation": "https://github.com/thehydroimpulse/nanomsg.rs",
        "downloads": 3888,
        "homepage": "https://github.com/thehydroimpulse/nanomsg.rs",
        "id": "nanomsg",
        "keywords": [
            "network",
        ],
        "license": "MIT",
        "links": {
            "owners": "/api/v1/crates/nanomsg/owners",
            "reverse_dependencies": "/api/v1/crates/nanomsg/reverse_dependencies",
            "version_downloads": "/api/v1/crates/nanomsg/downloads",
            "versions": null
        },
        "max_version": "0.6.1",
        "name": "nanomsg",
        "repository": "https://github.com/thehydroimpulse/nanomsg.rs",
        "updated_at": "2016-12-27T08:40:00Z",
        "versions": [
            40905,
            28431,
            21273,
            18445,
            17384,
            13574,
            9014,
            8236,
            7190,
            4944,
            940,
            924
        ]
    },
    "keywords": [
        {
            "crates_cnt": 38,
            "created_at": "2014-11-23T06:47:40Z",
            "id": "network",
            "keyword": "network"
        }
    ],
    "versions": [
        {
            "crate": "nanomsg",
            "created_at": "2016-12-27T08:40:00Z",
            "dl_path": "/api/v1/crates/nanomsg/0.6.1/download",
            "downloads": 260,
            "features": {
                "bundled": [
                    "nanomsg-sys/bundled"
                ]
            },
            "id": 40905,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.6.1/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.6.1/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.6.1/downloads"
            },
            "num": "0.6.1",
            "updated_at": "2016-12-27T08:40:00Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2016-06-10T20:03:55Z",
            "dl_path": "/api/v1/crates/nanomsg/0.6.0/download",
            "downloads": 904,
            "features": {},
            "id": 28431,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.6.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.6.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.6.0/downloads"
            },
            "num": "0.6.0",
            "updated_at": "2016-06-10T20:03:55Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2016-01-24T22:07:58Z",
            "dl_path": "/api/v1/crates/nanomsg/0.5.0/download",
            "downloads": 1217,
            "features": {},
            "id": 21273,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.5.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.5.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.5.0/downloads"
            },
            "num": "0.5.0",
            "updated_at": "2016-01-24T22:07:58Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-11-23T12:10:09Z",
            "dl_path": "/api/v1/crates/nanomsg/0.4.2/download",
            "downloads": 318,
            "features": {},
            "id": 18445,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.4.2/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.4.2/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.4.2/downloads"
            },
            "num": "0.4.2",
            "updated_at": "2015-12-16T00:01:56Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-10-29T22:13:45Z",
            "dl_path": "/api/v1/crates/nanomsg/0.4.1/download",
            "downloads": 168,
            "features": {},
            "id": 17384,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.4.1/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.4.1/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.4.1/downloads"
            },
            "num": "0.4.1",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-07-23T05:54:44Z",
            "dl_path": "/api/v1/crates/nanomsg/0.4.0/download",
            "downloads": 311,
            "features": {},
            "id": 13574,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.4.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.4.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.4.0/downloads"
            },
            "num": "0.4.0",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-04-18T20:45:03Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.4/download",
            "downloads": 237,
            "features": {},
            "id": 9014,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.4/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.4/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.4/downloads"
            },
            "num": "0.3.4",
            "updated_at": "2015-12-15T00:03:39Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-04-06T18:57:47Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.3/download",
            "downloads": 99,
            "features": {},
            "id": 8236,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.3/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.3/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.3/downloads"
            },
            "num": "0.3.3",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-03-26T06:51:10Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.2/download",
            "downloads": 98,
            "features": {},
            "id": 7190,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.2/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.2/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.2/downloads"
            },
            "num": "0.3.2",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-02-12T20:20:32Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.1/download",
            "downloads": 95,
            "features": {},
            "id": 4944,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.1/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.1/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.1/downloads"
            },
            "num": "0.3.1",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2014-12-08T16:21:01Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.0/download",
            "downloads": 102,
            "features": {},
            "id": 940,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.0/downloads"
            },
            "num": "0.3.0",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2014-12-08T02:08:06Z",
            "dl_path": "/api/v1/crates/nanomsg/0.2.0/download",
            "downloads": 79,
            "features": {},
            "id": 924,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.2.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.2.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.2.0/downloads"
            },
            "num": "0.2.0",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        }
    ]
};
<commit_msg>Set the latest version to be unstable<commit_after>// jscs:disable validateQuoteMarks
export default {
    "categories": [],
    "crate": {
        "badges": [],
        "categories": [],
        "created_at": "2014-12-08T02:08:06Z",
        "description": "A high-level, Rust idiomatic wrapper around nanomsg.",
        "documentation": "https://github.com/thehydroimpulse/nanomsg.rs",
        "downloads": 3888,
        "homepage": "https://github.com/thehydroimpulse/nanomsg.rs",
        "id": "nanomsg",
        "keywords": [
            "network",
        ],
        "license": "MIT",
        "links": {
            "owners": "/api/v1/crates/nanomsg/owners",
            "reverse_dependencies": "/api/v1/crates/nanomsg/reverse_dependencies",
            "version_downloads": "/api/v1/crates/nanomsg/downloads",
            "versions": null
        },
        "max_version": "0.7.0-alpha",
        "name": "nanomsg",
        "repository": "https://github.com/thehydroimpulse/nanomsg.rs",
        "updated_at": "2016-12-28T08:40:00Z",
        "versions": [
            40906,
            40905,
            28431,
            21273,
            18445,
            17384,
            13574,
            9014,
            8236,
            7190,
            4944,
            940,
            924
        ]
    },
    "keywords": [
        {
            "crates_cnt": 38,
            "created_at": "2014-11-23T06:47:40Z",
            "id": "network",
            "keyword": "network"
        }
    ],
    "versions": [
        {
            "crate": "nanomsg",
            "created_at": "2016-12-28T08:40:00Z",
            "dl_path": "/api/v1/crates/nanomsg/0.7.0-alpha/download",
            "downloads": 260,
            "features": {
                "bundled": [
                    "nanomsg-sys/bundled"
                ]
            },
            "id": 40906,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.7.0-alpha/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.7.0-alpha/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.7.0-alpha/downloads"
            },
            "num": "0.7.0-alpha",
            "updated_at": "2016-12-28T08:40:00Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2016-12-27T08:40:00Z",
            "dl_path": "/api/v1/crates/nanomsg/0.6.1/download",
            "downloads": 260,
            "features": {
                "bundled": [
                    "nanomsg-sys/bundled"
                ]
            },
            "id": 40905,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.6.1/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.6.1/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.6.1/downloads"
            },
            "num": "0.6.1",
            "updated_at": "2016-12-27T08:40:00Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2016-06-10T20:03:55Z",
            "dl_path": "/api/v1/crates/nanomsg/0.6.0/download",
            "downloads": 904,
            "features": {},
            "id": 28431,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.6.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.6.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.6.0/downloads"
            },
            "num": "0.6.0",
            "updated_at": "2016-06-10T20:03:55Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2016-01-24T22:07:58Z",
            "dl_path": "/api/v1/crates/nanomsg/0.5.0/download",
            "downloads": 1217,
            "features": {},
            "id": 21273,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.5.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.5.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.5.0/downloads"
            },
            "num": "0.5.0",
            "updated_at": "2016-01-24T22:07:58Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-11-23T12:10:09Z",
            "dl_path": "/api/v1/crates/nanomsg/0.4.2/download",
            "downloads": 318,
            "features": {},
            "id": 18445,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.4.2/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.4.2/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.4.2/downloads"
            },
            "num": "0.4.2",
            "updated_at": "2015-12-16T00:01:56Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-10-29T22:13:45Z",
            "dl_path": "/api/v1/crates/nanomsg/0.4.1/download",
            "downloads": 168,
            "features": {},
            "id": 17384,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.4.1/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.4.1/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.4.1/downloads"
            },
            "num": "0.4.1",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-07-23T05:54:44Z",
            "dl_path": "/api/v1/crates/nanomsg/0.4.0/download",
            "downloads": 311,
            "features": {},
            "id": 13574,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.4.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.4.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.4.0/downloads"
            },
            "num": "0.4.0",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-04-18T20:45:03Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.4/download",
            "downloads": 237,
            "features": {},
            "id": 9014,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.4/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.4/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.4/downloads"
            },
            "num": "0.3.4",
            "updated_at": "2015-12-15T00:03:39Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-04-06T18:57:47Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.3/download",
            "downloads": 99,
            "features": {},
            "id": 8236,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.3/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.3/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.3/downloads"
            },
            "num": "0.3.3",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-03-26T06:51:10Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.2/download",
            "downloads": 98,
            "features": {},
            "id": 7190,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.2/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.2/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.2/downloads"
            },
            "num": "0.3.2",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2015-02-12T20:20:32Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.1/download",
            "downloads": 95,
            "features": {},
            "id": 4944,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.1/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.1/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.1/downloads"
            },
            "num": "0.3.1",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2014-12-08T16:21:01Z",
            "dl_path": "/api/v1/crates/nanomsg/0.3.0/download",
            "downloads": 102,
            "features": {},
            "id": 940,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.3.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.3.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.3.0/downloads"
            },
            "num": "0.3.0",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        },
        {
            "crate": "nanomsg",
            "created_at": "2014-12-08T02:08:06Z",
            "dl_path": "/api/v1/crates/nanomsg/0.2.0/download",
            "downloads": 79,
            "features": {},
            "id": 924,
            "links": {
                "authors": "/api/v1/crates/nanomsg/0.2.0/authors",
                "dependencies": "/api/v1/crates/nanomsg/0.2.0/dependencies",
                "version_downloads": "/api/v1/crates/nanomsg/0.2.0/downloads"
            },
            "num": "0.2.0",
            "updated_at": "2015-12-11T23:54:29Z",
            "yanked": false
        }
    ]
};
<|endoftext|>


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

var express = require('../../');
var app = module.exports = express();
var logger = require('morgan');
var silent = 'test' == process.env.NODE_ENV;

// general config
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// our custom "verbose errors" setting
// which we can use in the templates
// via settings['verbose errors']
app.enable('verbose errors');

// disable them in production
// use $ NODE_ENV=production node examples/error-pages
if ('production' == app.settings.env) app.disable('verbose errors');

silent || app.use(logger('dev'));

// Routes

app.get('/', function(req, res){
  res.render('index.ejs');
});

app.get('/404', function(req, res, next){
  // trigger a 404 since no other middleware
  // will match /404 after this one, and we're not
  // responding here
  next();
});

app.get('/403', function(req, res, next){
  // trigger a 403 error
  var err = new Error('not allowed!');
  err.status = 403;
  next(err);
});

app.get('/500', function(req, res, next){
  // trigger a generic (500) error
  next(new Error('keyboard cat!'));
});

// Error handlers

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

// error-handling middleware, take the same form
// as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).
// when connect has an error, it will invoke ONLY error-handling
// middleware.

// If we were to next() here any remaining non-error-handling
// middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware
// would remain being executed, however here
// we simply respond with an error page.

app.use(function(err, req, res, next){
  // we may use properties of the error object
  // here and next(err) appropriately, or if
  // we possibly recovered from the error, simply next().
  res.status(err.status || 500);
  res.render('500', { error: err });
});

/* istanbul ignore next */
if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000');
}
<commit_msg>examples: use res.format in error-pages<commit_after>/**
 * Module dependencies.
 */

var express = require('../../');
var app = module.exports = express();
var logger = require('morgan');
var silent = 'test' == process.env.NODE_ENV;

// general config
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// our custom "verbose errors" setting
// which we can use in the templates
// via settings['verbose errors']
app.enable('verbose errors');

// disable them in production
// use $ NODE_ENV=production node examples/error-pages
if ('production' == app.settings.env) app.disable('verbose errors');

silent || app.use(logger('dev'));

// Routes

app.get('/', function(req, res){
  res.render('index.ejs');
});

app.get('/404', function(req, res, next){
  // trigger a 404 since no other middleware
  // will match /404 after this one, and we're not
  // responding here
  next();
});

app.get('/403', function(req, res, next){
  // trigger a 403 error
  var err = new Error('not allowed!');
  err.status = 403;
  next(err);
});

app.get('/500', function(req, res, next){
  // trigger a generic (500) error
  next(new Error('keyboard cat!'));
});

// Error handlers

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){
  res.status(404);

  res.format({
    html: function () {
      res.render('404', { url: req.url })
    },
    json: function () {
      res.json({ error: 'Not found' })
    },
    default: function () {
      res.type('txt').send('Not found')
    }
  })
});

// error-handling middleware, take the same form
// as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).
// when connect has an error, it will invoke ONLY error-handling
// middleware.

// If we were to next() here any remaining non-error-handling
// middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware
// would remain being executed, however here
// we simply respond with an error page.

app.use(function(err, req, res, next){
  // we may use properties of the error object
  // here and next(err) appropriately, or if
  // we possibly recovered from the error, simply next().
  res.status(err.status || 500);
  res.render('500', { error: err });
});

/* istanbul ignore next */
if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000');
}
<|endoftext|>


<commit_before>// Load the book metadata into MongoDB from book_metadata.json

var databaseURI = "localhost:27017/bldata";
var collections = ["bookmeta"];
var db = require("mongojs").connect(databaseURI, collections);

var fs = require('fs');
var file = '../../../data/bldata/imagedirectory/book_metadata.json';

var bookdata;
fs.readFile(file, 'utf8', function (err, data) {
	if (err) {
		console.log('Error: ' + err);
		return;
	}

	bookdata = JSON.parse(data);
	for (var id in bookdata) {
		var meta = bookdata[id];
		meta._id = id;
		// add to Mongo:
		db.bookmeta.update({"_id" : id}, meta, {"upsert" : true});
	}
});
<commit_msg>Update to match new book data JSON format (list not hash) Also fixed the waiting issue after completion<commit_after>// Load the book metadata into MongoDB from book_metadata.json

var databaseURI = "localhost:27017/bldata";
var collections = ["bookmeta"];
var db = require("mongojs").connect(databaseURI, collections);

var fs = require('fs');
var file = '../../../data/bldata/imagedirectory/book_metadata.json';

var bookdata;
var waitingCount = 0;
fs.readFile(file, 'utf8', function (err, data) {
	if (err) {
		console.log('Error: ' + err);
		return;
	}

	bookdata = JSON.parse(data);
	for (var i = 0; i < bookdata.length; i++) {
		var meta = bookdata[i];
		meta._id = meta.identifier;
		// add to Mongo:
		waitingCount++;
		db.bookmeta.update({"_id" : meta._id}, meta, {"upsert" : true}, function() { waitingCount--;});
	}

	// give save thread a chance to finish by waiting a second
	console.log("Waiting to finish..");
	waitForFinish();
});

function waitForFinish() {
	setTimeout((function() {
		console.log(waitingCount);
		if (waitingCount <= 0) {
			process.exit();
		} else {
			waitForFinish();
		}
	}), 1000);
}
<|endoftext|>


<commit_before>//require our dependencies
var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {
	//the base directory (absolute path) for resolving the entry option
	context: __dirname,
	//the entry point we created earlier. Note that './' means
	//your current directory. You don't have to specify the extension  now,
	//because you will specify extensions later in the `resolve` section
	entry: {
		menu:
		[
			'./mixtas/menu/assets/js/components/menu',
		]
	},

	output: {
		//where you want your compiled bundle to be stored
		path: path.resolve('./assets/bundles/'),
		//naming convention webpack should use for your files
		filename: '[name]-[hash].js',
	},

	plugins: [
		//tells webpack where to store data about your bundles.
		new BundleTracker({filename: './webpack-stats.json'}),
		//makes jQuery available in every module
		new webpack.ProvidePlugin({
			$: 'jquery',
			jQuery: 'jquery',
			'window.jQuery': 'jquery'
		})
	],

	module: {
		loaders: [
			//a regexp that tells webpack use the following loaders on all
			//.js and .jsx files
			{test: /\.jsx?$/,
				//we definitely don't want babel to transpile all the files in
				//node_modules. That would take a long time.
				exclude: /node_modules/,
				//use the babel loader
				loader: 'babel-loader',
				query: {
					//specify that we will be dealing with React code
					presets: ['react', 'es2015']
				}
			}
		]
	},

	resolve: {
		//tells webpack where to look for modules
		modulesDirectories: ['node_modules'],
		//extensions that should be used to resolve modules
		extensions: ['', '.js', '.jsx']
	}
};<commit_msg>webpack.config: pedidos route added<commit_after>//require our dependencies
var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {
	//the base directory (absolute path) for resolving the entry option
	context: __dirname,
	//the entry point we created earlier. Note that './' means
	//your current directory. You don't have to specify the extension  now,
	//because you will specify extensions later in the `resolve` section
	entry: {
		menu:
		[
			'./mixtas/menu/assets/js/components/menu',
		],
		pedidos:
		[
			'./mixtas/pedidos/assets/js/components/pedidos',
		]
	},

	output: {
		//where you want your compiled bundle to be stored
		path: path.resolve('./assets/bundles/'),
		//naming convention webpack should use for your files
		filename: '[name]-[hash].js',
	},

	plugins: [
		//tells webpack where to store data about your bundles.
		new BundleTracker({filename: './webpack-stats.json'}),
		//makes jQuery available in every module
		new webpack.ProvidePlugin({
			$: 'jquery',
			jQuery: 'jquery',
			'window.jQuery': 'jquery'
		})
	],

	module: {
		loaders: [
			//a regexp that tells webpack use the following loaders on all
			//.js and .jsx files
			{test: /\.jsx?$/,
				//we definitely don't want babel to transpile all the files in
				//node_modules. That would take a long time.
				exclude: /node_modules/,
				//use the babel loader
				loader: 'babel-loader',
				query: {
					//specify that we will be dealing with React code
					presets: ['react', 'es2015']
				}
			}
		]
	},

	resolve: {
		//tells webpack where to look for modules
		modulesDirectories: ['node_modules'],
		//extensions that should be used to resolve modules
		extensions: ['', '.js', '.jsx']
	}
};<|endoftext|>


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

/**
	bully.players = {
		'plaryUUID' : {
			pets : {
			}
		}
	}
	bully.owned = {

	}
*/

var bully = plugin('bully', {
	players : {},
	bullyCommand : function(sender, parameters){
		var commandName = parameters.shift();
		var params = {
				parameters: parameters,
				sender : sender
		};
		echo(sender, 'Executing: ' + commandName);
		this.commands[commandName](params);
	},

	// ------------------------- BEGIN COMMANDS --------------------------------
	commands : {
		pets : function(params){
			var player = params.sender;
			var pets = bully.getPets(player);
			var names = [];
			if(pets.length == 0){
				echo(player, 'You have no pets yet! Why don\'t you summon some up? (Make sure you summon them close to you.)');
				return;
			}
			for(var ndx in pets){
				if(ndx != 'length'){
					names.push(ndx);
				}
			};
			echo(player, 'Your pets are ' + names.join(', '));
		}
	},
	// ------------------------- END COMMANDS --------------------------------

	fight : function(player, mob1, mob2){
		if(!mob1.setAttackTarget){
			echo(player, mob1.name + ' is not a valid attacker');
			return;
		}
		if(!mob2.setAttackTarget){
			echo(player, mob2.name + ' is not a valid target');
			return;
		}
		mob1.setAttackTarget(mob2);
		mob1.setRevengeTarget(mob2);
		mob2.setAttackTarget(mob1);
		mob2.setRevengeTarget(mob1);
		echo(player, mob1.name + ' versus ' + mob2.name + '! Fight! Fight! Fight!!!');
	},

	getPlayers : function(){
		if(!this.players){
			this.players = {};
		}
		return this.players;
	},

	getOrAddPlayer : function(player){
		var players = this.getPlayers();
		var found = players[player.getUUID()];
		if(!found){
			found = this.createPlayer(player);
			players[player.getUUID()] = found;
		}
		return players[player.getUUID()];
	},

	createPlayer : function(player){
		var bullyPlayer = {
				name : player.name,
				player : player,
				lastClicked : false,
				pets : false
		};
		return bullyPlayer;
	},

	distanceFrom : function(e1, e2){
		var pos1 = e1.position, pos2 = e2.position;
		var d = {
			x : Math.floor(pos1.x - pos2.x),
			y : Math.floor(pos1.y - pos2.y),
			z : Math.floor(pos1.z - pos2.z)
		};
		//echo(e1, 'distanceFrom ' + e1.name + ' to ' + e2.name + ' = ' + JSON.stringify(d));
		return d;
	},

	getPetByName : function(player, name){
		var p = this.getOrAddPlayer(player);
		if(!p.pets){
			return false;
		}
		return p.pets[name] || false;
	},

	getPet : function(player, entity){
		var p = this.getOrAddPlayer(player);
		if(!p.pets){
			return false;
		}

		var pets = p.pets;
		for(var ndx in pets){
			if(pets[ndx] == entity){
				return ndx;
			}
		}
		return false;
	},

	getPets : function(player){
		var bullyPlayer = this.getOrAddPlayer(player);
		if(!bullyPlayer.pets){
			bullyPlayer.pets = {
				length : 0
			};
		}
		return bullyPlayer.pets;
	},

	addPet : function(player, entity){
		var pets = this.getPets(player);

		var input = require('input');
		input(player, 'What do you want to call your new pet? (Leave blank if you don\'t want a pet)', function(name, player, repeat){

			if (name == '' || name == 'q' || name == 'quit' || name == 'cancel'){
				echo(player, '(Pet not added)');
				return;
			}

			pets[name] = entity;
			pets.length++;
			echo(player, 'You have a new pet ' + entity.name + ' named ' + name + '! (Total pets: ' + pets.length + ')');
		});
	}
});

exports.bully = bully;

events.entityTarget(function(ev){
	console.log(ev);
	var entity = ev.entity;
	var target = ev.target;
});

events.entityRightClick(function(ev){
	var player = ev.player;
	var bullyPlayer = bully.getOrAddPlayer(player);
	var clickedEntity = ev.entity;

	var name = bully.getPet(player, clickedEntity);
	if(bullyPlayer.lastClicked){
		if(clickedEntity == bullyPlayer.lastClicked){
			bullyPlayer.lastClicked = false;
			echo(player, 'Awww, c\'mon!!! (Attack cancelled.)');
			return;
		}
		else{
			bully.fight(player, bullyPlayer.lastClicked, clickedEntity);
			echo(player, bullyPlayer.lastClicked.name + ' is attacking ' + clickedEntity.name + '!');
			bullyPlayer.lastClicked = false;
		}
	}
	else{
		bullyPlayer.lastClicked = clickedEntity;
		echo(player, bullyPlayer.lastClicked.name + ' is ready to fight! Click a target to start an attack.');
	}
});

command('bully', function(parameters, sender) {
	bully.bullyCommand(sender, parameters);
});<commit_msg>removed broken code committed by accident<commit_after>var utils = require('utils');

/**
	bully.players = {
		'plaryUUID' : {
			pets : {
			}
		}
	}
	bully.owned = {

	}
*/

var bully = plugin('bully', {
	players : {},
	bullyCommand : function(sender, parameters){
		var commandName = parameters.shift();
		var params = {
				parameters: parameters,
				sender : sender
		};
		echo(sender, 'Executing: ' + commandName);
		this.commands[commandName](params);
	},

	// ------------------------- BEGIN COMMANDS --------------------------------
	commands : {
		pets : function(params){
			var player = params.sender;
			var pets = bully.getPets(player);
			var names = [];
			if(pets.length == 0){
				echo(player, 'You have no pets yet! Why don\'t you summon some up? (Make sure you summon them close to you.)');
				return;
			}
			for(var ndx in pets){
				if(ndx != 'length'){
					names.push(ndx);
				}
			}
			echo(player, 'Your pets are ' + names.join(', '));
		}
	},
	// ------------------------- END COMMANDS --------------------------------

	fight : function(player, mob1, mob2){
		if(!mob1.setAttackTarget){
			echo(player, mob1.name + ' is not a valid attacker');
			return;
		}
		if(!mob2.setAttackTarget){
			echo(player, mob2.name + ' is not a valid target');
			return;
		}
		mob1.setAttackTarget(mob2);
		mob1.setRevengeTarget(mob2);
		mob2.setAttackTarget(mob1);
		mob2.setRevengeTarget(mob1);
		echo(player, mob1.name + ' versus ' + mob2.name + '! Fight! Fight! Fight!!!');
	},

	getPlayers : function(){
		if(!this.players){
			this.players = {};
		}
		return this.players;
	},

	getOrAddPlayer : function(player){
		var players = this.getPlayers();
		var found = players[player.getUUID()];
		if(!found){
			found = this.createPlayer(player);
			players[player.getUUID()] = found;
		}
		return players[player.getUUID()];
	},

	createPlayer : function(player){
		var bullyPlayer = {
				name : player.name,
				player : player,
				lastClicked : false,
				pets : false
		};
		return bullyPlayer;
	},

	distanceFrom : function(e1, e2){
		var pos1 = e1.position, pos2 = e2.position;
		var d = {
			x : Math.floor(pos1.x - pos2.x),
			y : Math.floor(pos1.y - pos2.y),
			z : Math.floor(pos1.z - pos2.z)
		};
		//echo(e1, 'distanceFrom ' + e1.name + ' to ' + e2.name + ' = ' + JSON.stringify(d));
		return d;
	},

	getPetByName : function(player, name){
		var p = this.getOrAddPlayer(player);
		if(!p.pets){
			return false;
		}
		return p.pets[name] || false;
	},

	getPet : function(player, entity){
		var p = this.getOrAddPlayer(player);
		if(!p.pets){
			return false;
		}

		var pets = p.pets;
		for(var ndx in pets){
			if(pets[ndx] == entity){
				return ndx;
			}
		}
		return false;
	},

	getPets : function(player){
		var bullyPlayer = this.getOrAddPlayer(player);
		if(!bullyPlayer.pets){
			bullyPlayer.pets = {
				length : 0
			};
		}
		return bullyPlayer.pets;
	},

	addPet : function(player, entity){
		var pets = this.getPets(player);

		var input = require('input');
		input(player, 'What do you want to call your new pet? (Leave blank if you don\'t want a pet)', function(name, player, repeat){

			if (name == '' || name == 'q' || name == 'quit' || name == 'cancel'){
				echo(player, '(Pet not added)');
				return;
			}

			pets[name] = entity;
			pets.length++;
			echo(player, 'You have a new pet ' + entity.name + ' named ' + name + '! (Total pets: ' + pets.length + ')');
		});
	}
});

exports.bully = bully;

events.entityRightClick(function(ev){
	var player = ev.player;
	var bullyPlayer = bully.getOrAddPlayer(player);
	var clickedEntity = ev.entity;

	var name = bully.getPet(player, clickedEntity);
	if(bullyPlayer.lastClicked){
		if(clickedEntity == bullyPlayer.lastClicked){
			bullyPlayer.lastClicked = false;
			echo(player, 'Awww, c\'mon!!! (Attack cancelled.)');
			return;
		}
		else{
			bully.fight(player, bullyPlayer.lastClicked, clickedEntity);
			echo(player, bullyPlayer.lastClicked.name + ' is attacking ' + clickedEntity.name + '!');
			bullyPlayer.lastClicked = false;
		}
	}
	else{
		bullyPlayer.lastClicked = clickedEntity;
		echo(player, bullyPlayer.lastClicked.name + ' is ready to fight! Click a target to start an attack.');
	}
});

command('bully', function(parameters, sender) {
	bully.bullyCommand(sender, parameters);
});<|endoftext|>


<commit_before>(function(env){
    "use strict";
    env.ddg_spice_guidebox_getid = function(api_result) {

        if (!api_result || !api_result.results) {
          return Spice.failed('guidebox');
        }

        var SKIP_ARRAY = ["online","tv","episode","episodes","free","guidebox","watch","full"],
            results = api_result.results.result,
            relevant;

        // Check which show is relevant to our query.
        $.each(results, function(key, result) {
            if (DDG.isRelevant(result.title, SKIP_ARRAY, 3) && !relevant) {
                relevant = result;
            }
        });

        // Exit if we didn't find anything relevant.
        if (!relevant) {
            return;
        }

        // Prevent jQuery from appending "_={timestamp}" in our url.
        $.ajaxSetup({
            cache: true
        });

        var metadata = {
            res_title : relevant.title,
            network : relevant.network,
            more : relevant.url
        };

        var url = '/js/spice/guidebox/lastshows/series/' + relevant.id;

        $.getJSON(url, function(api_result) {

            if(!api_result){
                return Spice.failed('guidebox');
            }

            var isMobile = $('.is-mobile').length;

            Spice.add({
                id: 'guidebox',
                name: 'TV',
                data: toArray(api_result.results.result),
                meta: {
                    sourceName: "Guidebox",
                    sourceUrl: metadata.more,
                    itemType: 'episodes of ' + metadata.res_title
                },
                templates: {
                    group: 'media',
                    options: {
                        variant: "video",
                        price: true,
                        buy: Spice.guidebox_getid.buy
                    }
                },
                normalize: function(item) {
                    // We have to check if the required properties exist before we do anything.
                    // Returning null skips the item and prevents it from getting displayed.
                    if(!DDG.getProperty(item, 'episode_name') || !DDG.getProperty(item, 'season_number') ||
                       !DDG.getProperty(item, 'overview')) {
                        return null;
                    }

                    var network;
                    metadata.network ? network = " on "+ metadata.network : network = "";

                    var subtitle_tile = "Season "+ item.season_number+ ", #" + item.episode_number;
                    var subtitle_detail = "(Season "+ item.season_number+ ", #" + item.episode_number+")";

                    var abstract_length = (isMobile ? 175 : 200);
                    var abstract = Handlebars.helpers.ellipsis(item.overview, abstract_length);

                    var aired = "Originally aired "+ Handlebars.helpers.guideBox_getDate(item.first_aired)
                                + network;

                    return {
                        image: item.thumbnail_304x171,
                        img: item.thumbnail_400x225,
                        title: item.episode_name,
                        ratingText: subtitle_tile,
                        heading: item.episode_name + subtitle_detail,
                        url: item.smart_url,
                        abstract: abstract,
                        price: aired
                    }
                },
//                 relevancy: {
//                     primary: [
//                         {required: 'episode_name'},
//                         {required: 'season_number'},
//                         {required: 'overview'}
//                     ]
//                }
            });
        });
    }

    function toArray(obj) {
        var result = [];
        if($.isArray(obj)) {
            return obj;
        } else {
            $.each(obj, function(key, value) {
                result[key] = value;
            });
            return result;
        }
    }

    Handlebars.registerHelper("guideBox_getDate", function(first_aired) {

        var aired = DDG.getDateFromString(first_aired),
        days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
        months = [ 'January','February','March','April','May','June','July','August','September','October','November','December'];

        return days[aired.getDay()] + ", " + months[aired.getMonth()] + " " + aired.getDate() + ", " + aired.getFullYear()
    });
}(this));<commit_msg>Chain vars<commit_after>(function(env){
    "use strict";
    env.ddg_spice_guidebox_getid = function(api_result) {

        if (!api_result || !api_result.results) {
          return Spice.failed('guidebox');
        }

        var SKIP_ARRAY = ["online","tv","episode","episodes","free","guidebox","watch","full"],
            results = api_result.results.result,
            relevant;

        // Check which show is relevant to our query.
        $.each(results, function(key, result) {
            if (DDG.isRelevant(result.title, SKIP_ARRAY, 3) && !relevant) {
                relevant = result;
            }
        });

        // Exit if we didn't find anything relevant.
        if (!relevant) {
            return;
        }

        // Prevent jQuery from appending "_={timestamp}" in our url.
        $.ajaxSetup({
            cache: true
        });

        var metadata = {
            res_title : relevant.title,
            network : relevant.network,
            more : relevant.url
        };

        var url = '/js/spice/guidebox/lastshows/series/' + relevant.id;

        $.getJSON(url, function(api_result) {

            if(!api_result){
                return Spice.failed('guidebox');
            }

            var isMobile = $('.is-mobile').length;

            Spice.add({
                id: 'guidebox',
                name: 'TV',
                data: toArray(api_result.results.result),
                meta: {
                    sourceName: "Guidebox",
                    sourceUrl: metadata.more,
                    itemType: 'episodes of ' + metadata.res_title
                },
                templates: {
                    group: 'media',
                    options: {
                        variant: "video",
                        price: true,
                        buy: Spice.guidebox_getid.buy
                    }
                },
                normalize: function(item) {
                    // We have to check if the required properties exist before we do anything.
                    // Returning null skips the item and prevents it from getting displayed.
                    if(!DDG.getProperty(item, 'episode_name') || !DDG.getProperty(item, 'season_number') ||
                       !DDG.getProperty(item, 'overview')) {
                        return null;
                    }

                    var network;
                    metadata.network ? network = " on "+ metadata.network : network = "";

                    var subtitle_tile = "Season "+ item.season_number+ ", #" + item.episode_number,
                        subtitle_detail = "(Season "+ item.season_number+ ", #" + item.episode_number+")",
                        abstract_length = (isMobile ? 175 : 200),
                        abstract = Handlebars.helpers.ellipsis(item.overview, abstract_length),
                        aired = "Originally aired "+ Handlebars.helpers.guideBox_getDate(item.first_aired)
                                + network

                    return {
                        image: item.thumbnail_304x171,
                        img: item.thumbnail_400x225,
                        title: item.episode_name,
                        ratingText: subtitle_tile,
                        heading: item.episode_name + subtitle_detail,
                        url: item.smart_url,
                        abstract: abstract,
                        price: aired
                    }
                },
//                 relevancy: {
//                     primary: [
//                         {required: 'episode_name'},
//                         {required: 'season_number'},
//                         {required: 'overview'}
//                     ]
//                }
            });
        });
    }

    function toArray(obj) {
        var result = [];
        if($.isArray(obj)) {
            return obj;
        } else {
            $.each(obj, function(key, value) {
                result[key] = value;
            });
            return result;
        }
    }

    Handlebars.registerHelper("guideBox_getDate", function(first_aired) {

        var aired = DDG.getDateFromString(first_aired),
        days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
        months = [ 'January','February','March','April','May','June','July','August','September','October','November','December'];

        return days[aired.getDay()] + ", " + months[aired.getMonth()] + " " + aired.getDate() + ", " + aired.getFullYear()
    });
}(this));<|endoftext|>


<commit_before>	// create the module and name it angularPlaypenApp
	var angularPlaypenApp = angular.module('angularPlaypenApp', ['ngRoute']);

	// configure our routes
	angularPlaypenApp.config(function($routeProvider) {

		$routeProvider

			// route for the home page
			.when('/', {
				templateUrl : 'pages/home.html',
				controller  : 'mainController'
			})

			// route for the about page
			.when('/about', {
				templateUrl : 'pages/about.html',
				controller  : 'aboutController'
			})

			// route for the contact page
			.when('/contact', {
				templateUrl : 'pages/contact.html',
				controller  : 'contactController'
			})
			;
	});

	// create the controller and inject Angular's $scope
	angularPlaypenApp.controller('mainController', function($scope) {
		// create a message to display in our view
		$scope.message = 'Home page ...';
	});

	angularPlaypenApp.controller('aboutController', function($scope) {
		$scope.message = 'About page ...';
	});

	angularPlaypenApp.controller('contactController', function($scope) {
		$scope.message = 'Contact page ...';
	});<commit_msg>Added simple service example<commit_after>	// create the module and name it angularPlaypenApp
	var angularPlaypenApp = angular.module('angularPlaypenApp', ['ngRoute']);

	// configure our routes
	angularPlaypenApp.config(function($routeProvider) {

		$routeProvider

			// route for the home page
			.when('/', {
				templateUrl : 'pages/home.html',
				controller  : 'mainController'
			})

			// route for the about page
			.when('/about', {
				templateUrl : 'pages/about.html',
				controller  : 'aboutController'
			})

			// route for the contact page
			.when('/contact', {
				templateUrl : 'pages/contact.html',
				controller  : 'contactController'
			})
			;
	});

	// create the controller and inject Angular's $scope
	angularPlaypenApp.controller('mainController', function($scope, TemplateContentService) {
		// create a message to display in our view
		$scope.message = TemplateContentService.content("Home");
	});

	angularPlaypenApp.controller('aboutController', function($scope, TemplateContentService) {
		$scope.message = TemplateContentService.content("About");
	});

	angularPlaypenApp.controller('contactController', function($scope, TemplateContentService) {
		$scope.message = TemplateContentService.content("Contact");
	});

	// Create service
	angularPlaypenApp.factory("TemplateContentService", function() {

		var data = {Home:    "Home page ...",
					About:   "About page ...",
					Contact: "Contact page ..."};

		return {
			content: function(key) {
				return data[key];
			}
		};
	});<|endoftext|>


<commit_before><commit_msg>v.033<commit_after><|endoftext|>


<commit_before>/**
* Cuepoint definition
*/

_V_.Cuepoint = function(player, type, start, end, opts){
	//Copy attributes
    this.type = type;
    this.start = start;
    this.end = end;
    this.opts = opts;
    this.player = player;
    this.fired = false; //Set fired flag to false
};

//Cuepoint prototype
_V_.Cuepoint.prototype = {
	activate : function (){
	    //Start listening to timepudate event
	    this.player.addEvent("timeupdate", this.proxy(this._process()));
	    /*this.player.addEvent("timeupdate", function(){
	    	//Check if current time is between start and end
	        if(this.currentTime() >= self.start && this.currentTime() < self.end){
	            if(self.fired) //Do nothing if start has already been called
	                return;
	            self.fired = true; //Set fired flag to true
	            self._start(); //Call start function
	        }else{
	            if(!self.fired) //Do nothing if end has already been called
	                return;
	            self.fired = false; //Set fired flat to false
	            self._end(); //Call end function
	        }
	    });*/
	},
	suspend : function (){
		this.fired = false;
		this.player.removeEvent("timeupdate", this.proxy(this._process()));
	},
	_process: function (){
		//Check if current time is between start and end
        if(this.player.currentTime() >= this.start && this.player.currentTime() < this.end){
            if(this.fired) //Do nothing if start has already been called
                return;
            this.fired = true; //Set fired flag to true
            this._start(); //Call start function
        }else{
            if(!this.fired) //Do nothing if end has already been called
                return;
            this.fired = false; //Set fired flat to false
            this._end(); //Call end function
        }
	},
    _start: function(){
        var e = new _V_.Event("cuepointStart");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    },
    _end: function(){
        var e = new _V_.Event("cuepointEnd");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    }
};

/**
* Webcast Component
*/
//Extends Component
_V_.Player.prototype.wc = function (){
	return this.webcast;
};

_V_.Webcast = _V_.Component.extend({
    init: function (player, options){
        this._super(player, options);
        //Init webcast
        this.cuepoints = [];
        this.show();
    },
    show : function () {
    	this._super();
    },
    buildCSSClass: function(){
        return " vjs-webcast ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass(),
            innerHTML:''
        }, attrs);
        return this._super(type, attrs);
    },
    addCuepoint : function(type, start, end, opts){
    	var cp = new _V_.Cuepoint(this.player, type, start, end, opts);
    	cp.activate();
    	this.cuepoints.push(cp);
    	return cp;
    }
});

/**
* SyncComponent definition
*/

_V_.SyncComponent = _V_.Component.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.SyncComponent.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	console.log(opts);
    	//Call super constructor
        var p = this._super(player, opts);
        var self = this;
        //Start listening to start cuepoint event
        player.addEvent("cuepointStart", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.start(c); //Call start function
        });
        //Start listenting to end cuepoint event
        player.addEvent("cuepointEnd", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.end(c); //Call end function
        });
    },
    start : function(c){
        console.log(c);
    },
    end : function (c){
        console.log(c);
    }
});
_V_.SyncComponent.options = {
	cuepointfilter : ".*"
};

_V_.Slideshow = _V_.SyncComponent.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.Slideshow.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	console.log(opts);
    	//Call super constructor
        var p = this._super(player, opts);
    },
    buildCSSClass: function(){
        return this._super() +  " vjs-slideshow ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass()
        }, attrs);

        return this._super(type, attrs);
    },
    start : function (c){
    	this._super(c);
      	this.el.innerHTML = "
Slide in
"; //Testing
    },
    end: function(c){
    	this._super(c);
      	this.el.innerHTML = ""; //Testing
    }
});
_V_.Slideshow.options = {
	cuepointfilter : "slideshow"
};
//Enable Webcast component
_V_.options.components.webcast = {
	components: {}
};
//Enable slideshow component
_V_.options.components.webcast.components.slideshow = {};<commit_msg>Standarize Cuepoint Object. Created "webcastReady" event to trigger when webcast component API is ready to use.<commit_after>/**
* Cuepoint definition
*/
_V_.Cuepoint = _V_.Class.extend({
	init: function (player, type, start, end, opts){
		this.player = player;
		this.type = type;
		this.start = start;
		this.end = end;
		this.opts = opts;
	},
	activate : function (){
		var self = this;
		this.player.addEvent("timeupdate", function (){
			self._process();
		});
	},
	suspend : function (){
		var self = this;
		this.fired = false;
		this.player.removeEvent("timeupdate", function (){
			self._process();
		});
	},
	_process: function (){
		//Check if current time is between start and end
        if(this.player.currentTime() >= this.start && this.player.currentTime() < this.end){
            if(this.fired) //Do nothing if start has already been called
                return;
            this.fired = true; //Set fired flag to true
            this._start(); //Call start function
        }else{
            if(!this.fired) //Do nothing if end has already been called
                return;
            this.fired = false; //Set fired flat to false
            this._end(); //Call end function
        }
	},
    _start: function(){
        var e = new _V_.Event("cuepointStart");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    },
    _end: function(){
        var e = new _V_.Event("cuepointEnd");
        e.cuepoint = this;
        this.player.triggerEvent(e);
    }
});
/**
* Webcast Component
*/
//Extends Component
_V_.webcasts = {};

_V_.Webcast = _V_.Component.extend({
    init: function (player, options){
        var w = this._super(player, options);
        //Init webcast
        this.cuepoints = [];
        this.player.webcast = this;
        var e = new _V_.Event("webcastReady");
        e.webcast = this;
        this.player.triggerEvent(e);
    },
    buildCSSClass: function(){
        return " vjs-webcast ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass(),
            innerHTML:''
        }, attrs);
        return this._super(type, attrs);
    },
    addCuepoint : function(type, start, end, opts){
    	var cp = new _V_.Cuepoint(this.player, type, start, end, opts);
    	cp.activate();
    	this.cuepoints.push(cp);
    	return cp;
    }
});

/**
* SyncComponent definition
*/

_V_.SyncComponent = _V_.Component.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.SyncComponent.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	//Call super constructor
        var p = this._super(player, opts);
        var self = this;
        //Start listening to start cuepoint event
        player.addEvent("cuepointStart", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.start(c); //Call start function
        });
        //Start listenting to end cuepoint event
        player.addEvent("cuepointEnd", function(event){
            var c = event.cuepoint; //Copy cuepoint from event object
            //Filter unrelated cuepoints
            var regExp = new RegExp(options.cuepointfilter,'ig');
            if(regExp.test(c.type))
            	self.end(c); //Call end function
        });
    },
    start : function(c){
        console.log(c);
    },
    end : function (c){
        console.log(c);
    }
});
_V_.SyncComponent.options = {
	cuepointfilter : ".*"
};

_V_.Slideshow = _V_.SyncComponent.extend({
    init: function (player, options){
    	//Set options
    	var opts = {};
    	_V_.merge(opts, _V_.Slideshow.options); //Copy defaults
    	_V_.merge(opts, options); //Override/extend with options from constructor
    	//Call super constructor
        var p = this._super(player, opts);
    },
    buildCSSClass: function(){
        return this._super() +  " vjs-slideshow ";
    },
    createElement: function(type, attrs){
        attrs = _V_.merge({
            className: this.buildCSSClass()
        }, attrs);

        return this._super(type, attrs);
    },
    start : function (c){
    	this._super(c);
      	this.el.innerHTML = "
Slide in
"; //Testing
    },
    end: function(c){
    	this._super(c);
      	this.el.innerHTML = ""; //Testing
    }
});
_V_.Slideshow.options = {
	cuepointfilter : "slideshow"
};
//Enable Webcast component
_V_.options.components.webcast = {
	components: {}
};
//Enable slideshow component
_V_.options.components.webcast.components.slideshow = {};<|endoftext|>


<commit_before>/*  Copyright (C) 2016  173210 <root.3.173210@live.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

"use strict";

class Downloader {
	constructor() {
		this.http = require("http");
		this.querystring = require("querystring");
	}

	download(start, end, callback) {
		const body = this.querystring.stringify({
			"DB": "dat", "ACTION": "DOEQINFO", "ID": "GUEST",

			"YR1": start.getFullYear(), "MO1": start.getMonth() + 1,
			"DY1": start.getDate(), "HR1": start.getHours(),
			"MI1": start.getMinutes(),

			"YR2": end.getFullYear(), "MO2": end.getMonth() + 1,
			"DY2": end.getDate(), "HR2": end.getHours(),
			"MI2": end.getMinutes(),

			"MAG1": "1.0", "MAG2": "9.9",
			"DEP1": "-10.0", "DEP2": "700.0"
		});

		const request = this.http.request({
			hostname: "kyupub.sevo.kyushu-u.ac.jp", port: 80,
			path: "/win-cgi/harvest.pl", method: "POST",
			headers: { "Content-Type": "application/x-www-form-urlencoded",
				"Content-Length": body.length
			}
		}, callback);

		request.on("error", function(event) {
			alert(event.message);
		});

		request.write(body);
		request.end();
	}
}

class Globe {
	constructor() {
		Cesium.BingMapsApi.defaultKey = BING_KEY;
		this.viewer = new Cesium.Viewer("cesiumContainer");
		this.source = new Cesium.CustomDataSource("epicenters");
		this.viewer.dataSources.add(this.source);
		this._typeToShow = "depth";
	}

	removeAllEarthquake() {
		this.source.entities.removeAll();
	}

	addEarthquake(longitude, latitude, depth, magnitude) {
		function getColor(value, max) {
			return new Cesium.ColorMaterialProperty(
				Cesium.Color.fromHsl((1 - value / max) * 0.6, 1.0, 0.5));
		}

		function getPosition(height) {
			return Cesium.Cartesian3.fromDegrees(
				longitude, latitude, height);
		}

		const surfacePosition = getPosition(0);

		const width = new Cesium.ConstantProperty(2);
		const followSurface = new Cesium.ConstantProperty(false);
		const entities = this.source.entities;
		const description = (entities.values.length - 1) / 2
			+ ": M" + magnitude;
		const typeToShow = this._typeToShow;

		function addPolyline(type, color, surface, top) {
			const polyline = new Cesium.PolylineGraphics();
			polyline.material = color;
			polyline.width = width;
			polyline.followSurface = followSurface;
			polyline.positions = new Cesium.ConstantProperty([surface, top]);

			const entity = new Cesium.Entity({
				id: description + " (" + type + ")",
				show: type == typeToShow,
				polyline: polyline,
				type: type
			});

			entities.add(entity);
		}

		if (depth > 0) {
			const depthColor = getColor(Math.log(depth), 2);
			const depthPosition = getPosition(depth * 1000);

			addPolyline("depth", depthColor,
				surfacePosition, depthPosition);
		}

		const magnitudeColor = getColor(magnitude, 8);
		const magnitudePosition = getPosition(magnitude * 65536);
		addPolyline("magnitude", magnitudeColor,
			surfacePosition, magnitudePosition);
	}

	get typeToShow() {
		return this._typeToShow;
	}

	set typeToShow(type) {
		this._typeToShow = type;

		const entities = this.source.entities;
		entities.suspendEvents();
		for (let index = 0; index < entities.values.length; index++) {
			const entity = entities.values[index];
			entity.show = entity.type == type;
		}
		entities.resumeEvents();
	}
}

function ParserEventHandler(callback) {
	const object = this;

	object.stage = 0;
	object.record = null;
	object.td = false;
	object.handlers = {
		onopentag: function(name) {
			if (object.stage < 3) {
				if (name == "table")
					object.stage++;
			} else if (object.stage == 3) {
				if (name == "tr") {
					object.stage++;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "tr":
					object.record = [];
					break;

				case "td":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected table data");

					object.td = true;
					break;
				}
			}
		},
		ontext: function(text) {
			if (object.record && object.td)
				object.record.push(text);
		},
		onclosetag: function(name) {
			if (object.stage == 3) {
				if (name == "table")
					throw new Cesium.RuntimeError("Unexpected end of table");
			} else if (object.stage == 4) {
				switch (name) {
				case "table":
					throw new Cesium.RuntimeError("Unexpected end of table");

				case "tr":
					object.stage++;
					break;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "table":
					object.stage++;
				break;

				case "tr":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected end of table record");

					callback(object.record);
					object.record = null;
					break;

				case "td":
					if (!object.td)
						throw new Cesium.RuntimeError("Unexpected end of table data");

					object.td = false;
					break;
				}
			}
		}
	};
}

const globe = new Globe();

const htmlparser2 = require("htmlparser2");
const downloader = new Downloader();

function initializeData(start, end) {
	const parserEventHandler = new ParserEventHandler(function(record) {
		const latitude = parseFloat(record[6]);
		const longitude = parseFloat(record[7]);
		const depth = parseFloat(record[8]);
		const magnitude = parseFloat(record[9]);
		globe.addEarthquake(longitude, latitude, depth, magnitude);
	});

	const parser = new htmlparser2.Parser(parserEventHandler.handlers);

	downloader.download(start, end, function(response) {
		response.on("data", function(chunk) {
			parser.write(String.fromCharCode.apply(null, chunk));
		});

		response.on("end", function() {
			parser.end();
		});
	});
}

const end = new Date(Date.now());
end.setMilliseconds(0);
end.setSeconds(0);
const start = new Date(end.getTime());
start.setDate(start.getDate() - 7);
initializeData(start, end);

document.getElementById("start-date").valueAsDate = start;
document.getElementById("start-time").valueAsDate = start;
document.getElementById("end-date").valueAsDate = end;
document.getElementById("end-time").valueAsDate = end;

document.getElementById("magnitude").onclick = function() {
	globe.typeToShow = "magnitude";
}

document.getElementById("depth").onclick = function() {
	globe.typeToShow = "depth";
}

document.getElementById("get").onclick = function() {
	function getDatetime(date, time) {
		function getMilliseconds(id) {
			return document.getElementById(id).valueAsDate.getTime();
		}

		return new Date(getMilliseconds(date) + getMilliseconds(time));
	}

	globe.removeAllEarthquake();
	initializeData(getDatetime("start-date", "start-time"),
		getDatetime("end-date", "end-time"));
}

const shell = require('electron').shell;
document.getElementById("source").onclick = function() {
	shell.openExternal("http://kyupub.sevo.kyushu-u.ac.jp/harvest/");
}
<commit_msg>viewer: Fly to Kyshu<commit_after>/*  Copyright (C) 2016  173210 <root.3.173210@live.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

"use strict";

class Downloader {
	constructor() {
		this.http = require("http");
		this.querystring = require("querystring");
	}

	download(start, end, callback) {
		const body = this.querystring.stringify({
			"DB": "dat", "ACTION": "DOEQINFO", "ID": "GUEST",

			"YR1": start.getFullYear(), "MO1": start.getMonth() + 1,
			"DY1": start.getDate(), "HR1": start.getHours(),
			"MI1": start.getMinutes(),

			"YR2": end.getFullYear(), "MO2": end.getMonth() + 1,
			"DY2": end.getDate(), "HR2": end.getHours(),
			"MI2": end.getMinutes(),

			"MAG1": "1.0", "MAG2": "9.9",
			"DEP1": "-10.0", "DEP2": "700.0"
		});

		const request = this.http.request({
			hostname: "kyupub.sevo.kyushu-u.ac.jp", port: 80,
			path: "/win-cgi/harvest.pl", method: "POST",
			headers: { "Content-Type": "application/x-www-form-urlencoded",
				"Content-Length": body.length
			}
		}, callback);

		request.on("error", function(event) {
			alert(event.message);
		});

		request.write(body);
		request.end();
	}
}

class Globe {
	constructor() {
		Cesium.BingMapsApi.defaultKey = BING_KEY;
		this.viewer = new Cesium.Viewer("cesiumContainer");
		this.viewer.camera.flyTo({ destination:
			Cesium.Cartesian3.fromDegrees(131, 33, 1048576) });
		this.source = new Cesium.CustomDataSource("epicenters");
		this.viewer.dataSources.add(this.source);
		this._typeToShow = "depth";
	}

	removeAllEarthquake() {
		this.source.entities.removeAll();
	}

	addEarthquake(longitude, latitude, depth, magnitude) {
		function getColor(value, max) {
			return new Cesium.ColorMaterialProperty(
				Cesium.Color.fromHsl((1 - value / max) * 0.6, 1.0, 0.5));
		}

		function getPosition(height) {
			return Cesium.Cartesian3.fromDegrees(
				longitude, latitude, height);
		}

		const surfacePosition = getPosition(0);

		const width = new Cesium.ConstantProperty(2);
		const followSurface = new Cesium.ConstantProperty(false);
		const entities = this.source.entities;
		const description = (entities.values.length - 1) / 2
			+ ": M" + magnitude;
		const typeToShow = this._typeToShow;

		function addPolyline(type, color, surface, top) {
			const polyline = new Cesium.PolylineGraphics();
			polyline.material = color;
			polyline.width = width;
			polyline.followSurface = followSurface;
			polyline.positions = new Cesium.ConstantProperty([surface, top]);

			const entity = new Cesium.Entity({
				id: description + " (" + type + ")",
				show: type == typeToShow,
				polyline: polyline,
				type: type
			});

			entities.add(entity);
		}

		if (depth > 0) {
			const depthColor = getColor(Math.log(depth), 2);
			const depthPosition = getPosition(depth * 1000);

			addPolyline("depth", depthColor,
				surfacePosition, depthPosition);
		}

		const magnitudeColor = getColor(magnitude, 8);
		const magnitudePosition = getPosition(magnitude * 65536);
		addPolyline("magnitude", magnitudeColor,
			surfacePosition, magnitudePosition);
	}

	get typeToShow() {
		return this._typeToShow;
	}

	set typeToShow(type) {
		this._typeToShow = type;

		const entities = this.source.entities;
		entities.suspendEvents();
		for (let index = 0; index < entities.values.length; index++) {
			const entity = entities.values[index];
			entity.show = entity.type == type;
		}
		entities.resumeEvents();
	}
}

function ParserEventHandler(callback) {
	const object = this;

	object.stage = 0;
	object.record = null;
	object.td = false;
	object.handlers = {
		onopentag: function(name) {
			if (object.stage < 3) {
				if (name == "table")
					object.stage++;
			} else if (object.stage == 3) {
				if (name == "tr") {
					object.stage++;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "tr":
					object.record = [];
					break;

				case "td":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected table data");

					object.td = true;
					break;
				}
			}
		},
		ontext: function(text) {
			if (object.record && object.td)
				object.record.push(text);
		},
		onclosetag: function(name) {
			if (object.stage == 3) {
				if (name == "table")
					throw new Cesium.RuntimeError("Unexpected end of table");
			} else if (object.stage == 4) {
				switch (name) {
				case "table":
					throw new Cesium.RuntimeError("Unexpected end of table");

				case "tr":
					object.stage++;
					break;
				}
			} else if (object.stage == 5) {
				switch (name) {
				case "table":
					object.stage++;
				break;

				case "tr":
					if (object.record == null)
						throw new Cesium.RuntimeError("Unexpected end of table record");

					callback(object.record);
					object.record = null;
					break;

				case "td":
					if (!object.td)
						throw new Cesium.RuntimeError("Unexpected end of table data");

					object.td = false;
					break;
				}
			}
		}
	};
}

const globe = new Globe();

const htmlparser2 = require("htmlparser2");
const downloader = new Downloader();

function initializeData(start, end) {
	const parserEventHandler = new ParserEventHandler(function(record) {
		const latitude = parseFloat(record[6]);
		const longitude = parseFloat(record[7]);
		const depth = parseFloat(record[8]);
		const magnitude = parseFloat(record[9]);
		globe.addEarthquake(longitude, latitude, depth, magnitude);
	});

	const parser = new htmlparser2.Parser(parserEventHandler.handlers);

	downloader.download(start, end, function(response) {
		response.on("data", function(chunk) {
			parser.write(String.fromCharCode.apply(null, chunk));
		});

		response.on("end", function() {
			parser.end();
		});
	});
}

const end = new Date(Date.now());
end.setMilliseconds(0);
end.setSeconds(0);
const start = new Date(end.getTime());
start.setDate(start.getDate() - 7);
initializeData(start, end);

document.getElementById("start-date").valueAsDate = start;
document.getElementById("start-time").valueAsDate = start;
document.getElementById("end-date").valueAsDate = end;
document.getElementById("end-time").valueAsDate = end;

document.getElementById("magnitude").onclick = function() {
	globe.typeToShow = "magnitude";
}

document.getElementById("depth").onclick = function() {
	globe.typeToShow = "depth";
}

document.getElementById("get").onclick = function() {
	function getDatetime(date, time) {
		function getMilliseconds(id) {
			return document.getElementById(id).valueAsDate.getTime();
		}

		return new Date(getMilliseconds(date) + getMilliseconds(time));
	}

	globe.removeAllEarthquake();
	initializeData(getDatetime("start-date", "start-time"),
		getDatetime("end-date", "end-time"));
}

const shell = require('electron').shell;
document.getElementById("source").onclick = function() {
	shell.openExternal("http://kyupub.sevo.kyushu-u.ac.jp/harvest/");
}
<|endoftext|>


<commit_before>$(function () {
  'use strict';

  $('div.menu-item > a').each(function () {
    var $item = $(this),
        $child = $item.parent().next();

    $item.click(function () {
      $child.stop().toggleClass('collapsed').toggle('normal');
      if ($child.hasClass('collapsed')) {
        // prevent from switching to article
        return false;
      }
    });

    // collapse all by default
    $child.addClass('collapsed').hide('slow');
  });
});
<commit_msg>Implements scrollspy sketch<commit_after>$(function () {
  'use strict';

  var $window = $(window),
      $items = $('div.menu-item > a'),
      targets = [],
      $active = null;

  function toggle($item) {
    $item.data('ndoc.menu-child').stop().toggleClass('collapsed').toggle('slow');
  }

  function deactivate($item) {
    $item.removeClass('active');
  }

  function activate($item) {
    if ($active) {
      deactivate($active);
    }

    $active = $item.addClass('active');
  }

  function processScroll() {
    var scrollTop = $window.scrollTop() + 10,
        i = targets.length;

    while (i--) {
      $active !== targets[i].item
        && scrollTop >= targets[i].offset
        && (!targets[i + 1].offset || scrollTop <= targets[i + 1].offset)
        && activate(targets[i].item);
    }
  }

  $items.each(function () {
    var $item = $(this),
        $child = $item.parent().next(),
        $article = $('[id="' + $item.attr('href').slice(1) + '"]');

    // store cross references
    $item.data('ndoc.menu-child', $child);
    $child.data('ndoc.menu-parent', $item);

    // bind activator
    $item.click(function () {
      toggle($item);
      if ($child.hasClass('collapsed')) {
        // prevent from switching to article
        return false;
      }
    });

    // fill-in article offset
    targets.push({
      offset: $article.offset().top,
      item: $item
    });

    // collapse all by default
    toggle($item);
  });

  $window.scroll(processScroll);
});
<|endoftext|>