<commit_before>const jsonfile = require('jsonfile');
const Discord = require('discord.js');
const cowsay_mod = require("cowsay");
const fortunes = require('fortunes');
const figlet_mod = require('figlet');
const client = new Discord.Client();
const config = require('./config.json');

var file = 'db.json';
var db = jsonfile.readFileSync(file);

function saveFile(file) {
  jsonfile.writeFile(file, db, function (err) {
    if(err) console.error(err);
  });
}
function help(msg) {
  msg.channel.send("Commands:\n\n`!info @user`: gives you the set info on a user\n`!chinfo <info>`: changes your listing\n`!rminfo`: removes your listing\n\nOther commands:\n\n`!interject`\n`!norichard`\n`!gentoo`\n`!paste`\n`!cowsay <text>`\n`!fortune`\n`!step`\n`!figlet`");
}
function info(msg) {
  let userId;
  if(msg.content.substr(8,1) === '!') {
    userId = msg.content.substr(9,18);
  }
  else if(msg.content.substr(6) === '') {
    userId = msg.author.id;
  }
  else {
    userId = msg.content.substr(8,18);
  }
  if(db.info[userId]) {
    msg.channel.send('```'+db.info[userId]+'```');
  }
  else {
    msg.channel.send('No info found for <@' + userId + '>');
  }
}

function chinfo(msg) {
  if(msg.content.substr(8) === '') {
    delete db.info[msg.author.id];
    msg.channel.send('Info removed.');
  }
  else {
    db.info[msg.author.id] = msg.content.substr(8).replace(/[`]/g, '');
    msg.channel.send('Info changed to: ```'+db.info[msg.author.id]+'```');
  }
  saveFile(file);
}

function rminfo(msg) {
  delete db.info[msg.author.id];
  msg.channel.send('Info removed.');
  saveFile(file);
}

function slap(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.send('<@'+msg.author.id+'> slaps around a bit with a large trout');
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.send('<@'+msg.author.id+'> slaps '+ msg.content.substr(6) +' around a bit with a large trout');
  }
  else {
    msg.channel.send(config.prefix + 'slap: Permission denied');
  }
}

function interject(msg) {
  const pasta = "I'd just like to interject for a moment. What you’re referring to as Linux, is in fact, GNU/Linux, or as I’ve recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the GNU system every day, without realizing it. Through a peculiar turn of events, the version of GNU which is widely used today is often called “Linux”, and many of its users are not aware that it is basically the GNU system, developed by the GNU Project. There really is a Linux, and these people are using it, but it is just a part of the system they use. Linux is the kernel: the program in the system that allocates the machine’s resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. Linux is normally used in combination with the GNU operating system: the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called “Linux” distributions are really distributions of GNU/Linux.";
  let args = msg.content.substr(11).split('/');
  if (args[1]) msg.channel.send(pasta.replace(/GNU/g, args[0]).replace(/Linux/g, args[1]));
  else msg.channel.send(pasta);
}

function norichard(msg) {
  msg.channel.send("No, Richard, it's 'Linux', not 'GNU/Linux'. The most important contributions that the FSF made to Linux were the creation of the GPL and the GCC compiler. Those are fine and inspired products. GCC is a monumental achievement and has earned you, RMS, and the Free Software Foundation countless kudos and much appreciation.\nFollowing are some reasons for you to mull over, including some already answered in your FAQ.\nOne guy, Linus Torvalds, used GCC to make his operating system (yes, Linux is an OS -- more on this later). He named it 'Linux' with a little help from his friends. Why doesn't he call it GNU/Linux? Because he wrote it, with more help from his friends, not you. You named your stuff, I named my stuff -- including the software I wrote using GCC -- and Linus named his stuff. The proper name is Linux because Linus Torvalds says so. Linus has spoken. Accept his authority. To do otherwise is to become a nag. You don't want to be known as a nag, do you?\n(An operating system) != (a distribution). Linux is an operating system. By my definition, an operating system is that software which provides and limits access to hardware resources on a computer. That definition applies whereever you see Linux in use. However, Linux is usually distributed with a collection of utilities and applications to make it easily configurable as a desktop system, a server, a development box, or a graphics workstation, or whatever the user needs. In such a configuration, we have a Linux (based) distribution. Therein lies your strongest argument for the unwieldy title 'GNU/Linux' (when said bundled software is largely from the FSF). Go bug the distribution makers on that one. Take your beef to Red Hat, Mandrake, and Slackware. At least there you have an argument. Linux alone is an operating system that can be used in various applications without any GNU software whatsoever. Embedded applications come to mind as an obvious example.");
  msg.channel.send("Next, even if we limit the GNU/Linux title to the GNU-based Linux distributions, we run into another obvious problem. XFree86 may well be more important to a particular Linux installation than the sum of all the GNU contributions. More properly, shouldn't the distribution be called XFree86/Linux? Or, at a minimum, XFree86/GNU/Linux? Of course, it would be rather arbitrary to draw the line there when many other fine contributions go unlisted. Yes, I know you've heard this one before. Get used to it. You'll keep hearing it until you can cleanly counter it.\nYou seem to like the lines-of-code metric. There are many lines of GNU code in a typical Linux distribution. You seem to suggest that (more LOC) == (more important). However, I submit to you that raw LOC numbers do not directly correlate with importance. I would suggest that clock cycles spent on code is a better metric. For example, if my system spends 90% of its time executing XFree86 code, XFree86 is probably the single most important collection of code on my system. Even if I loaded ten times as many lines of useless bloatware on my system and I never excuted that bloatware, it certainly isn't more important code than XFree86. Obviously, this metric isn't perfect either, but LOC really, really sucks. Please refrain from using it ever again in supporting any argument.\nLast, I'd like to point out that we Linux and GNU users shouldn't be fighting among ourselves over naming other people's software. But what the heck, I'm in a bad mood now. I think I'm feeling sufficiently obnoxious to make the point that GCC is so very famous and, yes, so very useful only because Linux was developed. In a show of proper respect and gratitude, shouldn't you and everyone refer to GCC as 'the Linux compiler'? Or at least, 'Linux GCC'? Seriously, where would your masterpiece be without Linux? Languishing with the HURD?");
  msg.channel.send("Be grateful for your abilities and your incredible success and your considerable fame. Continue to use that success and fame for good, not evil. Also, be especially grateful for Linux' huge contribution to that success. You, RMS, the Free Software Foundation, and GNU software have reached their current high profiles largely on the back of Linux. You have changed the world. Now, go forth and don't be a nag.\nThanks for listening.");
}

function gentoo(msg) {
  msg.channel.send("http://i.imgur.com/RLF8XyU.gif");
  msg.delete();
}
function paste(msg) {
  msg.channel.send("Please paste your log/message here: https://paste.fedoraproject.org/");
}
function cowsay(msg) {
  msg.channel.send("```\n"+ cowsay_mod.say({text: msg.content.substr(8)}) +"\n```");
}
function fortune(msg) {
  fortunes.search(function(results){
    msg.channel.send('```'+results[1]+'```');
  });
}
function step(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.send('<@'+msg.author.id+'> steps');
  }
  else if(msg.content.substr(6,2) === "on" && !/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.send('<@'+msg.author.id+'> steps on '+ msg.content.substr(9));
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.send('<@'+msg.author.id+'> steps on '+ msg.content.substr(6));
  }
  else {
    msg.channel.send(config.prefix + 'step: Permission denied');
  }
}
function figlet(msg) {
  msg.channel.send("```\n"+ figlet_mod.textSync(msg.content.substr(8)) +"\n```");
}
function sudo(msg) {
  if(!msg.member.roles.exists('name', 'sudoers')) {
    msg.channel.sendMessage('<@'+msg.author.id+'> is not in the sudoers file. This incident will be reported.');
    client.channels.get(config.sudoLogChannel).send('<@'+msg.author.id+'> is on santa\'s naughty list and will receive coal for Christmas.');
    return;
  }
  if(msg.content.substr(8, 4) === 'info') {
    let userId;
    let message;
    if(msg.content.substr(8,1) === '!') {
      userId = msg.content.substr(16,18);
      message = msg.content.substr(36);
    }
    else {
      userId = msg.content.substr(15,18);
      message = msg.content.substr(35);
    }
    if(msg.content.substr(6, 6) === 'chinfo') {
      db.info[userId] = message;
      msg.channel.send('Info changed to: ```'+db.info[userId]+'```');
    }
    else if(msg.content.substr(6, 6) === 'rminfo') {
      delete db.info[userId];
      msg.channel.send('Info removed.');
   }
    saveFile(file);
  }
  else if(msg.content.substr(6,4) === 'slap') {
    msg.channel.send('<@'+msg.author.id+'> slaps '+ msg.content.substr(11) +' around a bit with a large trout');
  }
}

client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', msg => {
  if(msg.author === client.user) return;
       if(msg.content.substr(0,  5) === config.prefix + 'help')          help(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'info')          info(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'chinfo')        chinfo(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'rminfo')        rminfo(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'slap')          slap(msg);
  else if(msg.content.substr(0, 10) === config.prefix + 'interject')     interject(msg);
  else if(msg.content.substr(0, 10) === config.prefix + 'norichard')     norichard(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'gentoo')        gentoo(msg);
  else if(msg.content.substr(0,  6) === config.prefix + 'paste')         paste(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'cowsay')        cowsay(msg);
  else if(msg.content.substr(0,  8) === config.prefix + 'fortune')       fortune(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'step')          step(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'figlet')        figlet(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'sudo')          sudo(msg);
});

client.on('guildMemberAdd', member => {
  client.channels.get(config.logChannel).send('Joined: <@' + member.id + '>');
});

client.login(config.token).then(function() {
  client.user.setGame("I can't remove this text");
});
<commit_msg>actually removed sendMessage<commit_after>const jsonfile = require('jsonfile');
const Discord = require('discord.js');
const cowsay_mod = require("cowsay");
const fortunes = require('fortunes');
const figlet_mod = require('figlet');
const client = new Discord.Client();
const config = require('./config.json');

var file = 'db.json';
var db = jsonfile.readFileSync(file);

function saveFile(file) {
  jsonfile.writeFile(file, db, function (err) {
    if(err) console.error(err);
  });
}
function help(msg) {
  msg.channel.send("Commands:\n\n`!info @user`: gives you the set info on a user\n`!chinfo <info>`: changes your listing\n`!rminfo`: removes your listing\n\nOther commands:\n\n`!interject`\n`!norichard`\n`!gentoo`\n`!paste`\n`!cowsay <text>`\n`!fortune`\n`!step`\n`!figlet`");
}
function info(msg) {
  let userId;
  if(msg.content.substr(8,1) === '!') {
    userId = msg.content.substr(9,18);
  }
  else if(msg.content.substr(6) === '') {
    userId = msg.author.id;
  }
  else {
    userId = msg.content.substr(8,18);
  }
  if(db.info[userId]) {
    msg.channel.send('```'+db.info[userId]+'```');
  }
  else {
    msg.channel.send('No info found for <@' + userId + '>');
  }
}

function chinfo(msg) {
  if(msg.content.substr(8) === '') {
    delete db.info[msg.author.id];
    msg.channel.send('Info removed.');
  }
  else {
    db.info[msg.author.id] = msg.content.substr(8).replace(/[`]/g, '');
    msg.channel.send('Info changed to: ```'+db.info[msg.author.id]+'```');
  }
  saveFile(file);
}

function rminfo(msg) {
  delete db.info[msg.author.id];
  msg.channel.send('Info removed.');
  saveFile(file);
}

function slap(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.send('<@'+msg.author.id+'> slaps around a bit with a large trout');
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.send('<@'+msg.author.id+'> slaps '+ msg.content.substr(6) +' around a bit with a large trout');
  }
  else {
    msg.channel.send(config.prefix + 'slap: Permission denied');
  }
}

function interject(msg) {
  const pasta = "I'd just like to interject for a moment. What you’re referring to as Linux, is in fact, GNU/Linux, or as I’ve recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the GNU system every day, without realizing it. Through a peculiar turn of events, the version of GNU which is widely used today is often called “Linux”, and many of its users are not aware that it is basically the GNU system, developed by the GNU Project. There really is a Linux, and these people are using it, but it is just a part of the system they use. Linux is the kernel: the program in the system that allocates the machine’s resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. Linux is normally used in combination with the GNU operating system: the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called “Linux” distributions are really distributions of GNU/Linux.";
  let args = msg.content.substr(11).split('/');
  if (args[1]) msg.channel.send(pasta.replace(/GNU/g, args[0]).replace(/Linux/g, args[1]));
  else msg.channel.send(pasta);
}

function norichard(msg) {
  msg.channel.send("No, Richard, it's 'Linux', not 'GNU/Linux'. The most important contributions that the FSF made to Linux were the creation of the GPL and the GCC compiler. Those are fine and inspired products. GCC is a monumental achievement and has earned you, RMS, and the Free Software Foundation countless kudos and much appreciation.\nFollowing are some reasons for you to mull over, including some already answered in your FAQ.\nOne guy, Linus Torvalds, used GCC to make his operating system (yes, Linux is an OS -- more on this later). He named it 'Linux' with a little help from his friends. Why doesn't he call it GNU/Linux? Because he wrote it, with more help from his friends, not you. You named your stuff, I named my stuff -- including the software I wrote using GCC -- and Linus named his stuff. The proper name is Linux because Linus Torvalds says so. Linus has spoken. Accept his authority. To do otherwise is to become a nag. You don't want to be known as a nag, do you?\n(An operating system) != (a distribution). Linux is an operating system. By my definition, an operating system is that software which provides and limits access to hardware resources on a computer. That definition applies whereever you see Linux in use. However, Linux is usually distributed with a collection of utilities and applications to make it easily configurable as a desktop system, a server, a development box, or a graphics workstation, or whatever the user needs. In such a configuration, we have a Linux (based) distribution. Therein lies your strongest argument for the unwieldy title 'GNU/Linux' (when said bundled software is largely from the FSF). Go bug the distribution makers on that one. Take your beef to Red Hat, Mandrake, and Slackware. At least there you have an argument. Linux alone is an operating system that can be used in various applications without any GNU software whatsoever. Embedded applications come to mind as an obvious example.");
  msg.channel.send("Next, even if we limit the GNU/Linux title to the GNU-based Linux distributions, we run into another obvious problem. XFree86 may well be more important to a particular Linux installation than the sum of all the GNU contributions. More properly, shouldn't the distribution be called XFree86/Linux? Or, at a minimum, XFree86/GNU/Linux? Of course, it would be rather arbitrary to draw the line there when many other fine contributions go unlisted. Yes, I know you've heard this one before. Get used to it. You'll keep hearing it until you can cleanly counter it.\nYou seem to like the lines-of-code metric. There are many lines of GNU code in a typical Linux distribution. You seem to suggest that (more LOC) == (more important). However, I submit to you that raw LOC numbers do not directly correlate with importance. I would suggest that clock cycles spent on code is a better metric. For example, if my system spends 90% of its time executing XFree86 code, XFree86 is probably the single most important collection of code on my system. Even if I loaded ten times as many lines of useless bloatware on my system and I never excuted that bloatware, it certainly isn't more important code than XFree86. Obviously, this metric isn't perfect either, but LOC really, really sucks. Please refrain from using it ever again in supporting any argument.\nLast, I'd like to point out that we Linux and GNU users shouldn't be fighting among ourselves over naming other people's software. But what the heck, I'm in a bad mood now. I think I'm feeling sufficiently obnoxious to make the point that GCC is so very famous and, yes, so very useful only because Linux was developed. In a show of proper respect and gratitude, shouldn't you and everyone refer to GCC as 'the Linux compiler'? Or at least, 'Linux GCC'? Seriously, where would your masterpiece be without Linux? Languishing with the HURD?");
  msg.channel.send("Be grateful for your abilities and your incredible success and your considerable fame. Continue to use that success and fame for good, not evil. Also, be especially grateful for Linux' huge contribution to that success. You, RMS, the Free Software Foundation, and GNU software have reached their current high profiles largely on the back of Linux. You have changed the world. Now, go forth and don't be a nag.\nThanks for listening.");
}

function gentoo(msg) {
  msg.channel.send("http://i.imgur.com/RLF8XyU.gif");
  msg.delete();
}
function paste(msg) {
  msg.channel.send("Please paste your log/message here: https://paste.fedoraproject.org/");
}
function cowsay(msg) {
  msg.channel.send("```\n"+ cowsay_mod.say({text: msg.content.substr(8)}) +"\n```");
}
function fortune(msg) {
  fortunes.search(function(results){
    msg.channel.send('```'+results[1]+'```');
  });
}
function step(msg) {
  if(msg.content.substr(6) === "") {
    msg.channel.send('<@'+msg.author.id+'> steps');
  }
  else if(msg.content.substr(6,2) === "on" && !/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.send('<@'+msg.author.id+'> steps on '+ msg.content.substr(9));
  }
  else if(!/everyone/g.test(msg.content) && !/here/g.test(msg.content)) {
    msg.channel.send('<@'+msg.author.id+'> steps on '+ msg.content.substr(6));
  }
  else {
    msg.channel.send(config.prefix + 'step: Permission denied');
  }
}
function figlet(msg) {
  msg.channel.send("```\n"+ figlet_mod.textSync(msg.content.substr(8)) +"\n```");
}
function sudo(msg) {
  if(!msg.member.roles.exists('name', 'sudoers')) {
    msg.channel.send('<@'+msg.author.id+'> is not in the sudoers file. This incident will be reported.');
    client.channels.get(config.sudoLogChannel).send('<@'+msg.author.id+'> is on santa\'s naughty list and will receive coal for Christmas.');
    return;
  }
  if(msg.content.substr(8, 4) === 'info') {
    let userId;
    let message;
    if(msg.content.substr(8,1) === '!') {
      userId = msg.content.substr(16,18);
      message = msg.content.substr(36);
    }
    else {
      userId = msg.content.substr(15,18);
      message = msg.content.substr(35);
    }
    if(msg.content.substr(6, 6) === 'chinfo') {
      db.info[userId] = message;
      msg.channel.send('Info changed to: ```'+db.info[userId]+'```');
    }
    else if(msg.content.substr(6, 6) === 'rminfo') {
      delete db.info[userId];
      msg.channel.send('Info removed.');
   }
    saveFile(file);
  }
  else if(msg.content.substr(6,4) === 'slap') {
    msg.channel.send('<@'+msg.author.id+'> slaps '+ msg.content.substr(11) +' around a bit with a large trout');
  }
}

client.on('ready', () => {
  console.log(`Logged in as ${client.user.username}!`);
});

client.on('message', msg => {
  if(msg.author === client.user) return;
       if(msg.content.substr(0,  5) === config.prefix + 'help')          help(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'info')          info(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'chinfo')        chinfo(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'rminfo')        rminfo(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'slap')          slap(msg);
  else if(msg.content.substr(0, 10) === config.prefix + 'interject')     interject(msg);
  else if(msg.content.substr(0, 10) === config.prefix + 'norichard')     norichard(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'gentoo')        gentoo(msg);
  else if(msg.content.substr(0,  6) === config.prefix + 'paste')         paste(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'cowsay')        cowsay(msg);
  else if(msg.content.substr(0,  8) === config.prefix + 'fortune')       fortune(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'step')          step(msg);
  else if(msg.content.substr(0,  7) === config.prefix + 'figlet')        figlet(msg);
  else if(msg.content.substr(0,  5) === config.prefix + 'sudo')          sudo(msg);
});

client.on('guildMemberAdd', member => {
  client.channels.get(config.logChannel).send('Joined: <@' + member.id + '>');
});

client.login(config.token).then(function() {
  client.user.setGame("I can't remove this text");
});
<|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_msg>Well that seemed pretty easy<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?",
 <|endoftext|>


<commit_before>var transformToScenes = require('./lib/transformToScenes');
var fs = require('fs');
var transformSmartObjects = require('./lib/transformSmartObjects');
var normalizeSceneData = require('./lib/normalizeSceneData');
var storeFrames = require('./lib/storeFrames');

(function (transformToScenes, fs, transformSmartObjects, normalizeSceneData, storeFrames) {
    "use strict";

    var PLUGIN_ID = require("./package.json").name;
    var MENU_ID = "json";
    var MENU_LABEL = "export JSON once";

    var _generator = null, _currentDocumentId = null, _config = null;

    function init(generator, config) {
        _generator = generator;
        _config = config;

        console.log("initializing generator highfive.js JSON with config %j", _config);

        _generator.addMenuItem(MENU_ID, MENU_LABEL, true, false).then(function () {
            console.log("Menu created", MENU_ID);
        }, function () {
            console.error("Menu creation failed", MENU_ID);
        });

        _generator.onPhotoshopEvent("generatorMenuChanged", handleGeneratorMenuClicked);
        _generator.onPhotoshopEvent("currentDocumentChanged", handleCurrentDocumentChanged);
    }

    function handleCurrentDocumentChanged(id) {
        if (_currentDocumentId === id) {
            return;
        }
        _currentDocumentId = id;
    }

    function handleGeneratorMenuClicked(event) {
        // Ignore changes to other menus
        var menu = event.generatorMenuChanged;
        if (!menu || menu.name !== MENU_ID) {
            return;
        }

        generateJSON();
    }

    function generateJSON() {
        console.log(Date() + " generate JSON started");

        var jsonFileName;
        var placedInfo;
        var h5doc;
        var once = true;

        _generator.getDocumentInfo(undefined, {
            expandSmartObjects: true,
            getPathData: true
        }).then(function (document) {
            jsonFileName = document.file.substring(0, document.file.lastIndexOf('.')) + '.json';
            placedInfo = document.placed;

            return transformToScenes(document);

        }).then(function (h5Document) {
            h5doc = h5Document;
            var keyFramesJSX = __dirname + '\\lib\\jsx\\GetKeyframes.jsx';
            var keyFramesParams = {
                ids: h5Document.animations
            };

            return _generator.evaluateJSXFile(keyFramesJSX, keyFramesParams);

        }).then(function (keyFrameResult) {
            var frames = Object.keys(keyFrameResult.transformFrames);
            var frameData = {};

            function nextFrame(frameNumberKey) {
                var toFrameJSX = __dirname + '\\lib\\jsx\\GoToFrame.jsx';
                var toFrameParams = {
                    frameNumber: parseInt(frameNumberKey)
                };
                var ids = keyFrameResult.transformFrames[frameNumberKey];
                _generator.evaluateJSXFile(toFrameJSX, toFrameParams).then(function () {
                    return _generator.getDocumentInfo();

                }).then(function (document) {
                    return transformSmartObjects(ids, document, placedInfo, toFrameParams.frameNumber);

                }).then(function (smartObjectFrames) {
                    storeFrames(smartObjectFrames, frameData);

                    if (frames.length > 0)
                        nextFrame(frames.shift()); else
                        return true;

                }).then(function (ready) {
                    if (ready && once) { // maybe cleaner if extracted to a finally block
                        once = false;
                        var output = normalizeSceneData(h5doc, keyFrameResult, frameData);
                        writeJSONFile(jsonFileName, output);
                    }
                });
            }

            nextFrame(frames.shift());
        });
    }

    function writeJSONFile(name, objectData) {
        fs.writeFile(name, JSON.stringify(objectData), function (err) {
            if (err) throw err;
            console.log('file saved to: ' + name);

            console.log(Date() + " generate JSON finished");
        });
    }

    exports.init = init;
})(transformToScenes, fs, transformSmartObjects, normalizeSceneData, storeFrames);<commit_msg>showing verbose info - how long it takes to generate the steps and total<commit_after>var transformToScenes = require('./lib/transformToScenes');
var fs = require('fs');
var transformSmartObjects = require('./lib/transformSmartObjects');
var normalizeSceneData = require('./lib/normalizeSceneData');
var storeFrames = require('./lib/storeFrames');

(function (transformToScenes, fs, transformSmartObjects, normalizeSceneData, storeFrames) {
    "use strict";

    var PLUGIN_ID = require("./package.json").name;
    var MENU_ID = "json";
    var MENU_LABEL = "export JSON once";

    var _generator = null, _currentDocumentId = null, _config = null;

    function init(generator, config) {
        _generator = generator;
        _config = config;

        console.log("initializing generator highfive.js JSON with config %j", _config);

        _generator.addMenuItem(MENU_ID, MENU_LABEL, true, false).then(function () {
            console.log("Menu created", MENU_ID);
        }, function () {
            console.error("Menu creation failed", MENU_ID);
        });

        _generator.onPhotoshopEvent("generatorMenuChanged", handleGeneratorMenuClicked);
        _generator.onPhotoshopEvent("currentDocumentChanged", handleCurrentDocumentChanged);
    }

    function handleCurrentDocumentChanged(id) {
        if (_currentDocumentId === id) {
            return;
        }
        _currentDocumentId = id;
    }

    function handleGeneratorMenuClicked(event) {
        // Ignore changes to other menus
        var menu = event.generatorMenuChanged;
        if (!menu || menu.name !== MENU_ID) {
            return;
        }

        generateJSON();
    }

    function generateJSON() {
        var veryStart = Date.now();
        console.log(Date() + " generate JSON started");

        var jsonFileName;
        var placedInfo;
        var h5doc;
        var once = true;
        var start = Date.now();
        _generator.getDocumentInfo(undefined, {
            expandSmartObjects: true,
            getPathData: true
        }).then(function (document) {
            console.log('initial document info ' + (Date.now() - start) + ' ms');
            start = Date.now();
            jsonFileName = document.file.substring(0, document.file.lastIndexOf('.')) + '.json';
            placedInfo = document.placed;

            return transformToScenes(document);

        }).then(function (h5Document) {
            console.log('scene transform ' + (Date.now() - start) + ' ms');
            start = Date.now();

            h5doc = h5Document;
            var keyFramesJSX = __dirname + '\\lib\\jsx\\GetKeyframes.jsx';
            var keyFramesParams = {
                ids: h5Document.animations
            };

            return _generator.evaluateJSXFile(keyFramesJSX, keyFramesParams);

        }).then(function (keyFrameResult) {
            console.log('get keyframes ' + (Date.now() - start) + ' ms');
            start = Date.now();

            var frames = Object.keys(keyFrameResult.transformFrames);
            var frameData = {};

            function nextFrame(frameNumberKey) {
                var toFrameJSX = __dirname + '\\lib\\jsx\\GoToFrame.jsx';
                var toFrameParams = {
                    frameNumber: parseInt(frameNumberKey)
                };
                var ids = keyFrameResult.transformFrames[frameNumberKey];
                _generator.evaluateJSXFile(toFrameJSX, toFrameParams).then(function () {
                    return _generator.getDocumentInfo();

                }).then(function (document) {
                    return transformSmartObjects(ids, document, placedInfo, toFrameParams.frameNumber);

                }).then(function (smartObjectFrames) {
                    storeFrames(smartObjectFrames, frameData);

                    if (frames.length > 0)
                        nextFrame(frames.shift()); else
                        return true;

                }).then(function (ready) {
                    if (ready && once) { // maybe cleaner if extracted to a finally block
                        once = false;

                        console.log('get smart object keyframes ' + (Date.now() - start) + ' ms');
                        start = Date.now();

                        var output = normalizeSceneData(h5doc, keyFrameResult, frameData);

                        console.log('normalize data ' + (Date.now() - start) + ' ms');
                        start = Date.now();

                        writeJSONFile(jsonFileName, output, function () {
                            console.log('write file ' + (Date.now() - start) + ' ms');

                            var totalTime = Date.now() - veryStart;
                            console.log('generate JSON successful ' + Math.floor(totalTime/60000) + ' min (' + totalTime + ' ms)');
                        });
                    }
                });
            }

            nextFrame(frames.shift());
        });
    }

    function writeJSONFile(name, objectData, callback) {
        fs.writeFile(name, JSON.stringify(objectData), function (err) {
            if (err) throw err;
            console.log('file saved to: ' + name);
            if (callback)
                callback();
            console.log(Date() + " generate JSON finished");
        });
    }

    exports.init = init;
})(transformToScenes, fs, transformSmartObjects, normalizeSceneData, storeFrames);<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.arg<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv<|endoftext|>


<commit_before>var LABEL_WIDTH = 200,
	GRAPH_WIDTH = 400, // Horizontal distance between centers of vertices on opposite sides
	VTX_DIST = 40, // Distance between centers of two consecutive vertices
	LABEL_OFFSET = 10, // Distance between label and center of vertex
	MARGIN = {top: 75, bottom: 75, left: 0, right: 0};

// Overall width of the graphics
var WIDTH = GRAPH_WIDTH + 2 * (LABEL_WIDTH + LABEL_OFFSET);

// Overall height of the graphics
var HEIGHT = MARGIN.top + MARGIN.bottom + VTX_DIST * (Math.max(tac_chars.length, asoiaf_chars.length) - 1);

// x-coordinates of vertices in left and right parts of the graph
var LEFT_X = MARGIN.left + LABEL_WIDTH + LABEL_OFFSET,
	RIGHT_X = LEFT_X + GRAPH_WIDTH;

var canvas = d3.select("#canvas");

canvas.attr("width", WIDTH)
	.attr("height", HEIGHT);

var sidePanel = d3.select("#side-panel")
	.style("height", HEIGHT + "px");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Draw vertices
var vertices = canvas.selectAll(".vertex") // Should be empty
	.data(vertices)
  .enter().append("g")
	.classed("vertex", true)
	.classed("tac", function(v) {return v.series == "tac";})
	.classed("asoiaf", function(v) {return v.series == "asoiaf";})
	.on("click", vertexClicked)
	.attr("id", function(v) {return v.id;})
	.attr("transform", function(v) {
			var pos = vertexPos(v);
			return "translate(" + pos.x + "," + pos.y + ")";
		});

vertices.append("circle");

vertices.append("text")
	.text(function(v) {return v.name;})
	.attr("x", function(v) {return v.series == "tac" ? -LABEL_OFFSET : LABEL_OFFSET;})
	.attr("y", 4);

// Draw edges
var edges = canvas.selectAll(".edge") // Should be empty
	.data(edges)
  .enter().append("line")
	.attr("x1", LEFT_X)
	.attr("y1", function(e) {return vertexPos(e.l).y;})
	.attr("x2", RIGHT_X)
	.attr("y2", function(e) {return vertexPos(e.r).y;})
	.classed("edge", true);

////////////////// Helper functions //////////////////

// Return absolute coordinates of center of vertex
// Accepts either a vertex object or an ID string
function vertexPos(v) {

	// If v is an ID string, use it to retrieve vertex
	if(v.name == undefined)
		v = canvas.select("#" + v).datum();

	var pos = {
		x: (v.series == "tac" ? LEFT_X : RIGHT_X),
		y: MARGIN.top + v.index * VTX_DIST
	};
	return pos;
}

// Callback for when a vertex is clicked
function vertexClicked(v) {

	// Hide all edges first
	edges.classed("active", false);

	// Select current vertex & deselect all others
	vertices.classed("selected", function(w) {return w.id == v.id;});

	// Show edges incident to the clicked vertex
	edges.classed("active", function(e) {
			return e.l == v.id || e.r == v.id;
		})
		.classed("selected", false);

	// Clear the side panel
	sidePanel.select("#instructions").remove();
	sidePanel.selectAll("div").html("");

	showInfo(v, sidePanel.select("#selected-char"));
}

// Fill selection with info from vertex v
function showInfo(v, selection) {
	selection.html("")
	  .append("img")
		.attr("src", "pics/" + v.id + ".jpg");
	selection.append("h2")
		.html(v.name);
}
<commit_msg>Show connected character's info when an edge is clicked<commit_after>var LABEL_WIDTH = 200,
	GRAPH_WIDTH = 400, // Horizontal distance between centers of vertices on opposite sides
	VTX_DIST = 40, // Distance between centers of two consecutive vertices
	LABEL_OFFSET = 10, // Distance between label and center of vertex
	MARGIN = {top: 75, bottom: 75, left: 0, right: 0};

// Overall width of the graphics
var WIDTH = GRAPH_WIDTH + 2 * (LABEL_WIDTH + LABEL_OFFSET);

// Overall height of the graphics
var HEIGHT = MARGIN.top + MARGIN.bottom + VTX_DIST * (Math.max(tac_chars.length, asoiaf_chars.length) - 1);

// x-coordinates of vertices in left and right parts of the graph
var LEFT_X = MARGIN.left + LABEL_WIDTH + LABEL_OFFSET,
	RIGHT_X = LEFT_X + GRAPH_WIDTH;

var canvas = d3.select("#canvas");

canvas.attr("width", WIDTH)
	.attr("height", HEIGHT);

var sidePanel = d3.select("#side-panel")
	.style("height", HEIGHT + "px");

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Draw vertices
var vertices = canvas.selectAll(".vertex") // Should be empty
	.data(vertices)
  .enter().append("g")
	.classed("vertex", true)
	.classed("tac", function(v) {return v.series == "tac";})
	.classed("asoiaf", function(v) {return v.series == "asoiaf";})
	.on("click", vertexClicked)
	.attr("id", function(v) {return v.id;})
	.attr("transform", function(v) {
			var pos = vertexPos(v);
			return "translate(" + pos.x + "," + pos.y + ")";
		});

vertices.append("circle");

vertices.append("text")
	.text(function(v) {return v.name;})
	.attr("x", function(v) {return v.series == "tac" ? -LABEL_OFFSET : LABEL_OFFSET;})
	.attr("y", 4);

// Draw edges
var edges = canvas.selectAll(".edge") // Should be empty
	.data(edges)
  .enter().append("line")
	.attr("x1", LEFT_X)
	.attr("y1", function(e) {return vertexPos(e.l).y;})
	.attr("x2", RIGHT_X)
	.attr("y2", function(e) {return vertexPos(e.r).y;})
	.on("click", edgeClicked)
	.classed("edge", true);

////////////////// Helper functions //////////////////

// Return absolute coordinates of center of vertex
// Accepts either a vertex object or an ID string
function vertexPos(v) {

	// If v is an ID string, use it to retrieve vertex
	if(v.name == undefined)
		v = canvas.select("#" + v).datum();

	var pos = {
		x: (v.series == "tac" ? LEFT_X : RIGHT_X),
		y: MARGIN.top + v.index * VTX_DIST
	};
	return pos;
}

// Callback for when a vertex is clicked
function vertexClicked(v) {

	// Hide all edges first
	edges.classed("active", false);

	// Select current vertex & deselect all others
	vertices.classed("selected", function(w) {return w.id == v.id;});

	// Show edges incident to the clicked vertex
	edges.classed("active", function(e) {
			return e.l == v.id || e.r == v.id;
		})
		.classed("selected", false);

	// Clear the side panel
	sidePanel.select("#instructions").remove();
	sidePanel.selectAll("div").html("");

	showInfo(v, sidePanel.select("#selected-char"));
}

// Fill selection with info from vertex v
function showInfo(v, selection) {
	selection.html("")
	  .append("img")
		.attr("src", "pics/" + v.id + ".jpg");
	selection.append("h2")
		.html(v.name);
}

function edgeClicked(e) {

	// Deselect other edges and select this one
	edges.classed("selected", function(f) {
			return f.l == e.l && f.r == e.r;
		});

	// Get the endpoint of e that is NOT the selected vertex
	var otherV = (canvas.select(".vertex.selected").classed("tac") ? e.r : e.l); // ID
	otherV = canvas.select("#" + otherV).datum(); // Vertex object

	showInfo(otherV, sidePanel.select("#connected-char"));

}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

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 args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new D<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

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 args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Da<|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 pu<commit_msg>Updated the readme<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 pun<|endoftext|>


<commit_before>import React    from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk                                             from 'redux-thunk';
import { Provider }                                      from 'react-redux';
import { Router, Route, browserHistory, IndexRoute }     from 'react-router';
import { syncHistoryWithStore, routerReducer }           from 'react-router-redux';
/* App对应总容器 */
/* 每一项对应一个页面 */
import App                 from './containers/app';
import PageIndex           from './containers/page_index';
import PageDirectory       from './containers/page_directory';
import PageDirectoryFilter from './containers/page_directory_filter';
import PagePaper           from './containers/page_paper';
import PageNewPaper        from './containers/page_new_paper';
/* 汇总成一个reducer */
import appReducer from './reducers';
/* 引入css样式 */
require('./static/font-awesome/css/font-awesome.min.css');
require('./static/bootstrap/css/bootstrap.min.css');
require('./static/bootstrap/css/bootstrap-theme.min.css');
require('./static/css/common.css');
require('./static/css/customer.css');

const store = createStore(
    combineReducers({
        appReducer,
        routing: routerReducer
    }),
    applyMiddleware(thunk)
);

const history = syncHistoryWithStore(browserHistory, store);

const appDom  = document.getElementById('app');

var render = () => {
    ReactDOM.render((
        <Provider store = { store }>
            <Router history = { history }>
                <Route path = "/" component = { App }>
                    <IndexRoute component = { PageIndex }/>
                    <Route path = "index" component = { PageIndex }/>
                    <Route path = "directory" component = { PageDirectory }/>
                    <Route path = "directoryFilter" component = { PageDirectoryFilter }/>
                    <Route path = "paper" component = { PagePaper }/>
                    <Route path = "newPaper" component = { PageNewPaper }/>
                </Route>
            </Router>
        </Provider>
        ), appDom
    );
};

render();
store.subscribe(render);<commit_msg>fix tiny bug<commit_after>import React    from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk                                             from 'redux-thunk';
import { Provider }                                      from 'react-redux';
import { Router, Route, browserHistory, IndexRoute }     from 'react-router';
import { syncHistoryWithStore, routerReducer }           from 'react-router-redux';
/* App对应总容器 */
/* 每一项对应一个页面 */
import App                 from './containers/app';
import PageIndex           from './containers/page_index';
import PageDirectory       from './containers/page_directory';
import PageDirectoryFilter from './containers/page_directory_filter';
import PagePaper           from './containers/page_paper';
import PageNewPaper        from './containers/page_new_paper';
/* 汇总成一个reducer */
import appReducer from './reducers';
/* 引入css样式 */
require('./static/font-awesome/css/font-awesome.min.css');
require('./static/bootstrap/css/bootstrap.min.css');
require('./static/bootstrap/css/bootstrap-theme.min.css');
require('./static/css/common.css');
require('./static/css/customer.css');

const store = createStore(
    combineReducers({
        appReducer,
        routing: routerReducer
    }),
    applyMiddleware(thunk)
);

const history = syncHistoryWithStore(browserHistory, store);
const appDom  = document.getElementById('app');
const routes  = (
    <Router history = { history }>
        <Route path = "/" component = { App }>
            <IndexRoute component = { PageIndex }/>
            <Route path = "index" component = { PageIndex }/>
            <Route path = "directory" component = { PageDirectory }/>
            <Route path = "directoryFilter" component = { PageDirectoryFilter }/>
            <Route path = "paper" component = { PagePaper }/>
            <Route path = "newPaper" component = { PageNewPaper }/>
        </Route>
    </Router>
);

var render = () => {
    ReactDOM.render((
        <Provider store = { store }>
            { routes }
        </Provider>
        ), appDom
    );
};

render();
store.subscribe(render);<|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",
  "Upd<commit_msg>Cleaned out the intertubes<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",
  "Upda<|endoftext|>


<commit_before>var debug = false;
var debugLine = true;
var debugPixelSize = 20;

var width;
var height;

var totalTime = 0;

var renderState = {
	framebuffer: undefined,
	depthbuffer: undefined,
	vertexShader: undefined,
	pixelShader: undefined,
	textureData: undefined,
	viewportMatrix: mat4.identity(),
	projectionMatrix: mat4.identity(),
	viewMatrix: mat4.identity(),
	worldMatrix: mat4.identity(),
};

function clearFramebuffer()
{
	for(var i = 0; i < height; ++i)
		for(var j = 0; j < width; ++j)
		{
			var pixelStartIndex = i * width * 4 + j * 4;
			renderState.framebuffer[pixelStartIndex] = 0;
			renderState.framebuffer[pixelStartIndex + 1] = 0;
			renderState.framebuffer[pixelStartIndex + 2] = 0;
		}
}

function clearDepthbuffer()
{
	for(var i = 0; i < height; ++i)
		for(var j = 0; j < width; ++j)
		{
			var pixelIndex = i * width + j;
			renderState.depthbuffer[pixelIndex] = 1;
		}
}

function drawPixel(x, y, z, r, g, b)
{
	var i = Math.floor(height - y - 0.5);
	if(i >= 0 && i < height)
	{
		var j = Math.floor(x + 0.5);
		if(j >= 0 && j < width)
		{
			var depthPixelIndex = i * width + j;
			if(z < renderState.depthbuffer[depthPixelIndex])
			{
				// Pass depth test
				renderState.depthbuffer[depthPixelIndex] = z;
				var pixelStartIndex = i * width * 4 + j * 4;
				renderState.framebuffer[pixelStartIndex] = r;
				renderState.framebuffer[pixelStartIndex + 1] = g;
				renderState.framebuffer[pixelStartIndex + 2] = b;
			}
		}
	}
}

function drawTriangle(vertex1, vertex2, vertex3)
{
	// The first element in each vertex is always position
	// Here the vertex position is homogenized
	var w1 = vertex1[0][3], w2 = vertex2[0][3], w3 = vertex3[0][3];
	var v1h = vec4.scale(1 / w1, vertex1[0]);
	var v2h = vec4.scale(1 / w2, vertex2[0]);
	var v3h = vec4.scale(1 / w3, vertex3[0]);

	var minX = Math.min(v1h[0], v2h[0], v3h[0]);
	var maxX = Math.max(v1h[0], v2h[0], v3h[0]);
	var minY = Math.min(v1h[1], v2h[1], v3h[1]);
	var maxY = Math.max(v1h[1], v2h[1], v3h[1]);

	var varyingCount = vertex1.length;

	function f12(x, y)
	{
		return (v1h[1] - v2h[1]) * x
			+ (v2h[0] - v1h[0]) * y
			+ v1h[0] * v2h[1] - v2h[0] * v1h[1];
	}

	function f23(x, y)
	{
		return (v2h[1] - v3h[1]) * x
			+ (v3h[0] - v2h[0]) * y
			+ v2h[0] * v3h[1] - v3h[0] * v2h[1];
	}

	function f31(x, y)
	{
		return (v3h[1] - v1h[1]) * x
			+ (v1h[0] - v3h[0]) * y
			+ v3h[0] * v1h[1] - v1h[0] * v3h[1];
	}

	for(var y = Math.floor(minY); y <= Math.ceil(maxY); ++y)
		for(var x = Math.floor(minX); x <= Math.ceil(maxX); ++x)
		{
			var alpha = f23(x, y) / f23(v1h[0], v1h[1]);
			var beta = f31(x, y) / f31(v2h[0], v2h[1]);
			var gamma = f12(x, y) / f12(v3h[0], v3h[1]);

			if(alpha > 0 && beta > 0 && gamma > 0)
			{
				// Interpolate attributes
				var oneOverW = alpha / w1 + beta / w2 + gamma / w3;
				var varyings = new Array(varyingCount);
				for(var varyingIndex = 0; varyingIndex < varyingCount; ++varyingIndex)
				{
					varyings[varyingIndex] = vec4.scale(1 / oneOverW, vec4.add(
						vec4.scale(alpha / w1, vertex1[varyingIndex]),
						vec4.add(vec4.scale(beta / w2, vertex2[varyingIndex]),
							vec4.scale(gamma / w3, vertex3[varyingIndex]))
						));
				}

				var color = renderState.pixelShader(varyings);
				drawPixel(x, y, varyings[0][2] / varyings[0][3], color[0], color[1], color[2]);
			}
		}
}

function draw(format, vertexBuffer)
{
	var vertexSize = format.reduce(function(previousValue, currentValue){return previousValue + currentValue;});
	var vertexCount = vertexBuffer.length / vertexSize;
	var processedVertexBuffer = new Array(vertexCount);
	for(var vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex)
	{
		// Process vertex one by one
		var attributes = new Array(format.length);
		for(var attributeIndex = 0, bufferIndex = 0; attributeIndex < attributes.length; ++attributeIndex)
		{
			var attribute = vec4.create();
			for(var i = 0; i < format[attributeIndex]; ++i)
			{
				attribute[i] = vertexBuffer[vertexIndex * vertexSize + bufferIndex];
				++bufferIndex;
			}
			attributes[attributeIndex] = attribute;
		}
		processedVertexBuffer[vertexIndex] = renderState.vertexShader(attributes);
	}

	var triangleCount = vertexCount / 3;

	for(var triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex)
	{
		var v1 = processedVertexBuffer[3 * triangleIndex];
		var v2 = processedVertexBuffer[3 * triangleIndex + 1];
		var v3 = processedVertexBuffer[3 * triangleIndex + 2];

		drawTriangle(v1, v2, v3);
	}
}

function drawScene(deltaTime)
{
	clearFramebuffer();
	clearDepthbuffer();
	renderState.vertexShader = vertexShader;
	renderState.pixelShader = pixelShader;
	renderState.viewportMatrix = mat4.viewport(width, height, 0, 1);
	var rotationMatrixX = mat4.fromRotationX(0.2 * totalTime);
	var rotationMatrixY = mat4.fromRotationY(0.3 * totalTime);
	var rotationMatrixZ = mat4.fromRotationZ(0.1 * totalTime);
	renderState.worldMatrix = mat4.mul(rotationMatrixX, mat4.mul(rotationMatrixY, rotationMatrixZ));
	renderState.viewMatrix = mat4.lookAt(vec4.fromValues(2, 1.5, 2, 1), vec4.fromValues(0, 0, 0, 1), vec4.fromValues(0, 1, 0, 0));
	renderState.projectionMatrix = mat4.perspective(Math.PI / 2, width / height, 1, 100);
	draw(modelCube.format, modelCube.vertices);
}

function render(deltaTime)
{
	drawScene(deltaTime);

	var canvas = document.getElementById("raster-canvas");
	var context = canvas.getContext("2d");

	if(debug)
	{
		for(var i = 0; i < height; ++i)
			for(var j = 0; j < width; ++j)
			{
				var pixelStartIndex = i * width * 4 + j * 4;
				r = Math.floor(255 * renderState.framebuffer[pixelStartIndex]);
				g = Math.floor(255 * renderState.framebuffer[pixelStartIndex + 1]);
				b = Math.floor(255 * renderState.framebuffer[pixelStartIndex + 2]);
				context.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
				context.fillRect(j * debugPixelSize, i * debugPixelSize, debugPixelSize, debugPixelSize);
			}

		if(debugLine)
		{
			context.beginPath();
			context.lineWidth = 2;
			context.strokeStyle = "rgb(0, 128, 255)";
			for(var i = 0; i <= height; ++i)
			{
				context.moveTo(0, i * debugPixelSize);
				context.lineTo(width * debugPixelSize, i * debugPixelSize);
			}
			for(var i = 0; i <= width; ++i)
			{
				context.moveTo(i * debugPixelSize, 0);
				context.lineTo(i * debugPixelSize, height * debugPixelSize);
			}
			context.stroke();
		}
	}
	else
	{
		var canvasWidth = canvas.attributes.width.value;
		var canvasHeight = canvas.attributes.height.value;
		var imageData = context.getImageData(0, 0, canvasWidth, canvasHeight);
		var data = imageData.data;

		for(var i = 0; i < height; ++i)
			for(var j = 0; j < width; ++j)
			{
				var pixelStartIndex = i * width * 4 + j * 4;
				data[pixelStartIndex] = 255 * renderState.framebuffer[pixelStartIndex];
				data[pixelStartIndex + 1] = 255 * renderState.framebuffer[pixelStartIndex + 1];
				data[pixelStartIndex + 2] = 255 * renderState.framebuffer[pixelStartIndex + 2];
				data[pixelStartIndex + 3] = 255;
			}
		context.putImageData(imageData, 0, 0);
	}
}

function initFramebufferDepthbuffer()
{
	var canvas = document.getElementById("raster-canvas");
	var canvasWidth = canvas.attributes.width.value;
	var canvasHeight = canvas.attributes.height.value;
	if(debug)
	{
		width = Math.floor(canvasWidth / debugPixelSize);
		height = Math.floor(canvasHeight / debugPixelSize);
	}
	else
	{
		width = canvasWidth;
		height = canvasHeight;
	}
	renderState.framebuffer = new Float32Array(width * height * 4);
	for(var i = 0; i < renderState.framebuffer.length; ++i)
		renderState.framebuffer[i] = 0;
	renderState.depthbuffer = new Float32Array(width * height);
	for(var i = 0; i < renderState.depthbuffer.length; ++i)
		renderState.depthbuffer[i] = 0;
}

function changeTexture(textureName)
{
	var img = document.getElementById(textureName);
	var canvas = document.getElementById("texture-canvas");
	var context = canvas.getContext("2d");
	context.drawImage(img, 0, 0);
	renderState.textureData = context.getImageData(0, 0, canvas.attributes.width.value, canvas.attributes.height.value);
}

function init()
{
	initFramebufferDepthbuffer();
	changeTexture("texture-madoka");
	var checkboxDebug = document.getElementById("checkbox-debug");
	checkboxDebug.checked = debug;
	var checkboxDebugLine = document.getElementById("checkbox-debug-line");
	checkboxDebugLine.checked = debugLine;
	var lastUpdateTime = (new Date).getTime();
	var lastUpdateFpsTime = lastUpdateTime;
	var frameCount = 0;
	setInterval(function(){
		var currentTime = (new Date).getTime();
		var deltaTime = (currentTime - lastUpdateTime) / 1000;
		lastUpdateTime = currentTime;
		if(currentTime - lastUpdateFpsTime > 1000)
		{
			var labelFps = document.getElementById("label-fps");
			labelFps.innerHTML = "FPS: " + frameCount;
			lastUpdateFpsTime = currentTime;
			frameCount = 0;
		}
		totalTime += deltaTime;
		render(deltaTime);
		++frameCount;
	}, 1000 / 60);
}

function toggleDebug()
{
	var checkboxDebug = document.getElementById("checkbox-debug");
	debug = checkboxDebug.checked;
	var canvas = document.getElementById("raster-canvas");
	var context = canvas.getContext("2d");
	var canvasWidth = canvas.attributes.width.value;
	var canvasHeight = canvas.attributes.height.value;
	context.fillStyle = "rgb(255,255,255)";
	context.fillRect(0, 0, canvasWidth, canvasHeight);
	initFramebufferDepthbuffer();
}

function toggleDebugLine()
{
	var checkboxDebugLine = document.getElementById("checkbox-debug-line");
	debugLine = checkboxDebugLine.checked;
}

function start()
{
	init();
}
<commit_msg>Rewrite the buffer cleaning functions to speed up rendering a little<commit_after>var debug = false;
var debugLine = true;
var debugPixelSize = 20;

var width;
var height;

var totalTime = 0;

var renderState = {
	framebuffer: undefined,
	depthbuffer: undefined,
	vertexShader: undefined,
	pixelShader: undefined,
	textureData: undefined,
	viewportMatrix: mat4.identity(),
	projectionMatrix: mat4.identity(),
	viewMatrix: mat4.identity(),
	worldMatrix: mat4.identity(),
};

function clearFramebuffer()
{
	for(var i = 0; i < height * width * 4; ++i)
		renderState.framebuffer[i] = 0;
}

function clearDepthbuffer()
{
	for(var i = 0; i < height * width; ++i)
		renderState.depthbuffer[i] = 1;
}

function drawPixel(x, y, z, r, g, b)
{
	var i = Math.floor(height - y - 0.5);
	if(i >= 0 && i < height)
	{
		var j = Math.floor(x + 0.5);
		if(j >= 0 && j < width)
		{
			var depthPixelIndex = i * width + j;
			if(z < renderState.depthbuffer[depthPixelIndex])
			{
				// Pass depth test
				renderState.depthbuffer[depthPixelIndex] = z;
				var pixelStartIndex = i * width * 4 + j * 4;
				renderState.framebuffer[pixelStartIndex] = r;
				renderState.framebuffer[pixelStartIndex + 1] = g;
				renderState.framebuffer[pixelStartIndex + 2] = b;
			}
		}
	}
}

function drawTriangle(vertex1, vertex2, vertex3)
{
	// The first element in each vertex is always position
	// Here the vertex position is homogenized
	var w1 = vertex1[0][3], w2 = vertex2[0][3], w3 = vertex3[0][3];
	var v1h = vec4.scale(1 / w1, vertex1[0]);
	var v2h = vec4.scale(1 / w2, vertex2[0]);
	var v3h = vec4.scale(1 / w3, vertex3[0]);

	var minX = Math.min(v1h[0], v2h[0], v3h[0]);
	var maxX = Math.max(v1h[0], v2h[0], v3h[0]);
	var minY = Math.min(v1h[1], v2h[1], v3h[1]);
	var maxY = Math.max(v1h[1], v2h[1], v3h[1]);

	var varyingCount = vertex1.length;

	function f12(x, y)
	{
		return (v1h[1] - v2h[1]) * x
			+ (v2h[0] - v1h[0]) * y
			+ v1h[0] * v2h[1] - v2h[0] * v1h[1];
	}

	function f23(x, y)
	{
		return (v2h[1] - v3h[1]) * x
			+ (v3h[0] - v2h[0]) * y
			+ v2h[0] * v3h[1] - v3h[0] * v2h[1];
	}

	function f31(x, y)
	{
		return (v3h[1] - v1h[1]) * x
			+ (v1h[0] - v3h[0]) * y
			+ v3h[0] * v1h[1] - v1h[0] * v3h[1];
	}

	for(var y = Math.floor(minY); y <= Math.ceil(maxY); ++y)
		for(var x = Math.floor(minX); x <= Math.ceil(maxX); ++x)
		{
			var alpha = f23(x, y) / f23(v1h[0], v1h[1]);
			var beta = f31(x, y) / f31(v2h[0], v2h[1]);
			var gamma = f12(x, y) / f12(v3h[0], v3h[1]);

			if(alpha > 0 && beta > 0 && gamma > 0)
			{
				// Interpolate attributes
				var oneOverW = alpha / w1 + beta / w2 + gamma / w3;
				var varyings = new Array(varyingCount);
				for(var varyingIndex = 0; varyingIndex < varyingCount; ++varyingIndex)
				{
					varyings[varyingIndex] = vec4.scale(1 / oneOverW, vec4.add(
						vec4.scale(alpha / w1, vertex1[varyingIndex]),
						vec4.add(vec4.scale(beta / w2, vertex2[varyingIndex]),
							vec4.scale(gamma / w3, vertex3[varyingIndex]))
						));
				}

				var color = renderState.pixelShader(varyings);
				drawPixel(x, y, varyings[0][2] / varyings[0][3], color[0], color[1], color[2]);
			}
		}
}

function draw(format, vertexBuffer)
{
	var vertexSize = format.reduce(function(previousValue, currentValue){return previousValue + currentValue;});
	var vertexCount = vertexBuffer.length / vertexSize;
	var processedVertexBuffer = new Array(vertexCount);
	for(var vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex)
	{
		// Process vertex one by one
		var attributes = new Array(format.length);
		for(var attributeIndex = 0, bufferIndex = 0; attributeIndex < attributes.length; ++attributeIndex)
		{
			var attribute = vec4.create();
			for(var i = 0; i < format[attributeIndex]; ++i)
			{
				attribute[i] = vertexBuffer[vertexIndex * vertexSize + bufferIndex];
				++bufferIndex;
			}
			attributes[attributeIndex] = attribute;
		}
		processedVertexBuffer[vertexIndex] = renderState.vertexShader(attributes);
	}

	var triangleCount = vertexCount / 3;

	for(var triangleIndex = 0; triangleIndex < triangleCount; ++triangleIndex)
	{
		var v1 = processedVertexBuffer[3 * triangleIndex];
		var v2 = processedVertexBuffer[3 * triangleIndex + 1];
		var v3 = processedVertexBuffer[3 * triangleIndex + 2];

		drawTriangle(v1, v2, v3);
	}
}

function drawScene(deltaTime)
{
	clearFramebuffer();
	clearDepthbuffer();
	renderState.vertexShader = vertexShader;
	renderState.pixelShader = pixelShader;
	renderState.viewportMatrix = mat4.viewport(width, height, 0, 1);
	var rotationMatrixX = mat4.fromRotationX(0.2 * totalTime);
	var rotationMatrixY = mat4.fromRotationY(0.3 * totalTime);
	var rotationMatrixZ = mat4.fromRotationZ(0.1 * totalTime);
	renderState.worldMatrix = mat4.mul(rotationMatrixX, mat4.mul(rotationMatrixY, rotationMatrixZ));
	renderState.viewMatrix = mat4.lookAt(vec4.fromValues(2, 1.5, 2, 1), vec4.fromValues(0, 0, 0, 1), vec4.fromValues(0, 1, 0, 0));
	renderState.projectionMatrix = mat4.perspective(Math.PI / 2, width / height, 1, 100);
	draw(modelCube.format, modelCube.vertices);
}

function render(deltaTime)
{
	drawScene(deltaTime);

	var canvas = document.getElementById("raster-canvas");
	var context = canvas.getContext("2d");

	if(debug)
	{
		for(var i = 0; i < height; ++i)
			for(var j = 0; j < width; ++j)
			{
				var pixelStartIndex = i * width * 4 + j * 4;
				r = Math.floor(255 * renderState.framebuffer[pixelStartIndex]);
				g = Math.floor(255 * renderState.framebuffer[pixelStartIndex + 1]);
				b = Math.floor(255 * renderState.framebuffer[pixelStartIndex + 2]);
				context.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
				context.fillRect(j * debugPixelSize, i * debugPixelSize, debugPixelSize, debugPixelSize);
			}

		if(debugLine)
		{
			context.beginPath();
			context.lineWidth = 2;
			context.strokeStyle = "rgb(0, 128, 255)";
			for(var i = 0; i <= height; ++i)
			{
				context.moveTo(0, i * debugPixelSize);
				context.lineTo(width * debugPixelSize, i * debugPixelSize);
			}
			for(var i = 0; i <= width; ++i)
			{
				context.moveTo(i * debugPixelSize, 0);
				context.lineTo(i * debugPixelSize, height * debugPixelSize);
			}
			context.stroke();
		}
	}
	else
	{
		var canvasWidth = canvas.attributes.width.value;
		var canvasHeight = canvas.attributes.height.value;
		var imageData = context.getImageData(0, 0, canvasWidth, canvasHeight);
		var data = imageData.data;

		for(var i = 0; i < height; ++i)
			for(var j = 0; j < width; ++j)
			{
				var pixelStartIndex = i * width * 4 + j * 4;
				data[pixelStartIndex] = 255 * renderState.framebuffer[pixelStartIndex];
				data[pixelStartIndex + 1] = 255 * renderState.framebuffer[pixelStartIndex + 1];
				data[pixelStartIndex + 2] = 255 * renderState.framebuffer[pixelStartIndex + 2];
				data[pixelStartIndex + 3] = 255;
			}
		context.putImageData(imageData, 0, 0);
	}
}

function initFramebufferDepthbuffer()
{
	var canvas = document.getElementById("raster-canvas");
	var canvasWidth = canvas.attributes.width.value;
	var canvasHeight = canvas.attributes.height.value;
	if(debug)
	{
		width = Math.floor(canvasWidth / debugPixelSize);
		height = Math.floor(canvasHeight / debugPixelSize);
	}
	else
	{
		width = canvasWidth;
		height = canvasHeight;
	}
	renderState.framebuffer = new Float32Array(width * height * 4);
	for(var i = 0; i < renderState.framebuffer.length; ++i)
		renderState.framebuffer[i] = 0;
	renderState.depthbuffer = new Float32Array(width * height);
	for(var i = 0; i < renderState.depthbuffer.length; ++i)
		renderState.depthbuffer[i] = 0;
}

function changeTexture(textureName)
{
	var img = document.getElementById(textureName);
	var canvas = document.getElementById("texture-canvas");
	var context = canvas.getContext("2d");
	context.drawImage(img, 0, 0);
	renderState.textureData = context.getImageData(0, 0, canvas.attributes.width.value, canvas.attributes.height.value);
}

function init()
{
	initFramebufferDepthbuffer();
	changeTexture("texture-madoka");
	var checkboxDebug = document.getElementById("checkbox-debug");
	checkboxDebug.checked = debug;
	var checkboxDebugLine = document.getElementById("checkbox-debug-line");
	checkboxDebugLine.checked = debugLine;
	var lastUpdateTime = (new Date).getTime();
	var lastUpdateFpsTime = lastUpdateTime;
	var frameCount = 0;
	setInterval(function(){
		var currentTime = (new Date).getTime();
		var deltaTime = (currentTime - lastUpdateTime) / 1000;
		lastUpdateTime = currentTime;
		if(currentTime - lastUpdateFpsTime > 1000)
		{
			var labelFps = document.getElementById("label-fps");
			labelFps.innerHTML = "FPS: " + frameCount;
			lastUpdateFpsTime = currentTime;
			frameCount = 0;
		}
		totalTime += deltaTime;
		render(deltaTime);
		++frameCount;
	}, 1000 / 60);
}

function toggleDebug()
{
	var checkboxDebug = document.getElementById("checkbox-debug");
	debug = checkboxDebug.checked;
	var canvas = document.getElementById("raster-canvas");
	var context = canvas.getContext("2d");
	var canvasWidth = canvas.attributes.width.value;
	var canvasHeight = canvas.attributes.height.value;
	context.fillStyle = "rgb(255,255,255)";
	context.fillRect(0, 0, canvasWidth, canvasHeight);
	initFramebufferDepthbuffer();
}

function toggleDebugLine()
{
	var checkboxDebugLine = document.getElementById("checkbox-debug-line");
	debugLine = checkboxDebugLine.checked;
}

function start()
{
	init();
}
<|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) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return Math.f<commit_msg>Found an issue with the letter 'a', so I fixed it.<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) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromInterval(min,max)
{
   return Math.fl<|endoftext|>


<commit_before>global.__root = __dirname;
var http = require('http');
var express = require('express');
var SockJS = require('sockjs');
var program = require('commander');
var updateNotifier = require('update-notifier');

var configJson = require('./config.json');
var logger = require('./core/console.js');
var apiData = require('./core/api_data.js');
var endedWith = require('./core/util/ended_with.js');

// if the environment variable is set to 1,
// this will log the file and line that outputs
// to the terminal
if(process.env.TRACE_CONSOLE) {
  ['log', 'warn'].forEach(function (method) {
    var old = console[method];
    console[method] = function () {
      var stack = (new Error()).stack.split(/\n/);
      // Chrome includes a single "Error" line, FF doesn't.
      if (stack[0].indexOf('Error') === 0) {
        stack = stack.slice(1);
      }
      var args = [].slice.apply(arguments).concat([stack[1].trim()]);
      return old.apply(console, args);
    };
  });
}

// update notification
var pkg = require('./package.json');
var notifier = updateNotifier({
  pkg: {
    name: pkg.name,
    version: pkg.version
  },
  updateCheckInterval: 1000 * 60 * 60 * 6, // check every 6 hours
  defer: false
});
notifier.notify();

//commands
var run       = require('./core/commands/run.js'),
    addApp    = require('./core/commands/add_app.js'),
    removeApp = require('./core/commands/remove_app.js');

process.title = "Silk GUI";

program
  .version(pkg.version)
  .option('-r, --remote', 'Remotely access Silk')
  .option('-d, --dev', 'Show debug messages')
  .option('-o, --open', 'Open Silk in a window');

program
  .command('run')
  .description('Starts silk. Default command.')
  .action(run);

program
  .command('add-app [path]')
  .description('add app')
  .action(addApp);

program
  .command('remove-app [path]')
  .description('remove app')
  .action(removeApp);

program
  .parse(process.argv);

var lastArgv = process.argv[process.argv.length - 1];
if(lastArgv === 'help' || lastArgv === 'help') {
  // silk help or npm start help was run.
  program.help();
  process.exit(0);
}

// Silk was run with no command, so we do the default
// Setting a default command appears to be broken in commander.js
// so we implement it ourselves.
if(lastArgv === 'silk-gui') {
  console.log('no command');
} else if(endedWith(lastArgv, 'main.js')) {
  run();
}

logger.logLevel(program.dev ? 0 : 1);
<commit_msg>run silk when no command<commit_after>global.__root = __dirname;
var http = require('http');
var express = require('express');
var SockJS = require('sockjs');
var program = require('commander');
var updateNotifier = require('update-notifier');

var configJson = require('./config.json');
var logger = require('./core/console.js');
var apiData = require('./core/api_data.js');
var endedWith = require('./core/util/ended_with.js');

// if the environment variable is set to 1,
// this will log the file and line that outputs
// to the terminal
if(process.env.TRACE_CONSOLE) {
  ['log', 'warn'].forEach(function (method) {
    var old = console[method];
    console[method] = function () {
      var stack = (new Error()).stack.split(/\n/);
      // Chrome includes a single "Error" line, FF doesn't.
      if (stack[0].indexOf('Error') === 0) {
        stack = stack.slice(1);
      }
      var args = [].slice.apply(arguments).concat([stack[1].trim()]);
      return old.apply(console, args);
    };
  });
}

// update notification
var pkg = require('./package.json');
var notifier = updateNotifier({
  pkg: {
    name: pkg.name,
    version: pkg.version
  },
  updateCheckInterval: 1000 * 60 * 60 * 6, // check every 6 hours
  defer: false
});
notifier.notify();

//commands
var run       = require('./core/commands/run.js'),
    addApp    = require('./core/commands/add_app.js'),
    removeApp = require('./core/commands/remove_app.js');

process.title = "Silk GUI";

program
  .version(pkg.version)
  .option('-r, --remote', 'Remotely access Silk')
  .option('-d, --dev', 'Show debug messages')
  .option('-o, --open', 'Open Silk in a window');

program
  .command('run')
  .description('Starts silk. Default command.')
  .action(run);

program
  .command('add-app [path]')
  .description('add app')
  .action(addApp);

program
  .command('remove-app [path]')
  .description('remove app')
  .action(removeApp);

program
  .parse(process.argv);

var lastArgv = process.argv[process.argv.length - 1];
if(lastArgv === 'help' || lastArgv === 'help') {
  // silk help or npm start help was run.
  program.help();
  process.exit(0);
}

// Silk was run with no command, so we do the default
// Setting a default command appears to be broken in commander.js
// so we implement it ourselves.
if(lastArgv === 'silk') {
  run();
} else if(endedWith(lastArgv, 'main.js')) {
  run();
}

logger.logLevel(program.dev ? 0 : 1);
<|endoftext|>


<commit_before>/* Copyright (c) 2013-present The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */
/* globals Handlebars, Nanobar, marked */
"use strict";

var isCordova;

var isWin;
var isWeb = (document.URL.startsWith('http') && !document.URL.startsWith('http://localhost:1212/'));
// var JSZip;
var maxPreviewSize = (1024 * 3) || {}; //3kb limit for preview

$(document).ready(function() {
  function getParameterByName(name) {
    name = name.replace(/[\[]/ , "\\\[").replace(/[\]]/ , "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)") ,
            results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g , " "));
  }

  var locale = getParameterByName("locale");

  var extSettings;
  loadExtSettings();

  // isCordova = parent.isCordova;
  // isWin = parent.isWin;

  // Init internationalization
  i18next.init({
    ns: {namespaces: ['ns.viewerZIP']} ,
    debug: true ,
    lng: locale ,
    fallbackLng: 'en_US'
  } , function() {
    jqueryI18next.init(i18next, $);
    $('[data-i18n]').localize();
  });

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem("viewerZIPSettings"));
  }
});

function showContentFilePreviewDialog(containFile) {
  var unitArr = containFile.asUint8Array();
  var previewText = "";
  var byteLength = (unitArr.byteLength > maxPreviewSize) ? maxPreviewSize : unitArr.byteLength;

  for (var i = 0; i < byteLength; i++) {
    previewText += String.fromCharCode(unitArr[i]);
  }

  var fileContent = $("
").text(previewText);
  var $htmlContent = $('#htmlContent');

  $.post("previewDialog.html" , function(uiTPL) {
    //console.log("Load modal " + uiTPL);
    if ($('#previewDialog').length < 1) {
      var uiTemplate = Handlebars.compile(uiTPL);
      $('body').append(uiTemplate());
    }
    var dialogPreview = $('#previewDialog');
    dialogPreview.find('.modal-body').empty().append(fileContent);
    dialogPreview.modal({
      backdrop: 'static' ,
      show: true
    });
    var nanobar = new Nanobar({
      bg: '#42BEDB' , //(optional) background css property, '#000' by default
      target: document.getElementById('nanoBar') , //(optional) Where to put the progress bar, nanobar will be fixed to top of document if target is null
      // id for new nanobar
      id: 'nanoBar' // (optional) id for nanobar d
    });

    var progressChunk = parseInt(byteLength / 100);
    var currentProgress = 0;
    for (var i = 0; i < byteLength; i++) {
      var check = ((i % progressChunk) === 0);
      if (check) {
        currentProgress++;
        if (currentProgress <= 100) {
          nanobar.go(currentProgress);
        }
      }
      previewText += String.fromCharCode(unitArr[i]);
    }
  }).always(function() {
    window.setTimeout(function() {
      document.getElementById('nanoBar').remove();
    } , 1000);
  });
}

function setContent(content , fileDirectory) {
  var $htmlContent = $('#htmlContent');
  $htmlContent.append(content);

  if (fileDirectory.indexOf("file://") === 0) {
    fileDirectory = fileDirectory.substring(("file://").length , fileDirectory.length);
  }

  $htmlContent.append('
').css({
    'overflow': 'auto' ,
    'padding': '5px' ,
    'background-color': 'white' ,
    'fontSize': 12 ,
    'width': '100%' ,
    'height': '100%'
  });
  $htmlContent.append("

 Contents of file " + fileDirectory + "

");
  var ulFiles = $htmlContent.append("
");
  var zipFile = content;

  function showPreviewDialog(event) {
    event.preventDefault();
    var containFile = zipFile.files[$(this).text()];
    showContentFilePreviewDialog(containFile);
  }

  if (!!Object.keys(zipFile.files) &&
          (typeof zipFile !== 'function' ||
          zipFile === null)) {
    for (var fileName in zipFile.files) {
      if (zipFile.files[fileName].dir === true) {
        continue;
      }
      var linkToFile = $('').attr('href' , '#').text(fileName);
      linkToFile.click(showPreviewDialog);
      var liFile = $('
').css('list-style-type' , 'none').append(linkToFile);
      ulFiles.append(liFile);
    }
  } else {
    throw new TypeError("Object.keys called on non-object");
  }
}
<commit_msg>load content externally<commit_after>/* Copyright (c) 2013-present The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */
/* globals Handlebars, Nanobar, marked */
"use strict";

var isCordova;

var isWin;
var loadContentExternally = true;
var isWeb = (document.URL.startsWith('http') && !document.URL.startsWith('http://localhost:1212/'));
var JSZip;
var maxPreviewSize = (1024 * 3) || {}; //3kb limit for preview

$(document).ready(function() {
  function getParameterByName(name) {
    name = name.replace(/[\[]/ , "\\\[").replace(/[\]]/ , "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)") ,
            results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g , " "));
  }

  var locale = getParameterByName("locale");

  var extSettings;
  loadExtSettings();

  // isCordova = parent.isCordova;
  // isWin = parent.isWin;

  // Init internationalization
  i18next.init({
    ns: {namespaces: ['ns.viewerZIP']} ,
    debug: true ,
    lng: locale ,
    fallbackLng: 'en_US'
  } , function() {
    jqueryI18next.init(i18next, $);
    $('[data-i18n]').localize();
  });

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem("viewerZIPSettings"));
  }
});

function showContentFilePreviewDialog(containFile) {
  var unitArr = containFile.asUint8Array();
  var previewText = "";
  var byteLength = (unitArr.byteLength > maxPreviewSize) ? maxPreviewSize : unitArr.byteLength;

  for (var i = 0; i < byteLength; i++) {
    previewText += String.fromCharCode(unitArr[i]);
  }

  var fileContent = $("
").text(previewText);
  var $htmlContent = $('#htmlContent');

  $.post("previewDialog.html" , function(uiTPL) {
    //console.log("Load modal " + uiTPL);
    if ($('#previewDialog').length < 1) {
      var uiTemplate = Handlebars.compile(uiTPL);
      $('body').append(uiTemplate());
    }
    var dialogPreview = $('#previewDialog');
    dialogPreview.find('.modal-body').empty().append(fileContent);
    dialogPreview.modal({
      backdrop: 'static' ,
      show: true
    });
    var nanobar = new Nanobar({
      bg: '#42BEDB' , //(optional) background css property, '#000' by default
      target: document.getElementById('nanoBar') , //(optional) Where to put the progress bar, nanobar will be fixed to top of document if target is null
      // id for new nanobar
      id: 'nanoBar' // (optional) id for nanobar d
    });

    var progressChunk = parseInt(byteLength / 100);
    var currentProgress = 0;
    for (var i = 0; i < byteLength; i++) {
      var check = ((i % progressChunk) === 0);
      if (check) {
        currentProgress++;
        if (currentProgress <= 100) {
          nanobar.go(currentProgress);
        }
      }
      previewText += String.fromCharCode(unitArr[i]);
    }
  }).always(function() {
    window.setTimeout(function() {
      document.getElementById('nanoBar').remove();
    } , 1000);
  });
}

function setContent(content , fileDirectory) {
  var $htmlContent = $('#htmlContent');
  $htmlContent.append(content);

  if (fileDirectory.indexOf("file://") === 0) {
    fileDirectory = fileDirectory.substring(("file://").length , fileDirectory.length);
  }

  $htmlContent.append('
').css({
    'overflow': 'auto' ,
    'padding': '5px' ,
    'background-color': 'white' ,
    'fontSize': 12 ,
    'width': '100%' ,
    'height': '100%'
  });
  $htmlContent.append("

 Contents of file " + fileDirectory + "

");
  var ulFiles = $htmlContent.append("
");
  var zipFile = content;

  function showPreviewDialog(event) {
    event.preventDefault();
    var containFile = zipFile.files[$(this).text()];
    showContentFilePreviewDialog(containFile);
  }

  if (!!Object.keys(zipFile.files) &&
          (typeof zipFile !== 'function' ||
          zipFile === null)) {
    for (var fileName in zipFile.files) {
      if (zipFile.files[fileName].dir === true) {
        continue;
      }
      var linkToFile = $('').attr('href' , '#').text(fileName);
      linkToFile.click(showPreviewDialog);
      var liFile = $('
').css('list-style-type' , 'none').append(linkToFile);
      ulFiles.append(liFile);
    }
  } else {
    throw new TypeError("Object.keys called on non-object");
  }
}
<|endoftext|>


<commit_before>Mousetrap.bind('enter', function() { parseText(); });

Mousetrap.bind('up', function() { increaseValue(5); });
Mousetrap.bind('down', function() { increaseValue(-5); });

function parseText(doNotTrack) {
  var outputValue = '';
  var inputValue = document.getElementById('inputBox').value;

  outputValue = getColorOrWavelength(doNotTrack, inputValue);
  if (formulaToFromText(inputValue)) outputValue = formulaToFromText(inputValue);

  //If we had no luck with anything
  if (outputValue.indexOf('Color: undefined') !== -1) outputValue = '';

  document.getElementById('outputText').innerHTML = outputValue;
}

function increaseValue(amt) {
  var value = document.getElementById('inputBox').value;
  if (parseFloat(value).toString().length == value.toString().length) {
    document.getElementById('inputBox').value = parseFloat(value) + amt;
  }
  getColorOrWavelength(true);
}

function shortenedHex(hex) {
  if (hex) {
    var x = hex.split('');
    return x[0]+x[1]+x[3]+x[5];
  } else return false;
}

function enlargedHex(hex) {
  var x = hex.split('');
  return x[0]+x[1]+x[1]+x[2]+x[2]+x[3]+x[3];
}

function getColorOrWavelength(doNotTrack, value) {
  var color, direction, error, frequency, energy;
  var nanometers = 0;

  if (value.indexOf('e') == -1 && parseFloat(value) && parseFloat(value).toString().length == value.toString().length) {
    //we have a value in nanometers
    nanometers = value;
    color = getColorFromWaveLength(nanometers);
    frequency = (299792458*1000000000)/nanometers;
    energy = 6.62606957e-34 * frequency;
    direction = "fromNanometers";
  }
  else if (value.indexOf('e') != -1 && (value.indexOf('14') != -1 || value.indexOf('-19') != -1)) {
    //I just evalled unsanitized user input. twice. dealwithit.gif
    //we have a number in sci-notation
    if (eval(value)>1e14 && eval(value)<1e15) {
      //frequency = speed of light/wavelength
      //wavelength = speed of light/frequency
      frequency = eval(value);
      energy = 6.62606957e-34 * frequency;
      direction = "fromFrequency";
    }
    else if (eval(value)>1e-20 && eval(value)<1e-18)  {
      energy = eval(value);
      frequency = energy/6.62606957e-34;
      direction = "fromEnergy"
    }
    nanometers = (299792458*1000000000)/frequency; //speed of light times a big number (to convert from m to nm)
    color = getColorFromWaveLength(nanometers);
  }
  else {
    direction = "fromColor"
    //we have a color
    if (colorNameToHex(value)) {
      //our color is a named color e.x. teal
      color = colorNameToHex(value);
    } else if (value.indexOf('#') != -1) {
      //we have a hex color, which is good
      if (value.length == 4) value = enlargedHex(value);
      color = value;
    }

    var step = 10;

    for (var i=350*step; i<780*step; i++) {
      if (shortenedHex(getColorFromWaveLength(i/step)) == shortenedHex(color)) nanometers = i/step;
    }

    if (nanometers != 0) {
    	frequency = (299792458*1000000000)/nanometers;
    	energy = 6.62606957e-34 * frequency;
    }
  }
  document.getElementById('outputColor').style.backgroundColor = color;

  var returnValue = false;

  if (nanometers != 0) {
    returnValue = nanometers + " nanometers = "+color+" = "+Math.round(1000*frequency/1e14)/1000 + "e14 inverse seconds = " + Math.round(1000*energy/1e-19)/1000 +"e-19 J";
    error = "none";
  } else {
    returnValue = "Sorry! Your chosen color does not exist as one wavelength of light! Color: "+color;
    error = "colorNotOneWavelength";
  }

  if (!doNotTrack) {
    mixpanel.track('getColorOrWavelength', {'color':color, 'wavelength':nanometers, 'direction': direction, 'error': error})
  }

  return returnValue;
}

function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}
<commit_msg>add element recognization<commit_after>Mousetrap.bind('enter', function() { parseText(); });

Mousetrap.bind('up', function() { increaseValue(5); });
Mousetrap.bind('down', function() { increaseValue(-5); });

function getElement(text) {
  var capitalized = text.substr(0,1).toUpperCase()+text.toLowerCase().substr(1)
  if (elements[capitalized]) return elements[capitalized]
  for (var i=0; i<elements.length; i++) {
    if (elements[i].symbol === text) return elements[i]
  }
}

function makeElementReadable(element) {
  return JSON.stringify(element).replace(/_/g,' ').replace(/{/g,'').replace(/}/g,'').replace(/,/g,'
').replace(/"/g,'')
}

function parseText(doNotTrack) {
  var outputValue = '';
  var inputValue = document.getElementById('inputBox').value;

  outputValue = getColorOrWavelength(doNotTrack, inputValue);
  if (formulaToFromText(inputValue)) outputValue = formulaToFromText(inputValue);
  if (getElement(inputValue)) outputValue = makeElementReadable(getElement(inputValue));

  //If we had no luck with anything
  if (outputValue.indexOf('Color: undefined') !== -1) outputValue = '';

  document.getElementById('outputText').innerHTML = outputValue;
}

function increaseValue(amt) {
  var value = document.getElementById('inputBox').value;
  if (parseFloat(value).toString().length == value.toString().length) {
    document.getElementById('inputBox').value = parseFloat(value) + amt;
  }
  getColorOrWavelength(true);
}

function shortenedHex(hex) {
  if (hex) {
    var x = hex.split('');
    return x[0]+x[1]+x[3]+x[5];
  } else return false;
}

function enlargedHex(hex) {
  var x = hex.split('');
  return x[0]+x[1]+x[1]+x[2]+x[2]+x[3]+x[3];
}

function getColorOrWavelength(doNotTrack, value) {
  var color, direction, error, frequency, energy;
  var nanometers = 0;

  if (value.indexOf('e') == -1 && parseFloat(value) && parseFloat(value).toString().length == value.toString().length) {
    //we have a value in nanometers
    nanometers = value;
    color = getColorFromWaveLength(nanometers);
    frequency = (299792458*1000000000)/nanometers;
    energy = 6.62606957e-34 * frequency;
    direction = "fromNanometers";
  }
  else if (value.indexOf('e') != -1 && (value.indexOf('14') != -1 || value.indexOf('-19') != -1)) {
    //I just evalled unsanitized user input. twice. dealwithit.gif
    //we have a number in sci-notation
    if (eval(value)>1e14 && eval(value)<1e15) {
      //frequency = speed of light/wavelength
      //wavelength = speed of light/frequency
      frequency = eval(value);
      energy = 6.62606957e-34 * frequency;
      direction = "fromFrequency";
    }
    else if (eval(value)>1e-20 && eval(value)<1e-18)  {
      energy = eval(value);
      frequency = energy/6.62606957e-34;
      direction = "fromEnergy"
    }
    nanometers = (299792458*1000000000)/frequency; //speed of light times a big number (to convert from m to nm)
    color = getColorFromWaveLength(nanometers);
  }
  else {
    direction = "fromColor"
    //we have a color
    if (colorNameToHex(value)) {
      //our color is a named color e.x. teal
      color = colorNameToHex(value);
    } else if (value.indexOf('#') != -1) {
      //we have a hex color, which is good
      if (value.length == 4) value = enlargedHex(value);
      color = value;
    }

    var step = 10;

    for (var i=350*step; i<780*step; i++) {
      if (shortenedHex(getColorFromWaveLength(i/step)) == shortenedHex(color)) nanometers = i/step;
    }

    if (nanometers != 0) {
    	frequency = (299792458*1000000000)/nanometers;
    	energy = 6.62606957e-34 * frequency;
    }
  }
  document.getElementById('outputColor').style.backgroundColor = color;

  var returnValue = false;

  if (nanometers != 0) {
    returnValue = nanometers + " nanometers = "+color+" = "+Math.round(1000*frequency/1e14)/1000 + "e14 inverse seconds = " + Math.round(1000*energy/1e-19)/1000 +"e-19 J";
    error = "none";
  } else {
    returnValue = "Sorry! Your chosen color does not exist as one wavelength of light! Color: "+color;
    error = "colorNotOneWavelength";
  }

  if (!doNotTrack) {
    mixpanel.track('getColorOrWavelength', {'color':color, 'wavelength':nanometers, 'direction': direction, 'error': error})
  }

  return returnValue;
}

function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}
<|endoftext|>