<commit_before>import {expect} from 'chai';
import webdriverio from 'webdriverio';
import path from 'path';

const BROWSER_OPTIONS = {
  desiredCapabilities: {
    browserName: 'PhantomJS'
  }
};
const VIEWPORT_SIZE = {
  width: 1024,
  height: 768
};
const URL = 'file://' + path.join(__dirname, '..', '..', 'visual-report',
            'statics', 'index.html');

describe('Mocha Mugshot acceptace tests', function() {
  let client;

  before(function() {
    return client = webdriverio.remote(BROWSER_OPTIONS).init()
      .setViewportSize(VIEWPORT_SIZE)
      .url(URL);
  });

  it('should display the navigation bar', function() {
    client
        .isExisting('.navbar')
        .then(function(exists) {
          return expect(exists).to.be.true;
        });
  });

  it('should display the results', function() {
    client
        .isExisting('.results')
        .then(function(exists) {
          return expect(exists).to.be.true;
        });
  });

  it('should toggle the details when clicking on a test title', function() {
    client
        .click('.test-title:first')
        // gets the class atribute for all tests
        // but only the first one is toggled
        .getAttribute('.test', 'class')
        .then(function(testsClasses) {
          return expect(testsClasses[0]).to.contain('toggled');
        });
  });

  it('should display only the passed tests when clicking on Passed',
    function() {
      client
          .click('.passes')
          .getText('.test-state')
          .then(function(content) {
            return expect(content).to.not.contain('failed');
          });
    });

  it('should display only the failed tests when clicking on Failures',
    function() {
      client
          .click('.failures')
          .getText('.test-state')
          .then(function(content) {
            return expect(content).to.not.contain('passed');
          });
    });
});
<commit_msg>Correct spelling #21<commit_after>import {expect} from 'chai';
import webdriverio from 'webdriverio';
import path from 'path';

const BROWSER_OPTIONS = {
  desiredCapabilities: {
    browserName: 'PhantomJS'
  }
};
const VIEWPORT_SIZE = {
  width: 1024,
  height: 768
};
const URL = 'file://' + path.join(__dirname, '..', '..', 'visual-report',
            'statics', 'index.html');

describe('Mocha Mugshot acceptance tests', function() {
  let client;

  before(function() {
    return client = webdriverio.remote(BROWSER_OPTIONS).init()
      .setViewportSize(VIEWPORT_SIZE)
      .url(URL);
  });

  it('should display the navigation bar', function() {
    client
        .isExisting('.navbar')
        .then(function(exists) {
          return expect(exists).to.be.true;
        });
  });

  it('should display the results', function() {
    client
        .isExisting('.results')
        .then(function(exists) {
          return expect(exists).to.be.true;
        });
  });

  it('should toggle the details when clicking on a test title', function() {
    client
        .click('.test-title:first')
        // gets the class atribute for all tests
        // but only the first one is toggled
        .getAttribute('.test', 'class')
        .then(function(testsClasses) {
          return expect(testsClasses[0]).to.contain('toggled');
        });
  });

  it('should display only the passed tests when clicking on Passed',
    function() {
      client
          .click('.passes')
          .getText('.test-state')
          .then(function(content) {
            return expect(content).to.not.contain('failed');
          });
    });

  it('should display only the failed tests when clicking on Failures',
    function() {
      client
          .click('.failures')
          .getText('.test-state')
          .then(function(content) {
            return expect(content).to.not.contain('passed');
          });
    });
});
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there<commit_msg>Should work now<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there"<|endoftext|>


<commit_before>module.exports = [
    {
        label: 'Perusmerit ja kreikkalaiset aakkoset',
        characters: [
            { character: '°', popular: true },
            { character: '·', latexCommand: '\\cdot', popular: true },
            { character: '±', latexCommand: '\\pm', popular: true },
            { character: '∞', latexCommand: '\\infty', popular: true },
            { character: '²', latexCommand: '^2', popular: true },
            { character: '³', latexCommand: '^3', popular: true },
            { character: '½', latexCommand: '1/2', popular: true },
            { character: '⅓', latexCommand: '1/3', popular: true },
            { character: 'π', latexCommand: '\\pi', popular: true },
            { character: 'α', latexCommand: '\\alpha', popular: true },
            { character: 'β', latexCommand: '\\beta', popular: true  },
            { character: 'Γ', latexCommand: '\\Gamma' },
            { character: 'γ', latexCommand: '\\gamma' },
            { character: 'Δ', latexCommand: '\\Delta' },
            { character: 'δ', latexCommand: '\\delta' },
            { character: 'ε', latexCommand: '\\varepsilon' },
            { character: 'ζ', latexCommand: '\\zeta' },
            { character: 'η', latexCommand: '\\eta' },
            { character: 'Θ', latexCommand: '\\Theta' },
            { character: 'ϑ', latexCommand: '\\vartheta' },
            { character: '𝜄', latexCommand: '\\iota' },
            { character: 'κ', latexCommand: '\\kappa' },
            { character: 'Λ', latexCommand: '\\Lambda' },
            { character: 'λ', latexCommand: '\\lambda' },
            { character: 'µ', latexCommand: '\\mu' },
            { character: 'Ξ', latexCommand: '\\Xi' },
            { character: 'ξ', latexCommand: '\\xi' },
            { character: '∏', latexCommand: '\\Pi' },
            { character: 'ρ', latexCommand: '\\rho' },
            { character: '∑', latexCommand: '\\Sigma' },
            { character: 'σ', latexCommand: '\\sigma' },
            { character: 'τ', latexCommand: '\\tau' },
            { character: 'Υ', latexCommand: '\\Upsilon' },
            { character: 'υ', latexCommand: '\\upsilon' },
            { character: 'Φ', latexCommand: '\\Phi' },
            { character: 'Ф', latexCommand: '\\phi' },
            { character: 'χ', latexCommand: '\\chi' },
            { character: 'Ψ', latexCommand: '\\Psi' },
            { character: 'ψ', latexCommand: '\\psi' },
            { character: 'Ω', latexCommand: '\\Omega' },
            { character: 'ω', latexCommand: '\\omega' },
            { character: '∂', latexCommand: '\\partial' }
        ]
    },
    {
        label: 'Algebra',
        characters: [
            { character: '≠', latexCommand: '\\neq', popular: true },
            { character: '≈', latexCommand: '\\approx', popular: true },
            { character: '≤', latexCommand: '\\leq', popular: true },
            { character: '≥', latexCommand: '\\geq' },
            { character: '∼', latexCommand: '\\sim' },
            { character: '≡', latexCommand: '\\equiv' },
            { character: '≢' }, // \nequiv or \not\equiv
            { character: '∘', latexCommand: '\\circ' },
            { character: '…', latexCommand: '\\ldots' },
            { character: '|' }
        ]
    },
    {
        label: 'Geometria ja vektorioppi',
        characters: [
            { character: '∠', latexCommand: '\\angle', popular: true },
            { character: '→', latexCommand: '\\rightarrow', popular: true },
            { character: '⇅', popular: true  },
            { character: '↑', latexCommand: '\\uparrow' },
            { character: '↓', latexCommand: '\\downarrow' },
            { character: '↔', latexCommand: '\\leftrightarrow' },
            { character: '⊥', latexCommand: '\\perp'},
            { character: '‖', latexCommand: '\\parallel'},
            { character: '⇌' } // \rightleftharpoons
        ]
    },
    {
        label: 'Logiikka ja joukko-oppi',
        characters: [
            { character: '⇒', latexCommand: '\\Rightarrow', popular: true },
            { character: '⇔', latexCommand: '\\Leftrightarrow', popular: true },
            { character: '∃', latexCommand: '\\exists', popular: true },
            { character: '∀', latexCommand: '\\forall', popular: true },
            { character: 'ℝ', popular: true },
            { character: 'ℕ' },
            { character: 'ℤ' },
            { character: 'ℚ' },
            { character: '∩', latexCommand: '\\cap' },
            { character: '∪', latexCommand: '\\cup' },
            { character: '∖', latexCommand: '\\setminus' },
            { character: '⊂', latexCommand: '\\subset' },
            { character: '⊄', latexCommand: '\\notsubset' },
            { character: '∈', latexCommand: '\\in' },
            { character: '∉', latexCommand: '\\notin' },
            { character: '∅', latexCommand: '\\empty' },
            { character: '∧', latexCommand: '\\and' },
            { character: '∨', latexCommand: '\\or' },
            { character: '¬' }
        ]
    }
]
<commit_msg>Put | in correct column<commit_after>module.exports = [
    {
        label: 'Perusmerit ja kreikkalaiset aakkoset',
        characters: [
            { character: '°', popular: true },
            { character: '·', latexCommand: '\\cdot', popular: true },
            { character: '±', latexCommand: '\\pm', popular: true },
            { character: '∞', latexCommand: '\\infty', popular: true },
            { character: '²', latexCommand: '^2', popular: true },
            { character: '³', latexCommand: '^3', popular: true },
            { character: '½', latexCommand: '1/2', popular: true },
            { character: '⅓', latexCommand: '1/3', popular: true },
            { character: 'π', latexCommand: '\\pi', popular: true },
            { character: 'α', latexCommand: '\\alpha', popular: true },
            { character: 'β', latexCommand: '\\beta', popular: true  },
            { character: 'Γ', latexCommand: '\\Gamma' },
            { character: 'γ', latexCommand: '\\gamma' },
            { character: 'Δ', latexCommand: '\\Delta' },
            { character: 'δ', latexCommand: '\\delta' },
            { character: 'ε', latexCommand: '\\varepsilon' },
            { character: 'ζ', latexCommand: '\\zeta' },
            { character: 'η', latexCommand: '\\eta' },
            { character: 'Θ', latexCommand: '\\Theta' },
            { character: 'ϑ', latexCommand: '\\vartheta' },
            { character: '𝜄', latexCommand: '\\iota' },
            { character: 'κ', latexCommand: '\\kappa' },
            { character: 'Λ', latexCommand: '\\Lambda' },
            { character: 'λ', latexCommand: '\\lambda' },
            { character: 'µ', latexCommand: '\\mu' },
            { character: 'Ξ', latexCommand: '\\Xi' },
            { character: 'ξ', latexCommand: '\\xi' },
            { character: '∏', latexCommand: '\\Pi' },
            { character: 'ρ', latexCommand: '\\rho' },
            { character: '∑', latexCommand: '\\Sigma' },
            { character: 'σ', latexCommand: '\\sigma' },
            { character: 'τ', latexCommand: '\\tau' },
            { character: 'Υ', latexCommand: '\\Upsilon' },
            { character: 'υ', latexCommand: '\\upsilon' },
            { character: 'Φ', latexCommand: '\\Phi' },
            { character: 'Ф', latexCommand: '\\phi' },
            { character: 'χ', latexCommand: '\\chi' },
            { character: 'Ψ', latexCommand: '\\Psi' },
            { character: 'ψ', latexCommand: '\\psi' },
            { character: 'Ω', latexCommand: '\\Omega' },
            { character: 'ω', latexCommand: '\\omega' },
            { character: '∂', latexCommand: '\\partial' }
        ]
    },
    {
        label: 'Algebra',
        characters: [
            { character: '≠', latexCommand: '\\neq', popular: true },
            { character: '≈', latexCommand: '\\approx', popular: true },
            { character: '≤', latexCommand: '\\leq', popular: true },
            { character: '≥', latexCommand: '\\geq' },
            { character: '∼', latexCommand: '\\sim' },
            { character: '≡', latexCommand: '\\equiv' },
            { character: '≢' }, // \nequiv or \not\equiv
            { character: '∘', latexCommand: '\\circ' },
            { character: '…', latexCommand: '\\ldots' }
        ]
    },
    {
        label: 'Geometria ja vektorioppi',
        characters: [
            { character: '∠', latexCommand: '\\angle', popular: true },
            { character: '→', latexCommand: '\\rightarrow', popular: true },
            { character: '⇅', popular: true  },
            { character: '↑', latexCommand: '\\uparrow' },
            { character: '↓', latexCommand: '\\downarrow' },
            { character: '↔', latexCommand: '\\leftrightarrow' },
            { character: '⊥', latexCommand: '\\perp'},
            { character: '‖', latexCommand: '\\parallel'},
            { character: '⇌' }, // \rightleftharpoons
            { character: '|' } // \pipe
        ]
    },
    {
        label: 'Logiikka ja joukko-oppi',
        characters: [
            { character: '⇒', latexCommand: '\\Rightarrow', popular: true },
            { character: '⇔', latexCommand: '\\Leftrightarrow', popular: true },
            { character: '∃', latexCommand: '\\exists', popular: true },
            { character: '∀', latexCommand: '\\forall', popular: true },
            { character: 'ℝ', popular: true },
            { character: 'ℕ' },
            { character: 'ℤ' },
            { character: 'ℚ' },
            { character: '∩', latexCommand: '\\cap' },
            { character: '∪', latexCommand: '\\cup' },
            { character: '∖', latexCommand: '\\setminus' },
            { character: '⊂', latexCommand: '\\subset' },
            { character: '⊄', latexCommand: '\\notsubset' },
            { character: '∈', latexCommand: '\\in' },
            { character: '∉', latexCommand: '\\notin' },
            { character: '∅', latexCommand: '\\empty' },
            { character: '∧', latexCommand: '\\and' },
            { character: '∨', latexCommand: '\\or' },
            { character: '¬' }
        ]
    }
]
<|endoftext|>


<commit_before>$(function(){

	//these should correspond to name.xml files in the xml dir
	var subjectcampaigns = {
		"science" : ["OneDayTrash", "TrashType"],
		"math" : ["Nutrition"],
		"ecs" : ["Media", "Snack"]
	};

	//will be set automatically from login
	var teachername;
	var teacherorg;

	//downloads a campaign.xml file
	function campaignxml(campaign, handler){
		var filename = 'xml/' + campaign + ".xml";
		return $.ajax({
			url: filename,
			data: {},
			success: handler,
			dataType: "text"
		}).fail(function() {
			alert("Failed to download:" + filename);
		});
	}

	//repopulates GUI
	function populateclasses(class_urn){
		$("#inputClass").empty();
		$("#classtable tbody").empty();
		oh.user.info(function(res){
			var userdata = res.data[first(res.data)];
			$.each(userdata.classes, function(key, value){
				if(key.substr(0,15) == "urn:class:lausd"){
					$("#inputClass").append($("<option/>", {value: key, text:value}));
					var mytr = $("
").appendTo("#classtable tbody");
					td(value).appendTo(mytr);
					td(key).appendTo(mytr);

					var mybtn = $(' Select')
					.attr("href", "editclass.html?class=" + key)

					if(key == class_urn){
						mytr.addClass("success")
					}

					$("").append(mybtn).appendTo(mytr);
				}
			});
		});

		function first(obj) {
		    for (var a in obj) return a;
		}
	}

	$("#createbutton").on("click", function createclass(e){
		e.preventDefault();
		var school = teacherorg;
		var quarter = $("#inputQuarter").val();
		var period = $("#inputPeriod").val();
		var subject = $("#inputSubject").val();

		var class_urn = ("urn:class:lausd:" + quarter + ":" + school + ":"  + teachername + ":" + subject + ":" + period).toLowerCase();
		var class_name = toTitleCase(subject) + " " + period + " " + teachername + " " + quarter.replace(":", " ");
		var campaigns = subjectcampaigns[subject];

		//test if valid subject
		if(!campaigns){
			alert("No campaigns found for subject:", subject);
			return;
		}

		//test if campaign files exists
		var requests = [];
		var xmlstrings = {};
		$.each(campaigns, function(index, value) {
			requests.push(campaignxml(value, function(myxml){
				xmlstrings[value] = myxml;
			}));
		});

	    // all requests finished successfully
		$.when.apply($, requests).done(function() {
			oh.class.create(class_urn, class_name, function(){
				populateclasses(class_urn);
				$.each(campaigns, function(index, value) {
					var mycampaign = value;
					var myxml = xmlstrings[mycampaign];
					var campaign_urn = class_urn.replace("urn:class:lausd", "urn:campaign:lausd") + ":" + mycampaign.toLowerCase();
					var campaign_name = mycampaign + " " + period + " " + teachername + " " + quarter.replace(":", " ");

					oh.campaign.create(myxml, campaign_urn, campaign_name, class_urn, function(){
						console.log("Campaign created: " + campaign_urn)
					});
				});
			});
		});
	});

	$("#deletebutton").on("click", function deleteclass(e){
		e.preventDefault();

		var class_urn = $("#inputClass").val();
		if(!class_urn) {
			alert("No class selected to delete.");
			return
		}

		//confirm
		if(!confirm("Are you sure you want to delete class: " + class_urn + "?\n\nThis can not be undone!")){
			return
		};

		//delete class
		oh.class.delete(class_urn, function(){
			populateclasses();
		});

		//try to delete corresponding campaigns
		var subject = class_urn.replace("urn:class:lausd:", "").split(":")[4];
		console.log("Deleting campaigns for subject: " + subject);

		//lookup campaigns
		var campaigns = subjectcampaigns[subject];

		//delete some campaigns
		$.each(campaigns, function(index, value) {
			var mycampaign = value;
			var campaign_urn = class_urn.replace("urn:class:lausd", "urn:campaign:lausd") + ":" + mycampaign;
			oh.campaign.delete(campaign_urn, function(){
				console.log("Campaign deleted: " + campaign_urn)
			});
		});
	});

	function td(x){
		return($("").text(x));
	}

	function toTitleCase(str) {
	    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}

	//init page
	oh.ping(function(){
		oh.user.whoami(function(x){
			oh.user.read(x, function(data){
				var thisname = data[x].last_name;
				var thisorg = data[x].organization;

				if(!thisname){
					alert("ERROR: this account has no last name set. Please contact mobilize support.")
				}
				if(!thisorg){
					alert("ERROR: this account has no organization set. Please contact mobilize support.")
				}

				teachername = utf2ascii(thisname || "empty" );
				teacherorg = utf2ascii(thisorg || "empty" );

				oh.keepalive();
				populateclasses();
			});
		});
	});

	$("#signoutbutton").on("click", function(e){
		e.preventDefault();
		oh.logout(function(){
			location.reload(true);
		});
	});
});

<commit_msg>changed class delete warning msg<commit_after>$(function(){

	//these should correspond to name.xml files in the xml dir
	var subjectcampaigns = {
		"science" : ["OneDayTrash", "TrashType"],
		"math" : ["Nutrition"],
		"ecs" : ["Media", "Snack"]
	};

	//will be set automatically from login
	var teachername;
	var teacherorg;

	//downloads a campaign.xml file
	function campaignxml(campaign, handler){
		var filename = 'xml/' + campaign + ".xml";
		return $.ajax({
			url: filename,
			data: {},
			success: handler,
			dataType: "text"
		}).fail(function() {
			alert("Failed to download:" + filename);
		});
	}

	//repopulates GUI
	function populateclasses(class_urn){
		$("#inputClass").empty();
		$("#classtable tbody").empty();
		oh.user.info(function(res){
			var userdata = res.data[first(res.data)];
			$.each(userdata.classes, function(key, value){
				if(key.substr(0,15) == "urn:class:lausd"){
					$("#inputClass").append($("<option/>", {value: key, text:value}));
					var mytr = $("
").appendTo("#classtable tbody");
					td(value).appendTo(mytr);
					td(key).appendTo(mytr);

					var mybtn = $(' Select')
					.attr("href", "editclass.html?class=" + key)

					if(key == class_urn){
						mytr.addClass("success")
					}

					$("").append(mybtn).appendTo(mytr);
				}
			});
		});

		function first(obj) {
		    for (var a in obj) return a;
		}
	}

	$("#createbutton").on("click", function createclass(e){
		e.preventDefault();
		var school = teacherorg;
		var quarter = $("#inputQuarter").val();
		var period = $("#inputPeriod").val();
		var subject = $("#inputSubject").val();

		var class_urn = ("urn:class:lausd:" + quarter + ":" + school + ":"  + teachername + ":" + subject + ":" + period).toLowerCase();
		var class_name = toTitleCase(subject) + " " + period + " " + teachername + " " + quarter.replace(":", " ");
		var campaigns = subjectcampaigns[subject];

		//test if valid subject
		if(!campaigns){
			alert("No campaigns found for subject:", subject);
			return;
		}

		//test if campaign files exists
		var requests = [];
		var xmlstrings = {};
		$.each(campaigns, function(index, value) {
			requests.push(campaignxml(value, function(myxml){
				xmlstrings[value] = myxml;
			}));
		});

	    // all requests finished successfully
		$.when.apply($, requests).done(function() {
			oh.class.create(class_urn, class_name, function(){
				populateclasses(class_urn);
				$.each(campaigns, function(index, value) {
					var mycampaign = value;
					var myxml = xmlstrings[mycampaign];
					var campaign_urn = class_urn.replace("urn:class:lausd", "urn:campaign:lausd") + ":" + mycampaign.toLowerCase();
					var campaign_name = mycampaign + " " + period + " " + teachername + " " + quarter.replace(":", " ");

					oh.campaign.create(myxml, campaign_urn, campaign_name, class_urn, function(){
						console.log("Campaign created: " + campaign_urn)
					});
				});
			});
		});
	});

	$("#deletebutton").on("click", function deleteclass(e){
		e.preventDefault();

		var class_urn = $("#inputClass").val();
		var class_name = $("#inputClass").text();
		if(!class_urn) {
			alert("No class selected to delete.");
			return
		}

		//confirm
		if(!confirm("Are you sure you want to delete class: " + class_name + "?\n\nThis can not be undone!")){
			return
		};

		//delete class
		oh.class.delete(class_urn, function(){
			populateclasses();
		});

		//try to delete corresponding campaigns
		var subject = class_urn.replace("urn:class:lausd:", "").split(":")[4];
		console.log("Deleting campaigns for subject: " + subject);

		//lookup campaigns
		var campaigns = subjectcampaigns[subject];

		//delete some campaigns
		$.each(campaigns, function(index, value) {
			var mycampaign = value;
			var campaign_urn = class_urn.replace("urn:class:lausd", "urn:campaign:lausd") + ":" + mycampaign;
			oh.campaign.delete(campaign_urn, function(){
				console.log("Campaign deleted: " + campaign_urn)
			});
		});
	});

	function td(x){
		return($("").text(x));
	}

	function toTitleCase(str) {
	    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}

	//init page
	oh.ping(function(){
		oh.user.whoami(function(x){
			oh.user.read(x, function(data){
				var thisname = data[x].last_name;
				var thisorg = data[x].organization;

				if(!thisname){
					alert("ERROR: this account has no last name set. Please contact mobilize support.")
				}
				if(!thisorg){
					alert("ERROR: this account has no organization set. Please contact mobilize support.")
				}

				teachername = utf2ascii(thisname || "empty" );
				teacherorg = utf2ascii(thisorg || "empty" );

				oh.keepalive();
				populateclasses();
			});
		});
	});

	$("#signoutbutton").on("click", function(e){
		e.preventDefault();
		oh.logout(function(){
			location.reload(true);
		});
	});
});

<|endoftext|>


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

var args = require('optimist').argv;
var ircee = require('ircee');
var cp = require('child_process');
var net = require('net');
var through = require('through');

var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var path = require('path');

var Config = require('../lib/config.js');

var configFile = path.resolve(process.cwd(), args._[0] || 'config.yaml');

function connection(config) {
    var irc =  ircee(),
        self = new EventEmitter();

    irc.config = config;
    irc.use(require('ircee/core'));

    var instream = through(),
        outstream = through();

    irc.instream = instream;
    irc.outstream = outstream;

    var pings = 0;
    function connect() {
        pings = 0;
        var connectOpts = {
            port: config.port,
            host: config.server,
        };
        if (config.vhost)
            connectOpts.localAddress = config.vhost;
        var socket = net.connect(connectOpts);
        socket.pipe(instream, {end: false});
        outstream.pipe(socket, {end: false});
        socket.pipe(irc, {end: false}).pipe(socket);
        socket.on('error', function(err) {
            console.log("socket error:", err);
        });
        socket.on('timeout', function() {
            if (++pings > 1) socket.destroy();
            else irc.send('PING', new Date().getTime());
        });
        socket.setTimeout(90 * 1000);
        socket.on('close', function(err) {
            console.log("Connection closed, trying to reconnect");
            setTimeout(connect, irc.config.reconnectDelay * 1000 || 15000);
        });
    };
    irc.on('pong', function() { --pings; });

    connect();
    return irc;
}

function child(irc) {

    var ipcadr = '/tmp/triplie-' + process.pid + '.sock';

    var config = Config.load(args),
        self = {},
        socket = null,
        ipc = net.createServer(function(cli) {
            console.log("parent: child process connected");
            irc.instream.pipe(cli, {end: false});
            cli.pipe(irc.outstream, {end: false});
        }), child;

    child = run(config);

    ipc.listen(ipcadr);

    irc.on('connect', function() {
        function childReady(k) {
            if (child)
                try { return child.send({connection: true});
                } catch (e) {}
            if (k < 10)
                setTimeout(childReady.bind(null, k+1), 1000); // try again in 1s
        }
        childReady(0);
    });

    function run(config) {
        var child = cp.fork(__dirname + '/../lib/child.js');
        child.on('exit', function(c) {
            console.log("Child exit with status code", c);
            if (c) {
                setTimeout(reload, 3000);
            }
        });
        try {
            child.stdout.pipe(process.stdout);
            child.stderr.pipe(process.stderr);
        } catch (e) { }
        child.on('message', function(msg, handler) {
            if (msg.reload) reload();
            if (msg.save) Config.save(configFile, JSON.parse(msg.save));
        });
        child.send({init: true, config: config, ipc: ipcadr });
        return child;
    };

    function reload() {
        try { config = Config.load(args); } catch (e) {}
        irc.config = config;
        try { child.kill('SIGKILL'); }
        catch (e) {}
        child = run(config);
    }

}

child(connection(Config.load(args)));

<commit_msg>better logging for connection errors<commit_after>#!/usr/bin/env node

var args = require('optimist').argv;
var ircee = require('ircee');
var cp = require('child_process');
var net = require('net');
var through = require('through');

var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var path = require('path');

var Config = require('../lib/config.js');

var configFile = path.resolve(process.cwd(), args._[0] || 'config.yaml');

function connection(config) {
    var irc =  ircee(),
        self = new EventEmitter();

    irc.config = config;
    irc.use(require('ircee/core'));

    var instream = through(),
        outstream = through();

    irc.instream = instream;
    irc.outstream = outstream;

    var pings = 0;
    function connect() {
        pings = 0;
        var connectOpts = {
            port: config.port,
            host: config.server,
        };
        if (config.vhost)
            connectOpts.localAddress = config.vhost;
        var socket = net.connect(connectOpts);
        socket.pipe(instream, {end: false});
        outstream.pipe(socket, {end: false});
        socket.pipe(irc, {end: false}).pipe(socket);
        socket.on('error', function(err) {
            console.log("socket error:", err);
        });
        socket.on('timeout', function() {
            if (++pings > 1) socket.destroy();
            else irc.send('PING', new Date().getTime());
        });
        socket.setTimeout(90 * 1000);
        socket.on('close', function(err) {
            console.log("Connection closed with error", err);
            console.log("trying to reconnect...");
            setTimeout(connect, irc.config.reconnectDelay * 1000 || 15000);
        });
    };
    irc.on('pong', function() { --pings; });

    connect();
    return irc;
}

function child(irc) {

    var ipcadr = '/tmp/triplie-' + process.pid + '.sock';

    var config = Config.load(args),
        self = {},
        socket = null,
        ipc = net.createServer(function(cli) {
            console.log("parent: child process connected");
            irc.instream.pipe(cli, {end: false});
            cli.pipe(irc.outstream, {end: false});
        }), child;

    child = run(config);

    ipc.listen(ipcadr);

    irc.on('connect', function() {
        function childReady(k) {
            if (child)
                try { return child.send({connection: true});
                } catch (e) {}
            if (k < 10)
                setTimeout(childReady.bind(null, k+1), 1000); // try again in 1s
        }
        childReady(0);
    });

    function run(config) {
        var child = cp.fork(__dirname + '/../lib/child.js');
        child.on('exit', function(c) {
            console.log("Child exit with status code", c);
            if (c) {
                setTimeout(reload, 3000);
            }
        });
        try {
            child.stdout.pipe(process.stdout);
            child.stderr.pipe(process.stderr);
        } catch (e) { }
        child.on('message', function(msg, handler) {
            if (msg.reload) reload();
            if (msg.save) Config.save(configFile, JSON.parse(msg.save));
        });
        child.send({init: true, config: config, ipc: ipcadr });
        return child;
    };

    function reload() {
        try { config = Config.load(args); } catch (e) {}
        irc.config = config;
        try { child.kill('SIGKILL'); }
        catch (e) {}
        child = run(config);
    }

}

child(connection(Config.load(args)));

<|endoftext|>


<commit_before>// Trigger collection resolver
// Utility used by notifications and statusLog features

'use strict';

var isObject = require('es5-ext/object/is-object')
  , db       = require('mano').db
  , users    = require('../users');

module.exports = function (trigger, value) {
	if (trigger == null) throw new TypeError("No trigger found");
	if (typeof trigger === 'function') {
		if (db.BusinessProcess) {
			return db.BusinessProcess.filter(trigger);
		}
		return users.filter(trigger);
	}
	if (isObject(trigger)) return trigger;
	if (db.BusinessProcess) {
		return db.BusinessProcess.filterByKey(trigger, (value === undefined) ? true : value);
	}
	return users.filterByKey(trigger, (value === undefined) ? true : value);
};
<commit_msg>Improve BusinessProcess detection<commit_after>// Trigger collection resolver
// Utility used by notifications and statusLog features

'use strict';

var isObject = require('es5-ext/object/is-object')
  , db       = require('mano').db
  , users    = require('../users');

module.exports = function (trigger, value) {
	if (trigger == null) throw new TypeError("No trigger found");
	if (typeof trigger === 'function') {
		if (db.Object.isPrototypeOf(db.BusinessProcess)) return db.BusinessProcess.filter(trigger);
		return users.filter(trigger);
	}
	if (isObject(trigger)) return trigger;
	if (db.Object.isPrototypeOf(db.BusinessProcess)) {
		return db.BusinessProcess.filterByKey(trigger, (value === undefined) ? true : value);
	}
	return users.filterByKey(trigger, (value === undefined) ? true : value);
};
<|endoftext|>


<commit_before>const StatesService = nodeRequire('./src/services/states.js');
const ScreensService = nodeRequire('./src/services/screens.js');
const settings = nodeRequire('electron-settings');
//const Log = nodeRequire('./src/controllers/log.js');
const Trace = nodeRequire('./src/controllers/trace.js');
const ATM = nodeRequire('./src/controllers/atm.js');

//let log = new Log();
let trace = new Trace();
let atm = new ATM(settings, log);

let states = new StatesService(settings, log);
let screens = new ScreensService(settings, log);

var options = {
  edges: {
    smooth: {
      type: 'cubicBezier',
      forceDirection: 'horizontal',
      roundness: 0.4
    }
  },
  layout: {
    hierarchical: {
        direction: 'LR',
        levelSeparation: 160,
        nodeSpacing: 160
    }
  },
  physics: false,
};

nodes = states.getNodes();

nodes.forEach(node => {
  node['size'] = 160;
  node['color'] = 'silver';
  node['shape'] = 'box';
  node['font'] = {'size': '32', 'face': 'monospace', 'align': 'center'};
  node['heightConstraint'] = { minimum: 100 };
  node['widthConstraint'] = { minimum: 100 };
})

edges = states.getEdges()

edges.forEach( edge => {
  edge['arrows'] = 'to';
  edge['physics'] = false;
  edge['smooth'] = {'type': 'cubicBezier'};
});

var container = document.getElementById('mynetwork');
var data = {'nodes': nodes, 'edges': edges}
var graph = new vis.Network(container, data, options);

// Focus on state 000
graph.focus('000', {
  scale: 0.3,
  offset: {x:100, y:400}
});

$(function(){
  const mousetrap = nodeRequire('mousetrap');

  function updateState(state){
    if($.isEmptyObject(state))
      state = states.get('000');

    graph.focus(
      state.number,
      {
        scale: 0.3,
        offset: {x:400, y:300}
      }
    );  // Center
    graph.selectNodes([state.number,]);   // Select node

    updateScreen(screens.get(state.screen_number));
    updateStateDetails(state, states.getExtensionState(state));
    // updateOpcodeBuffer(state);
  };

  /**
   * [updateScreen description]
   * @param  {[type]} screen [description]
   * @return {[type]}        [description]
   */
  function updateScreen(screen){
    if(screen && screen.actions){
      screen.actions.forEach((element) => {
        if(element.display_image)
          $('#states-screen').attr('src', '/home/tim/share/screens/' + element.display_image);
      });
    }
  };

  /**
   * [updateStateDetails description]
   * @param  {[type]} state [description]
   * @return {[type]}       [description]
   */
  function updateStateDetails(state, extension_state){
    $('#state-details').html(trace.object(state));
    if(extension_state)
      $('#state-details').append(trace.object(extension_state));
  };

  /**
   * [updateOpcodeBuffer description]
   * @param  {[type]} state [description]
   * @return {[type]}       [description]
   */
  function updateOpcodeBuffer(state, extension_state){
    if(state && state.type === 'D'){
      atm.opcode.setBufferFromState(state, extension_state);
      $('#opcode-buffer').val(atm.opcode.getBuffer().split(' ').join('_'));
      $('#opcode-buffer').removeAttr('disabled');
    }else{
      $('#opcode-buffer').attr('disabled', true);
    }
  };

  $("#search-state-form").submit(function(e) {
    e.preventDefault();
    var state_number = $('#search-state-input').val();

    if(state_number.length == 2){
      state_number = '0' + state_number;
      $('#search-state-input').val(state_number)
    }
    else if (state_number.length === 1){
      state_number = '00' + state_number;
      $('#search-state-input').val(state_number)
    }

    updateState(states.get(state_number));
    $("#search-state-input").blur();
  });

  graph.on("click", function (params) {
    var node_id = this.getNodeAt(params.pointer.DOM);

    if(node_id){
      var state = states.get(node_id);

      updateScreen(screens.get(state.screen_number));
      updateStateDetails(state, states.getExtensionState(state));
      // graph.focus(state.number, {});  // Center

      // updateOpcodeBuffer(state);
    }
  });

  // cursor keys
  var cursorButtons = ['left', 'right', 'up', 'down'];
  cursorButtons.forEach( (element) => {
    mousetrap.bind(element, function() {
      var move_x = 0;
      var move_y = 0;

      switch(element){
        case 'left':
          move_x = -700;
          break;
        case 'right':
          move_x = 700;
          break;
        case 'up':
          move_y = -700;
          break;
        case 'down':
          move_y = 700;
          break;
      }

      var current_position = graph.getViewPosition();
      graph.moveTo({
        position: {
          'x': current_position.x + move_x,
          'y': current_position.y + move_y,
        },
        animation: {
          duration: 300,
          easingFunction: 'easeOutQuad'
        }
      });
    });
  });

  ipc.on('ui-change-current-state-on-states-page', (event, state) => {
    console.log(state);
    updateState(state);
  });

  // Set to 000 initially
  //updateState();
});
<commit_msg>Fixed centered state search<commit_after>const StatesService = nodeRequire('./src/services/states.js');
const ScreensService = nodeRequire('./src/services/screens.js');
const settings = nodeRequire('electron-settings');
//const Log = nodeRequire('./src/controllers/log.js');
const Trace = nodeRequire('./src/controllers/trace.js');
const ATM = nodeRequire('./src/controllers/atm.js');

//let log = new Log();
let trace = new Trace();
let atm = new ATM(settings, log);

let states = new StatesService(settings, log);
let screens = new ScreensService(settings, log);

var options = {
  edges: {
    smooth: {
      type: 'cubicBezier',
      forceDirection: 'horizontal',
      roundness: 0.4
    }
  },
  layout: {
    hierarchical: {
        direction: 'LR',
        levelSeparation: 160,
        nodeSpacing: 160
    }
  },
  physics: false,
};

nodes = states.getNodes();

nodes.forEach(node => {
  node['size'] = 160;
  node['color'] = 'silver';
  node['shape'] = 'box';
  node['font'] = {'size': '32', 'face': 'monospace', 'align': 'center'};
  node['heightConstraint'] = { minimum: 100 };
  node['widthConstraint'] = { minimum: 100 };
})

edges = states.getEdges()

edges.forEach( edge => {
  edge['arrows'] = 'to';
  edge['physics'] = false;
  edge['smooth'] = {'type': 'cubicBezier'};
});

var container = document.getElementById('mynetwork');
var data = {'nodes': nodes, 'edges': edges}
var graph = new vis.Network(container, data, options);

$(function(){
  const mousetrap = nodeRequire('mousetrap');

  function updateState(state){
    if($.isEmptyObject(state))
      state = states.get('000');

    graph.focus(
      state.number,
      {
        scale: 0.3,
        offset: {}
      }
    );  // Center
    graph.selectNodes([state.number,]);   // Select node

    updateScreen(screens.get(state.screen_number));
    updateStateDetails(state, states.getExtensionState(state));
    // updateOpcodeBuffer(state);
  };

  /**
   * [updateScreen description]
   * @param  {[type]} screen [description]
   * @return {[type]}        [description]
   */
  function updateScreen(screen){
    if(screen && screen.actions){
      screen.actions.forEach((element) => {
        if(element.display_image)
          $('#states-screen').attr('src', '/home/tim/share/screens/' + element.display_image);
      });
    }
  };

  /**
   * [updateStateDetails description]
   * @param  {[type]} state [description]
   * @return {[type]}       [description]
   */
  function updateStateDetails(state, extension_state){
    $('#state-details').html(trace.object(state));
    if(extension_state)
      $('#state-details').append(trace.object(extension_state));
  };

  /**
   * [updateOpcodeBuffer description]
   * @param  {[type]} state [description]
   * @return {[type]}       [description]
   */
  function updateOpcodeBuffer(state, extension_state){
    if(state && state.type === 'D'){
      atm.opcode.setBufferFromState(state, extension_state);
      $('#opcode-buffer').val(atm.opcode.getBuffer().split(' ').join('_'));
      $('#opcode-buffer').removeAttr('disabled');
    }else{
      $('#opcode-buffer').attr('disabled', true);
    }
  };

  $("#search-state-form").submit(function(e) {
    e.preventDefault();
    var state_number = $('#search-state-input').val();

    if(state_number.length == 2){
      state_number = '0' + state_number;
      $('#search-state-input').val(state_number)
    }
    else if (state_number.length === 1){
      state_number = '00' + state_number;
      $('#search-state-input').val(state_number)
    }

    updateState(states.get(state_number));
    $("#search-state-input").blur();
  });

  graph.on("click", function (params) {
    var node_id = this.getNodeAt(params.pointer.DOM);

    if(node_id){
      var state = states.get(node_id);

      updateScreen(screens.get(state.screen_number));
      updateStateDetails(state, states.getExtensionState(state));
      // graph.focus(state.number, {});  // Center

      // updateOpcodeBuffer(state);
    }
  });

  // cursor keys
  var cursorButtons = ['left', 'right', 'up', 'down'];
  cursorButtons.forEach( (element) => {
    mousetrap.bind(element, function() {
      var move_x = 0;
      var move_y = 0;

      switch(element){
        case 'left':
          move_x = -700;
          break;
        case 'right':
          move_x = 700;
          break;
        case 'up':
          move_y = -700;
          break;
        case 'down':
          move_y = 700;
          break;
      }

      var current_position = graph.getViewPosition();
      graph.moveTo({
        position: {
          'x': current_position.x + move_x,
          'y': current_position.y + move_y,
        },
        animation: {
          duration: 300,
          easingFunction: 'easeOutQuad'
        }
      });
    });
  });

  ipc.on('ui-change-current-state-on-states-page', (event, state) => {
    console.log(state);
    updateState(state);
  });

  // Set to 000 initially
  updateState();
});
<|endoftext|>


<commit_before>//the client needs an agent to connect to so that it may access consul services
//supply a host IP address
var shell = require('../lib/shell.js');
var uuid = require('node-uuid');
var logger = require('../lib/logger');

module.exports = function (app, io) {
	//connect to the consul agent
	//let the shell handle the websocket server
	shell.init(process.env.CLIENT_AGENT_IP, io, function () {
		//set up watches one time. listen forever for changes in consul's services
		shell.startWatches(process.env.POST_CONNECTION_ADDR);
	});

	//start core and hmi
	app.post('/v1/cores', jwtGetUserData, function (req, res) {
		//pretend we have some unique identifier for the client so that
		//we know which client wants what core
		logger.debug("/v1/cores");
		logger.debug(req.body);
		shell.requestCore(req.body.id, req.body);
		var response = shell.requestConnection(req.body.id);
		res.send(response);
	});

	//get logs from core
	app.post('/v1/logs', jwtGetUserData, function (req, res) {
		logger.debug("/v1/logs");
		logger.debug(req.body);
		shell.requestLogs(req.body.id);
		res.sendStatus(200);
	});

	//get a list of HMIs and their branches
	app.get('/v1/hmis', jwtGetUserData, function (req, res) {
		let hmis = {
			hmis: [
				{
					name: "generic",
					branches: ["master"]
				}
			]
		};
		res.json(hmis);
	});

	//given an HMI, get all valid core branches
	app.get('/v1/cores/:hmiName', jwtGetUserData, function (req, res) {
		//do something with req.params.hmiName
		let branches = {
			branches: [
				"master"
			]
		}
		res.json(branches);
	});

	//given a core branch, get all valid build configurations
	app.get('/v1/builds/:coreBranchName', jwtGetUserData, function (req, res) {
		//do something with req.params.coreBranchName
		let builds = {
			builds: [
				"TIME_TESTER",
				"BUILD_BT_SUPPORT"
			]
		}
		res.json(builds);
	});

	//delete a core passing in an id
	app.delete('/v1/cores/:id', jwtGetUserData, function (req, res) {
		//do something with req.params.id
		res.sendStatus(200);
	});
}

//if a JWT token is expected, extract the user data from the payload
function jwtGetUserData (req, res, next) {
	// check header or url parameters or post parameters for token
	if (process.env.JWT_SECRET) {
		var token = req.body.token || req.query.token || req.headers['x-access-token'];

		if (token) {
			//check the authenticity of the token using the shared secret
			jwt.verify(token, process.env.JWT_SECRET, function (err, data) {
				if (err) {
					res.status(401).send({ error: 'Authentication failure' }); //failed authentication
				} else {
					req.userData = data;
					logger.debug("AUTHENTICATION! PARSE TOKEN DATA:");
					logger.debug(JSON.stringify(data, null, 4));
					next();
				}
			});
		}
		else {
			res.status(401).send({ error: 'Authentication failure' }); //token doesn't even exist
		}
	}
	else { //no JWT secret shared. manticore isn't expected to verify anything
		next();
	}

}<commit_msg>Fix authorization issues<commit_after>//the client needs an agent to connect to so that it may access consul services
//supply a host IP address
var shell = require('../lib/shell.js');
var uuid = require('node-uuid');
var logger = require('../lib/logger');
var jwt = require('jsonwebtoken');

module.exports = function (app, io) {
	//connect to the consul agent
	//let the shell handle the websocket server
	shell.init(process.env.CLIENT_AGENT_IP, io, function () {
		//set up watches one time. listen forever for changes in consul's services
		shell.startWatches(process.env.POST_CONNECTION_ADDR);
	});

	//start core and hmi
	app.post('/v1/cores', function (req, res) {
		//pretend we have some unique identifier for the client so that
		//we know which client wants what core
		logger.debug("/v1/cores");
		logger.debug(req.body);
		logger.debug(JSON.stringify(req.user, null, 4));
		shell.requestCore(req.body.id, req.body);
		var response = shell.requestConnection(req.body.id);
		res.send(response);
	});

	//get logs from core
	app.post('/v1/logs', function (req, res) {
		logger.debug("/v1/logs");
		logger.debug(req.body);
		shell.requestLogs(req.body.id);
		res.sendStatus(200);
	});

	//get a list of HMIs and their branches
	app.get('/v1/hmis', function (req, res) {
		let hmis = {
			hmis: [
				{
					name: "generic",
					branches: ["master"]
				}
			]
		};
		res.json(hmis);
	});

	//given an HMI, get all valid core branches
	app.get('/v1/cores/:hmiName', function (req, res) {
		//do something with req.params.hmiName
		let branches = {
			branches: [
				"master"
			]
		}
		res.json(branches);
	});

	//given a core branch, get all valid build configurations
	app.get('/v1/builds/:coreBranchName', function (req, res) {
		//do something with req.params.coreBranchName
		let builds = {
			builds: [
				"TIME_TESTER",
				"BUILD_BT_SUPPORT"
			]
		}
		res.json(builds);
	});

	//delete a core passing in an id
	app.delete('/v1/cores/:id', function (req, res) {
		//do something with req.params.id
		res.sendStatus(200);
	});
}<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky pun<commit_msg>What do you mean you can't pack up the commit?<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme."<commit_msg>Can work my way through the Kanban<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",<|endoftext|>


<commit_before>'use strict';

// Protractor configuration
var config = {
  specs: ['modules/*/tests/e2e/*.js']
};

if (process.env.TRAVIS) {
  config.capabilities = {
    browserName: 'firefox'
  };
}

exports.config = config;
<commit_msg>using phantomjs for selenium tests<commit_after>'use strict';

// Protractor configuration
var config = {
  specs: ['modules/*/tests/e2e/*.js']
};

if (process.env.TRAVIS) {
  config.capabilities = {
    browserName: 'firefox'
  };
} else {
  config.capabilities = {
    browserName: 'chrome'
  };
}
config.capabilities = {
  browserName: 'phantomjs'
};
exports.config = config;
<|endoftext|>


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

var path      = require('path');
var fs        = require('fs');
var program   = require('commander');
var log       = console.log;

program
  .usage('[command] [options]')
  .version(require('../package.json').version)
  .on('--version', function(){
    return require('../package.json').version;
  })
  .on('--help', function(){
    log('  Examples:\n');
    log('    ' + [
      '# `electrify` without a command defaults to `electrify run`',
      '',
      'electrify',
      'electrify run',
      'electrify package',
      'electrify package -o /dist/dir',
      'electrify package -o /dist/dir -s file.json',
      'electrify package -i /app/dir -o /dist/dir -s dev.json',
      'electrify package -i /app/dir -o /dist/dir -s dev.json -c config.json'
    ].join('\n    ') + '\n');
  });

program
  .option('-i, --input    <path>', 'meteor app dir (default=.)')
  .option('-o, --output   <path>', 'output dir (default=.electrify/.dist)')
  .option('-c, --config   <path>', 'electrify config file (default=.electrify/electrify.json)')
  .option('-s, --settings <path>', 'meteor settings file (optional, default=null)');

program
  .command('run')
  .description('start meteor app within electrify context')
  .action(function(){
    electrify().app.run();
  });

program
  .command('bundle')
  .description('bundle everything as an electron project at `.electrify` dir')
  .action(function(){
    electrify().app.bundle(/* server_url */);
  });

program
  .command('package')
  .description('bundle and package `.electrify` electron app to `--output` dir')
  .action(function(){
    electrify().app.package(/* server_url */);
  });

program.parse(process.argv);

// default command = run
var cmd = process.argv[2];
if(process.argv.length == 2 || -1 == 'run|bundle|package'.indexOf(cmd))
  electrify().app.run();

// helpers
function electrify() {
  var input, error_msg, meteor_dir;

  // validates input dir (app-root folder)
  if(program.input && !fs.existsSync(program.input)) {
    error_msg = 'Input folder doesn\'t exist: ' + program.input;
    throw new Error(error_msg);
  }

  input = program.input || process.cwd();

  // validates meteor project
  meteor_dir = path.join(input, '.meteor');

  if(!fs.existsSync(meteor_dir)) {
    error_msg = 'Not a meteor app: ' + meteor_dir;
    throw new Error(error_msg);
  }

  if(program.output && !fs.existsSync(program.output)) {
    error_msg = 'Output folder doesn\'t exist: ' + program.output;
    throw new Error(error_msg);
  }

  var elec_mod = require('../lib');
  return elec_mod(input, program.output, program.config, meteor_settings());
}

function meteor_settings() {
  if(!program.settings) return {};

  var relative = path.join(process.cwd(), program.settings);
  var absolute = path.resolve(program.settings);
  var settings = (absolute == program.settings ? absolute : relative);

  if(!fs.existsSync(settings)) {
    log('settings file not found: ', relative);
    process.exit();
  }

  return require(settings);
}<commit_msg>improving docs<commit_after>#!/usr/bin/env node

var path      = require('path');
var fs        = require('fs');
var program   = require('commander');
var log       = console.log;

program
  .usage('[command] [options]')
  .version(require('../package.json').version)
  .on('--version', function(){
    return require('../package.json').version;
  })
  .on('--help', function(){
    log('  Examples:\n');
    log('    ' + [
      '# cd into meteor dir first',
      'cd /you/meteor/app',
      '',
      'electrify',
      'electrify run',
      'electrify package',
      'electrify package -o /dist/dir',
      'electrify package -o /dist/dir -s file.json',
      'electrify package -i /app/dir -o /dist/dir -s dev.json',
      'electrify package -i /app/dir -o /dist/dir -s dev.json -c config.json'
    ].join('\n    ') + '\n');
  });

program
  .option('-i, --input    <path>', 'meteor app dir         | default = .')
  .option('-o, --output   <path>', 'output dir             | default = .electrify/.dist')
  .option('-c, --config   <path>', 'electrify config file  | default = .electrify/electrify.json')
  .option('-s, --settings <path>', 'meteor settings file   | default = null (optional)');

program
  .command('run')
  .description('(default) start meteor app within electrify context, used for dev')
  .action(function(){
    electrify().app.run();
  });

program
  .command('bundle')
  .description('bundle meteor app into an electron project at `.electrify` dir')
  .action(function(){
    electrify().app.bundle(/* server_url */);
  });

program
  .command('package')
  .description('all in one, bundle + package `.electrify` electron app to `--output` dir')
  .action(function(){
    electrify().app.package(/* server_url */);
  });

program.parse(process.argv);

// default command = run
var cmd = process.argv[2];
if(process.argv.length == 2 || -1 == 'run|bundle|package'.indexOf(cmd))
  electrify().app.run();

// helpers
function electrify() {
  var input, error_msg, meteor_dir;

  // validates input dir (app-root folder)
  if(program.input && !fs.existsSync(program.input)) {
    error_msg = 'Input folder doesn\'t exist: ' + program.input;
    throw new Error(error_msg);
  }

  input = program.input || process.cwd();

  // validates meteor project
  meteor_dir = path.join(input, '.meteor');

  if(!fs.existsSync(meteor_dir)) {
    error_msg = 'Not a meteor app: ' + meteor_dir;
    throw new Error(error_msg);
  }

  if(program.output && !fs.existsSync(program.output)) {
    error_msg = 'Output folder doesn\'t exist: ' + program.output;
    throw new Error(error_msg);
  }

  var elec_mod = require('../lib');
  return elec_mod(input, program.output, program.config, meteor_settings());
}

function meteor_settings() {
  if(!program.settings) return {};

  var relative = path.join(process.cwd(), program.settings);
  var absolute = path.resolve(program.settings);
  var settings = (absolute == program.settings ? absolute : relative);

  if(!fs.existsSync(settings)) {
    log('settings file not found: ', relative);
    process.exit();
  }

  return require(settings);
}<|endoftext|>


<commit_before>var path                  = require("path");
var fs                    = require("fs");
var underscore            = require("underscore");
var AsyncCollectionRunner = require("async_collection_runner");
var config                = require(path.join(__dirname, "..", "..", "config"));
var Spotbox               = require(path.join(config.root, "app", "lib", "spotbox"));
var Spotify               = require(path.join(config.root, "app", "lib", "spotify"));
var PlaylistManager       = require(path.join(config.root, "app", "lib", "playlist_manager"));

var properties = {
  state: "stopped",
  track: null,
  queue: [],
  recent: [],
  progress: "0",
};

var event_hollabacks = {
  state: [],
  track: [],
  queue: [],
  recent: [],
  progress: [],
};

function set_property(key, new_value) {
  if (!underscore.isUndefined(properties[key])) {
    if (properties[key] !== new_value) {
      properties[key] = new_value;
      trigger(key);
    }
  }
};

function trigger(key) {
  underscore.each(event_hollabacks[key], function(hollaback) {
    underscore.defer(function() {
      hollaback(underscore.clone(properties));
    });
  });
};

function play(uri) {
  config.pub_socket.send(Spotbox.namespace("players:spotify::play::" + uri));
  PlaylistManager.remove_track(uri);
  Player.add_to_recent(uri);
}

function play_next() {
  if (properties.queue.length > 0) {
    uri = properties.queue.shift();
    trigger("queue");
    play(uri);
  } else {
    PlaylistManager.random(function(error, uri) {
      if (error) {
        console.log(error);
      } else {
        play(uri);
      }
    });
  }
};

var Player = function() {};

Player.on = function(key, hollaback) {
  event_hollabacks[key].push(hollaback);
};

Player.play = function(uri) {
  if (properties.state === "paused") {
    config.pub_socket.send(Spotbox.namespace("players:spotify::unpause"));
  } else {
    if (uri) {
      play(uri);
    } else {
      play_next();
    }
  }
};

Player.stop = function() {
  config.pub_socket.send(Spotbox.namespace("players:spotify::stop"));
};

Player.pause = function() {
  config.pub_socket.send(Spotbox.namespace("players:spotify::pause"));
};

Player.set_state = function(state) {
  set_property("state", state);
};

Player.get_state = function(hollaback) {
  hollaback(null, { state: properties.state });
};

Player.add_to_queue = function(uri) {
  properties.queue.push(uri);
  trigger("queue");
};

Player.remove_from_queue = function(uri) {
  set_property("queue", underscore.filter(properties.queue, function(track) {
    return track !== uri
  }));
};

Player.get_queue = function(hollaback) {
  new AsyncCollectionRunner(properties.queue, Spotify.retrieve).run(hollaback);
};

Player.add_to_recent = function(uri) {
  properties.recent.push(uri);
  trigger("recent");
};

Player.get_recent = function(hollaback) {
  new AsyncCollectionRunner(properties.recent, Spotify.retrieve).run(hollaback);
};

Player.set_track = function(uri) {
  set_property("track", uri);
};

Player.get_track = function(hollaback) {
  if (properties.track) {
    Spotify.retrieve(properties.track, hollaback);
  }
};

Player.set_progress = function(progress) {
  set_property("progress", progress);
};

module.exports = Player;
<commit_msg>Limit recent tracks size<commit_after>var path                  = require("path");
var fs                    = require("fs");
var underscore            = require("underscore");
var AsyncCollectionRunner = require("async_collection_runner");
var config                = require(path.join(__dirname, "..", "..", "config"));
var Spotbox               = require(path.join(config.root, "app", "lib", "spotbox"));
var Spotify               = require(path.join(config.root, "app", "lib", "spotify"));
var PlaylistManager       = require(path.join(config.root, "app", "lib", "playlist_manager"));

var RECENT_TRACK_SIZE = 25;

var properties = {
  state: "stopped",
  track: null,
  queue: [],
  recent: [],
  progress: "0",
};

var event_hollabacks = {
  state: [],
  track: [],
  queue: [],
  recent: [],
  progress: [],
};

function set_property(key, new_value) {
  if (!underscore.isUndefined(properties[key])) {
    if (properties[key] !== new_value) {
      properties[key] = new_value;
      trigger(key);
    }
  }
};

function trigger(key) {
  underscore.each(event_hollabacks[key], function(hollaback) {
    underscore.defer(function() {
      hollaback(underscore.clone(properties));
    });
  });
};

function play(uri) {
  config.pub_socket.send(Spotbox.namespace("players:spotify::play::" + uri));
  PlaylistManager.remove_track(uri);
  Player.add_to_recent(uri);
}

function play_next() {
  if (properties.queue.length > 0) {
    uri = properties.queue.shift();
    trigger("queue");
    play(uri);
  } else {
    PlaylistManager.random(function(error, uri) {
      if (error) {
        console.log(error);
      } else {
        play(uri);
      }
    });
  }
};

var Player = function() {};

Player.on = function(key, hollaback) {
  event_hollabacks[key].push(hollaback);
};

Player.play = function(uri) {
  if (properties.state === "paused") {
    config.pub_socket.send(Spotbox.namespace("players:spotify::unpause"));
  } else {
    if (uri) {
      play(uri);
    } else {
      play_next();
    }
  }
};

Player.stop = function() {
  config.pub_socket.send(Spotbox.namespace("players:spotify::stop"));
};

Player.pause = function() {
  config.pub_socket.send(Spotbox.namespace("players:spotify::pause"));
};

Player.set_state = function(state) {
  set_property("state", state);
};

Player.get_state = function(hollaback) {
  hollaback(null, { state: properties.state });
};

Player.add_to_queue = function(uri) {
  properties.queue.push(uri);
  trigger("queue");
};

Player.remove_from_queue = function(uri) {
  set_property("queue", underscore.filter(properties.queue, function(track) {
    return track !== uri
  }));
};

Player.get_queue = function(hollaback) {
  new AsyncCollectionRunner(properties.queue, Spotify.retrieve).run(hollaback);
};

Player.add_to_recent = function(uri) {
  properties.recent.push(uri);
  while (properties.recent.length > RECENT_TRACK_SIZE) {
    properties.recent.shift();
  }
  trigger("recent");
};

Player.get_recent = function(hollaback) {
  new AsyncCollectionRunner(properties.recent, Spotify.retrieve).run(hollaback);
};

Player.set_track = function(uri) {
  set_property("track", uri);
};

Player.get_track = function(hollaback) {
  if (properties.track) {
    Spotify.retrieve(properties.track, hollaback);
  }
};

Player.set_progress = function(progress) {
  set_property("progress", progress);
};

module.exports = Player;
<|endoftext|>


<commit_before>// dynamically edit nodes

const rmElement = require('../helpers/rmElement.js')

/**
 * creates a form to edit the node
 *
 * @param {Object} selectedNode selected node
 */
const createForm = selectedNode => {
  const htmlElement = document.getElementById('message-area-id')
  const form = document.createElement('form')
  form.className = 'bubble'
  form.id = 'form-id'

  let label = ''
  let input = ''
  let inputIds = []

  const nodeData = selectedNode.data().asto
  Object.keys(nodeData).map(key => {
    // device layer attribute
    // TODO refactor
    if (key === 'layer') {
      label = document.createElement('label')
      label.setAttribute('for', key)
      label.textContent = 'layer:'

      const layerOptions = ['perception', 'gateway', 'application']
      const layerList = document.createElement('select')
      layerList.className = 'input-form'
      layerList.id = key

      const keyToFind = nodeData[key]
      const index = layerOptions.indexOf(keyToFind)

      form.appendChild(label)
      form.appendChild(layerList)
      layerOptions.map(value => {
        let option = document.createElement('option')
        option.value = value
        option.text = value
        layerList.appendChild(option)
      })
      // set the value the stored selection
      layerList.selectedIndex = index
      // store the keys to later render them dynamically
      inputIds.push(key)
    } else if (key === 'input') {
      label = document.createElement('label')
      label.setAttribute('for', key)
      label.textContent = 'input:'

      const layerOptions = [
        'dataDigital',
        'dataEnvironmental',
        'command',
        'action',
        'notification',
        'trigger'
      ]
      const layerList = document.createElement('select')
      layerList.className = 'input-form'
      layerList.id = key

      const keyToFind = nodeData[key]
      const index = layerOptions.indexOf(keyToFind)

      form.appendChild(label)
      form.appendChild(layerList)
      layerOptions.map(value => {
        let option = document.createElement('option')
        option.value = value
        option.text = value
        layerList.appendChild(option)
      })
      // set the value the stored selection
      layerList.selectedIndex = index
      // store the keys to later render them dynamically
      inputIds.push(key)
    } else if (key !== 'concept') {
      // won't display the concept attribute
      label = document.createElement('label')
      input = document.createElement('input')
      input.className = 'input-form'
      // create an key-based id
      // to iterate on the submitted attributes
      input.id = key
      input.type = 'text'
      input.name = 'nodeValue'
      input.value = nodeData[key]

      label.setAttribute('for', key)
      label.textContent = `${key}: `
      form.appendChild(label)
      form.appendChild(input)
      // store the keys to later render them dynamically
      inputIds.push(key)
    }
  })

  // create a submit button
  const submit = document.createElement('input')
  submit.className = 'submit-form'
  submit.type = 'submit'
  submit.value = 'Submit'
  form.appendChild(submit)
  htmlElement.appendChild(form)

  const formId = document.getElementById('form-id')
  // capture the changed values of the node
  formId.onsubmit = () => {
    inputIds.map(keyValue => {
      let id = document.getElementById(keyValue)
      selectedNode.data().asto[keyValue] = id.value
    })
    // remove elements once the submit is clicked
    rmElement('message-area-id', 'form-id')
    // return false to prevent the default form behavior
    return false
  }

  // focus on the description attribute of the form
  document.getElementById('description').focus()
}

/**
 * add/remove the form element
 *
 * @param {Object} selectedNode selected node
 */
const formNode = selectedNode => {
  const form = document.getElementById('form-id')
  if (form !== null) {
    rmElement('message-area-id', 'form-id')
    createForm(selectedNode)
  } else if (form === null) {
    createForm(selectedNode)
  }
}

module.exports = {
  formNode
}
<commit_msg>:hammer: refactor enumerated value selection<commit_after>// dynamically edit nodes

const rmElement = require('../helpers/rmElement.js')

// options of the enumerated selections
const layerOptions = ['perception', 'gateway', 'application']
const inOutOptions = [
  'dataDigital',
  'dataEnvironmental',
  'command',
  'action',
  'notification',
  'trigger'
]

/**
 * creates dynamic selections for enumerated values
 *
 * @param {string} selectionForm form div element (= form)
 * @param {string} selectionKey iterator of node element
 * @param {Array} selectionOptions options of the enumerated selections
 * @param {Object} data node element data (= nodeData)
 * @param {Array} ids id div element (= inputIds)
 */
const selectionLayout = (
  selectionForm,
  selectionKey,
  selectionOptions,
  data,
  ids
) => {
  const selectionLabel = document.createElement('label')
  selectionLabel.setAttribute('for', selectionKey)
  selectionLabel.textContent = 'layer:'

  const selectionList = document.createElement('select')
  selectionList.className = 'input-form'
  selectionList.id = selectionKey

  const keyToFind = data[selectionKey]
  const index = selectionOptions.indexOf(keyToFind)

  selectionForm.appendChild(selectionLabel)
  selectionForm.appendChild(selectionList)
  selectionOptions.map(value => {
    let option = document.createElement('option')
    option.value = value
    option.text = value
    selectionList.appendChild(option)
  })
  // set the value the stored selection
  selectionList.selectedIndex = index
  // store the keys to later render them dynamically
  ids.push(selectionKey)
}

/**
 * creates a form to edit the node
 *
 * @param {Object} selectedNode selected node
 */
const createForm = selectedNode => {
  const htmlElement = document.getElementById('message-area-id')
  const form = document.createElement('form')
  form.className = 'bubble'
  form.id = 'form-id'

  let inputIds = []

  const nodeData = selectedNode.data().asto
  Object.keys(nodeData).map(key => {
    if (key === 'layer') {
      // device layer attribute
      selectionLayout(form, key, layerOptions, nodeData, inputIds)
    } else if (key === 'input' || key === 'output') {
      // device input/output
      selectionLayout(form, key, inOutOptions, nodeData, inputIds)
    } else if (key !== 'concept') {
      // won't display the concept attribute
      const label = document.createElement('label')
      const input = document.createElement('input')
      input.className = 'input-form'
      // create an key-based id
      // to iterate on the submitted attributes
      input.id = key
      input.type = 'text'
      input.name = 'nodeValue'
      input.value = nodeData[key]

      label.setAttribute('for', key)
      label.textContent = `${key}: `
      form.appendChild(label)
      form.appendChild(input)
      // store the keys to later render them dynamically
      inputIds.push(key)
    }
  })

  // create a submit button
  const submit = document.createElement('input')
  submit.className = 'submit-form'
  submit.type = 'submit'
  submit.value = 'Submit'
  form.appendChild(submit)
  htmlElement.appendChild(form)

  // capture the changed values of the node
  const formId = document.getElementById('form-id')
  formId.onsubmit = () => {
    inputIds.map(keyValue => {
      let id = document.getElementById(keyValue)
      selectedNode.data().asto[keyValue] = id.value
    })
    // remove elements once the submit is clicked
    rmElement('message-area-id', 'form-id')
    // return false to prevent the default form behavior
    return false
  }

  // focus on the description attribute of the form
  document.getElementById('description').focus()
}

/**
 * add/remove the form element
 *
 * @param {Object} selectedNode selected node
 */
const formNode = selectedNode => {
  const form = document.getElementById('form-id')
  if (form !== null) {
    rmElement('message-area-id', 'form-id')
    createForm(selectedNode)
  } else if (form === null) {
    createForm(selectedNode)
  }
}

module.exports = {
  formNode
}
<|endoftext|>


<commit_before>import Promise from 'core-js-pure/es/promise';
import ITERATOR from 'core-js-pure/full/symbol/iterator';
import ASYNC_ITERATOR from 'core-js-pure/full/symbol/async-iterator';

export function is(a, b) {
  // eslint-disable-next-line no-self-compare -- NaN check
  return a === b ? a !== 0 || 1 / a === 1 / b : a != a && b != b;
}

export function createIterator(elements, methods) {
  let index = 0;
  const iterator = {
    called: false,
    next() {
      iterator.called = true;
      return {
        value: elements[index++],
        done: index > elements.length,
      };
    },
  };
  if (methods) for (const key in methods) iterator[key] = methods[key];
  return iterator;
}

export function createIterable(elements, methods) {
  const iterable = {
    called: false,
    received: false,
    [ITERATOR]() {
      iterable.received = true;
      let index = 0;
      const iterator = {
        next() {
          iterable.called = true;
          return {
            value: elements[index++],
            done: index > elements.length,
          };
        },
      };
      if (methods) for (const key in methods) iterator[key] = methods[key];
      return iterator;
    },
  };
  return iterable;
}

export function createAsyncIterable(elements, methods) {
  const iterable = {
    called: false,
    received: false,
    [ASYNC_ITERATOR]() {
      iterable.received = true;
      let index = 0;
      const iterator = {
        next() {
          iterable.called = true;
          return Promise.resolve({
            value: elements[index++],
            done: index > elements.length,
          });
        },
      };
      if (methods) for (const key in methods) iterator[key] = methods[key];
      return iterator;
    },
  };
  return iterable;
}

export function arrayFromArrayLike(source) {
  const { length } = source;
  const result = Array(length);
  for (let index = 0; index < length; index++) {
    result[index] = source[index];
  } return result;
}

export function includes(target, wanted) {
  for (const element of target) if (wanted === element) return true;
  return false;
}

export const nativeSubclass = (() => {
  try {
    if (Function(`
      'use strict';
      class Subclass extends Object { /* empty */ };
      return new Subclass() instanceof Subclass;
    `)()) return Function('Parent', `
      'use strict';
      return class extends Parent { /* empty */ };
    `);
  } catch { /* empty */ }
})();

export function timeLimitedPromise(time, fn) {
  return Promise.race([
    new Promise(fn), new Promise((resolve, reject) => {
      setTimeout(reject, time);
    }),
  ]);
}

// This function is used to force RegExp.prototype[Symbol.*] methods
// to not use the native implementation.
export function patchRegExp$exec(run) {
  return assert => {
    const originalExec = RegExp.prototype.exec;
    // eslint-disable-next-line no-extend-native -- required for testing
    RegExp.prototype.exec = function () {
      return originalExec.apply(this, arguments);
    };
    try {
      return run(assert);
    // eslint-disable-next-line no-useless-catch -- in very old IE try / finally does not work without catch
    } catch (error) {
      throw error;
    } finally {
      // eslint-disable-next-line no-extend-native -- required for testing
      RegExp.prototype.exec = originalExec;
    }
  };
}

export function fromSource(source) {
  try {
    return Function(`return ${ source }`)();
  } catch { /* empty */ }
}
<commit_msg>use one namespace for consistency<commit_after>import Promise from 'core-js-pure/es/promise';
import ITERATOR from 'core-js-pure/es/symbol/iterator';
import ASYNC_ITERATOR from 'core-js-pure/es/symbol/async-iterator';

export function is(a, b) {
  // eslint-disable-next-line no-self-compare -- NaN check
  return a === b ? a !== 0 || 1 / a === 1 / b : a != a && b != b;
}

export function createIterator(elements, methods) {
  let index = 0;
  const iterator = {
    called: false,
    next() {
      iterator.called = true;
      return {
        value: elements[index++],
        done: index > elements.length,
      };
    },
  };
  if (methods) for (const key in methods) iterator[key] = methods[key];
  return iterator;
}

export function createIterable(elements, methods) {
  const iterable = {
    called: false,
    received: false,
    [ITERATOR]() {
      iterable.received = true;
      let index = 0;
      const iterator = {
        next() {
          iterable.called = true;
          return {
            value: elements[index++],
            done: index > elements.length,
          };
        },
      };
      if (methods) for (const key in methods) iterator[key] = methods[key];
      return iterator;
    },
  };
  return iterable;
}

export function createAsyncIterable(elements, methods) {
  const iterable = {
    called: false,
    received: false,
    [ASYNC_ITERATOR]() {
      iterable.received = true;
      let index = 0;
      const iterator = {
        next() {
          iterable.called = true;
          return Promise.resolve({
            value: elements[index++],
            done: index > elements.length,
          });
        },
      };
      if (methods) for (const key in methods) iterator[key] = methods[key];
      return iterator;
    },
  };
  return iterable;
}

export function arrayFromArrayLike(source) {
  const { length } = source;
  const result = Array(length);
  for (let index = 0; index < length; index++) {
    result[index] = source[index];
  } return result;
}

export function includes(target, wanted) {
  for (const element of target) if (wanted === element) return true;
  return false;
}

export const nativeSubclass = (() => {
  try {
    if (Function(`
      'use strict';
      class Subclass extends Object { /* empty */ };
      return new Subclass() instanceof Subclass;
    `)()) return Function('Parent', `
      'use strict';
      return class extends Parent { /* empty */ };
    `);
  } catch { /* empty */ }
})();

export function timeLimitedPromise(time, fn) {
  return Promise.race([
    new Promise(fn), new Promise((resolve, reject) => {
      setTimeout(reject, time);
    }),
  ]);
}

// This function is used to force RegExp.prototype[Symbol.*] methods
// to not use the native implementation.
export function patchRegExp$exec(run) {
  return assert => {
    const originalExec = RegExp.prototype.exec;
    // eslint-disable-next-line no-extend-native -- required for testing
    RegExp.prototype.exec = function () {
      return originalExec.apply(this, arguments);
    };
    try {
      return run(assert);
    // eslint-disable-next-line no-useless-catch -- in very old IE try / finally does not work without catch
    } catch (error) {
      throw error;
    } finally {
      // eslint-disable-next-line no-extend-native -- required for testing
      RegExp.prototype.exec = originalExec;
    }
  };
}

export function fromSource(source) {
  try {
    return Function(`return ${ source }`)();
  } catch { /* empty */ }
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

<commit_msg>Fixing an important issue with the universe.<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

p<|endoftext|>


<commit_before>import webpack from 'webpack';
import config  from '../../config';

const paths   = config.get('utils_paths'),
      globals = config.get('globals');

const webpackConfig = {
  name    : 'server',
  target  : 'node',
  entry   : {
    app : [
      paths.src('entry-points/server')
    ]
  },
  output : {
    filename : 'index.js',
    path     : paths.dist('server'),
    libraryTarget : 'commonjs2'
  },
  plugins : [
    new webpack.DefinePlugin(Object.assign(config.get('globals'), {
      __SERVER__ : true
    })),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin()
  ],
  resolve : {
    extensions : ['', '.js', '.jsx'],
    alias : config.get('utils_aliases')
  },
  module : {
    preLoaders : [
      {
        test : /\.(js|jsx)$/,
        loaders : ['eslint-loader'],
        include : paths.project(config.get('dir_src'))
      }
    ],
    loaders : [
      {
        test    : /\.(js|jsx)$/,
        include :  paths.project(config.get('dir_src')),
        loaders : ['babel?optional[]=runtime&stage=0']
      },
      {
        test    : /\.scss$/,
        loaders : [
          'css/locals?module&localIdentName=[name]__[local]___[hash:base64:5]',
          'sass-loader?includePaths[]=' + paths.src('styles')
        ]
      }
    ]
  },
  eslint : {
    configFile  : paths.project('.eslintrc'),
    failOnError : globals.__PROD__
  }
};

// ----------------------------------
// Environment-Specific Defaults
// ----------------------------------
if (globals.__PROD__) {
  webpackConfig.plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      output : {
        'comments'  : false
      },
      compress : {
        'unused'    : true,
        'dead_code' : true
      }
    })
  );
}

export default webpackConfig;
<commit_msg>fix(webpack): specify npm externals in server bundle to reduce bundle size<commit_after>import webpack from 'webpack';
import config  from '../../config';

const paths   = config.get('utils_paths'),
      globals = config.get('globals');

const webpackConfig = {
  name    : 'server',
  target  : 'node',
  entry   : {
    app : [
      paths.src('entry-points/server')
    ]
  },
  // Don't include npm packages since these can be imported at runtime
  // from the Koa application.
  externals : fs.readdirSync('node_modules').filter(x => x !== '.bin'),
  output : {
    filename : 'index.js',
    path     : paths.dist('server'),
    libraryTarget : 'commonjs2'
  },
  plugins : [
    new webpack.DefinePlugin(Object.assign(config.get('globals'), {
      __SERVER__ : true
    })),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin()
  ],
  resolve : {
    extensions : ['', '.js', '.jsx'],
    alias : config.get('utils_aliases')
  },
  module : {
    preLoaders : [
      {
        test : /\.(js|jsx)$/,
        loaders : ['eslint-loader'],
        include : paths.project(config.get('dir_src'))
      }
    ],
    loaders : [
      {
        test    : /\.(js|jsx)$/,
        include :  paths.project(config.get('dir_src')),
        loaders : ['babel?optional[]=runtime&stage=0']
      },
      {
        test    : /\.scss$/,
        loaders : [
          'css/locals?module&localIdentName=[name]__[local]___[hash:base64:5]',
          'sass-loader?includePaths[]=' + paths.src('styles')
        ]
      }
    ]
  },
  eslint : {
    configFile  : paths.project('.eslintrc'),
    failOnError : globals.__PROD__
  }
};

// ----------------------------------
// Environment-Specific Defaults
// ----------------------------------
if (globals.__PROD__) {
  webpackConfig.plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      output : {
        'comments'  : false
      },
      compress : {
        'unused'    : true,
        'dead_code' : true
      }
    })
  );
}

export default webpackConfig;
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var l<commit_msg>Fixing punctuation<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var le<|endoftext|>


<commit_before>'use strict';

angular.module('flowsimUiApp')
  .directive('fgPacket', function (Protocols) {

    return {
      restrict: 'E',                      // HTML Element
      transclude: true,                   // Copy element body in
      templateUrl: 'views/fgpacket.html',  // Location of template
      scope: {
        packet: '=',
        setDirty: '&'      // callback for persisting changes
      },
      controller: function($scope) {
        $scope.loaded = false;
        $scope.nodeType = '';  // input type to create node
        $scope.options  = {};  // input select options

       $scope.addProtocol = function() {
          $scope.packet.pushProtocol($scope.nodeType);
          _.last($scope.packet.protocols).isOpen = true;
          $scope.nodeType = '';
          $scope.setOptions();
          $scope.setDirty()();

       };

       $scope.popProtocol = function() {
          $scope.packet.popProtocol();
          _.last($scope.packet.protocols).isOpen = true;
          $scope.setOptions();
          $scope.setDirty()();

       };

       $scope.setOptions = function() {
        $scope.options = _.values(Protocols.Payloads[$scope.packet.protocols[$scope.packet.protocols.length - 1].name])[0];

       };

      //FIXME ... this belongs else where
      $scope.calcPayloadBytes = function() {
        if(_.last($scope.packet.protocols).name === 'Payload'){
          var payload = _.last($scope.packet.protocols);
          var payloadSize = payload.fields[0].value.value;
          _.last($scope.packet.protocols).bytes = parseInt( payload.fields[0].dispStr(payloadSize, 10), 16 );
            $scope.packet.bytes = 0;
          _($scope.packet.protocols).each(function(proto){
            $scope.packet.bytes += proto.bytes;
          });
        }
      };

      $scope.$watch('packet', function() {
        // directive runs before controller,
        // using $scope.loaded to determine if ctrl has run
        // need to rework
        if($scope.packet && $scope.loaded){
          $scope.calcPayloadBytes();
        }
        if($scope.packet){
          $scope.loaded = true;
          $scope.setOptions();
          if(_.isUndefined(_.last($scope.packet.protocols).isOpen)){
            _.last($scope.packet.protocols).isOpen =true;
          }

        }
      }, false);

      }
    };
  });
<commit_msg>issue 169<commit_after>'use strict';

angular.module('flowsimUiApp')
  .directive('fgPacket', function (Protocols) {

    return {
      restrict: 'E',                      // HTML Element
      transclude: true,                   // Copy element body in
      templateUrl: 'views/fgpacket.html',  // Location of template
      scope: {
        packet: '=',
        setDirty: '&'      // callback for persisting changes
      },
      controller: function($scope) {
        $scope.loaded = false;
        $scope.nodeType = '';  // input type to create node
        $scope.options  = {};  // input select options

       $scope.addProtocol = function() {
          $scope.packet.pushProtocol($scope.nodeType);
          _.last($scope.packet.protocols).isOpen = true;
          $scope.nodeType = '';
          $scope.setOptions();
          $scope.setDirty()();

       };

       $scope.popProtocol = function() {
          $scope.packet.popProtocol();
          _.last($scope.packet.protocols).isOpen = true;
          $scope.setOptions();
          $scope.setDirty()();

       };

       $scope.setOptions = function() {
        $scope.options = _.values(Protocols.Payloads[$scope.packet.protocols[$scope.packet.protocols.length - 1].name])[0];

       };

      //FIXME ... this belongs else where
      $scope.calcPayloadBytes = function() {
        if(_.last($scope.packet.protocols).name === 'Payload'){
          var payload = _.last($scope.packet.protocols);
          var payloadSize = payload.fields[0].value.value;
          _.last($scope.packet.protocols).bytes = parseInt( payload.fields[0].dispStr(payloadSize, 10), 16 );
            $scope.packet.bytes = 0;
          _($scope.packet.protocols).each(function(proto){
            $scope.packet.bytes += proto.bytes;
          });
        }
      };

      $scope.$watch('packet', function() {
        // directive runs before controller,
        // using $scope.loaded to determine if ctrl has run
        // need to rework
        if($scope.packet && $scope.loaded){
          $scope.calcPayloadBytes();
        }
        if($scope.packet){
          $scope.loaded = true;
          $scope.setOptions();
          if(_.isUndefined(_.last($scope.packet.protocols).isOpen)){
            _.last($scope.packet.protocols).isOpen =true;
          }

        }
      }, true);

      }
    };
  });
<|endoftext|>