<commit_before>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('db/words.db');

var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
               'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

exports.get = function(string, callback) {
  var time = process.hrtime();
  var start = time.pop() / 1000000000 + time.pop();

  var output = {
    words: [],
    score_total: 0
  };

  var words = uniq_fast(
    scramble(string)
      .map(combinations)
      .reduce(function(prev, cur) { return prev.concat(cur) })
      .filter(function(word) { return word.length > 1; })
  );

  var query = 'SELECT word, score FROM words WHERE word IN ("' + words.join('", "') + '")';
  db.all(query, function(error, rows) {
    if(error)
      throw error;

    rows.forEach(function(row) {
      output.words.push({
        word: row.word,
        score: row.score
      });
      output.score_total += row.score;
    });

    // fraction of combinations being valid words
    output.fraction = rows.length / words.length;

    // execution time
    time = process.hrtime();
    output.time = (time.pop() / 1000000000 + time.pop()) - start;

    // sort by word length, then alphabetically
    output.words.sort(function(a, b) {
      if(a.word.length < b.word.length) return -1;
      if(a.word.length > b.word.length) return 1;
      if(a.word < b.word) return -1;
      if(a.word > b.word) return 1;

      return 0;
    });

    callback(null, output);
  });
};

// helper to remove duplicates from array
function uniq_fast(a) {
  var seen = {};
  var out = [];
  var len = a.length;
  var j = 0;
  for(var i = 0; i < len; i++) {
     var item = a[i];
     if(seen[item] !== 1) {
       seen[item] = 1;
       out[j++] = item;
     }
  }
  return out;
}

// helper to find all combinations of letters from a string
function combinations(str) {
  var fn = function(active, rest, a) {
    if(!active && !rest)
      return;
    if(!rest) {
      a.push(active);
    } else {
      fn(active + rest[0], rest.slice(1), a);
      fn(active, rest.slice(1), a);
    }
    return a;
  }
  return fn("", str, []);
}

// helper to scramble string
function scramble(str){
  //Array to store the generated words
  var words = [];

  /**
   * Recursive function to split a string and rearrange
   * it's characters and then join the results
   * @str: String [String to split]
   * @prefix: String [Characters to prepend to the string]
   */
  function rearrange(str, prefix) {
    var i, singleChar, balanceStr, word;

    //The first time round, prefix will be empty
    prefix = prefix || '';

    //Loop over the str to separate each single character
    //from the rest of it's characters
    for(i = 0; i < str.length; i++) {
      singleChar = str[i];
      balanceStr = str.slice(0, i) + str.slice(i+1);

      //join the prefix with each of the combinations
      word = prefix + singleChar + balanceStr;

      //Inject this word only if it does not exist
      if(words.indexOf(word) < 0) words.push(word);

      //Recursively call this function in case there are balance characters
      if(balanceStr.length > 1) rearrange(balanceStr, prefix + singleChar);
    }
  }

  //kick start recursion
  rearrange(str);
  return words;
}<commit_msg>add db.close()<commit_after>var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('db/words.db');

var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
               'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

exports.get = function(string, callback) {
  var time = process.hrtime();
  var start = time.pop() / 1000000000 + time.pop();

  var output = {
    words: [],
    score_total: 0
  };

  var words = uniq_fast(
    scramble(string)
      .map(combinations)
      .reduce(function(prev, cur) { return prev.concat(cur) })
      .filter(function(word) { return word.length > 1; })
  );

  var query = 'SELECT word, score FROM words WHERE word IN ("' + words.join('", "') + '")';
  db.all(query, function(error, rows) {
    if(error)
      throw error;

    rows.forEach(function(row) {
      output.words.push({
        word: row.word,
        score: row.score
      });
      output.score_total += row.score;
    });

    // fraction of combinations being valid words
    output.fraction = rows.length / words.length;

    // execution time
    time = process.hrtime();
    output.time = (time.pop() / 1000000000 + time.pop()) - start;

    // sort by word length, then alphabetically
    output.words.sort(function(a, b) {
      if(a.word.length < b.word.length) return -1;
      if(a.word.length > b.word.length) return 1;
      if(a.word < b.word) return -1;
      if(a.word > b.word) return 1;

      return 0;
    });

    callback(null, output);
    db.close();
  });
};

// helper to remove duplicates from array
function uniq_fast(a) {
  var seen = {};
  var out = [];
  var len = a.length;
  var j = 0;
  for(var i = 0; i < len; i++) {
     var item = a[i];
     if(seen[item] !== 1) {
       seen[item] = 1;
       out[j++] = item;
     }
  }
  return out;
}

// helper to find all combinations of letters from a string
function combinations(str) {
  var fn = function(active, rest, a) {
    if(!active && !rest)
      return;
    if(!rest) {
      a.push(active);
    } else {
      fn(active + rest[0], rest.slice(1), a);
      fn(active, rest.slice(1), a);
    }
    return a;
  }
  return fn("", str, []);
}

// helper to scramble string
function scramble(str){
  //Array to store the generated words
  var words = [];

  /**
   * Recursive function to split a string and rearrange
   * it's characters and then join the results
   * @str: String [String to split]
   * @prefix: String [Characters to prepend to the string]
   */
  function rearrange(str, prefix) {
    var i, singleChar, balanceStr, word;

    //The first time round, prefix will be empty
    prefix = prefix || '';

    //Loop over the str to separate each single character
    //from the rest of it's characters
    for(i = 0; i < str.length; i++) {
      singleChar = str[i];
      balanceStr = str.slice(0, i) + str.slice(i+1);

      //join the prefix with each of the combinations
      word = prefix + singleChar + balanceStr;

      //Inject this word only if it does not exist
      if(words.indexOf(word) < 0) words.push(word);

      //Recursively call this function in case there are balance characters
      if(balanceStr.length > 1) rearrange(balanceStr, prefix + singleChar);
    }
  }

  //kick start recursion
  rearrange(str);
  return words;
}<|endoftext|>


<commit_before>var ws2801 = require('rpi-ws2801'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 75,
    loops: 5, // number of times to run the light loops i.e. for appointments booked
    currentLoop: 0,

    init: function () {

        socket = socket('https://appointments.spruce.me');

        ws2801.connect(this.totalLeds);

        socket.on('connect', function(){
            console.log('connected');
        });

        socket.on('did-book-appointments', function(){
            this.roll();
        }.bind(this));

    },
    //Create a pattern that is every other one
    //Acceptable values for each array are : 0 - 255
    //color: array[red, green, blue] e.g [255,0,0]
    dotted: function (colorOne, colorTwo) {
        _.times(this.totalLeds, function (i) {
            if (i % 2 == 1) {
                ws2801.setColor(i, colorOne);
            }
            else {
                ws2801.setColor(i, colorTwo);
            }
        });
        this.update();

    },
    roll: function() {

        _(this.totalLeds).times(function(i) {
            setTimeout(function() {
                ws2801.setColor(i, [this.randomValue(), this.randomValue(), this.randomValue()]);
                ws2801.update();

                if(i == (this.totalLeds - 1)) {
                    if(this.currentLoop < this.loops) {
                        this.currentLoop++;
                        this.roll();
                    }
                    else
                    {
                        this.currentLoop = 0;
                        this.allWhite();
                    }
                }

            }.bind(this), 10 * i);
        }.bind(this));

    },
    runner: function () {

            var index = 0,
            i = 1,
            ri = 1,
            r = 0;

        setInterval(function () {

            ws2801.setColor(index, [r, 0, 255]);
            r += ri;
            index += i;
            ws2801.update();

            if (r >= 255 || r <= 0) {
                ri *= -1;
            }

            if (index >= this.totalLeds || index <= 0) {
                i *= -1;
            }
        }, 10);

    },
    // fill(r, g, b)
    // r, g, b: value as hex (0x00 = 0, 0xFF = 255, 0x7F = 127)
    fill: function (color1, color2, color3) {
        ws2801.fill(color1, color2, color3);
        //this.update();d
    },
    allWhite: function() {
        this.fill(255, 255, 255);
    },
    randomValue: function() {
        return Math.random() * (255 - 0) + 0;
    },
    invert: function () {
        ws2801.invert();
    },
    clear: function () {
        ws2801.clear();
    },
    update: function () {
        ws2801.update();
    },
    disconnect: function () {
        ws2801.disconnect();
    }

};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if(args.length > 0) {
    // We have passed a custom command, lets make sure we call that
    sign[args[0]]()
}
else
{
    // Sign defaults to
    sign.allWhite();
}
<commit_msg>delay on startup fill white console log<commit_after>var ws2801 = require('rpi-ws2801'),
    _ = require('underscore'),
    socket = require('socket.io-client');

var sign = {

    totalLeds: 250,
    loops: 5, // number of times to run the light loops i.e. for appointments booked
    currentLoop: 0,

    init: function () {

        socket = socket('https://appointments.spruce.me');

        ws2801.connect(this.totalLeds);

        socket.on('connect', function(){
            console.log('connected');
        });

        socket.on('did-book-appointments', function(){
            this.roll();
        }.bind(this));

    },
    //Create a pattern that is every other one
    //Acceptable values for each array are : 0 - 255
    //color: array[red, green, blue] e.g [255,0,0]
    dotted: function (colorOne, colorTwo) {
        _.times(this.totalLeds, function (i) {
            if (i % 2 == 1) {
                ws2801.setColor(i, colorOne);
            }
            else {
                ws2801.setColor(i, colorTwo);
            }
        });
        this.update();

    },
    roll: function() {

        console.log('calling roll');
        _(this.totalLeds).times(function(i) {
            setTimeout(function() {
                console.log('setting timeout', i);
                ws2801.setColor(i, [this.randomValue(), this.randomValue(), this.randomValue()]);
                ws2801.update();

                if(i == (this.totalLeds - 1)) {

                    if(this.currentLoop < this.loops) {
                        console.log('incrementing loop', this.currentLoop);
                        this.currentLoop++;
                        this.roll();
                    }
                    else
                    {
                        console.log('filling with white');
                        this.currentLoop = 0;
                        this.allWhite();
                    }
                }

            }.bind(this), 10 * i);
        }.bind(this));

    },
    runner: function () {

            var index = 0,
            i = 1,
            ri = 1,
            r = 0;

        setInterval(function () {

            ws2801.setColor(index, [r, 0, 255]);
            r += ri;
            index += i;
            ws2801.update();

            if (r >= 255 || r <= 0) {
                ri *= -1;
            }

            if (index >= this.totalLeds || index <= 0) {
                i *= -1;
            }
        }, 10);

    },
    // fill(r, g, b)
    // r, g, b: value as hex (0x00 = 0, 0xFF = 255, 0x7F = 127)
    fill: function (color1, color2, color3) {
        ws2801.fill(color1, color2, color3);
        //this.update();d
    },
    allWhite: function() {
        this.fill(255, 255, 255);
        this.update();
    },
    randomValue: function() {
        return Math.random() * (255 - 0) + 0;
    },
    invert: function () {
        ws2801.invert();
    },
    clear: function () {
        ws2801.clear();
    },
    update: function () {
        ws2801.update();
    },
    disconnect: function () {
        ws2801.disconnect();
    }

};

sign.init();

// Do we have any custom commands to run?
var args = process.argv.slice(2);

if(args.length > 0) {
    sign.allWhite();

    // We have passed a custom command, lets make sure we call that
    setTimeout(function() {
        sign[args[0]]()
    }, 5000);

}
else
{
    // Sign defaults to
    sign.allWhite();
}
<|endoftext|>


<commit_before>// This component handles a transaction response and that's it. It should never appear except as a response.
var payment = {
  vm: {
    handleQueryParameters: function() {

      // Interpret query parameters.
      var paymentID = m.route.param("paymentId");
      var token = m.route.param("token");
      var payerID = m.route.param("PayerID");

      // If query parameters aren't provided, route to home.
      if (paymentID == null || paymentID == "" ||
          payerID == null || payerID == "") {
        if (token != null && token != "") {
          m.route("/");
          openModal(null, genericMessageModal,
            {
              messageTitle:"Payment cancelled!",
              message:"Returning to the Adventure Guild website.",
            }
          );
        }
        else {
          m.route("/");
          openModal(null, genericMessageModal,
            {
              messageTitle:"Payment error!",
              message:"No payment data to process.",
            }
          );
        }
      }
      else {
        // Make the payment and wait for a response.
      }
    }
  },
  view: function() {
    return [
      m.component(nav, {page: "payment"}),
      m.component(waitingForPayment),
      m.component(footer)
    ];
  }
}

// Component that displays while waiting for a response from the ajax call.
var waitingForPayment = {
  view: function() {
    return m("section", {
      class: "hero position-under-nav",
      config: function(el, isInit) {if(!isInit){payment.vm.handleQueryParameters();}}
    }, [
      m(".vertical-center-always payment-processing", m("div", [
        m("h1", "Processing Payment..."),
        m("div", m("img", {src:"imgs/icons/ajax-loader.gif", alt:"AJAX"}))
      ]))
    ])
  }
}
<commit_msg>Payment page now shoots valid request to PayPal to execute payment, and responds with proper modal and message<commit_after>// This component handles a transaction response and that's it. It should never appear except as a response.
var payment = {
  vm: {
    handleQueryParameters: function() {

      // Interpret query parameters.
      var paymentID = m.route.param("paymentId");
      var token = m.route.param("token");
      var payerID = m.route.param("PayerID");

      // If query parameters aren't provided, route to home.
      if (paymentID == null || paymentID == "" ||
          payerID == null || payerID == "") {
        if (token != null && token != "") {
          m.route("/");
          openModal(null, genericMessageModal,
            {
              messageTitle:"Payment cancelled!",
              message:"Returning to the Adventure Guild website.",
            }
          );
        }
        else {
          m.route("/");
          openModal(null, genericMessageModal,
            {
              messageTitle:"Payment error!",
              message:"No payment data to process.",
            }
          );
        }
      }
      else {
        // Make the payment and wait for a response.
        storeExecuteOrder(paymentID, payerID, function(response) {
            m.route("/");
            openModal(null, genericMessageModal,
                {
                    messageTitle: "Thank You!",
                    message: "Your purchase has been completed!\n\nYou can now use the Guildium you purchased inside our in-game store. Happy Adventuring!"
                }
            );
        });
      }
    }
  },
  view: function() {
    return [
      m.component(nav, {page: "payment"}),
      m.component(waitingForPayment),
      m.component(footer)
    ];
  }
}

// Component that displays while waiting for a response from the ajax call.
var waitingForPayment = {
  view: function() {
    return m("section", {
      class: "hero position-under-nav",
      config: function(el, isInit) {if(!isInit){payment.vm.handleQueryParameters();}}
    }, [
      m(".vertical-center-always payment-processing", [
        m("h1", "Processing Payment..."),
        m("img", {src:"imgs/icons/ajax-loader.gif", alt:"AJAX"})
        ])
    ])
  }
}
<|endoftext|>


<commit_before>export default function () {
  const swiper = this;
  swiper.realIndex = parseInt(swiper.slides.eq(swiper.activeIndex).attr('data-swiper-slide-index') || swiper.activeIndex, 10);
}
<commit_msg>Emit index change events<commit_after>export default function () {
  const swiper = this;
  const previousRealIndex = swiper.realIndex;
  swiper.realIndex = parseInt(swiper.slides.eq(swiper.activeIndex).attr('data-swiper-slide-index') || swiper.activeIndex, 10);
  if (previousRealIndex !== swiper.realIndex) {
    swiper.emit('realIndexChange');
  }
}
<|endoftext|>


<commit_before>var stats = new Object();
stats["loc"] = 0;
stats["bug"] = 0;
stats["money"] = 0;
stats["locPerSecond"] = 0;
stats["moneyMultiplier"] = 1;
var programmersCount = 0;
var bugPercentage = 37;
var programmersMultiplier = 0.1;

function init() {
	updateStats();
	Cookies.setCookie("name", "vasyok", 365);
	//Cookies.checkCookie(name);
	//bugPercentage = $("#bugs").text();
}

function hireProgrammer() {
	if(stats.money >= 10*makeRound(Math.pow(1.15,programmersCount),1)) {
		stats.locPerSecond += 0.1;
		programmersCount++;
		stats.money -= 10*makeRound(Math.pow(1.15,programmersCount - 1),1);
	}
	updateStats();
}

window.onload = function() {
	init();
	setInterval(function() {
		stats.loc+=stats.locPerSecond;
		if (programmersCount > 0)
			bugAdd(bugPercentage - 30);
		updateStats();
	}, 1000);
	setInterval(function() {
		updateStats();
	}, 100);
}

function fixBug() {
	bugRemove(bugPercentage - 20);
}

function makeRound(number, decimals) {
	return Math.floor(number*Math.pow(10, decimals))/Math.pow(10, decimals);
}

function updateStats() {
	$("#prog").html(programmersCount);
	$("#lps").html(makeRound(stats.locPerSecond, 1));
	$("body>#div").html(makeRound(stats.loc, 1) + " " + stats.bug + " " + makeRound(stats.money, 1));
	//$("#locArea>div>h1").html(makeRound(stats.loc, 1));
	//$("#locArea>div>h2").html(makeRound(stats.locPerSecond, 1))
}

function clickFunction() {
	stats.loc++;
	bugAdd(bugPercentage);
	updateStats();
}
function bugChange(bugPercentage) {
	return Math.floor(Math.random()*(45 - bugPercentage) + 1) == 1;
}
function bugAdd(bugPercentage) {
	if(bugChange(bugPercentage) && Math.floor(stats.loc) > stats.bug) {
		stats.bug++;
	}
}
function bugRemove(bugPercentage) {
	if(bugChange(bugPercentage) && (stats.bug != 0)) {
		stats.bug--;
	}
}

function addMoney(bugMultiplier, currentBugs) {
		if (stats.bug != currentBugs && currentBugs != 0)
			stats.money += stats.moneyMultiplier/bugMultiplier;
		else stats.money += stats.moneyMultiplier;
}

function sellProject() {
		alert(1);
}

function sellLOC() {
	var currentBugs = stats.bug;
	var bugMultiplier = stats.bug == 0 ? 1 : 1.15*stats.bug;
	if(Math.floor(stats.loc) > 0) {
		if(Math.floor(stats.loc) > stats.bug) {
			stats.loc--;
			bugRemove(bugPercentage);
		}
		else {
			stats.loc--;
			stats.bug--;
		}
		addMoney(bugMultiplier, currentBugs);
		updateStats();
	}
}
<commit_msg>cookies functions become stronger<commit_after>var stats = new Object();
stats["loc"] = 0;
stats["bug"] = 0;
stats["money"] = 0;
stats["locPerSecond"] = 0;
stats["moneyMultiplier"] = 1;
var programmersCount = 0;
var bugPercentage = 37;
var programmersMultiplier = 0.1;

function init() {
	updateStats();
	Cookies.setCookie("name", "vasyok", 365);

	//bugPercentage = $("#bugs").text();
}

function hireProgrammer() {
	if(stats.money >= 10*makeRound(Math.pow(1.15,programmersCount),1)) {
		stats.locPerSecond += 0.1;
		programmersCount++;
		stats.money -= 10*makeRound(Math.pow(1.15,programmersCount - 1),1);
	}
	alert(Cookies.getCookie("name"));
	updateStats();
}

window.onload = function() {
	init();
	setInterval(function() {
		stats.loc+=stats.locPerSecond;
		if (programmersCount > 0)
			bugAdd(bugPercentage - 30);
		updateStats();
	}, 1000);
	setInterval(function() {
		updateStats();
	}, 100);
}

function fixBug() {
	bugRemove(bugPercentage - 20);
}

function makeRound(number, decimals) {
	return Math.floor(number*Math.pow(10, decimals))/Math.pow(10, decimals);
}

function updateStats() {
	$("#prog").html(programmersCount);
	$("#lps").html(makeRound(stats.locPerSecond, 1));
	$("body>#div").html(makeRound(stats.loc, 1) + " " + stats.bug + " " + makeRound(stats.money, 1));
	//$("#locArea>div>h1").html(makeRound(stats.loc, 1));
	//$("#locArea>div>h2").html(makeRound(stats.locPerSecond, 1))
}

function clickFunction() {
	stats.loc++;
	bugAdd(bugPercentage);
	updateStats();
}
function bugChange(bugPercentage) {
	return Math.floor(Math.random()*(45 - bugPercentage) + 1) == 1;
}
function bugAdd(bugPercentage) {
	if(bugChange(bugPercentage) && Math.floor(stats.loc) > stats.bug) {
		stats.bug++;
	}
}
function bugRemove(bugPercentage) {
	if(bugChange(bugPercentage) && (stats.bug != 0)) {
		stats.bug--;
	}
}

function addMoney(bugMultiplier, currentBugs) {
		if (stats.bug != currentBugs && currentBugs != 0)
			stats.money += stats.moneyMultiplier/bugMultiplier;
		else stats.money += stats.moneyMultiplier;
}

function sellProject() {
		alert(1);
}

function sellLOC() {
	var currentBugs = stats.bug;
	var bugMultiplier = stats.bug == 0 ? 1 : 1.15*stats.bug;
	if(Math.floor(stats.loc) > 0) {
		if(Math.floor(stats.loc) > stats.bug) {
			stats.loc--;
			bugRemove(bugPercentage);
		}
		else {
			stats.loc--;
			stats.bug--;
		}
		addMoney(bugMultiplier, currentBugs);
		updateStats();
	}
}
<|endoftext|>


<commit_before>import { Menu } from './Menu'

export const Credits = () =>

		<Menu />

github

       <commit_msg>Eve Porcello and Alex Banks credit<commit_after>import { Menu } from './Menu'

export const Credits = () =>

		<Menu />

glsl editor by Particio Gonzalez Vivo

the_Force by Shawn Lawson

Eve Porcello and Alex Banks for their excellent react/nodejs courses on LinkedIn

       <|endoftext|>


<commit_before>import angular from 'angular';

import AriaModule from 'angular-aria';
import DialogModule from 'ng-dialog';
import DragAndDropModule from 'angular-native-dragdrop';
import MessagesModule from 'angular-messages';
import RateLimiterModule from 'ng-http-rate-limiter';
import SliderModule from 'angularjs-slider';
import ToasterModule from 'angularjs-toaster';
import TranslateModule from 'angular-translate';
import TranslateMessageFormatModule from 'angular-translate-interpolation-messageformat';
import UIRouterModule from '@uirouter/angularjs';
import 'angular-hotkeys';
import 'angular-promise-tracker';

import bungieApiModule from './bungie-api/bungie-api.module';
import { ShellModule } from './shell/shell.module';
import inventoryModule from './store/inventory.module';
import recordBooksModule from './record-books/record-books.module';
import vendorsModule from './vendors/vendors.module';
import itemReviewModule from './item-review/item-review.module';
import loadoutBuilderModule from './loadout-builder/loadout-builder.module';
import infuseModule from './infuse/infuse.module';
import settingsModule from './settings/settings.module';
import oauthModule from './oauth/oauth.module';
import storageModule from './storage/storage.module';

import config from './dimApp.config';
import routes from './dimApp.routes';
import run from './dimApp.run';
import state from './state';
import loadingTracker from './services/dimLoadingTracker.factory';

const dependencies = [
  AriaModule,
  DialogModule,
  DragAndDropModule,
  MessagesModule,
  RateLimiterModule,
  ShellModule,
  SliderModule,
  ToasterModule,
  TranslateModule,
  TranslateMessageFormatModule,
  UIRouterModule,
  bungieApiModule,
  inventoryModule,
  recordBooksModule,
  vendorsModule,
  itemReviewModule,
  loadoutBuilderModule,
  infuseModule,
    settingsModule,
  oauthModule,
  storageModule,
  'ajoslin.promise-tracker',
  'cfp.hotkeys'
];

if ($featureFlags.materialsExchangeEnabled) {
  const materialsExchangeModule = require('./materials-exchange/materials-exchange.module').default;
  dependencies.push(materialsExchangeModule);
}

export const DimAppModule = angular
  .module('dimApp', dependencies)
  .config(config)
  .config(routes)
  .run(run)
  .value('dimState', state)
  .factory('loadingTracker', loadingTracker)
  .name;
<commit_msg>Update dimApp.module.js<commit_after>import angular from 'angular';

import AriaModule from 'angular-aria';
import DialogModule from 'ng-dialog';
import DragAndDropModule from 'angular-native-dragdrop';
import MessagesModule from 'angular-messages';
import RateLimiterModule from 'ng-http-rate-limiter';
import SliderModule from 'angularjs-slider';
import ToasterModule from 'angularjs-toaster';
import TranslateModule from 'angular-translate';
import TranslateMessageFormatModule from 'angular-translate-interpolation-messageformat';
import UIRouterModule from '@uirouter/angularjs';
import 'angular-hotkeys';
import 'angular-promise-tracker';

import bungieApiModule from './bungie-api/bungie-api.module';
import { ShellModule } from './shell/shell.module';
import inventoryModule from './store/inventory.module';
import recordBooksModule from './record-books/record-books.module';
import vendorsModule from './vendors/vendors.module';
import itemReviewModule from './item-review/item-review.module';
import loadoutBuilderModule from './loadout-builder/loadout-builder.module';
import infuseModule from './infuse/infuse.module';
import settingsModule from './settings/settings.module';
import oauthModule from './oauth/oauth.module';
import storageModule from './storage/storage.module';

import config from './dimApp.config';
import routes from './dimApp.routes';
import run from './dimApp.run';
import state from './state';
import loadingTracker from './services/dimLoadingTracker.factory';

const dependencies = [
  AriaModule,
  DialogModule,
  DragAndDropModule,
  MessagesModule,
  RateLimiterModule,
  ShellModule,
  SliderModule,
  ToasterModule,
  TranslateModule,
  TranslateMessageFormatModule,
  UIRouterModule,
  bungieApiModule,
  inventoryModule,
  recordBooksModule,
  vendorsModule,
  itemReviewModule,
  loadoutBuilderModule,
  infuseModule,
  settingsModule,
  oauthModule,
  storageModule,
  'ajoslin.promise-tracker',
  'cfp.hotkeys'
];

if ($featureFlags.materialsExchangeEnabled) {
  const materialsExchangeModule = require('./materials-exchange/materials-exchange.module').default;
  dependencies.push(materialsExchangeModule);
}

export const DimAppModule = angular
  .module('dimApp', dependencies)
  .config(config)
  .config(routes)
  .run(run)
  .value('dimState', state)
  .factory('loadingTracker', loadingTracker)
  .name;
<|endoftext|>


<commit_before>/**
 * @file Defines the provider settings.
 *
 * Will set the path to Mongo, and applications id
 * Most of the configuration can be done using system environment variables.
 */
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();

// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.NODE_ENV || "development";

// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var defaultPort = 8000;
if(nodeEnv === "production") {
  defaultPort = 80;
}

// Exports configuration for use by app.js
module.exports = {
  env: nodeEnv,
  port: process.env.PORT || defaultPort,

  mongoUrl: process.env.MONGO_URL || process.env.MONGOLAB_URI,
  redisUrl: process.env.REDIS_URL || process.env.REDISCLOUD_URL,

  // Optional params
  usersConcurrency: process.env.USERS_CONCURRENCY || 1,
  concurrency: process.env.CONCURRENCY || 1,

  providerUrl: process.env.PROVIDER_URL,
  appId: process.env.ANYFETCH_API_ID,
  appSecret: process.env.ANYFETCH_API_SECRET,
  linkedin: {
    fake: process.env.LINKEDIN_FAKE_ACCESS_TOKEN,
    api: process.env.LINKEDIN_API_KEY,
    secret: process.env.LINKEDIN_SECRET_TOKEN,
  },

  opbeat: {
    organizationId: process.env.OPBEAT_ORGANIZATION_ID,
    appId: process.env.OPBEAT_APP_ID,
    secretToken: process.env.OPBEAT_SECRET_TOKEN
  }
};
<commit_msg>Changing env var<commit_after>/**
 * @file Defines the provider settings.
 *
 * Will set the path to Mongo, and applications id
 * Most of the configuration can be done using system environment variables.
 */
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();

// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.NODE_ENV || "development";

// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var defaultPort = 8000;
if(nodeEnv === "production") {
  defaultPort = 80;
}

// Exports configuration for use by app.js
module.exports = {
  env: nodeEnv,
  port: process.env.PORT || defaultPort,

  mongoUrl: process.env.MONGO_URL || process.env.MONGOLAB_URI,
  redisUrl: process.env.REDIS_URL || process.env.REDISCLOUD_URL,

  // Optional params
  usersConcurrency: process.env.USERS_CONCURRENCY || 1,
  concurrency: process.env.CONCURRENCY || 1,

  providerUrl: process.env.PROVIDER_URL,
  appId: process.env.ANYFETCH_API_ID,
  appSecret: process.env.ANYFETCH_API_SECRET,
  linkedin: {
    fake: process.env.LINKEDIN_FAKE_ACCESS_TOKEN,
    api: process.env.LINKEDIN_API_ID,
    secret: process.env.LINKEDIN_API_SECRET,
  },

  opbeat: {
    organizationId: process.env.OPBEAT_ORGANIZATION_ID,
    appId: process.env.OPBEAT_APP_ID,
    secretToken: process.env.OPBEAT_SECRET_TOKEN
  }
};
<|endoftext|>


<commit_before>function generate(){
    save();

    if(charlist.length <= 0){
        document.getElementById('passwords').innerHTML = 'You must select at least one option.';
        return;
    }

    var passwords = '';

    // Create new password.
    var password_loopcounter = document.getElementById('number-of-passwords').value - 1;
    do{
        // Add character to current password.
        var character_loopcounter = document.getElementById('length').value - 1;
        do{
            // Select random characters from possible character list...
            //   ...handle the HTML symbols...
            //   ...and add it to the passwords string.
            passwords += charlist.substr(
              Math.floor(Math.random() * charlist.length - 1),
              1
            ).replace(/&/g,'&') // &
             .replace(/>/g,'>') // >
             .replace(/</g,'<') // <
             .replace(/"/g,'"'); // "
        }while(character_loopcounter--);

        passwords += '
';
    }while(password_loopcounter--);

    document.getElementById('passwords').innerHTML = passwords;
}

function reset(){
    if(!confirm('Reset settings?')){
        return;
    }

    document.getElementById('latin-lowercase').checked = true;
    document.getElementById('latin-uppercase').checked = true;
    document.getElementById('length').value = 15;
    document.getElementById('number-of-passwords').value = 1;
    document.getElementById('numbers').checked = true;
    document.getElementById('other-lowercase').checked = true;
    document.getElementById('other-uppercase').checked = true;
    document.getElementById('passwords').innerHTML = '';
    document.getElementById('symbols').checked = true;

    save();
}

function save(){
    // Validate settings.

    if(isNaN(document.getElementById('length').value)
      || document.getElementById('length').value < 1
      || document.getElementById('length').value == 15){
        document.getElementById('length').value = 15;
        window.localStorage.removeItem('PasswordGenerator.htm-length');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-length',
          document.getElementById('length').value
        );
    }

    if(isNaN(document.getElementById('number-of-passwords').value)
      || document.getElementById('number-of-passwords').value < 1
      || document.getElementById('number-of-passwords').value == 1){
        document.getElementById('number-of-passwords').value = 1;
        window.localStorage.removeItem('PasswordGenerator.htm-number-of-passwords');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-number-of-passwords',
          document.getElementById('number-of-passwords').value
        );
    }

    // Create list of possible characters.
    // If not checked, store value in window.localStorage.
    charlist = '';

    if(document.getElementById('latin-lowercase').checked){
        charlist += 'abcdefghijklmnopqrstuvwxyz';
        window.localStorage.removeItem('PasswordGenerator.htm-latin-lowercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-latin-lowercase',
          1
        );
    }

    if(document.getElementById('latin-uppercase').checked){
        charlist += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        window.localStorage.removeItem('PasswordGenerator.htm-latin-uppercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-latin-uppercase',
          1
        );
    }

    if(document.getElementById('numbers').checked){
        charlist += '0123456789';
        window.localStorage.removeItem('PasswordGenerator.htm-numbers');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-numbers',
          1
        );
    }

    if(document.getElementById('other-lowercase').checked){
        charlist += document.getElementById('other-lowercase-touse').value;
        window.localStorage.removeItem('PasswordGenerator.htm-other-lowercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-other-lowercase',
          1
        );
    }

    if(document.getElementById('other-uppercase').checked){
        charlist += document.getElementById('other-uppercase-touse').value;
        window.localStorage.removeItem('PasswordGenerator.htm-other-uppercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-other-uppercase',
          1
        );
    }

    if(document.getElementById('symbols').checked){
        charlist += document.getElementById('symbols-touse').value;
        window.localStorage.removeItem('PasswordGenerator.htm-symbols');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-symbols',
          1
        );
    }
}

var charlist = '';

// Check or uncheck settings based on window.localStorage.
document.getElementById('length').value = window.localStorage.getItem('PasswordGenerator.htm-length') === null
  ? 15
  : window.localStorage.getItem('PasswordGenerator.htm-length');

document.getElementById('latin-lowercase').checked =
  window.localStorage.getItem('PasswordGenerator.htm-latin-lowercase') === null;

document.getElementById('latin-uppercase').checked =
  window.localStorage.getItem('PasswordGenerator.htm-latin-uppercase') === null;

document.getElementById('number-of-passwords').value =
  window.localStorage.getItem('PasswordGenerator.htm-number-of-passwords') === null
    ? 1
    : window.localStorage.getItem('PasswordGenerator.htm-number-of-passwords');

document.getElementById('numbers').checked =
  window.localStorage.getItem('PasswordGenerator.htm-numbers') === null;

document.getElementById('other-lowercase').checked =
  window.localStorage.getItem('PasswordGenerator.htm-other-lowercase') === null;

document.getElementById('other-lowercase-touse').value = 'áčďéěiíňóřšťúůýž';

document.getElementById('other-uppercase').checked =
  window.localStorage.getItem('PasswordGenerator.htm-other-uppercase') === null;

document.getElementById('other-uppercase-touse').value = 'ÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ';

document.getElementById('symbols').checked =
  window.localStorage.getItem('PasswordGenerator.htm-symbols') === null;

document.getElementById('symbols-touse').value = '~!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/?';

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // ENTER: generate a new password.
    if(key === 13){
        generate();
    }
};
<commit_msg>improved formatting<commit_after>function generate(){
    save();

    if(charlist.length <= 0){
        document.getElementById('passwords').innerHTML = 'You must select at least one option.';
        return;
    }

    var passwords = '';

    // Create new password.
    var password_loopcounter = document.getElementById('number-of-passwords').value - 1;
    do{
        // Add character to current password.
        var character_loopcounter = document.getElementById('length').value - 1;
        do{
            // Select random characters from possible character list...
            //   ...handle the HTML symbols...
            //   ...and add it to the passwords string.
            passwords += charlist.substr(
              Math.floor(Math.random() * charlist.length - 1),
              1
            ).replace(/&/g,'&') // &
             .replace(/>/g,'>') // >
             .replace(/</g,'<') // <
             .replace(/"/g,'"'); // "
        }while(character_loopcounter--);

        passwords += '
';
    }while(password_loopcounter--);

    document.getElementById('passwords').innerHTML = passwords;
}

function reset(){
    if(!confirm('Reset settings?')){
        return;
    }

    document.getElementById('latin-lowercase').checked = true;
    document.getElementById('latin-uppercase').checked = true;
    document.getElementById('length').value = 15;
    document.getElementById('number-of-passwords').value = 1;
    document.getElementById('numbers').checked = true;
    document.getElementById('other-lowercase').checked = true;
    document.getElementById('other-uppercase').checked = true;
    document.getElementById('passwords').innerHTML = '';
    document.getElementById('symbols').checked = true;

    save();
}

// Save settings into window.localStorage if they differ from default.
function save(){
    if(isNaN(document.getElementById('length').value)
      || document.getElementById('length').value < 1
      || document.getElementById('length').value == 15){
        document.getElementById('length').value = 15;
        window.localStorage.removeItem('PasswordGenerator.htm-length');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-length',
          document.getElementById('length').value
        );
    }

    if(isNaN(document.getElementById('number-of-passwords').value)
      || document.getElementById('number-of-passwords').value < 1
      || document.getElementById('number-of-passwords').value == 1){
        document.getElementById('number-of-passwords').value = 1;
        window.localStorage.removeItem('PasswordGenerator.htm-number-of-passwords');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-number-of-passwords',
          document.getElementById('number-of-passwords').value
        );
    }

    // Create list of possible characters.
    charlist = '';

    if(document.getElementById('latin-lowercase').checked){
        charlist += 'abcdefghijklmnopqrstuvwxyz';
        window.localStorage.removeItem('PasswordGenerator.htm-latin-lowercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-latin-lowercase',
          1
        );
    }

    if(document.getElementById('latin-uppercase').checked){
        charlist += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        window.localStorage.removeItem('PasswordGenerator.htm-latin-uppercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-latin-uppercase',
          1
        );
    }

    if(document.getElementById('numbers').checked){
        charlist += '0123456789';
        window.localStorage.removeItem('PasswordGenerator.htm-numbers');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-numbers',
          1
        );
    }

    if(document.getElementById('other-lowercase').checked){
        charlist += document.getElementById('other-lowercase-touse').value;
        window.localStorage.removeItem('PasswordGenerator.htm-other-lowercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-other-lowercase',
          1
        );
    }

    if(document.getElementById('other-uppercase').checked){
        charlist += document.getElementById('other-uppercase-touse').value;
        window.localStorage.removeItem('PasswordGenerator.htm-other-uppercase');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-other-uppercase',
          1
        );
    }

    if(document.getElementById('symbols').checked){
        charlist += document.getElementById('symbols-touse').value;
        window.localStorage.removeItem('PasswordGenerator.htm-symbols');

    }else{
        window.localStorage.setItem(
          'PasswordGenerator.htm-symbols',
          1
        );
    }
}

var charlist = '';

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // ENTER: generate a new password.
    if(key === 13){
        generate();
    }
};

window.onload = function(e){
    // Fetch settings from window.localStorage and update settings inputs.
    document.getElementById('length').value = window.localStorage.getItem('PasswordGenerator.htm-length') === null
      ? 15
      : window.localStorage.getItem('PasswordGenerator.htm-length');

    document.getElementById('latin-lowercase').checked =
      window.localStorage.getItem('PasswordGenerator.htm-latin-lowercase') === null;

    document.getElementById('latin-uppercase').checked =
      window.localStorage.getItem('PasswordGenerator.htm-latin-uppercase') === null;

    document.getElementById('number-of-passwords').value =
      window.localStorage.getItem('PasswordGenerator.htm-number-of-passwords') === null
        ? 1
        : window.localStorage.getItem('PasswordGenerator.htm-number-of-passwords');

    document.getElementById('numbers').checked =
      window.localStorage.getItem('PasswordGenerator.htm-numbers') === null;

    document.getElementById('other-lowercase').checked =
      window.localStorage.getItem('PasswordGenerator.htm-other-lowercase') === null;

    document.getElementById('other-lowercase-touse').value = 'áčďéěiíňóřšťúůýž';

    document.getElementById('other-uppercase').checked =
      window.localStorage.getItem('PasswordGenerator.htm-other-uppercase') === null;

    document.getElementById('other-uppercase-touse').value = 'ÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ';

    document.getElementById('symbols').checked =
      window.localStorage.getItem('PasswordGenerator.htm-symbols') === null;

    document.getElementById('symbols-touse').value = '~!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/?';
};
<|endoftext|>


<commit_before>'use strict';

angular.module('emulvcApp')
	.service('Soundhandlerservice', function Soundhandlerservice($document) {
		// shared service object
		var sServObj = {};

		sServObj.wavJSO = {};;

		sServObj.player = $document[0].createElement('audio');
		sServObj.player.isPlaying = false;

		sServObj.setPlayerSrc = function(buf) {
			var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(buf)));
			this.player.src = 'data:audio/wav;base64,' + base64String;
		};

		sServObj.resetPlayerSrcFromTo = function(startSample, endSample) {
			var bytePerSample = this.wavJSO.BitsPerSample / 8;
			var header = this.wavJSO.origArrBuf.subarray(0, 44);
			var data = this.wavJSO.origArrBuf.subarray(44, this.wavJSO.Data.length * bytePerSample)

			var dv = new DataView(header);
			dv.setUint32(40, (endSample - startSample) * bytePerSample, true);
			var Subchunk2Size = dv.getUint32(40, true);
			// console.log(Subchunk2Size);

			var newData = data.subarray(startSample * bytePerSample, (endSample - startSample) * bytePerSample);

			var tmp = new Uint8Array(header.byteLength + newData.byteLength);
			tmp.set(new Uint8Array(header), 0);
			tmp.set(new Uint8Array(newData), header.byteLength);

			var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(tmp.buffer)));
			this.player.src = 'data:audio/wav;base64,' + base64String;
		};

		sServObj.playFromTo = function(startSample, endSample) {
			this.resetPlayerSrcFromTo(startSample, endSample);

			if (this.player.isPlaying) {
				this.player.isPlaying = false;
				this.player.pause();
			} else {
				this.player.isPlaying = true;
				this.player.play();
			}

		};

		sServObj.player.addEventListener('ended', function() {
			this.isPlaying = false;
		}, false);

		return sServObj;

		// sServObj.currentBuffer = {};

		// generate audio context according to browser type
		// if (navigator.userAgent.indexOf('Firefox') !== -1) {
		// 	sServObj.ac = new window.AudioContext();
		// } else {
		// 	sServObj.ac = new window.webkitAudioContext();

		// }

		// // check if sample rate is 44100...
		// if (sServObj.ac.sampleRate !== 44100) {
		// 	alert('sample rate not 44100!! Currently only 44100 supported! Sorry');
		// }
		// sServObj.destination = sServObj.ac.destination;

		// /**
		//  * decode audio file data
		//  *
		//  * @param {AudioBuffer} audioData Audio data.
		//  * @param cb call back function to call when done decoding
		//  */
		// sServObj.decodeAudioFile = function(audioData, cb) {
		// 	var my = this;

		// 	this.pause();
		// 	// console.log(audioData)

		// 	this.ac.decodeAudioData(
		// 		audioData,
		// 		function(buffer) {
		// 			my.currentBuffer = buffer;
		// 			my.lastStart = 0; // all set to 0?????
		// 			my.lastPause = 0;
		// 			my.startTime = null;
		// 			//console.log(buffer);
		// 			cb(buffer);
		// 		},
		// 		Error
		// 	);

		// };

		// /**
		//  * Plays the loaded audio region.
		//  *
		//  * @param {Number} start Start offset in seconds,
		//  * relative to the beginning of the track.
		//  *
		//  * @param {Number} end End offset in seconds,
		//  * relative to the beginning of the track.
		//  */
		// sServObj.play = function(start, end, delay) {

		// 	if (!this.currentBuffer) {
		// 		return;
		// 	}

		// 	// this.pause();

		// 	this.setSource(this.ac.createBufferSource());
		// 	this.source.buffer = this.currentBuffer;

		// 	//console.log(this.source);
		// 	//console.log(this.currentBuffer);
		// 	//if (null == start) { start = this.getCurrentTime(); }
		// 	//if (null == end  ) { end = this.source.buffer.duration; }
		// 	//if (null == delay) { delay = 0; }

		// 	this.lastStart = start;
		// 	this.startTime = this.ac.currentTime;

		// 	this.source.start(delay, start, end - start); //when, offset, duration in seconds
		// 	// this.source.noteOn(delay, start, end - start); //when, offset, duration in seconds

		// 	this.paused = false;
		// };

		// /**
		//  *
		//  */
		// sServObj.setSource = function(source) {
		// 	// this.source && this.source.disconnect();
		// 	this.source = source;
		// 	// this.source.connect(this.analyser);
		// 	// this.source.connect(this.proc);

		// 	this.source.connect(this.destination);
		// 	// this.source.connect(this.verb);
		// };

		// /**
		//  * Pauses the loaded audio.
		//  */
		// sServObj.pause = function(delay) {
		// 	if (!this.currentBuffer || this.paused) {
		// 		return;
		// 	}

		// 	// this.lastPause = this.getCurrentTime();

		// 	this.source.stop(delay || 0);

		// 	// this.source.noteOff(delay || 0); // deprecated version for safari... yay

		// 	this.paused = true;
		// };

	});<commit_msg>using new function to create base64 sting<commit_after>'use strict';

angular.module('emulvcApp')
	.service('Soundhandlerservice', function Soundhandlerservice($document) {
		// shared service object
		var sServObj = {};

		sServObj.wavJSO = {};;

		sServObj.player = $document[0].createElement('audio');
		sServObj.player.isPlaying = false;

		sServObj.setPlayerSrc = function(buf) {
			var base64String = this.arrayBufferToBase64(buf);
			this.player.src = 'data:audio/wav;base64,' + base64String;
		};

		sServObj.resetPlayerSrcFromTo = function(startSample, endSample) {
			var bytePerSample = this.wavJSO.BitsPerSample / 8;
			var header = this.wavJSO.origArrBuf.subarray(0, 44);
			var data = this.wavJSO.origArrBuf.subarray(44, this.wavJSO.Data.length * bytePerSample)

			var dv = new DataView(header);
			dv.setUint32(40, (endSample - startSample) * bytePerSample, true);
			var Subchunk2Size = dv.getUint32(40, true);
			// console.log(Subchunk2Size);

			var newData = data.subarray(startSample * bytePerSample, (endSample - startSample) * bytePerSample);

			var tmp = new Uint8Array(header.byteLength + newData.byteLength);
			tmp.set(new Uint8Array(header), 0);
			tmp.set(new Uint8Array(newData), header.byteLength);

			var base64String = this.arrayBufferToBase64(tmp.buffer);
			this.player.src = 'data:audio/wav;base64,' + base64String;
		};

		sServObj.playFromTo = function(startSample, endSample) {
			this.resetPlayerSrcFromTo(startSample, endSample);

			if (this.player.isPlaying) {
				this.player.isPlaying = false;
				this.player.pause();
			} else {
				this.player.isPlaying = true;
				this.player.play();
			}

		};

		sServObj.player.addEventListener('ended', function() {
			this.isPlaying = false;
		}, false);

		/**
		 * decode audio file data
		 *
		 * @param {AudioBuffer} audioData Audio data.
		 * @param cb call back function to call when done decoding
		 */

		sServObj.arrayBufferToBase64 = function(buffer) {
			var binary = '';
			var bytes = new Uint8Array(buffer);
			var len = bytes.byteLength;
			for (var i = 0; i < len; i++) {
				binary += String.fromCharCode(bytes[i])
			}
			return window.btoa(binary);
		};

		return sServObj;

		// sServObj.currentBuffer = {};

		// generate audio context according to browser type
		// if (navigator.userAgent.indexOf('Firefox') !== -1) {
		// 	sServObj.ac = new window.AudioContext();
		// } else {
		// 	sServObj.ac = new window.webkitAudioContext();

		// }

		// // check if sample rate is 44100...
		// if (sServObj.ac.sampleRate !== 44100) {
		// 	alert('sample rate not 44100!! Currently only 44100 supported! Sorry');
		// }
		// sServObj.destination = sServObj.ac.destination;

		// /**
		//  * decode audio file data
		//  *
		//  * @param {AudioBuffer} audioData Audio data.
		//  * @param cb call back function to call when done decoding
		//  */
		// sServObj.decodeAudioFile = function(audioData, cb) {
		// 	var my = this;

		// 	this.pause();
		// 	// console.log(audioData)

		// 	this.ac.decodeAudioData(
		// 		audioData,
		// 		function(buffer) {
		// 			my.currentBuffer = buffer;
		// 			my.lastStart = 0; // all set to 0?????
		// 			my.lastPause = 0;
		// 			my.startTime = null;
		// 			//console.log(buffer);
		// 			cb(buffer);
		// 		},
		// 		Error
		// 	);

		// };

		// /**
		//  * Plays the loaded audio region.
		//  *
		//  * @param {Number} start Start offset in seconds,
		//  * relative to the beginning of the track.
		//  *
		//  * @param {Number} end End offset in seconds,
		//  * relative to the beginning of the track.
		//  */
		// sServObj.play = function(start, end, delay) {

		// 	if (!this.currentBuffer) {
		// 		return;
		// 	}

		// 	// this.pause();

		// 	this.setSource(this.ac.createBufferSource());
		// 	this.source.buffer = this.currentBuffer;

		// 	//console.log(this.source);
		// 	//console.log(this.currentBuffer);
		// 	//if (null == start) { start = this.getCurrentTime(); }
		// 	//if (null == end  ) { end = this.source.buffer.duration; }
		// 	//if (null == delay) { delay = 0; }

		// 	this.lastStart = start;
		// 	this.startTime = this.ac.currentTime;

		// 	this.source.start(delay, start, end - start); //when, offset, duration in seconds
		// 	// this.source.noteOn(delay, start, end - start); //when, offset, duration in seconds

		// 	this.paused = false;
		// };

		// /**
		//  *
		//  */
		// sServObj.setSource = function(source) {
		// 	// this.source && this.source.disconnect();
		// 	this.source = source;
		// 	// this.source.connect(this.analyser);
		// 	// this.source.connect(this.proc);

		// 	this.source.connect(this.destination);
		// 	// this.source.connect(this.verb);
		// };

		// /**
		//  * Pauses the loaded audio.
		//  */
		// sServObj.pause = function(delay) {
		// 	if (!this.currentBuffer || this.paused) {
		// 		return;
		// 	}

		// 	// this.lastPause = this.getCurrentTime();

		// 	this.source.stop(delay || 0);

		// 	// this.source.noteOff(delay || 0); // deprecated version for safari... yay

		// 	this.paused = true;
		// };

	});<|endoftext|>


<commit_before>module.exports = scheme => {

    scheme.statics.createOrUpdate = function (query, update, options) {

        return this.findOne(query).exec().then(doc => {

            if (!doc) {

                return this.create(update, options);

            }

            return doc.update(update, options).exec();

        });

    };

};
<commit_msg>Removed unused options parameter from create method.<commit_after>module.exports = scheme => {

    scheme.statics.createOrUpdate = function (query, update, options) {

        return this.findOne(query).exec().then(doc => {

            if (!doc) {

                return this.create(update);

            }

            return doc.update(update, options).exec();

        });

    };

};
<|endoftext|>


<commit_before>goog.provide('ngeo.StateManager');

goog.require('goog.asserts');
goog.require('ngeo');
goog.require('ngeo.Location');

ngeo.module.value('ngeoUsedKeyRegexp', [new RegExp('.*')]);

/**
 * Provides a service for managing the application state.
 * The application state is written to both the URL and the local storage.
 * @constructor
 * @struct
 * @param {!ngeo.Location} ngeoLocation ngeo location service.
 * @param {!Array.<!RegExp>} ngeoUsedKeyRegexp regexp used to identify the used keys.
 * @ngInject
 */
ngeo.StateManager = function(ngeoLocation, ngeoUsedKeyRegexp) {

  /**
   * Object representing the application's initial state.
   * @type {!Object.<string, string>}
   */
  this.initialState = {};

  /**
   * @type {!ngeo.Location}
   */
  this.ngeoLocation = ngeoLocation;

  /**
   * @type {!Array.<!RegExp>}
   */
  this.usedKeyRegexp = ngeoUsedKeyRegexp;

  /**
   * @type {boolean}
   */
  this.useLocalStorage = true;

  try {
    if ('localStorage' in window) {
      window.localStorage['test'] = '';
      delete window.localStorage['test'];
    } else {
      this.useLocalStorage = false;
    }
  } catch (err) {
    console.error(err);
    this.useLocalStorage = false;
  }

  // Populate initialState with the application's initial state. The initial
  // state is read from the location URL, or from the local storage if there
  // is no state in the location URL.

  const paramKeys = ngeoLocation.getParamKeys().filter(key => key != 'debug' && key != 'no_redirect');

  if (paramKeys.length === 0) {
    if (this.useLocalStorage) {
      for (const key in window.localStorage) {
        goog.asserts.assert(key);

        this.usedKeyRegexp.some((keyRegexp) => {
          if (key.match(keyRegexp)) {
            const value = window.localStorage[key];
            if (value !== undefined || value !== null) {
              this.initialState[key] = value;
            } else {
              this.initialState[key] = '';
            }
            return true;
          }
        });
      }
    }
  } else {
    paramKeys.forEach((key) => {
      this.usedKeyRegexp.some((keyRegexp) => {
        if (key.match(keyRegexp)) {
          const value = this.ngeoLocation.getParam(key);
          if (value !== undefined) {
            this.initialState[key] = value;
            return true;
          }
        }
      });
    });
  }
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialValue = function(key) {
  return this.initialState[key];
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialStringValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value;
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {number|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialNumberValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return parseFloat(value);
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {boolean|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialBooleanValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value === 'true';
};

/**
 * Update the application state with the values in `object`.
 * @param {!Object.<string, string>} object Object.
 */
ngeo.StateManager.prototype.updateState = function(object) {
  this.ngeoLocation.updateParams(object);
  if (this.useLocalStorage) {
    for (const key in object) {
      goog.asserts.assert(key);
      const value = object[key];
      goog.asserts.assert(value !== undefined);
      window.localStorage[key] = value;
    }
  }
};

/**
 * Delete a parameter
 * @param {string} key Key.
 */
ngeo.StateManager.prototype.deleteParam = function(key) {
  this.ngeoLocation.deleteParam(key);
  if (this.useLocalStorage) {
    delete window.localStorage[key];
  }
};

ngeo.module.service('ngeoStateManager', ngeo.StateManager);
<commit_msg>Disable the localstorage by default<commit_after>goog.provide('ngeo.StateManager');

goog.require('goog.asserts');
goog.require('ngeo');
goog.require('ngeo.Location');

ngeo.module.value('ngeoUsedKeyRegexp', [new RegExp('.*')]);

/**
 * Provides a service for managing the application state.
 * The application state is written to both the URL and the local storage.
 * @constructor
 * @struct
 * @param {!ngeo.Location} ngeoLocation ngeo location service.
 * @param {!Array.<!RegExp>} ngeoUsedKeyRegexp regexp used to identify the used keys.
 * @ngInject
 */
ngeo.StateManager = function(ngeoLocation, ngeoUsedKeyRegexp) {

  /**
   * Object representing the application's initial state.
   * @type {!Object.<string, string>}
   */
  this.initialState = {};

  /**
   * @type {!ngeo.Location}
   */
  this.ngeoLocation = ngeoLocation;

  /**
   * @type {!Array.<!RegExp>}
   */
  this.usedKeyRegexp = ngeoUsedKeyRegexp;

  /**
   * @type {boolean}
   */
  this.useLocalStorage = false;

  try {
    if ('localStorage' in window) {
      window.localStorage['test'] = '';
      delete window.localStorage['test'];
    } else {
      this.useLocalStorage = false;
    }
  } catch (err) {
    console.error(err);
    this.useLocalStorage = false;
  }

  // Populate initialState with the application's initial state. The initial
  // state is read from the location URL, or from the local storage if there
  // is no state in the location URL.

  const paramKeys = ngeoLocation.getParamKeys().filter(key => key != 'debug' && key != 'no_redirect');

  if (paramKeys.length === 0) {
    if (this.useLocalStorage) {
      for (const key in window.localStorage) {
        goog.asserts.assert(key);

        this.usedKeyRegexp.some((keyRegexp) => {
          if (key.match(keyRegexp)) {
            const value = window.localStorage[key];
            if (value !== undefined || value !== null) {
              this.initialState[key] = value;
            } else {
              this.initialState[key] = '';
            }
            return true;
          }
        });
      }
    }
  } else {
    paramKeys.forEach((key) => {
      this.usedKeyRegexp.some((keyRegexp) => {
        if (key.match(keyRegexp)) {
          const value = this.ngeoLocation.getParam(key);
          if (value !== undefined) {
            this.initialState[key] = value;
            return true;
          }
        }
      });
    });
  }
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialValue = function(key) {
  return this.initialState[key];
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {string|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialStringValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value;
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {number|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialNumberValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return parseFloat(value);
};

/**
 * Get the state value for `key`.
 * @param {string} key State key.
 * @return {boolean|undefined} State value.
 */
ngeo.StateManager.prototype.getInitialBooleanValue = function(key) {
  const value = this.initialState[key];
  if (value === undefined) {
    return undefined;
  }
  return value === 'true';
};

/**
 * Update the application state with the values in `object`.
 * @param {!Object.<string, string>} object Object.
 */
ngeo.StateManager.prototype.updateState = function(object) {
  this.ngeoLocation.updateParams(object);
  if (this.useLocalStorage) {
    for (const key in object) {
      goog.asserts.assert(key);
      const value = object[key];
      goog.asserts.assert(value !== undefined);
      window.localStorage[key] = value;
    }
  }
};

/**
 * Delete a parameter
 * @param {string} key Key.
 */
ngeo.StateManager.prototype.deleteParam = function(key) {
  this.ngeoLocation.deleteParam(key);
  if (this.useLocalStorage) {
    delete window.localStorage[key];
  }
};

ngeo.module.service('ngeoStateManager', ngeo.StateManager);
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 12,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // default font weight: 'normal' or 'bold'
    fontWeight: 'normal',

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: 'bold',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BLOCK',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#C51E14',
      green: '#1DC121',
      yellow: '#C7C329',
      blue: '#0A2FC4',
      magenta: '#C839C5',
      cyan: '#20C5C6',
      white: '#C7C7C7',
      lightBlack: '#686868',
      lightRed: '#FD6F6B',
      lightGreen: '#67F86F',
      lightYellow: '#FFFA72',
      lightBlue: '#6A76FB',
      lightMagenta: '#FD7CFC',
      lightCyan: '#68FDFE',
      lightWhite: '#FFFFFF',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '/usr/local/bin/zsh',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'SOUND',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    'shades-of-purple-hyper',
    'hyper-opacity'
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};
<commit_msg>Update hyper settings<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 12,

    // font family with optional fallbacks
    fontFamily: 'Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // default font weight: 'normal' or 'bold'
    fontWeight: 'normal',

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: 'bold',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BLOCK',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#C51E14',
      green: '#1DC121',
      yellow: '#C7C329',
      blue: '#0A2FC4',
      magenta: '#C839C5',
      cyan: '#20C5C6',
      white: '#C7C7C7',
      lightBlack: '#686868',
      lightRed: '#FD6F6B',
      lightGreen: '#67F86F',
      lightYellow: '#FFFA72',
      lightBlue: '#6A76FB',
      lightMagenta: '#FD7CFC',
      lightCyan: '#68FDFE',
      lightWhite: '#FFFFFF',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '/usr/local/bin/zsh',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'SOUND',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
    paneNavigation: {
      debug: false,
      hotkeys: {
        navigation: {
          up: 'ctrl+shift+k',
          down: 'ctrl+shift+j',
          left: 'ctrl+shift+h',
          right: 'ctrl+shift+l'
        },
        jump_prefix: 'ctrl+alt', // completed with 1-9 digits
        permutation_modifier: 'shift', // Added to jump and navigation hotkeys for pane permutation
        maximize: 'meta+enter'
      },
      showIndicators: false, // Show pane number
      indicatorPrefix: '^⌥', // Will be completed with pane number
      indicatorStyle: { // Added to indicator <div>
        position: 'absolute',
        top: 0,
        left: 0,
        fontSize: '10px'
      },
      focusOnMouseHover: false,
      inactivePaneOpacity: 0.6 // Set to 1 to disable inactive panes dimming
    },
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    'shades-of-purple-hyper',
    'hyper-opacity',
    'hyperterm-summon',
    'hyperterm-cursor',
    'hyper-pane'
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};
<|endoftext|>


<commit_before>class FunctionCall {
  constructor(func) {
    this.func = func;
  }
  toString() {
    return ();
  }
}
<commit_msg>got fucked<commit_after>class FunctionCall {
  constructor(id, args) {
    this.id = id;
    this.args = args;
  }
  toString() {
    return (`${this.id} (${this.args}) `);
  }
}

module.exports = FunctionCall;
<|endoftext|>


<commit_before>//Power is connected to pin4 (5V), ground is pin6, tx (output) is pin 8,
// rx (input) is pin10

var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
var EMIC = (function() {
var isOpen = false;
var isReady = true;

var emic = {};
emic.init = function () {

	console.log('Successfully loaded SerialPort module');

	console.log('Successfully initialised /dev/ttyAMA0');

	serialPort.on('open', function () {
		console.log('Port is open')
		isOpen = true;
		serialPort.on('data', function(msg) {
			msg = msg.toString('ascii');
			console.log(msg);
			serialPort.flush();
			if (msg == ':') {
				isReady = true
				console.log('Emic is ready for an instruction')
			}
		});
		serialPort.write(':SHello World to all\r');
	});
};
emic.speak = function (data) {
	data = data.toString('ascii');
	while (isOpen == false || isReady == false) {};
	if (data.length > 1000) {
		console.log('Error: Message exceeds the character limit');
	} else {
		//serialPort.write(':SHello World to all\r');
		serialPort.write(':S' + data + '\r');
		console.log(':S' + data + '\r');
		isReady = false
		console.log('Emic is busy')
	};
};

emic.demo = function (id) {
	id = id.toString('ascii');
	if (id == '0' || id == '1' || id == '2') {
		serialPort.write(':D' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.stopNow = function () {
	serialPort.write(':X\r');
}

emic.pause = function () {
	serialPort.write(':Z\r');
};

emic.voice = function (id) {
	var idN = id.parseInt();
	if (idN >= 0 && idN <= 8) {
		id.toString('ascii');
		serialPort.write(':N' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.volume = function (level) {
	var levelN = id.parseInt();
	if (levelN >= -48 && levelN <= 18) {
		level = level.toString('ascii');
		serialPort.write(':V' + level + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.rate = function (wpm) {
	var wpmN = wpm.parseInt();
	if (wpmN >= 75 && wpmN <= 600) {
		wpm = wpm.toString('ascii');
		serialPort.write(':W' + wpm + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.parser = function (id) {
	id = id.toString('ascii');
	if (parser == '0' || parser == '1' || parser == '2') {
		serialPort.write(':P' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.revert = function () {
	serialPort.write(':R\r');
};

emic.callCurrentSettings = function () {
	serialPort.write(':C\r');
};

emic.callVersionInfo = function () {
	serialPort.write(':I\r');
};

emic.callCommands = function () {
	serialPort.write(':I\r');
};
return emic
}());

/*function writeLog(logFile, output){
	var logf = new File(logFile);
	logf.writeln(output);
	logf.close()*/

module.exports = EMIC;

<commit_msg>update<commit_after>//Power is connected to pin4 (5V), ground is pin6, tx (output) is pin 8,
// rx (input) is pin10

var SerialPort = require('serialport').SerialPort;
var serialPort = new SerialPort('/dev/ttyAMA0', {
	baudRate: 9600
});
var EMIC = (function() {
var isOpen = false;
var isReady = true;

var emic = {};
emic.init = function () {

	console.log('Successfully loaded SerialPort module');

	console.log('Successfully initialised /dev/ttyAMA0');

	serialPort.on('open', function () {
		console.log('Port is open')
		isOpen = true;
		serialPort.on('data', function(msg) {
			msg = msg.toString('ascii');
			console.log(msg);
			serialPort.flush();
			if (msg == ':') {
				isReady = true
				console.log('Emic is ready for an instruction')
			}
		});
		serialPort.write(':SHello World to all\r');
	});
};
emic.speak = function (data) {
	data = data.toString('ascii');
	while (isOpen == false) {};
	if (data.length > 1000) {
		console.log('Error: Message exceeds the character limit');
	} else {
		//serialPort.write(':SHello World to all\r');
		serialPort.write(':S' + data + '\r');
		console.log(':S' + data + '\r');
		isReady = false
		console.log('Emic is busy')
	};
};

emic.demo = function (id) {
	id = id.toString('ascii');
	if (id == '0' || id == '1' || id == '2') {
		serialPort.write(':D' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.stopNow = function () {
	serialPort.write(':X\r');
}

emic.pause = function () {
	serialPort.write(':Z\r');
};

emic.voice = function (id) {
	var idN = id.parseInt();
	if (idN >= 0 && idN <= 8) {
		id.toString('ascii');
		serialPort.write(':N' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.volume = function (level) {
	var levelN = id.parseInt();
	if (levelN >= -48 && levelN <= 18) {
		level = level.toString('ascii');
		serialPort.write(':V' + level + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.rate = function (wpm) {
	var wpmN = wpm.parseInt();
	if (wpmN >= 75 && wpmN <= 600) {
		wpm = wpm.toString('ascii');
		serialPort.write(':W' + wpm + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.parser = function (id) {
	id = id.toString('ascii');
	if (parser == '0' || parser == '1' || parser == '2') {
		serialPort.write(':P' + id + '\r');
	} else {
		console.log('Error: Invalid Command');
	};
};

emic.revert = function () {
	serialPort.write(':R\r');
};

emic.callCurrentSettings = function () {
	serialPort.write(':C\r');
};

emic.callVersionInfo = function () {
	serialPort.write(':I\r');
};

emic.callCommands = function () {
	serialPort.write(':I\r');
};
return emic
}());

/*function writeLog(logFile, output){
	var logf = new File(logFile);
	logf.writeln(output);
	logf.close()*/

module.exports = EMIC;

<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var app = express();
var bodyParser = require("body-parser");
var server = require('http').Server(app);
var mongo = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var io = require('socket.io').listen(server);
var nodemailer = require('nodemailer');

app.use('/css',express.static(__dirname + '/app/css'));
app.use('/game',express.static(__dirname + '/game/js'));
app.use('/assets',express.static(__dirname + '/game/assets'));
app.use('/app',express.static(__dirname + '/app'));
app.use('/ctrl',express.static(__dirname + '/app/controllers'));
app.use('/views',express.static(__dirname + '/app/views'));
app.use('/images',express.static(__dirname + '/app/images'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/',function(req,res){
    res.sendFile(__dirname+'/app/index.html');
});

//mongoHost = 'localhost:27017';
//mongoDBName = 'ensemble';

server.listen(process.env.PORT || 8081,function(){
    mongo.connect('mongodb://'+process.env.mongoHost+'/'+process.env.mongoDBName,function(err,db){
        if(err) throw(err);
        server.db = db;
        console.log('Connection to db established');
    });
    console.log('Listening on '+server.address().port);
});

// Handles submission of a new feature
app.post('/api/newfeature', function(req, res) {
    console.log(req.body);
    var doc = req.body;
    if(doc.desc === undefined) { // no content in the description
        res.status(400).end();
        return;
    }
    doc.stamp = Date.now();
    doc.upvotes = 0;
    doc.downvotes = 0;
    if(doc.username !== undefined) doc.username = doc.username.substring(0,30); // Limit username length to 30 characters
    if(doc.twitter != undefined) doc.twitter = doc.twitter.substring(0,20); // Limit twitter handle length to 20 characters
    doc.desc = doc.desc.substring(0,500); // Limit description to 500 characters

    server.db.collection('features').insertOne(doc,function(err){
        if(err) {
            res.status(500).end();
            throw err;
        }else {
            res.status(201).end();
        }
    });
});

// Request for the list of submitted features
app.get('/api/features',function(req,res){
    server.db.collection('features').find({}).toArray(function(err,docs){
        if(err) {
            res.status(500).end();
            throw err;
        }else {
            if(docs.length == 0){
                res.status(204).end();
            }else {
                res.status(200).send(docs).end();
            }
        }
    });
});

//  Whenever someone votes, his IP and the ID of the feature for which the vote was cast are combined, and stored
//  together with the timestamp of the vote. No vote for the same IP/ID pair is allowed within a certain time interval.
//  Obviously this is not the strongest defense against multi-vote, but it's good enough at the moment.
app.voteLog = {};

app.post('/api/vote', function(req, res) {
    var doc = req.body;
    if(!app.voteAllowed(req.ip,doc.id)){// Check if no vote was cast for the given IP/ID pair in the interval
        res.status(403).end();
        return;
    }

    var action = {};
    if(doc.change == 1){ // upvote
        action['$inc'] = {upvotes:1};
    }else if(doc.change == -1){ // downvote
        action['$inc'] = {downvotes:1};
    }else{ // unknwon action
        res.status(400).end();
        return;
    }

    server.db.collection('features').updateOne(
        {_id: new ObjectId(doc.id)},
        action,
        function(err){
            if(err) {
                res.status(500).end();
                throw err;
            }else {
                res.status(200).end();
            }
        }
    );
});

app.voteAllowed = function(ip,id){
    var hash = id+'-'+ip; // simple "hash" that concatenates the feature id with the ip address
    if(!app.voteLog.hasOwnProperty(hash) || (Date.now() - app.voteLog[hash]) > 1000*60*6*2) {
        app.voteLog[hash] = Date.now();
        return true;
    }
    return false;
};

var multipartyMiddleware = require('connect-multiparty')(); // Needed to access req.body.files

app.mailTransporter = nodemailer.createTransport({ // transporter used to send the artworks by e-mail
    service: 'gmail',
    auth: {
        //user: 'dynetisgames@gmail.com',
        //pass: 'dynetisgames2017'
        user: process.env.dynetisMailAddress,
        pass: process.env.dynetisMailPassword
    },
    tls: { rejectUnauthorized: false }
});

// Handles artwork submissions
app.post('/api/newart', multipartyMiddleware,function(req,res){
    var filePath = req.files.file.path;
    if (!fs.existsSync(filePath)) {
        res.status(404).end();
        return;
    }
    var text = (req.body.comment || 'No comment');
    if(req.body.username) text += "\n\n By "+req.body.username;
    if(req.body.email) text += " ("+req.body.email+")";
    mailOptions = {
        from: req.body.email || process.env.dynetisMailAddress,
        to: process.env.adminAddress,
        subject: 'New art submission for the Ensemble project',
        text: text,
        attachments: [{
            filename: req.files.file.name,
            path: filePath
        }]
    };
    app.mailTransporter.sendMail(mailOptions, function(err) {
        if (err) {
            console.log(err);
            res.status(500).end();
        }
        res.status(200).end()
    });
});

module.exports.io = io;

require('./game/js/server/gameserver.js');<commit_msg>Modifying mongodb URI to match Heroku style<commit_after>var express = require('express');
var fs = require('fs');
var app = express();
var bodyParser = require("body-parser");
var server = require('http').Server(app);
var mongo = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var io = require('socket.io').listen(server);
var nodemailer = require('nodemailer');

app.use('/css',express.static(__dirname + '/app/css'));
app.use('/game',express.static(__dirname + '/game/js'));
app.use('/assets',express.static(__dirname + '/game/assets'));
app.use('/app',express.static(__dirname + '/app'));
app.use('/ctrl',express.static(__dirname + '/app/controllers'));
app.use('/views',express.static(__dirname + '/app/views'));
app.use('/images',express.static(__dirname + '/app/images'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/',function(req,res){
    res.sendFile(__dirname+'/app/index.html');
});

//mongoHost = 'localhost:27017';
//mongoDBName = 'ensemble';

server.listen(process.env.PORT || 8081,function(){
    mongo.connect(process.env.MONGODB_URI,function(err,db){
        if(err) throw(err);
        server.db = db;
        console.log('Connection to db established');
    });
    console.log('Listening on '+server.address().port);
});

// Handles submission of a new feature
app.post('/api/newfeature', function(req, res) {
    console.log(req.body);
    var doc = req.body;
    if(doc.desc === undefined) { // no content in the description
        res.status(400).end();
        return;
    }
    doc.stamp = Date.now();
    doc.upvotes = 0;
    doc.downvotes = 0;
    if(doc.username !== undefined) doc.username = doc.username.substring(0,30); // Limit username length to 30 characters
    if(doc.twitter != undefined) doc.twitter = doc.twitter.substring(0,20); // Limit twitter handle length to 20 characters
    doc.desc = doc.desc.substring(0,500); // Limit description to 500 characters

    server.db.collection('features').insertOne(doc,function(err){
        if(err) {
            res.status(500).end();
            throw err;
        }else {
            res.status(201).end();
        }
    });
});

// Request for the list of submitted features
app.get('/api/features',function(req,res){
    server.db.collection('features').find({}).toArray(function(err,docs){
        if(err) {
            res.status(500).end();
            throw err;
        }else {
            if(docs.length == 0){
                res.status(204).end();
            }else {
                res.status(200).send(docs).end();
            }
        }
    });
});

//  Whenever someone votes, his IP and the ID of the feature for which the vote was cast are combined, and stored
//  together with the timestamp of the vote. No vote for the same IP/ID pair is allowed within a certain time interval.
//  Obviously this is not the strongest defense against multi-vote, but it's good enough at the moment.
app.voteLog = {};

app.post('/api/vote', function(req, res) {
    var doc = req.body;
    if(!app.voteAllowed(req.ip,doc.id)){// Check if no vote was cast for the given IP/ID pair in the interval
        res.status(403).end();
        return;
    }

    var action = {};
    if(doc.change == 1){ // upvote
        action['$inc'] = {upvotes:1};
    }else if(doc.change == -1){ // downvote
        action['$inc'] = {downvotes:1};
    }else{ // unknwon action
        res.status(400).end();
        return;
    }

    server.db.collection('features').updateOne(
        {_id: new ObjectId(doc.id)},
        action,
        function(err){
            if(err) {
                res.status(500).end();
                throw err;
            }else {
                res.status(200).end();
            }
        }
    );
});

app.voteAllowed = function(ip,id){
    var hash = id+'-'+ip; // simple "hash" that concatenates the feature id with the ip address
    if(!app.voteLog.hasOwnProperty(hash) || (Date.now() - app.voteLog[hash]) > 1000*60*6*2) {
        app.voteLog[hash] = Date.now();
        return true;
    }
    return false;
};

var multipartyMiddleware = require('connect-multiparty')(); // Needed to access req.body.files

app.mailTransporter = nodemailer.createTransport({ // transporter used to send the artworks by e-mail
    service: 'gmail',
    auth: {
        //user: 'dynetisgames@gmail.com',
        //pass: 'dynetisgames2017'
        user: process.env.dynetisMailAddress,
        pass: process.env.dynetisMailPassword
    },
    tls: { rejectUnauthorized: false }
});

// Handles artwork submissions
app.post('/api/newart', multipartyMiddleware,function(req,res){
    var filePath = req.files.file.path;
    if (!fs.existsSync(filePath)) {
        res.status(404).end();
        return;
    }
    var text = (req.body.comment || 'No comment');
    if(req.body.username) text += "\n\n By "+req.body.username;
    if(req.body.email) text += " ("+req.body.email+")";
    mailOptions = {
        from: req.body.email || process.env.dynetisMailAddress,
        to: process.env.adminAddress,
        subject: 'New art submission for the Ensemble project',
        text: text,
        attachments: [{
            filename: req.files.file.name,
            path: filePath
        }]
    };
    app.mailTransporter.sendMail(mailOptions, function(err) {
        if (err) {
            console.log(err);
            res.status(500).end();
        }
        res.status(200).end()
    });
});

module.exports.io = io;

require('./game/js/server/gameserver.js');<|endoftext|>