<commit_before>const nitro = require('bbcparse/nitroSdk.js');
const x2j = require('jgexml/xml2json.js');
const j2x = require('jgexml/json2xml.js');
const moment = require('moment-timezone');

function toArray(o) {
	if (!Array.isArray(o)) {
		var a = [];
		if (typeof o != 'undefined') a.push(o);
		return a;
	}
	return o;
}

function respond(category,obj,res) {
	var feed = {};
	var rss = {};
	rss['@version'] = '2.0';
	rss["@xmlns:atom"] = 'http://www.w3.org/2005/Atom';
	rss.channel = {};
	rss.channel.title = 'Films RSS programmes feed - '+category;
	rss.channel.link = 'http://bbc-rss.herokuapp.com/rss/film4/'+category+'.rss';
	rss.channel["atom:link"] = {};
	rss.channel["atom:link"]["@rel"] = 'self';
	rss.channel["atom:link"]["@href"] = rss.channel.link;
	rss.channel["atom:link"]["@type"] = 'application/rss+xml';
	rss.channel.description = 'Unofficial Films RSS feeds';
	rss.channel.webMaster = 'mike.ralphson@gmail.com (Mike Ralphson)';
	rss.channel.pubDate = new Date().toUTCString();
	rss.channel.generator = 'openSky by Mermade Software http://github.com/mermade/opensky';
	rss.channel.item = [];

    if (obj.channels) {
        let channels = toArray(obj.channels);
        for (let channel of channels) {
        for (let prog of channel.program) {
            // genre "6" is movies, subgenre "8" is scifi, subgenre "10" is horror
            if ((prog.genre === "6") && ((prog.subgenre === "8") || (prog.subgenre === "10"))) {

/*
{"eventid":"5660","channelid":"4044","date":"01\/02\/18","start":"1517496300000","dur":"6600","title":"The Day the Earth Stood Still","shortDesc":"(1951) Sci-fi classic starring Michael Rennie. An alien called Klaatu visits Earth to warn humans to stop warring or risk destroying the planet. But, inevitably, he's met with hostility.","genre":"6","subgenre":"8","edschoice":"false","parentalrating":{"k":"1","v":"U "},"widescreen":"","sound":{"k":"3","v":"Digital surround sound"},"remoteRecordable":"true","record":"1","scheduleStatus":"NOT_STARTED","blackout":"false","movielocator":"null"}
*/

                let include = true;
		        var i = {};
		        i.title = prog.title;
		        i.pubDate = new Date(new Number(prog.start)).toUTCString();
                let prefix = moment(i.pubDate).tz('Europe/London').format('ddd MMM Do HH:mm z ');
                let chan;
                if (prog.channelid === '4044') {
                    //chan = '@Film4';
                    i.link = 'http://www.channel4.com/programmes/'+encodeURIComponent(prog.title.toLowerCase().split(' ').join('-'));
                }
                else if (prog.channelid === "4075") {
                    //chan = '@channel4';
                    i.link = 'http://www.channel4.com/programmes/'+encodeURIComponent(prog.title.toLowerCase().split(' ').join('-'));
                }
                else if (prog.channelid === "4058") {
                    //chan = '@channel5_tv';
                    i.link = 'http://www.channel5.com/show/'+encodeURIComponent(prog.title.toLowerCase().split(' ').join('-'));
                }
                else if (prog.channelid === "3605") {
                    //chan = '@horror_channel';
                    i.link = 'http://www.horrorchannel.co.uk/shows.php?title='+encodeURIComponent(prog.title);
                    if (prog.subgenre === "10") { // horror
                        include = false;
                        let desc = prog.shortDesc.toLowerCase().split('-').join('');
                        if (desc.toLowerCase().indexOf('scifi')>=0) include = true;
                        if (desc.toLowerCase().indexOf('timetravel')>=0) include = true;
                        if (desc.toLowerCase().indexOf('classic')>=0) include = true;
                        if (desc.toLowerCase().indexOf('fantasy')>=0) include = true;
                    }
                }
                else if (prog.channelid === "1043") {
                    //chan = '@ITV';
                    i.link = 'http://www.itv.com/search?q='+encodeURIComponent(prog.title);
                }
                else if (prog.channelid === "6532") {
                    //chan = '@itv2';
                    i.link = 'http://www.itv.com/search?q='+encodeURIComponent(prog.title);
                }
		        i.description = prefix+' '+prog.shortDesc;
		        i.category = 'audio_video';
		        i.guid = {};
		        i.guid["@isPermaLink"] = 'false';
		        i.guid[""] = 'SKYevent:' + prog.channelid+'/'+prog.eventid;

                i.title = i.title + ' ' + i.description;
                if (i.title.length > 220) {
                    i.title = i.title.substr(0,220)+'...';
                }

		        if (include) rss.channel.item.push(i);
            }
        }
        }
    }
	feed.rss = rss;
	s = j2x.getXml(feed,'@','',2);

	res.set('Content-Type', 'text/xml');
	res.send(s);
}

module.exports = {

	getCategory : function (req,res) {
        let day = new Date();
        let dateStr = day.toISOString().slice(0, 16).split('-').join('').split(':').join('').replace('T','');

// http://epgservices.sky.com/tvlistings-proxy/TVListingsProxy/tvlistings.json?detail=2&dur=2880&time=201801311300&channels=4044
		var query = nitro.newQuery();
        query.add('detail',2);
        query.add('dur',2880);
        query.add('time',dateStr);
        query.add('channels',"4044,4058,4075,3605,1043,6532");
		var options = {};

		nitro.make_request('epgservices.sky.com','/tvlistings-proxy/TVListingsProxy/tvlistings.json','',query,options,function(obj){
            respond('scifi',obj,res);
		},function(stateCode,obj){
            respond('scifi',{},res);
		});

	}

};
<commit_msg>films; add Talking Pictures TV<commit_after>const nitro = require('bbcparse/nitroSdk.js');
const x2j = require('jgexml/xml2json.js');
const j2x = require('jgexml/json2xml.js');
const moment = require('moment-timezone');

function toArray(o) {
	if (!Array.isArray(o)) {
		var a = [];
		if (typeof o != 'undefined') a.push(o);
		return a;
	}
	return o;
}

function respond(category,obj,res) {
	var feed = {};
	var rss = {};
	rss['@version'] = '2.0';
	rss["@xmlns:atom"] = 'http://www.w3.org/2005/Atom';
	rss.channel = {};
	rss.channel.title = 'Films RSS programmes feed - '+category;
	rss.channel.link = 'http://bbc-rss.herokuapp.com/rss/film4/'+category+'.rss';
	rss.channel["atom:link"] = {};
	rss.channel["atom:link"]["@rel"] = 'self';
	rss.channel["atom:link"]["@href"] = rss.channel.link;
	rss.channel["atom:link"]["@type"] = 'application/rss+xml';
	rss.channel.description = 'Unofficial Films RSS feeds';
	rss.channel.webMaster = 'mike.ralphson@gmail.com (Mike Ralphson)';
	rss.channel.pubDate = new Date().toUTCString();
	rss.channel.generator = 'openSky by Mermade Software http://github.com/mermade/opensky';
	rss.channel.item = [];

    if (obj.channels) {
        let channels = toArray(obj.channels);
        for (let channel of channels) {
        for (let prog of channel.program) {
            // genre "6" is movies, subgenre "8" is scifi, subgenre "10" is horror
            if ((prog.genre === "6") && ((prog.subgenre === "8") || (prog.subgenre === "10"))) {

/*
{"eventid":"5660","channelid":"4044","date":"01\/02\/18","start":"1517496300000","dur":"6600","title":"The Day the Earth Stood Still","shortDesc":"(1951) Sci-fi classic starring Michael Rennie. An alien called Klaatu visits Earth to warn humans to stop warring or risk destroying the planet. But, inevitably, he's met with hostility.","genre":"6","subgenre":"8","edschoice":"false","parentalrating":{"k":"1","v":"U "},"widescreen":"","sound":{"k":"3","v":"Digital surround sound"},"remoteRecordable":"true","record":"1","scheduleStatus":"NOT_STARTED","blackout":"false","movielocator":"null"}
*/

                let include = true;
		        var i = {};
		        i.title = prog.title;
		        i.pubDate = new Date(new Number(prog.start)).toUTCString();
                let prefix = moment(i.pubDate).tz('Europe/London').format('ddd MMM Do HH:mm z ');
                let chan;
                if (prog.channelid === '4044') {
                    //chan = '@Film4';
                    i.link = 'http://www.channel4.com/programmes/'+encodeURIComponent(prog.title.toLowerCase().split(' ').join('-'));
                }
                else if (prog.channelid === "4075") {
                    //chan = '@channel4';
                    i.link = 'http://www.channel4.com/programmes/'+encodeURIComponent(prog.title.toLowerCase().split(' ').join('-'));
                }
                else if (prog.channelid === "4058") {
                    //chan = '@channel5_tv';
                    i.link = 'http://www.channel5.com/show/'+encodeURIComponent(prog.title.toLowerCase().split(' ').join('-'));
                }
                else if (prog.channelid === "3605") {
                    //chan = '@horror_channel';
                    i.link = 'http://www.horrorchannel.co.uk/shows.php?title='+encodeURIComponent(prog.title);
                    if (prog.subgenre === "10") { // horror
                        include = false;
                        let desc = prog.shortDesc.toLowerCase().split('-').join('');
                        if (desc.toLowerCase().indexOf('scifi')>=0) include = true;
                        if (desc.toLowerCase().indexOf('timetravel')>=0) include = true;
                        if (desc.toLowerCase().indexOf('classic')>=0) include = true;
                        if (desc.toLowerCase().indexOf('fantasy')>=0) include = true;
                    }
                }
                else if (prog.channelid === "1043") {
                    //chan = '@ITV';
                    i.link = 'http://www.itv.com/search?q='+encodeURIComponent(prog.title);
                }
                else if (prog.channelid === "6532") {
                    //chan = '@itv2';
                    i.link = 'http://www.itv.com/search?q='+encodeURIComponent(prog.title);
                }
                else if (prog.channelid === "5252") {
                    //chan = '@talkingpicstv';
                    i.link = 'https://talkingpicturestv.co.uk/schedule/';
                }
		        i.description = prefix+' '+prog.shortDesc;
		        i.category = 'audio_video';
		        i.guid = {};
		        i.guid["@isPermaLink"] = 'false';
		        i.guid[""] = 'SKYevent:' + prog.channelid+'/'+prog.eventid;

                i.title = i.title + ' ' + i.description;
                if (i.title.length > 220) {
                    i.title = i.title.substr(0,220)+'...';
                }

		        if (include) rss.channel.item.push(i);
            }
        }
        }
    }
	feed.rss = rss;
	s = j2x.getXml(feed,'@','',2);

	res.set('Content-Type', 'text/xml');
	res.send(s);
}

module.exports = {

	getCategory : function (req,res) {
        let day = new Date();
        let dateStr = day.toISOString().slice(0, 16).split('-').join('').split(':').join('').replace('T','');

// http://epgservices.sky.com/tvlistings-proxy/TVListingsProxy/tvlistings.json?detail=2&dur=2880&time=201801311300&channels=4044
		var query = nitro.newQuery();
        query.add('detail',2);
        query.add('dur',2880);
        query.add('time',dateStr);
        query.add('channels',"4044,4058,4075,3605,1043,6532,5252");
		var options = {};

		nitro.make_request('epgservices.sky.com','/tvlistings-proxy/TVListingsProxy/tvlistings.json','',query,options,function(obj){
            respond('scifi',obj,res);
		},function(stateCode,obj){
            respond('scifi',{},res);
		});

	}

};
<|endoftext|>


<commit_before>describe("SpecIt", function() {
  it("should match on inclusion", function() {
    [1, 2].should(include, 1);
    [1, 2].should(include, 1, 2);
    ({one: 1, two: 2}).should(include, "one");

    [1, 2].shouldNot(include, [1, 2]);
    [1, 2].shouldNot(include, [1, 2], 1, 2);
    [1, 2].shouldNot(include, 3);
    [1, 2].shouldNot(include, 3, 4);
    ({one: 1}).shouldNot(include, "two");

    "string".should(include, "string");
    "string".should(include, "ring");
    "string".should(include, "tr");

    "string".shouldNot(include, "  string");
    "string".shouldNot(include, "string ");
    "string".shouldNot(include, "cat");
  });

  it("should match on equality", function() {
    "string".should(eql, "string");
    (1).should(eql, 1);
    true.should(eql, true);

    "string".shouldNot(eql, "junk");
    [].shouldNot(eql, []);
    ["tree"].shouldNot(eql, ["tree"]);
    ({}).shouldNot(eql, {});
    true.shouldNot(eql, false);
  });

  it("should match on similarity", function() {
    "string".should(beSimilarTo, "string");
    (1).should(beSimilarTo, 1);
    true.should(beSimilarTo, true);
    [].should(beSimilarTo, []);
    ["tree"].should(beSimilarTo, ["tree"]);
    ({}).should(beSimilarTo, {});
    ({a: 1}).should(beSimilarTo, {"a": 1});

    "string".shouldNot(beSimilarTo, "junk");
    true.shouldNot(beSimilarTo, false);
    ({a: 1}).shouldNot(beSimilarTo, {b: 1});
  });

  it("should match on truthiness", function() {
    "string".should(be);
    true.should(be);
    (1).should(be);

    "".shouldNot(be);
    false.shouldNot(be);
    (0).shouldNot(be);
  });

  it("should match by type comparison", function() {
    "string".should(beA, String);
    (function() {}).should(beA, Function);
    true.should(beA, Boolean);
    ({}).should(beAn, Object);
    [].should(beAn, Array);
    (1).should(beA, Number);
    /regular-expression/.should(beA, RegExp);

    "string".shouldNot(beAn, Object);
    "string".shouldNot(beA, Number);
    [].shouldNot(beAn, Object);
  });

  it("should match against regular expressions", function() {
    "string".should(match, /string/);
    "202-555-1212".should(match, /\d{3}.\d{3}.\d{4}/);
    "string".shouldNot(match, /\w{10}/);
  });

  it("should match on method presence", function() {
    var myObject = {
      attribute1: 1,
      booleanAttr: true,
      methodAttr: function() {}
    };

    myObject.should(respondTo, "methodAttr");
    myObject.shouldNot(respondTo, "attribute1");
    myObject.shouldNot(respondTo, "booleanAttr");
    myObject.shouldNot(respondTo, "junkMethod");

    var Person = function(options) {
      this.name = options.name || "";
      this.age = options.age || 13;
      this.sayHi = function() {
        return "Hello; my name is " + this.name;
      };
      return this;
    };

    var john = new Person({name: "John Doe", age: 35});
    john.should(respondTo, "sayHi");
    john.shouldNot(respondTo, "name");
    john.shouldNot(respondTo, "age");
    john.shouldNot(respondTo, "sayGoodbye");
  });

  it("should match on less than", function() {
    (  2).should(beLessThan, 5);
    ( -5).should(beLessThan, 0);
    (  0).should(beLessThan, 0.1);
    "awesome".should(beLessThan, "great");
    (  5).shouldNot(beLessThan, 3);
    (0.1).shouldNot(beLessThan, 0);
    (0.1).shouldNot(beLessThan, 0.05);
    (  5).shouldNot(beLessThan, 5);
  });

  it("should match on less than or equal to", function() {
    (  2).should(beLessThanOrEqualTo, 5);
    ( -5).should(beLessThanOrEqualTo, 0);
    (  0).should(beLessThanOrEqualTo, 0.1);
    (  5).should(beLessThanOrEqualTo, 5);
    "awesome".should(beLessThanOrEqualTo, "great");
    "great".should(beLessThanOrEqualTo, "great");
    (0.1).should(beLessThanOrEqualTo, 0.1);

    (  5).shouldNot(beLessThanOrEqualTo, 3);
    (0.1).shouldNot(beLessThanOrEqualTo, 0);
    (0.1).shouldNot(beLessThanOrEqualTo, 0.05);
  });

  it("should match on greater than", function() {
    (  2).should(beGreaterThan, 1);
    ( -5).should(beGreaterThan, -10);
    (  0).should(beGreaterThan, -0.1);
    "awesome".should(beGreaterThan, "absolute");
    (  5).shouldNot(beGreaterThan, 30);
    (0.1).shouldNot(beGreaterThan, 0.2);
    (0.01).shouldNot(beGreaterThan, 0.05);
    (  5).shouldNot(beGreaterThan, 5);
  });

  it("should match on greater than or equal to", function() {
    (  2).should(beGreaterThanOrEqualTo, 1);
    ( -5).should(beGreaterThanOrEqualTo, -10);
    (  0).should(beGreaterThanOrEqualTo, -0.1);
    (  5).should(beGreaterThanOrEqualTo, 5);
    "awesome".should(beGreaterThanOrEqualTo, "awesome");
    (  5).shouldNot(beGreaterThanOrEqualTo, 30);
    (0.1).shouldNot(beGreaterThanOrEqualTo, 0.2);
    (0.01).shouldNot(beGreaterThanOrEqualTo, 0.05);
  });

  it("should match on elements on a page", function() {
   $(".workspace").append("
");

   $(".workspace .great").should(beOnThePage);
   $(".workspace .non-existant").shouldNot(beOnThePage);
   $(".workspace").empty();
  });
});

var john, beforeCallbackTest;

describe("SpecIt with a before callback", function() {
  var jane = {name: "Jane"};

  before(function() {
    beforeCallbackTest = true;
    john = {name: "John Doe"};
  });

  it("should support before", function() {
    ok(beforeCallbackTest);
    equal(afterCallbackTest, undefined);
  });

  it("should run before every test", function() {
    john.name = "Wrong name";
    jane.age = 26;
  });

  it("should run before every test", function() {
    equals(john.name, "John Doe");
  });

  it("should not know attributes from another before callback", function() {
    equals(john.age, undefined);
  });

  it("should not modify attributes on a local object if untouched in before", function() {
    equals(jane.age, 26);
  });
});

// the john object will carry over, but the jane object will not
describe("SpecIt with a different before callback", function() {
  before(function() { john.age = 35; });

  it("should not run other describes' before callbacks", function() {
    john.name = "whatever";
    equals(john.age, 35);
  });

  it("should not run other describes' before callbacks", function() {
    equals(john.name, "whatever");
    equals(john.age, 35);
  });

  it("should not know of other objects in a different describe", function() {
    equals(typeof jane, "undefined");
  });
});

describe("SpecIt with an after callback", function() {
  var changedFromAfterCallback = "unchanged";

  after(function() {
    changedFromAfterCallback = "changed";
  });

  it("should not call after callback until after a test is run", function() {
    equals(changedFromAfterCallback, "unchanged");
  });

  it("should call the after callback the first test is run", function() {
    equals(changedFromAfterCallback, "changed");
    changedFromAfterCallback = "bogus";
  });

  it("should call the after callback after each test is run", function() {
    equals(changedFromAfterCallback, "changed");
  });
});
<commit_msg>Fix test<commit_after>describe("SpecIt", function() {
  it("should match on inclusion", function() {
    [1, 2].should(include, 1);
    [1, 2].should(include, 1, 2);
    ({one: 1, two: 2}).should(include, "one");

    [1, 2].shouldNot(include, [1, 2]);
    [1, 2].shouldNot(include, [1, 2], 1, 2);
    [1, 2].shouldNot(include, 3);
    [1, 2].shouldNot(include, 3, 4);
    ({one: 1}).shouldNot(include, "two");

    "string".should(include, "string");
    "string".should(include, "ring");
    "string".should(include, "tr");

    "string".shouldNot(include, "  string");
    "string".shouldNot(include, "string ");
    "string".shouldNot(include, "cat");
  });

  it("should match on equality", function() {
    "string".should(eql, "string");
    (1).should(eql, 1);
    true.should(eql, true);

    "string".shouldNot(eql, "junk");
    [].shouldNot(eql, []);
    ["tree"].shouldNot(eql, ["tree"]);
    ({}).shouldNot(eql, {});
    true.shouldNot(eql, false);
  });

  it("should match on similarity", function() {
    "string".should(beSimilarTo, "string");
    (1).should(beSimilarTo, 1);
    true.should(beSimilarTo, true);
    [].should(beSimilarTo, []);
    ["tree"].should(beSimilarTo, ["tree"]);
    ({}).should(beSimilarTo, {});
    ({a: 1}).should(beSimilarTo, {"a": 1});

    "string".shouldNot(beSimilarTo, "junk");
    true.shouldNot(beSimilarTo, false);
    ({a: 1}).shouldNot(beSimilarTo, {b: 1});
  });

  it("should match on truthiness", function() {
    "string".should(be);
    true.should(be);
    (1).should(be);

    "".shouldNot(be);
    false.shouldNot(be);
    (0).shouldNot(be);
  });

  it("should match by type comparison", function() {
    "string".should(beA, String);
    (function() {}).should(beA, Function);
    true.should(beA, Boolean);
    ({}).should(beAn, Object);
    [].should(beAn, Array);
    (1).should(beA, Number);
    /regular-expression/.should(beA, RegExp);

    "string".shouldNot(beAn, Object);
    "string".shouldNot(beA, Number);
    [].shouldNot(beAn, Object);
  });

  it("should match against regular expressions", function() {
    "string".should(match, /string/);
    "202-555-1212".should(match, /\d{3}.\d{3}.\d{4}/);
    "string".shouldNot(match, /\w{10}/);
  });

  it("should match on method presence", function() {
    var myObject = {
      attribute1: 1,
      booleanAttr: true,
      methodAttr: function() {}
    };

    myObject.should(respondTo, "methodAttr");
    myObject.shouldNot(respondTo, "attribute1");
    myObject.shouldNot(respondTo, "booleanAttr");
    myObject.shouldNot(respondTo, "junkMethod");

    var Person = function(options) {
      this.name = options.name || "";
      this.age = options.age || 13;
      this.sayHi = function() {
        return "Hello; my name is " + this.name;
      };
      return this;
    };

    var john = new Person({name: "John Doe", age: 35});
    john.should(respondTo, "sayHi");
    john.shouldNot(respondTo, "name");
    john.shouldNot(respondTo, "age");
    john.shouldNot(respondTo, "sayGoodbye");
  });

  it("should match on less than", function() {
    (  2).should(beLessThan, 5);
    ( -5).should(beLessThan, 0);
    (  0).should(beLessThan, 0.1);
    "awesome".should(beLessThan, "great");
    (  5).shouldNot(beLessThan, 3);
    (0.1).shouldNot(beLessThan, 0);
    (0.1).shouldNot(beLessThan, 0.05);
    (  5).shouldNot(beLessThan, 5);
  });

  it("should match on less than or equal to", function() {
    (  2).should(beLessThanOrEqualTo, 5);
    ( -5).should(beLessThanOrEqualTo, 0);
    (  0).should(beLessThanOrEqualTo, 0.1);
    (  5).should(beLessThanOrEqualTo, 5);
    "awesome".should(beLessThanOrEqualTo, "great");
    "great".should(beLessThanOrEqualTo, "great");
    (0.1).should(beLessThanOrEqualTo, 0.1);

    (  5).shouldNot(beLessThanOrEqualTo, 3);
    (0.1).shouldNot(beLessThanOrEqualTo, 0);
    (0.1).shouldNot(beLessThanOrEqualTo, 0.05);
  });

  it("should match on greater than", function() {
    (  2).should(beGreaterThan, 1);
    ( -5).should(beGreaterThan, -10);
    (  0).should(beGreaterThan, -0.1);
    "awesome".should(beGreaterThan, "absolute");
    (  5).shouldNot(beGreaterThan, 30);
    (0.1).shouldNot(beGreaterThan, 0.2);
    (0.01).shouldNot(beGreaterThan, 0.05);
    (  5).shouldNot(beGreaterThan, 5);
  });

  it("should match on greater than or equal to", function() {
    (  2).should(beGreaterThanOrEqualTo, 1);
    ( -5).should(beGreaterThanOrEqualTo, -10);
    (  0).should(beGreaterThanOrEqualTo, -0.1);
    (  5).should(beGreaterThanOrEqualTo, 5);
    "awesome".should(beGreaterThanOrEqualTo, "awesome");
    (  5).shouldNot(beGreaterThanOrEqualTo, 30);
    (0.1).shouldNot(beGreaterThanOrEqualTo, 0.2);
    (0.01).shouldNot(beGreaterThanOrEqualTo, 0.05);
  });

  it("should match on elements on a page", function() {
   $(".workspace").append("
");

   $(".workspace .great").should(beOnThePage);
   $(".workspace .non-existant").shouldNot(beOnThePage);
   $(".workspace").empty();
  });
});

var john, beforeCallbackTest, afterCallbackTest;

describe("SpecIt with a before callback", function() {
  var jane = {name: "Jane"};

  before(function() {
    beforeCallbackTest = true;
    john = {name: "John Doe"};
  });

  it("should support before", function() {
    ok(beforeCallbackTest);
    equal(afterCallbackTest, undefined);
  });

  it("should run before every test", function() {
    john.name = "Wrong name";
    jane.age = 26;
  });

  it("should run before every test", function() {
    equals(john.name, "John Doe");
  });

  it("should not know attributes from another before callback", function() {
    equals(john.age, undefined);
  });

  it("should not modify attributes on a local object if untouched in before", function() {
    equals(jane.age, 26);
  });
});

// the john object will carry over, but the jane object will not
describe("SpecIt with a different before callback", function() {
  before(function() { john.age = 35; });

  it("should not run other describes' before callbacks", function() {
    john.name = "whatever";
    equals(john.age, 35);
  });

  it("should not run other describes' before callbacks", function() {
    equals(john.name, "whatever");
    equals(john.age, 35);
  });

  it("should not know of other objects in a different describe", function() {
    equals(typeof jane, "undefined");
  });
});

describe("SpecIt with an after callback", function() {
  var changedFromAfterCallback = "unchanged";

  after(function() {
    changedFromAfterCallback = "changed";
  });

  it("should not call after callback until after a test is run", function() {
    equals(changedFromAfterCallback, "unchanged");
  });

  it("should call the after callback the first test is run", function() {
    equals(changedFromAfterCallback, "changed");
    changedFromAfterCallback = "bogus";
  });

  it("should call the after callback after each test is run", function() {
    equals(changedFromAfterCallback, "changed");
  });
});
<|endoftext|>


<commit_before>(function(lib, undefined) {
    lib.array = {
        toArray: function toArray(object) {
            var array = [];
            try {
                array = Array.prototype.slice.call(object, 0);
            } catch (e) {
                for (var i = 0, len = object.length; i < len; i++) array[i] = object[i];
            }
            return array;
        },

        inArray: function inArray(array, object) {
            for (var i = 0, len = array.length; i < len; i++) {
                if (array[i] === object) return true;
            }
            return false;
        },

        forEach: function forEach(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("forEach" in array) {
                array.forEach(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    callback.call(thisObject || lib.window, array[i], i, array);
                }
            }
        },

        every: function every(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("every" in array) {
                return array.every(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && !callback.call(thisObject || lib.window, array[i], i, array)) return false;
                }
                return true;
            }
        },

        some: function some(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("some" in array) {
                return array.some(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && callback.call(thisObject || lib.window, array[i], i, array)) return true;
                }
                return false;
            }
        },

        filter: function filter(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("filter" in array) {
                return array.filter(callback, thisObject || lib.window);
            } else {
                var out = [];
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array) {
                        if (callback.call(thisObject || lib.window, array[i], i, array)) out.push(array[i]);
                    }
                }
                return out;
            }
        },

        map: function map(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("map" in array) {
                return array.map(callback, thisObject || lib.window);
            } else {
                var len = array.length,
                    out = new Array(len);
                for (var i = 0; i < len; i++) {
                    if (i in array) out[i] = callback.call(thisObject || lib.window, array[i], i, array);
                }
                return out;
            }
        },

        reduce: function reduce(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduce" in array) {
                return array.reduce(callback, initialValue);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = 0,
                    out = (isUndefined) ? initialValue : array[i++];

                for (; i < len; i++) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        reduceRight: function reduceRight(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduceRight" in array) {
                return array.reduceRight(callback, initialValue);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = len - 1,
                    out = (isUndefined) ? initialValue : array[i--];

                for (; i >= 0; i--) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        equal: function equal(array) {
            var out = true,
                len = array.length;
            for (var i = 1, argsLen = arguments.length; i < argsLen; i++) {
                if (len != arguments[i].length) return false;
                for (var j = 0; j < len; j++) {
                    if (array[j] instanceof Array || arguments[i][j] instanceof Array) {
                        if (array[j] instanceof Array && arguments[i][j] instanceof Array) {
                            out = this.equal(array[j], arguments[i][j]);
                            if (!out) break;
                        } else {
                            return false;
                        }
                    } else {
                        out = (array[j] == arguments[i][j]);
                        if (!out) break;
                    }
                }
                if (!out) break;
            }
            return out;
        },

        subtract: function subtract(array) {
            var outPrev = array,
                outCurr = [],
                subtrahend = [];

            for (var i = 1, argsLen = arguments.length; i < argsLen; i++) {
                if (arguments[i] instanceof Array) {
                    for (var j = 0, len = arguments[i].length; j < len; j++) {
                        subtrahend.push(arguments[i][j]);
                    }
                } else {
                    subtrahend.push(arguments[i]);
                }
            }

            for (var i = 0, len = subtrahend.length; i < len; i++) {
                for (var j = 0, outLen = outPrev.length; j < outLen; j++) {
                    if (subtrahend[i] instanceof Array) {
                        if (!this.equal(outPrev[j], subtrahend[i])) {
                            outCurr.push(outPrev[j]);
                        }
                    } else {
                        if (outPrev[j] != subtrahend[i]) {
                            outCurr.push(outPrev[j]);
                        }
                    }
                }
                outPrev = outCurr;
                outCurr = [];
            }
            return outPrev;
        },

        intersect: function intersect(array) {
            var out = array;
            for (var i = 1, len = arguments.length; i < len; i++) {
                var tmp = this.subtract(array, arguments[i]);
                out = this.subtract(out, tmp);
            }
            return out;
        }
    };
})(lib);
<commit_msg>added indexOf and lastIndexOf to lib.array<commit_after>(function(lib, undefined) {
    lib.array = {
        toArray: function toArray(object) {
            var array = [];
            try {
                array = Array.prototype.slice.call(object, 0);
            } catch (e) {
                for (var i = 0, len = object.length; i < len; i++) array[i] = object[i];
            }
            return array;
        },

        indexOf: function indexOf(array, object) {
            for (var i = 0, len = array.length; i < len; i++) {
                if (array[i] === object) return i;
            }
            return -1;
        },

        lastIndexOf: function lastIndexOf(array, object) {
            for (var len = array.length, i = len - 1; i >= 0; i--) {
                if (array[i] === object) return i;
            }
            return -1;
        },

        inArray: function inArray(array, object) {
            return (this.indexOf(array, object) > -1) ? true : false;
        },

        forEach: function forEach(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("forEach" in array) {
                array.forEach(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    callback.call(thisObject || lib.window, array[i], i, array);
                }
            }
        },

        every: function every(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("every" in array) {
                return array.every(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && !callback.call(thisObject || lib.window, array[i], i, array)) return false;
                }
                return true;
            }
        },

        some: function some(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("some" in array) {
                return array.some(callback, thisObject || lib.window);
            } else {
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array && callback.call(thisObject || lib.window, array[i], i, array)) return true;
                }
                return false;
            }
        },

        filter: function filter(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("filter" in array) {
                return array.filter(callback, thisObject || lib.window);
            } else {
                var out = [];
                for (var i = 0, len = array.length; i < len; i++) {
                    if (i in array) {
                        if (callback.call(thisObject || lib.window, array[i], i, array)) out.push(array[i]);
                    }
                }
                return out;
            }
        },

        map: function map(array, callback, thisObject) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("map" in array) {
                return array.map(callback, thisObject || lib.window);
            } else {
                var len = array.length,
                    out = new Array(len);
                for (var i = 0; i < len; i++) {
                    if (i in array) out[i] = callback.call(thisObject || lib.window, array[i], i, array);
                }
                return out;
            }
        },

        reduce: function reduce(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduce" in array) {
                return array.reduce(callback, initialValue);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = 0,
                    out = (isUndefined) ? initialValue : array[i++];

                for (; i < len; i++) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        reduceRight: function reduceRight(array, callback, initialValue) {
            if (typeof callback != "function") throw new TypeError(callback + " is not a function");

            if ("reduceRight" in array) {
                return array.reduceRight(callback, initialValue);
            } else {
                var len = array.length,
                    isUndefined = typeof initialValue == "undefined";

                if (len == 0 && isUndefined) {
                    throw new TypeError("Reduce of empty array with no initial value");
                }

                var i = len - 1,
                    out = (isUndefined) ? initialValue : array[i--];

                for (; i >= 0; i--) {
                    if (i in array) out = callback.call(lib.window, out, array[i], i, array);
                }
                return out;
            }
        },

        equal: function equal(array) {
            var out = true,
                len = array.length;
            for (var i = 1, argsLen = arguments.length; i < argsLen; i++) {
                if (len != arguments[i].length) return false;
                for (var j = 0; j < len; j++) {
                    if (array[j] instanceof Array || arguments[i][j] instanceof Array) {
                        if (array[j] instanceof Array && arguments[i][j] instanceof Array) {
                            out = this.equal(array[j], arguments[i][j]);
                            if (!out) break;
                        } else {
                            return false;
                        }
                    } else {
                        out = (array[j] == arguments[i][j]);
                        if (!out) break;
                    }
                }
                if (!out) break;
            }
            return out;
        },

        subtract: function subtract(array) {
            var outPrev = array,
                outCurr = [],
                subtrahend = [];

            for (var i = 1, argsLen = arguments.length; i < argsLen; i++) {
                if (arguments[i] instanceof Array) {
                    for (var j = 0, len = arguments[i].length; j < len; j++) {
                        subtrahend.push(arguments[i][j]);
                    }
                } else {
                    subtrahend.push(arguments[i]);
                }
            }

            for (var i = 0, len = subtrahend.length; i < len; i++) {
                for (var j = 0, outLen = outPrev.length; j < outLen; j++) {
                    if (subtrahend[i] instanceof Array) {
                        if (!this.equal(outPrev[j], subtrahend[i])) {
                            outCurr.push(outPrev[j]);
                        }
                    } else {
                        if (outPrev[j] != subtrahend[i]) {
                            outCurr.push(outPrev[j]);
                        }
                    }
                }
                outPrev = outCurr;
                outCurr = [];
            }
            return outPrev;
        },

        intersect: function intersect(array) {
            var out = array;
            for (var i = 1, len = arguments.length; i < len; i++) {
                var tmp = this.subtract(array, arguments[i]);
                out = this.subtract(out, tmp);
            }
            return out;
        }
    };
})(lib);
<|endoftext|>


<commit_before>$(document).ready(function () {

  canvas = document.getElementById('map-canvas');
  $layerControl = $('#layer-control');

  var map;
  var autoCompleteInput;
  var layersDrawn = [];
  var storyMarkersDrawn = [];

  function drawLayerControls (layersDrawn) {
    var $layerList = $('
');

    $.each(layersDrawn, function (i, layer){
      i++;
      $layer = $('
');
      $layer.append(drawLayerCheckbox(i, layer));
      $layerList.append($layer);
    });

    $layerControl.append($layerList);
  }

  function drawLayerCheckbox (id, layer) {
    var $label = $('');
    var $checkbox = $('<input type="checkbox" id="layer_'+ id +'">');

    $checkbox.attr("checked", false);

    $checkbox.click(function (){
      layer.setMap($(this).is(':checked') ? map : null);
    });

    $label
      .append($checkbox)
      .append(layer.layerOriginal.name);

    return $label;
  }

  function addPhotoStories(stories) {

    $.each(stories, function(i, storyObject) {

      var contentString = '
' +
        ''+storyObject['Title']+'' +
        '' +
        '
';

      var infowindow = new google.maps.InfoWindow({
        content: contentString
      });

      var photoStoryMarker = new google.maps.Marker({
        position: new google.maps.LatLng(storyObject['Latitude'],storyObject['Longitude']),
        map: map,
        title: storyObject['Title']
      });

      google.maps.event.addListener(photoStoryMarker, 'click', function() {
        infowindow.open(map,photoStoryMarker);
      });

      storyMarkersDrawn.push(photoStoryMarker);
    });
  }

  function initializeMap() {
    var mapOptions = {
      // WA State
      // center: new google.maps.LatLng(-27.288135,121.972796),
      // Perth
      center: new google.maps.LatLng(-31.9528536,115.8573389),
      clickable: true,
      streetViewControl: false,
      // Only show default (road) map
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoom: 10,
      minZoom: 5,
      maxZoom: 18
    };

    var westernAustraliaBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-34.981,111.203),
      new google.maps.LatLng(-12.861,129.878)
    );

    var autocompleteOptions = {
      bounds: westernAustraliaBounds,
      componentRestrictions: {country: 'au'}
    };

    map = new google.maps.Map(canvas, mapOptions);

    autoCompleteInput = document.getElementById('pac-input');

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(autoCompleteInput);

    var autocomplete = new google.maps.places.Autocomplete(autoCompleteInput, autocompleteOptions);
    autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29)
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      // hide any visible marker
      marker.setVisible(true);

      var place = autocomplete.getPlace();

      if (!place.geometry) {
        window.alert("Sorry, no geometry data found.");
        return;
      }

      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }

      marker.setIcon(({
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(35, 35)
      }));
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);

    });

    $.each(MapAllTheThings.slip_layers, function(i, layerObject) {
      // Create a data layer for each layer set availale and hide it by default
      var layer = new google.maps.visualization.MapsEngineLayer({
        layerId: layerObject.assetId,
        layerOriginal: layerObject,
        map: null,
      });

      layersDrawn.push(layer);
    });

    drawLayerControls(layersDrawn);

    addPhotoStories(MapAllTheThings.photo_stories);
  }

 if(canvas) google.maps.event.addDomListener(window, 'load', initializeMap);

});
<commit_msg>Add Noongar Suburbs and Native Title WA KMA layers<commit_after>$(document).ready(function () {

  canvas = document.getElementById('map-canvas');
  $layerControl = $('#layer-control');

  var map;
  var autoCompleteInput;
  var layersDrawn = [];
  var storyMarkersDrawn = [];
  var noongarSuburbs = "https://raw.githubusercontent.com/GovHack2015TeamBoba/MapAllTheThings/master/src/javascripts/data/NoongarSuburbs.kml";
  var nativeTitleWA = "https://raw.githubusercontent.com/GovHack2015TeamBoba/MapAllTheThings/master/src/javascripts/data/NativeTitleWA.kml";

  function drawLayerControls (layersDrawn) {
    var $layerList = $('
');

    $.each(layersDrawn, function (i, layer){
      i++;
      $layer = $('
');
      $layer.append(drawLayerCheckbox(i, layer));
      $layerList.append($layer);
    });

    $layerControl.append($layerList);
  }

  function addKMLayer (layerUrl) {

    var ctaLayer = new google.maps.KmlLayer({
      url: layerUrl
    });
    ctaLayer.setMap(map);
  }

  function drawLayerCheckbox (id, layer) {
    var $label = $('');
    var $checkbox = $('<input type="checkbox" id="layer_'+ id +'">');

    $checkbox.attr("checked", false);

    $checkbox.click(function (){
      layer.setMap($(this).is(':checked') ? map : null);
    });

    $label
      .append($checkbox)
      .append(layer.layerOriginal.name);

    return $label;
  }

  function addPhotoStories(stories) {

    $.each(stories, function(i, storyObject) {

      if ((storyObject['Latitude'] || storyObject['Longitude']) === null) {
        return;
      }

      var contentString = '
' +
        '
'+storyObject['Title']+'
' +
        '

' +
        '
';

      var infowindow = new google.maps.InfoWindow({
        content: contentString
      });

      var photoStoryMarker = new google.maps.Marker({
        position: new google.maps.LatLng(storyObject['Latitude'],storyObject['Longitude']),
        map: map,
        title: storyObject['Title']
      });

      google.maps.event.addListener(photoStoryMarker, 'click', function() {
        infowindow.open(map,photoStoryMarker);
      });

      storyMarkersDrawn.push(photoStoryMarker);
    });
  }

  function initializeMap() {
    var mapOptions = {
      // WA State
      // center: new google.maps.LatLng(-27.288135,121.972796),
      // Perth
      center: new google.maps.LatLng(-31.9528536,115.8573389),
      clickable: true,
      streetViewControl: false,
      // Only show default (road) map
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoom: 10,
      minZoom: 5,
      maxZoom: 18
    };

    var westernAustraliaBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-34.981,111.203),
      new google.maps.LatLng(-12.861,129.878)
    );

    var autocompleteOptions = {
      bounds: westernAustraliaBounds,
      componentRestrictions: {country: 'au'}
    };

    map = new google.maps.Map(canvas, mapOptions);

    autoCompleteInput = document.getElementById('pac-input');

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(autoCompleteInput);

    var autocomplete = new google.maps.places.Autocomplete(autoCompleteInput, autocompleteOptions);
    autocomplete.bindTo('bounds', map);

    var marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29)
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      // hide any visible marker
      marker.setVisible(true);

      var place = autocomplete.getPlace();

      if (!place.geometry) {
        window.alert("Sorry, no geometry data found.");
        return;
      }

      // If the place has a geometry, then present it on a map.
      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }

      marker.setIcon(({
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(35, 35)
      }));
      marker.setPosition(place.geometry.location);
      marker.setVisible(true);

    });

    $.each(MapAllTheThings.slip_layers, function(i, layerObject) {
      // Create a data layer for each layer set availale and hide it by default
      var layer = new google.maps.visualization.MapsEngineLayer({
        layerId: layerObject.assetId,
        layerOriginal: layerObject,
        map: null,
      });

      layersDrawn.push(layer);
    });

    drawLayerControls(layersDrawn);

    addPhotoStories(MapAllTheThings.photo_stories);

    addKMLayer(noongarSuburbs);

    addKMLayer(nativeTitleWA);
  }

 if(canvas) google.maps.event.addDomListener(window, 'load', initializeMap);

});
<|endoftext|>


<commit_before>/*
0xor1   http://github.com/0xor1
*/

(function () {

    window.Sudoku = {};

    Sudoku.textures = [
        THREE.ImageUtils.loadTexture("textures/empty.png"),
        THREE.ImageUtils.loadTexture("textures/1.png"),
        THREE.ImageUtils.loadTexture("textures/2.png"),
        THREE.ImageUtils.loadTexture("textures/3.png"),
        THREE.ImageUtils.loadTexture("textures/4.png"),
        THREE.ImageUtils.loadTexture("textures/5.png"),
        THREE.ImageUtils.loadTexture("textures/6.png"),
        THREE.ImageUtils.loadTexture("textures/7.png"),
        THREE.ImageUtils.loadTexture("textures/8.png"),
        THREE.ImageUtils.loadTexture("textures/9.png"),
        THREE.ImageUtils.loadTexture("textures/A.png"),
        THREE.ImageUtils.loadTexture("textures/B.png"),
        THREE.ImageUtils.loadTexture("textures/C.png"),
        THREE.ImageUtils.loadTexture("textures/D.png"),
        THREE.ImageUtils.loadTexture("textures/E.png"),
        THREE.ImageUtils.loadTexture("textures/F.png"),
        THREE.ImageUtils.loadTexture("textures/G.png"),
        THREE.ImageUtils.loadTexture("textures/H.png"),
        THREE.ImageUtils.loadTexture("textures/I.png"),
        THREE.ImageUtils.loadTexture("textures/J.png"),
        THREE.ImageUtils.loadTexture("textures/K.png"),
        THREE.ImageUtils.loadTexture("textures/L.png"),
        THREE.ImageUtils.loadTexture("textures/M.png"),
        THREE.ImageUtils.loadTexture("textures/N.png"),
        THREE.ImageUtils.loadTexture("textures/O.png"),
        THREE.ImageUtils.loadTexture("textures/P.png"),
        THREE.ImageUtils.loadTexture("textures/Q.png"),
        THREE.ImageUtils.loadTexture("textures/R.png"),
        THREE.ImageUtils.loadTexture("textures/S.png"),
        THREE.ImageUtils.loadTexture("textures/T.png"),
        THREE.ImageUtils.loadTexture("textures/U.png"),
        THREE.ImageUtils.loadTexture("textures/V.png"),
        THREE.ImageUtils.loadTexture("textures/W.png"),
        THREE.ImageUtils.loadTexture("textures/X.png"),
        THREE.ImageUtils.loadTexture("textures/Y.png"),
        THREE.ImageUtils.loadTexture("textures/Z.png"),
        THREE.ImageUtils.loadTexture("textures/hash.png")
    ];

    Sudoku.getTextureIndexFromKeyCode = function (kc) {

        if (kc === 8 || kc === 46 || kc === 96 || kc === 48) { /*delete or backspace or 0 on numberpad or number row*/
            return 0;
            /*Empty*/
        } else if (kc >= 49 && kc <= 57) {
            return kc - 48;
            /*1-9*/
        } else if (kc >= 97 && kc <= 105) {
            return kc - 96;
            /*1-9 numberpad*/
        } else if (kc >= 65 && kc <= 90) {
            return kc - 55;
            /*A-Z*/
        } else if (kc === 222) {
            return 36;
            /*#*/
        }

    };

    Sudoku.getNewStartingConfig = function () {

        var rand = Math.floor(Math.random() * (Sudoku.startingConfigs.length));

        return Sudoku.startingConfigs[rand];

    };

})();
<commit_msg>comment out unused image loads<commit_after>/*
0xor1   http://github.com/0xor1
*/

(function () {

    window.Sudoku = {};

    Sudoku.textures = [
        THREE.ImageUtils.loadTexture("textures/empty.png"),
        THREE.ImageUtils.loadTexture("textures/1.png"),
        THREE.ImageUtils.loadTexture("textures/2.png"),
        THREE.ImageUtils.loadTexture("textures/3.png"),
        THREE.ImageUtils.loadTexture("textures/4.png"),
        THREE.ImageUtils.loadTexture("textures/5.png"),
        THREE.ImageUtils.loadTexture("textures/6.png"),
        THREE.ImageUtils.loadTexture("textures/7.png"),
        THREE.ImageUtils.loadTexture("textures/8.png"),
        THREE.ImageUtils.loadTexture("textures/9.png"),
        /*THREE.ImageUtils.loadTexture("textures/A.png"),
        THREE.ImageUtils.loadTexture("textures/B.png"),
        THREE.ImageUtils.loadTexture("textures/C.png"),
        THREE.ImageUtils.loadTexture("textures/D.png"),
        THREE.ImageUtils.loadTexture("textures/E.png"),
        THREE.ImageUtils.loadTexture("textures/F.png"),
        THREE.ImageUtils.loadTexture("textures/G.png"),
        THREE.ImageUtils.loadTexture("textures/H.png"),
        THREE.ImageUtils.loadTexture("textures/I.png"),
        THREE.ImageUtils.loadTexture("textures/J.png"),
        THREE.ImageUtils.loadTexture("textures/K.png"),
        THREE.ImageUtils.loadTexture("textures/L.png"),
        THREE.ImageUtils.loadTexture("textures/M.png"),
        THREE.ImageUtils.loadTexture("textures/N.png"),
        THREE.ImageUtils.loadTexture("textures/O.png"),
        THREE.ImageUtils.loadTexture("textures/P.png"),
        THREE.ImageUtils.loadTexture("textures/Q.png"),
        THREE.ImageUtils.loadTexture("textures/R.png"),
        THREE.ImageUtils.loadTexture("textures/S.png"),
        THREE.ImageUtils.loadTexture("textures/T.png"),
        THREE.ImageUtils.loadTexture("textures/U.png"),
        THREE.ImageUtils.loadTexture("textures/V.png"),
        THREE.ImageUtils.loadTexture("textures/W.png"),
        THREE.ImageUtils.loadTexture("textures/X.png"),
        THREE.ImageUtils.loadTexture("textures/Y.png"),
        THREE.ImageUtils.loadTexture("textures/Z.png"),
        THREE.ImageUtils.loadTexture("textures/hash.png")*/
    ];

    Sudoku.getTextureIndexFromKeyCode = function (kc) {

        if (kc === 8 || kc === 46 || kc === 96 || kc === 48) { /*delete or backspace or 0 on numberpad or number row*/
            return 0;
            /*Empty*/
        } else if (kc >= 49 && kc <= 57) {
            return kc - 48;
            /*1-9*/
        } else if (kc >= 97 && kc <= 105) {
            return kc - 96;
            /*1-9 numberpad*/
        } else if (kc >= 65 && kc <= 90) {
            return kc - 55;
            /*A-Z*/
        } else if (kc === 222) {
            return 36;
            /*#*/
        }

    };

    Sudoku.getNewStartingConfig = function () {

        var rand = Math.floor(Math.random() * (Sudoku.startingConfigs.length));

        return Sudoku.startingConfigs[rand];

    };

})();
<|endoftext|>


<commit_before>'use babel'

import { CompositeDisposable } from 'atom'
import { unmount, togglePanel, getStore } from '../utils/render'

import { connectToGithub } from '../actions/login'

let subscriptions

export function onActivate() {
  subscriptions = new CompositeDisposable

  subscriptions.add(
    atom.commands.add('atom-workspace', {
      'atom-video:toggle': togglePanel
    })
  )

  subscriptions.add(
    atom.config.onDidChange('atom-video.token', ({newValue}) => {
      getStore().dispatch(connectToGithub(newValue))
    })
  )
}

export function onDeactivate() {
  window.onresize = null
  unmount()
  subscriptions.dispose()
}
<commit_msg>destroy peer on deactivate<commit_after>'use babel'

import { CompositeDisposable } from 'atom'
import { unmount, togglePanel, getStore } from '../utils/render'

import { connectToGithub } from '../actions/login'
import { destroy } from '../actions/session'

let subscriptions

export function onActivate() {
  subscriptions = new CompositeDisposable

  subscriptions.add(
    atom.commands.add('atom-workspace', {
      'atom-video:toggle': togglePanel
    })
  )

  subscriptions.add(
    atom.config.onDidChange('atom-video.token', ({newValue}) => {
      getStore().dispatch(connectToGithub(newValue))
    })
  )
}

export function onDeactivate() {
  getStore().dispatch(destroy())
  window.onresize = null
  unmount()
  subscriptions.dispose()
}
<|endoftext|>


<commit_before>// This file is here if you'd like to use Exponent XDE
// Swap out the RN dependency for the latest from Exponent.
// E.G. "react-native": "github:exponentjs/react-native#2016-01-02"

import { AppRegistry } from 'react-native'
import Root from './App/Root'

AppRegistry.registerComponent('main', () => Root)
<commit_msg>we're not really supporting exponent anymore<commit_after><|endoftext|>


<commit_before>/**
 * New node file
 */

var db = require('../lib/mongodb');
var FeedParser = require("feedparser");
var request = require('request');
var globals = require('../lib/globalsDao');
var alerter = require('../lib/alerter');
var utils = require('../lib/utils');

var alertDao = require('../lib/alertDao');

function storeAlert(alert)
{
	alert._id = alert.guid;
	for (var key in alert)
	{
		// remove all the "atom:" keys - they're duplicates and they just use up space
		if (key.lastIndexOf("atom") === 0)
		{
			delete alert[key];
		}
	}
	db.alerts.update({"_id": alert._id}, alert, {upsert: true});
}

function updateAlertsFromFeed(feed)
{
	// hmm.. this is where async gets  annoying. I wonder if promises would make
	// for clearer code,
	globals.lastUpdated().then(function(lastUpdated) {
		console.log("Feed date: " + feed.meta.pubDate + ", lastupdated = " + lastUpdated);
		if (feed.meta.pubDate > lastUpdated)
		{
			console.log("Updating alerts in database..");
			for (var i = 0; i < feed.entries.length; i++)
			{
				var item = feed.entries[i];
				if (item.pubDate > lastUpdated)
				{
					storeAlert(item);
					item.description = utils.stripHtml(item.description);
					alerter.triggerAlert(item).then();
				}
			}
			console.log("Finished updating alerts in database.");
			globals.setLastUpdated(feed.meta.pubDate).then();
		}
		else
		{
			console.log("Not updating, no changes detected");
		}
	}).catch(function(err) {
		console.log("Error updating alerts from feed: " + err);
	});
}

function fetchAlerts(onFinish, onError)
{
	console.log("Fetching alerts..");
	var feed = { entries: [] };

	// NB, FCO site doesn't appear to support if-modified-since, so we have to fetch
	// the whole lot each time.
	request('https://www.gov.uk/foreign-travel-advice.atom')
	.on('error', function(error) {
		if (onError) {onError(error);}
	})
	.pipe(new FeedParser({addmeta: false}))
	.on('error', function(error) {
		if (onError) {onError(error);}
	})
	.on('meta', function (meta) {
		feed.meta = meta;
	})
	.on('readable', function () {
		var stream = this;
		var item = stream.read();
		while (item)
		{
			feed.entries.push(item);
			item = stream.read();
		}
	})
	.on('end', function() {
		if (onFinish) {onFinish(feed);}
		console.log("Finished fetching alerts.");
	});

}

function updateAlerts()
{
	fetchAlerts(updateAlertsFromFeed, null);
}

exports.refresh = function(req, res)
{
	fetchAlerts(
			function(feed) {
				updateAlertsFromFeed(feed);
				res.send(feed);
			},
			function(error) {
				res.status(500).send(error);
			});
};

exports.updateAlerts = updateAlerts;
<commit_msg>alert feed routing now uses promises<commit_after>/**
 * New node file
 */

var RSVP = require('rsvp');
var FeedParser = require("feedparser");
var request = require('request');

var alerter = require('../lib/alerter');
var alertDao = require('../lib/alertDao');
var globals = require('../lib/globalsDao');
var utils = require('../lib/utils');

function updateAlertsFromFeed(feed)
{
	return new RSVP.Promise(function(resolve, reject) {
		globals.lastUpdated().then(function(lastUpdated) {
			console.log("Feed date: " + feed.meta.pubDate + ", lastupdated = " + lastUpdated);
			if (feed.meta.pubDate > lastUpdated)
			{
				console.log("Updating alerts in database..");
				var promises = [];
				for (var i = 0; i < feed.entries.length; i++)
				{
					var item = feed.entries[i];
					if (item.pubDate > lastUpdated)
					{
						promises.push(alertDao.upsertAlert(item).then(function() {
							item.description = utils.stripHtml(item.description);
							return alerter.triggerAlert(item);
						}));
					}
				}
				RSVP.allSettled(promises)
					.then(function(states) {
						// TODO: ignoring states for now, may need to log failures later
						console.log("Finished updating alerts in database.");
						return globals.setLastUpdated(feed.meta.pubDate);
					})
					.then(function() {
						resolve(feed);
					})
					.catch(reject);
			}
			else
			{
				console.log("Not updating, no changes detected");
				resolve(feed);
			}
		}).catch(function(err) {
			console.log("Error updating alerts from feed: ", err);
			reject(err);
		});
	});
}

function fetchAlerts()
{
	return new RSVP.Promise(function(resolve, reject)
	{
		console.log("Fetching alerts..");
		var feed = { entries: [] };

		// NB, FCO site doesn't appear to support if-modified-since, so we have to fetch
		// the whole lot each time.
		request('https://www.gov.uk/foreign-travel-advice.atom')
			.on('error', reject) // errors on request
			.pipe(new FeedParser({addmeta: false}))
				.on('error', reject) // errors on pipe, I think we need both
				.on('meta', function (meta) {
					feed.meta = meta;
				})
				.on('readable', function () {
					var stream = this;
					var item = stream.read();
					while (item)
					{
						feed.entries.push(item);
						item = stream.read();
					}
				})
				.on('end', function() {
					console.log("Finished fetching alerts");
					resolve(feed);
				});
	});

}

/**
 * Call this outside of a web environment - returns a promise
 */
exports.updateAlerts = function(onFinish)
{
	return new RSVP.Promise(function(resolve, reject) {
		fetchAlerts()
			.then(updateAlertsFromFeed)
			.then(resolve)
			.catch(reject);
	});
};

/**
 * Call this inside a web environment - ensures a response is always sent.
 */
exports.refresh = function(req, res)
{
	fetchAlerts()
		.then(updateAlertsFromFeed)
		.then(function(feed) {
			// for some reason, just passing res.send here doesn't work, we need to
			// create this anonymous function. Dunno why.
			console.log("placing feed on HTTP response..");
			res.send(feed);
		})
		.catch(function(err) {
			res.status(500).send(err);
		});
};
<|endoftext|>


<commit_before>export default function WelcomeController(state, R, storage) {
  this.isStorageConnected = storage.isConnected;

  let savedUsersCursor = state.cloudUnencrypted.cursor;
  let updateSavedUsers = () => {
    this.users = R.keys(savedUsersCursor.get()).length;
  };

  state.addListener(savedUsersCursor, updateSavedUsers, $scope);
}
<commit_msg>Fixed missed $scope dependency<commit_after>export default function WelcomeController(state, R, storage, $scope) {
  this.isStorageConnected = storage.isConnected;

  let savedUsersCursor = state.cloudUnencrypted.cursor;
  let updateSavedUsers = () => {
    this.users = R.keys(savedUsersCursor.get()).length;
  };

  state.addListener(savedUsersCursor, updateSavedUsers, $scope);
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import AutoFormInternal from './AutoFormInternal';
import MetadataProvider from './metadata/MetadataProvider';
import metadataValidator from './metadata/validator/metadataValidator';
import modelProcessor from './metadata/model/modelParser';

class AutoForm extends Component {
    static propTypes = {
        uiType: PropTypes.string,
        componentFactory: PropTypes.object,
        schema: PropTypes.object.isRequired,
        entityName: PropTypes.string.isRequired,
        layoutName: PropTypes.string.isRequired,
        errorRenderer: PropTypes.func,
        onSubmit: PropTypes.func.isRequired,
        onSubmitSuccess: PropTypes.func,
        onSubmitFail: PropTypes.func,
        form: PropTypes.string.isRequired,
        buttonBar: PropTypes.func.isRequired,
        fieldLayout: PropTypes.string
    };

    render() {
        let { uiType, schema, entityName, layoutName, componentFactory, onSubmit, onSubmitFail, onSubmitSuccess, errorRenderer, form, buttonBar, fieldLayout, initialValues } = this.props;

        try {
            schema = MetadataProvider.canonizeSchema(schema); // This will allow for flexible schema definition (arrays vs. objects)

            let { entity, layout } =    MetadataProvider.getEntityAndLayout(schema, entityName, layoutName);
            let fieldMetadata = MetadataProvider.getFields(schema, entity, layout, f => {
                f.componentFactory = componentFactory;
                f.fieldLayout = fieldLayout;
            });
            let fields = MetadataProvider.getReduxFormFields(fieldMetadata);
            let validate = (values) => {
                let modelParsed = modelProcessor.process(values, fieldMetadata);
                return metadataValidator.validate(fieldMetadata, modelParsed) || {};
            };

            let autoFormProps = { uiType, form, fields, fieldMetadata, entity, layout, validate, componentFactory, onSubmit, onSubmitSuccess, onSubmitFail, buttonBar, fieldLayout, initialValues };

            return <AutoFormInternal {...autoFormProps}/>
        } catch(ex) {
            return errorRenderer ? errorRenderer(ex) : <div> {ex.message} </div>;
        }
    }
}

export default AutoForm;<commit_msg>Start to merge changes:<commit_after>import React, { Component, PropTypes } from 'react'
import AutoFormInternal from './AutoFormInternal';
import MetadataProvider from './metadata/MetadataProvider';
import metadataValidator from './metadata/validator/metadataValidator';
import modelProcessor from './metadata/model/modelParser';

class AutoForm extends Component {
    static propTypes = {
        uiType: PropTypes.string,
        componentFactory: PropTypes.object,
        schema: PropTypes.object.isRequired,
        entityName: PropTypes.string,
        layoutName: PropTypes.string,
        errorRenderer: PropTypes.func,
        onSubmit: PropTypes.func.isRequired,
        onSubmitSuccess: PropTypes.func,
        onSubmitFail: PropTypes.func,
        form: PropTypes.string.isRequired,
        buttonBar: PropTypes.func.isRequired,
        fieldLayout: PropTypes.string
    };

    render() {
        let { uiType, schema, entityName, layoutName, componentFactory, onSubmit, onSubmitFail, onSubmitSuccess, errorRenderer, form, buttonBar, fieldLayout, initialValues } = this.props;

        try {
            schema = MetadataProvider.canonizeSchema(schema); // This will allow for flexible schema definition (arrays vs. objects)

            let { entity, layout } =    MetadataProvider.getEntityAndLayout(schema, entityName, layoutName);
            let fieldMetadata = MetadataProvider.getFields(schema, entity, layout, f => {
                f.componentFactory = componentFactory;
                f.fieldLayout = fieldLayout;
            });
            let fields = MetadataProvider.getReduxFormFields(fieldMetadata);
            let validate = (values) => {
                let modelParsed = modelProcessor.process(values, fieldMetadata);
                return metadataValidator.validate(fieldMetadata, modelParsed) || {};
            };

            let autoFormProps = { uiType, form, fields, fieldMetadata, entity, layout, validate, componentFactory, onSubmit, onSubmitSuccess, onSubmitFail, buttonBar, fieldLayout, initialValues };

            return <AutoFormInternal {...autoFormProps}/>
        } catch(ex) {
            return errorRenderer ? errorRenderer(ex) : <div> {ex.message} </div>;
        }
    }
}

export default AutoForm;<|endoftext|>


<commit_before><commit_msg>set applab app title<commit_after><|endoftext|>


<commit_before>$( document ).ready(function() {
  var href = [];
  function appendDataFun (data) {
     $(".onlyPrint").append(data);
   }
  $(".testLinks").each(function () {
      href = href.push($(this).attr("href"));
  });
  for (var i = 0; i < href.length; i++) {
    $.get(href[i], appendDataFun(data));
  }

});
<commit_msg>test links html<commit_after>$(document).ready(function() {
  var href = [];
  function appendDataFun (data) {
     $(".onlyPrint").append(data);
   }
  $(".testLinks").each(function () {
    console.log(typeof href);
      href = href.push($(this).attr("href"));
  });
  for (var i = 0; i < href.length; i++) {
    $.get(href[i], appendDataFun(data));
  }
});
<|endoftext|>


<commit_before><commit_msg>correção da div<commit_after><|endoftext|>


<commit_before>/*
 * 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.
 */
var g_currentQuery, g_currentSearchOption;
var shortname = getURLParameter('shortname');

$(document).ready(function () {
    var query = getURLParameter('query');
    g_currentSearchOption = getURLParameter('searchOption');
    if (query) {
        $("#query").val(query);
    }
    if (g_currentSearchOption) {
        $('#searchOption_' + g_currentSearchOption).prop('checked', true);
    }

    $("#query").keydown(function (event) {
        if (event.keyCode == 13) {
            $("#searchButton").click();
        }
    });

    $("#searchButton").click(function () {
        redirect("search", "query", $("#query").val(), "searchOption", $("input[name='searchOption']:checked").val());
    });

    $("#ontologyUL").on("click", "li a", function () {
        redirect("search", "query", $(this).data("word"), "searchOption", $("input[name='searchOption']:checked").val());
    });

    g_currentQuery = encodeURI(query);

    // invoke SearchVocabResource.java
    loadVocubulary(query);
    loadMetaData(shortname);
    loadHybirdRecomData(shortname);
});

function loadVocubulary(query) {
    $.ajax({
        url: "services/vocabulary/search",
        data: {
            "query": query
        },
        success: function completeHandler(response) {
            if (response != null && !jQuery.isEmptyObject(response)) {
                var ontologyResults = response.graph.ontology;
                if (ontologyResults.length == 0) {
                    $("#ontologyUL").append("
Did not find any results.
");
                } else {
                    for (var i = 0; i < ontologyResults.length; i++) {
                        $("#ontologyUL").append("
" + ontologyResults[i].word + " (" + ontologyResults[i].weight + ")
");
                    }
                }
            }
        }
    });
}

function loadHybirdRecomData(shortname) {
    if (shortname != "") {
        $("#dataset").show();
        $.ajax({
            url: "services/hrecommendation/search",
            data: {
                "shortname": shortname
            },
            success: function completeHandler(response) {
                if (response != null && !jQuery.isEmptyObject(response)) {
                    var recomdata = response.HybridRecommendationData;
                    var linked = recomdata.linked;
                    if (linked.length == 0) {
                        $("#hybirdul").append("
Did not find any results.
");
                    } else {

                        $.each(linked, function (i, item) {
                            console.log("hh");
                            var li = $("

");
                            $("#hybirdul").append(li);
                            //$("a",li).text(item.name  + "(" + item.weight + ")");
                            $("a", li).text(item.name);
                            $("a", li).attr("href", "./dataset.html?query=" + g_currentQuery + "&searchOption=" + g_currentSearchOption + "&shortname=" + item.name);
                        });
                    }
                }
            }
        });
    }
}

function loadMetaData(shortname) {
    if (shortname != "") {
        $("#dataset").show();
        $.ajax({
            url: "services/datasetdetail/search",
            data: {
                "shortname": shortname
            },
            success: function completeHandler(response) {
                if (response != null && !jQuery.isEmptyObject(response)) {
                    $("#searchLoading").hide();
                    var searchResults = response.PDResults;

                    console.log(searchResults);
                    if (searchResults.length == 0) {
                        $("#NotFound").show();
                    } else {
                        createResultTable();

                        $("#shortName").html(searchResults[0]["Short Name"]);
                        $('#ResultsTable').bootstrapTable('load', searchResults);
                    }
                }
            }
        });
    }
}

function urlFormatter(value, row) {
	var urls = value.split(",");
	var html = "";
	for (i = 0; i < urls.length; i++) {
	    html += '' + urls[i] + '' + "
";
	}
	return html;
}

function createResultTable() {
    var layout = {
        cache: false,
        cardView: true,
        columns: [{
            'title': 'Long Name',
            'field': 'Long Name',
        }, {
            'title': 'Doi',
            'field': 'Dataset-Doi',
        }, {
            'title': 'Topic',
            'field': 'Topic',
        }, {
            'title': 'Category',
            'field': 'DatasetParameter-Category',
        }, {
            'title': 'Variable',
            'field': 'DatasetParameter-Variable',
        }, {
            'title': 'Term',
            'field': 'DatasetParameter-Term',
        }, {
            'title': 'Version',
            'field': 'Version',
        }, {
            'title': 'Description',
            'field': 'Dataset-Description',
        }, {
            'title': 'Processing Level',
            'field': 'Processing Level',
        },{
            'title': 'Region',
            'field': 'Region',
        }, {
            'title': 'Coverage',
            'field': 'Coverage'
        }, {
            'title': 'Time Span',
            'field': 'Time Span',
        }, {
            'title': 'Spatial Resolution',
            'field': 'SpatiallResolution',
        }, {
            'title': 'Temporal Repeat',
            'field': 'TemporalResolution',
        }, {
            'title': 'Sensor',
            'field': 'DatasetSource-Sensor-ShortName',
        }, {
            'title': 'Project',
            'field': 'DatasetProject-Project-ShortName',
        }, {
            'title': 'Format',
            'field': 'DataFormat',
        }, {
            'title': 'Data Access',
            'field': 'DatasetLocationPolicy-BasePath',
            'formatter' : urlFormatter
        }
        ]
    };

    $('#ResultsTable').bootstrapTable(layout);
}<commit_msg>Added PO.DAAC landing page url to the dataset page<commit_after>/*
 * 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.
 */
var g_currentQuery, g_currentSearchOption;
var shortname = getURLParameter('shortname');

$(document).ready(function () {
    var query = getURLParameter('query');
    g_currentSearchOption = getURLParameter('searchOption');
    if (query) {
        $("#query").val(query);
    }
    if (g_currentSearchOption) {
        $('#searchOption_' + g_currentSearchOption).prop('checked', true);
    }

    $("#query").keydown(function (event) {
        if (event.keyCode == 13) {
            $("#searchButton").click();
        }
    });

    $("#searchButton").click(function () {
        redirect("search", "query", $("#query").val(), "searchOption", $("input[name='searchOption']:checked").val());
    });

    $("#ontologyUL").on("click", "li a", function () {
        redirect("search", "query", $(this).data("word"), "searchOption", $("input[name='searchOption']:checked").val());
    });

    g_currentQuery = encodeURI(query);

    // invoke SearchVocabResource.java
    loadVocubulary(query);
    loadMetaData(shortname);
    loadHybirdRecomData(shortname);
});

function loadVocubulary(query) {
    $.ajax({
        url: "services/vocabulary/search",
        data: {
            "query": query
        },
        success: function completeHandler(response) {
            if (response != null && !jQuery.isEmptyObject(response)) {
                var ontologyResults = response.graph.ontology;
                if (ontologyResults.length == 0) {
                    $("#ontologyUL").append("
Did not find any results.
");
                } else {
                    for (var i = 0; i < ontologyResults.length; i++) {
                        $("#ontologyUL").append("
" + ontologyResults[i].word + " (" + ontologyResults[i].weight + ")
");
                    }
                }
            }
        }
    });
}

function loadHybirdRecomData(shortname) {
    if (shortname != "") {
        $("#dataset").show();
        $.ajax({
            url: "services/hrecommendation/search",
            data: {
                "shortname": shortname
            },
            success: function completeHandler(response) {
                if (response != null && !jQuery.isEmptyObject(response)) {
                    var recomdata = response.HybridRecommendationData;
                    var linked = recomdata.linked;
                    if (linked.length == 0) {
                        $("#hybirdul").append("
Did not find any results.
");
                    } else {

                        $.each(linked, function (i, item) {
                            console.log("hh");
                            var li = $("

");
                            $("#hybirdul").append(li);
                            //$("a",li).text(item.name  + "(" + item.weight + ")");
                            $("a", li).text(item.name);
                            $("a", li).attr("href", "./dataset.html?query=" + g_currentQuery + "&searchOption=" + g_currentSearchOption + "&shortname=" + item.name);
                        });
                    }
                }
            }
        });
    }
}

function loadMetaData(shortname) {
    if (shortname != "") {
        $("#dataset").show();
        $.ajax({
            url: "services/datasetdetail/search",
            data: {
                "shortname": shortname
            },
            success: function completeHandler(response) {
                if (response != null && !jQuery.isEmptyObject(response)) {
                    $("#searchLoading").hide();
                    var searchResults = response.PDResults;

                    console.log(searchResults);
                    if (searchResults.length == 0) {
                        $("#NotFound").show();
                    } else {
                        createResultTable();

                        $("#shortName").html(searchResults[0]["Short Name"]);
                        $('#ResultsTable').bootstrapTable('load', searchResults);
                    }
                }
            }
        });
    }
}

function urlFormatter(value, row) {
	var urls = value.split(",");
	var html = "";
	for (i = 0; i < urls.length; i++) {
	    html += '' + urls[i] + '' + "
";
	}
	return html;
}

function landingPageFormatter(value, row) {
	var html = "https://podaac.jpl.nasa.gov/dataset/";
	html = '' + html + value + '';
	return html;
}

function createResultTable() {
    var layout = {
        cache: false,
        cardView: true,
        columns: [{
            'title': 'Long Name',
            'field': 'Long Name',
        }, {
            'title': 'Doi',
            'field': 'Dataset-Doi',
        }, {
            'title': 'Topic',
            'field': 'Topic',
        }, {
            'title': 'Category',
            'field': 'DatasetParameter-Category',
        }, {
            'title': 'Variable',
            'field': 'DatasetParameter-Variable',
        }, {
            'title': 'Term',
            'field': 'DatasetParameter-Term',
        }, {
            'title': 'Version',
            'field': 'Version',
        }, {
            'title': 'Description',
            'field': 'Dataset-Description',
        }, {
            'title': 'Processing Level',
            'field': 'Processing Level',
        },{
            'title': 'Region',
            'field': 'Region',
        }, {
            'title': 'Coverage',
            'field': 'Coverage'
        }, {
            'title': 'Time Span',
            'field': 'Time Span',
        }, {
            'title': 'Spatial Resolution',
            'field': 'SpatiallResolution',
        }, {
            'title': 'Temporal Repeat',
            'field': 'TemporalResolution',
        }, {
            'title': 'Sensor',
            'field': 'DatasetSource-Sensor-ShortName',
        }, {
            'title': 'Project',
            'field': 'DatasetProject-Project-ShortName',
        }, {
            'title': 'Format',
            'field': 'DataFormat',
        }, {
            'title': 'Data Access',
            'field': 'DatasetLocationPolicy-BasePath',
            'formatter' : urlFormatter
        },
        {
            'title': 'Landing Page',
            'field': 'Short Name',
            'formatter' : landingPageFormatter
        }
        ]
    };

    $('#ResultsTable').bootstrapTable(layout);
}<|endoftext|>


<commit_before>Package.describe({
    summary: "Input autocompletion using data from Meteor collections",
  version: "0.1.4",
  git: "https://github.com/sebdah/meteor-autocompletion.git"
});

Package.on_use(function (api) {
  api.versionsFrom("METEOR@0.9.0");
    api.use("mrt:jquery-ui@1.9.2", 'client');

    api.export('AutoCompletion', 'client');

    api.add_files([
        'autocompletion.js',
        'css/jquery-ui-smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png',
        'css/jquery-ui-smoothness/images/ui-bg_flat_75_ffffff_40x100.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_65_ffffff_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_75_dadada_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_95_fef1ec_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png',
        'css/jquery-ui-smoothness/images/ui-icons_222222_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_2e83ff_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_454545_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_888888_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_cd0a0a_256x240.png',
        'css/jquery-ui-smoothness/jquery-ui-1.9.2.custom.css'
    ], 'client');

});
<commit_msg>Bumped version to 0.2.0<commit_after>Package.describe({
    summary: "Input autocompletion using data from Meteor collections",
  version: "0.2.0",
  git: "https://github.com/sebdah/meteor-autocompletion.git"
});

Package.on_use(function (api) {
  api.versionsFrom("METEOR@0.9.0");
    api.use("mrt:jquery-ui@1.9.2", 'client');

    api.export('AutoCompletion', 'client');

    api.add_files([
        'autocompletion.js',
        'css/jquery-ui-smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png',
        'css/jquery-ui-smoothness/images/ui-bg_flat_75_ffffff_40x100.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_65_ffffff_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_75_dadada_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_glass_95_fef1ec_1x400.png',
        'css/jquery-ui-smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png',
        'css/jquery-ui-smoothness/images/ui-icons_222222_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_2e83ff_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_454545_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_888888_256x240.png',
        'css/jquery-ui-smoothness/images/ui-icons_cd0a0a_256x240.png',
        'css/jquery-ui-smoothness/jquery-ui-1.9.2.custom.css'
    ], 'client');

});
<|endoftext|>


<commit_before>/*
* Raphael SVG Import Classic 0.1.0 - Extension to Raphael JS
* https://github.com/crccheck/raphael-svg-import-classic
*
* Copyright (c) 2009 Wout Fierens
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*
*/

/* global Raphael */
Raphael.fn.importSVG = function (svgXML) {
  var myNewSet = this.set();
  try {
    this.parseElement = function(elShape) {
      var attr = {"stroke": "transparent", "stroke-width": 0, "fill":"#000"}, i;
      if (elShape.attributes){
        for (i = elShape.attributes.length - 1; i >= 0; --i){
          attr[elShape.attributes[i].name] = elShape.attributes[i].value;
        }
      }
      var shape, style;
      var shapeName = elShape.nodeName;
      switch(shapeName) {
        case "svg":
        case "g":
          // pass the id to the first child, parse the children
          var groupId = elShape.getAttribute('id');
          if (groupId && elShape.childNodes.length) {
            elShape.childNodes.item(1).setAttribute('id', groupId);
          }
          for (i = 0; i < elShape.childNodes.length; ++i) {
            this.parseElement(elShape.childNodes.item(i));
          }
          return;
        case "rect":
          if (attr.rx && attr.ry) {
            attr.r = (+(attr.rx || 0) + +(attr.ry || 0)) / 2;
            delete attr.rx;
            delete attr.ry;
          } else {
            attr.r = attr.rx || attr.ry;
            delete attr.rx;
            delete attr.ry;
          }
        case "circle":
        case "ellipse":
          shape = this[shapeName]();
        break;
        case "path":
          shape = this.path(attr.d);
          delete attr.d;
        break;
        case "polygon":
          shape = this.polygon(attr);
        break;
        case "polyline":
          shape = this.polyline(attr);
        break;
        case "line":
          shape = this.line(attr);
        break;
        case "image":
          shape = this.image();
        break;
        case "text":
          shape = this.text(attr.x, attr.y, elShape.text || elShape.textContent);
          shape.attr("stroke","none");
          shape.origFontPt = parseInt(attr["font-size"], 10);
        break;
        default:
          return;
      }

      // apply matrix transformation
      var matrix = attr.transform;
      if (matrix) {
        matrix = matrix.substring(7, matrix.length-1).split(', ');
        shape.matrix(+matrix[0], +matrix[1], +matrix[2], +matrix[3]);
        shape.translate(matrix[4], matrix[5]);
        delete attr.transform;
      }

      shape.attr(attr);

      // assign an arbitrary id
      var nodeID = elShape.getAttribute("id");
      if (nodeID) {
        shape.node.id = nodeID;
      }

      myNewSet.push(shape);
      return shape;
    };

    var elSVG = svgXML.getElementsByTagName("svg")[0];
    elSVG.normalize();
    this.parseElement(elSVG);
  } catch (error) {
    throw "SVGParseError (" + error + ")";
  }

  return myNewSet;
};

Raphael.fn.line = function(attr){
  var pathString = ["M",
                    attr.x1,
                    attr.y1,
                    "L",
                    attr.x2,
                    attr.y2,
                    "Z"];
  delete attr.x1;
  delete attr.y1;
  delete attr.x2;
  delete attr.y2;
  return this.path(pathString);
}

// extending raphael with a polygon function
Raphael.fn.polygon = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  poly.push('Z');
  delete attr.points;
  return this.path(poly);
};

Raphael.fn.polyline = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  delete attr.points;
  return this.path(poly);
};
<commit_msg>if there are groups with IDs, attach them in a .groups property for future reference<commit_after>/*
* Raphael SVG Import Classic 0.1.0 - Extension to Raphael JS
* https://github.com/crccheck/raphael-svg-import-classic
*
* Copyright (c) 2009 Wout Fierens
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*
*/

/* global Raphael */
Raphael.fn.importSVG = function (svgXML) {
  var myNewSet = this.set();
  var groupSet = {};
  try {
    this.parseElement = function(elShape) {
      var attr = {"stroke": "transparent", "stroke-width": 0, "fill":"#000"}, i;
      if (elShape.attributes){
        for (i = elShape.attributes.length - 1; i >= 0; --i){
          attr[elShape.attributes[i].name] = elShape.attributes[i].value;
        }
      }
      var shape, style;
      var shapeName = elShape.nodeName;
      switch(shapeName) {
        case "svg":
        case "g":
          // pass the id to the first child, parse the children
          var groupId = elShape.getAttribute('id');
          if (groupId && elShape.childNodes.length) {
            elShape.childNodes.item(1).setAttribute('id', groupId);
            groupSet[groupId] = this.set();
          }
          for (i = 0; i < elShape.childNodes.length; ++i) {
            if (groupId) {
              groupSet[groupId].push(this.parseElement(elShape.childNodes.item(i)));
            } else {
              this.parseElement(elShape.childNodes.item(i));
            }
          }
          return;
        case "rect":
          if (attr.rx && attr.ry) {
            attr.r = (+(attr.rx || 0) + +(attr.ry || 0)) / 2;
            delete attr.rx;
            delete attr.ry;
          } else {
            attr.r = attr.rx || attr.ry;
            delete attr.rx;
            delete attr.ry;
          }
        case "circle":
        case "ellipse":
          shape = this[shapeName]();
        break;
        case "path":
          shape = this.path(attr.d);
          delete attr.d;
        break;
        case "polygon":
          shape = this.polygon(attr);
        break;
        case "polyline":
          shape = this.polyline(attr);
        break;
        case "line":
          shape = this.line(attr);
        break;
        case "image":
          shape = this.image();
        break;
        case "text":
          shape = this.text(attr.x, attr.y, elShape.text || elShape.textContent);
          shape.attr("stroke","none");
          shape.origFontPt = parseInt(attr["font-size"], 10);
        break;
        default:
          return;
      }

      // apply matrix transformation
      var matrix = attr.transform;
      if (matrix) {
        matrix = matrix.substring(7, matrix.length-1).split(', ');
        shape.matrix(+matrix[0], +matrix[1], +matrix[2], +matrix[3]);
        shape.translate(matrix[4], matrix[5]);
        delete attr.transform;
      }

      shape.attr(attr);

      // assign an arbitrary id
      var nodeID = elShape.getAttribute("id");
      if (nodeID) {
        shape.node.id = nodeID;
      }

      myNewSet.push(shape);
      return shape;
    };

    var elSVG = svgXML.getElementsByTagName("svg")[0];
    elSVG.normalize();
    this.parseElement(elSVG);
  } catch (error) {
    throw "SVGParseError (" + error + ")";
  }

  var groupsExist = false, x;
  for (x in groupSet){
    groupsExist = true;
    break;
  }
  if (groupsExist) {
    myNewSet.groups = groupSet;
  }
  return myNewSet;
};

Raphael.fn.line = function(attr){
  var pathString = ["M",
                    attr.x1,
                    attr.y1,
                    "L",
                    attr.x2,
                    attr.y2,
                    "Z"];
  delete attr.x1;
  delete attr.y1;
  delete attr.x2;
  delete attr.y2;
  return this.path(pathString);
}

// extending raphael with a polygon function
Raphael.fn.polygon = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  poly.push('Z');
  delete attr.points;
  return this.path(poly);
};

Raphael.fn.polyline = function(attr) {
  var pointString = attr.points;
  var poly = ['M'],
      point = pointString.split(' ');

  for(var i=0; i < point.length; i++) {
     var c = point[i].split(',');
     for(var j=0; j < c.length; j++) {
        var d = parseFloat(c[j]);
        if (!isNaN(d))
          poly.push(d);
     }
     if (i === 0)
      poly.push('L');
  }
  delete attr.points;
  return this.path(poly);
};
<|endoftext|>