<commit_before>'use strict';

const express = require('express');
const bodyParser = require('body-parser');

const restService = express();
restService.use(bodyParser.json());

restService.post('/webhook', function (req, res) {

    console.log('hook request');

    try {
        var speech = 'empty speech';
        var data = {};
        var slack_message = {};

        var menu = [
            {
                "name": "Strawberry Basil Soda",
                "price": "10",
                "isSpecial": false
            },
            {
                 "name": "Cucumber Gimlet",
                "price": "8",
                "isSpecial": false
            },
            {
                 "name": "The Bright & Bitter",
                "price": "6",
                "isSpecial": false
            },
            {
                 "name": "Blueberry Hard Lemonade",
                "price": "9",
                "isSpecial": false
            },
            ,
            {
                 "name": "Bubbly Lemonade",
                "price": "15",
                "isSpecial": true
            },
            ,
            {
                 "name": "Mojito",
                "price": "12",
                "isSpecial": true
            }
        ];

        if (req.body) {
            var requestBody = req.body;

            if (requestBody.result) {
                speech = '';

                if (requestBody.result.fulfillment) {
                    speech += requestBody.result.fulfillment.speech;
                    speech += ' ';
                }

                if (requestBody.result.action) {
                    if(requestBody.result.action == "getTotalCost" || requestBody.result.action == "reorderTotalCost")
                    {
                        var quantity = parseInt(requestBody.result.parameters.number);
                        var ice = requestBody.result.parameters.ice;
                        var ingredients =requestBody.result.parameters.ingredients;
                        var drinkname =requestBody.result.parameters.name;
                        var cost = 0;

                        menu.forEach(function(drinks) {
                            if(drinkname == drinks.name){
                            cost = quantity * parseInt(drinks.price);
                        }
                        }, this);

                        if(requestBody.result.action == "getTotalCost")
                        {
                            speech = "So, your order is "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. This would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I confirm?";
                            slack_message = {
                                "text": "So, your order is "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. \nThis would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I confirm?"
                            }
                        }
                        else if(requestBody.result.action == "reorderTotalCost")
                        {
                            speech = "Your last order was "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. This would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I repeat same?";
                            slack_message = {
                                "text": "Your last order was "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. \nThis would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I repeat same?"
                            }
                        }

                    }
                    else if(requestBody.result.action == "getTotalCostMultiple")
                    {
                        var quantity1 = parseInt(requestBody.result.parameters.number1);
                        var ice1 = requestBody.result.parameters.ice1;
                        var ingredients1 =requestBody.result.parameters.ingredients1;
                        var drinkname1 =requestBody.result.parameters.name1;
                        var quantity2 = parseInt(requestBody.result.parameters.number2);
                        var ice2 = requestBody.result.parameters.ice2;
                        var ingredients2 =requestBody.result.parameters.ingredients2;
                        var drinkname2 =requestBody.result.parameters.name2;
                        var cost = 0;

                        menu.forEach(function(drinks) {
                            if(drinkname1 == drinks.name) {
                            cost += quantity1 * parseInt(drinks.price);
                        }
                        else if(drinkname2 == drinks.name) {
                             cost += quantity2 * parseInt(drinks.price);
                        }
                        }, this);

                        speech = "So, your order is "+ quantity1 +" "+ drinkname1 +" with "+ ingredients1 + " ingredient and "+ ice1 + " ice and "+ quantity2 +" "+ drinkname2 +" with "+ ingredients2 + " ingredient and "+ ice2 + " ice. This would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should i confirm?";
                        slack_message = {
                            "text": "So, your order is "+ quantity1 +" "+ drinkname1 +" with "+ ingredients1 + " ingredient and "+ ice1 + " ice and "+ quantity2 +" "+ drinkname2 +" with "+ ingredients2 + " ingredient and "+ ice2 + " ice. \nThis would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should i confirm?"
                        }
                    }
                    else if(requestBody.result.action == "help")
                    {
                        speech = "Hi, here are some example tasks that you can ask me to do: **See menu by saying: *I want to see menu *What is special today? *I want to order a drink **Or simply order a drink from menu by saying: *I want 2 mojito. *Get me 1 strawberry basil soda. **Confirm or update your drink order: *I wanna update my order. *I want to change drink to blueberry hard lemonade. *update ingredients *update ice quantity **Repeat order";
                        slack_message = {
                            "text": "Hi, here are some example tasks that you can ask me to do:\n\nSee menu by saying:\nI want to see menu\nWhat is special today?\nI want to order a drink\n\nOr simply order a drink from menu by saying:\nI want 2 mojito.\nGet me 1 strawberry basil soda.\n\nConfirm or update your drink order:\nI wanna update my order.\nI want to change drink to blueberry hard lemonade.\nupdate ingredients\nupdate ice quantity\n\nRepeat order"
                        }
                    }
                    else if(requestBody.result.action == "getDrinksMenu")
                    {
                        speech = "Main menu: * Strawberry Basil Soda * Cucumber Gimlet * The Bright & Bitter * Blueberry Hard Lemonade Today's special menu: * Bubbly Lemonade * Mojito";
                        slack_message = {
                            "text": "Main menu: \n* Strawberry Basil Soda \n* Cucumber Gimlet \n* The Bright & Bitter \n* Blueberry Hard Lemonade \nToday's special menu: \n* Bubbly Lemonade \n* Mojito"
                        }
                    }
                    else if(requestBody.result.action == "getSpecialMenu")
                    {
                        speech = "Today's special menu: * Bubbly Lemonade * Mojito";
                        slack_message = {
                            "text": "Today's special menu: \n* Bubbly Lemonade \n* Mojito"
                        }
                    }
                    data = {"slack": slack_message};
                }
            }
        }

        console.log('result: ', speech);

        return res.json({
            speech: speech,
            displayText: speech,
            data: data,
            source: 'apiai-webhook-calculation-sample'
        });
    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

restService.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});<commit_msg>try image<commit_after>'use strict';

const express = require('express');
const bodyParser = require('body-parser');

const restService = express();
restService.use(bodyParser.json());

restService.post('/webhook', function (req, res) {

    console.log('hook request');

    try {
        var speech = 'empty speech';
        var data = {};
        var slack_message = {};

        var menu = [
            {
                "name": "Strawberry Basil Soda",
                "price": "10",
                "isSpecial": false
            },
            {
                 "name": "Cucumber Gimlet",
                "price": "8",
                "isSpecial": false
            },
            {
                 "name": "The Bright & Bitter",
                "price": "6",
                "isSpecial": false
            },
            {
                 "name": "Blueberry Hard Lemonade",
                "price": "9",
                "isSpecial": false
            },
            ,
            {
                 "name": "Bubbly Lemonade",
                "price": "15",
                "isSpecial": true
            },
            ,
            {
                 "name": "Mojito",
                "price": "12",
                "isSpecial": true
            }
        ];

        if (req.body) {
            var requestBody = req.body;

            if (requestBody.result) {
                speech = '';

                if (requestBody.result.fulfillment) {
                    speech += requestBody.result.fulfillment.speech;
                    speech += ' ';
                }

                if (requestBody.result.action) {
                    if(requestBody.result.action == "getTotalCost" || requestBody.result.action == "reorderTotalCost")
                    {
                        var quantity = parseInt(requestBody.result.parameters.number);
                        var ice = requestBody.result.parameters.ice;
                        var ingredients =requestBody.result.parameters.ingredients;
                        var drinkname =requestBody.result.parameters.name;
                        var cost = 0;

                        menu.forEach(function(drinks) {
                            if(drinkname == drinks.name){
                            cost = quantity * parseInt(drinks.price);
                        }
                        }, this);

                        if(requestBody.result.action == "getTotalCost")
                        {
                            speech = "So, your order is "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. This would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I confirm?";
                            slack_message = {
                                "text": "So, your order is "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. \nThis would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I confirm?"
                            }
                        }
                        else if(requestBody.result.action == "reorderTotalCost")
                        {
                            speech = "Your last order was "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. This would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I repeat same?";
                            slack_message = {
                                "text": "Your last order was "+ quantity +" "+ drinkname +" with "+ ingredients + " ingredient and "+ ice + " ice. \nThis would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should I repeat same?"
                            }
                        }

                    }
                    else if(requestBody.result.action == "getTotalCostMultiple")
                    {
                        var quantity1 = parseInt(requestBody.result.parameters.number1);
                        var ice1 = requestBody.result.parameters.ice1;
                        var ingredients1 =requestBody.result.parameters.ingredients1;
                        var drinkname1 =requestBody.result.parameters.name1;
                        var quantity2 = parseInt(requestBody.result.parameters.number2);
                        var ice2 = requestBody.result.parameters.ice2;
                        var ingredients2 =requestBody.result.parameters.ingredients2;
                        var drinkname2 =requestBody.result.parameters.name2;
                        var cost = 0;

                        menu.forEach(function(drinks) {
                            if(drinkname1 == drinks.name) {
                            cost += quantity1 * parseInt(drinks.price);
                        }
                        else if(drinkname2 == drinks.name) {
                             cost += quantity2 * parseInt(drinks.price);
                        }
                        }, this);

                        speech = "So, your order is "+ quantity1 +" "+ drinkname1 +" with "+ ingredients1 + " ingredient and "+ ice1 + " ice and "+ quantity2 +" "+ drinkname2 +" with "+ ingredients2 + " ingredient and "+ ice2 + " ice. This would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should i confirm?";
                        slack_message = {
                            "text": "So, your order is "+ quantity1 +" "+ drinkname1 +" with "+ ingredients1 + " ingredient and "+ ice1 + " ice and "+ quantity2 +" "+ drinkname2 +" with "+ ingredients2 + " ingredient and "+ ice2 + " ice. \nThis would be a total of "+"$" +cost +" including taxes & 10% gratuity. Should i confirm?"
                        }
                    }
                    else if(requestBody.result.action == "help")
                    {
                        speech = "Hi, here are some example tasks that you can ask me to do: **See menu by saying: *I want to see menu *What is special today? *I want to order a drink **Or simply order a drink from menu by saying: *I want 2 mojito. *Get me 1 strawberry basil soda. **Confirm or update your drink order: *I wanna update my order. *I want to change drink to blueberry hard lemonade. *update ingredients *update ice quantity **Repeat order";
                        //slack_message = {
                        //    "text": "Hi, here are some example tasks that you can ask me to do:\n\nSee menu by saying:\nI want to see menu\nWhat is special today?\nI want to order a drink\n\nOr simply order a drink from menu by saying:\nI want 2 mojito.\nGet me 1 strawberry basil soda.\n\nConfirm or update your drink order:\nI wanna update my order.\nI want to change drink to blueberry hard lemonade.\nupdate ingredients\nupdate ice quantity\n\nRepeat order"
                        //}
                         {
                            "text": "Now back in stock! :tada:",
                            "attachments": [
                                {
                                    "title": "The Further Adventures of Slackbot",
                                    "author_name": "Stanford S. Strickland",
                                    "author_icon": "https://api.slack.com/img/api/homepage_custom_integrations-2x.png",
                                    "image_url": "http://i.imgur.com/OJkaVOI.jpg?1"
                                },
                                {
                                    "fields": [
                                        {
                                            "title": "Volume",
                                            "value": "1",
                                            "short": true
                                        },
                                        {
                                            "title": "Issue",
                                            "value": "3",
                                            "short": true
                                        }
                                    ]
                                },
                                {
                                    "title": "Sypnopsis",
                                    "text": "After @episod pushed exciting changes to a devious new branch back in Issue 1, Slackbot notifies @don about an unexpected deploy..."
                                },
                                {
                                    "fallback": "Would you recommend it to customers?",
                                    "title": "Would you recommend it to customers?",
                                    "callback_id": "comic_1234_xyz",
                                    "color": "#3AA3E3",
                                    "attachment_type": "default",
                                    "actions": [
                                        {
                                            "name": "recommend",
                                            "text": "Recommend",
                                            "type": "button",
                                            "value": "recommend"
                                        },
                                        {
                                            "name": "no",
                                            "text": "No",
                                            "type": "button",
                                            "value": "bad"
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                    else if(requestBody.result.action == "getDrinksMenu")
                    {
                        speech = "Main menu: * Strawberry Basil Soda * Cucumber Gimlet * The Bright & Bitter * Blueberry Hard Lemonade Today's special menu: * Bubbly Lemonade * Mojito";
                        slack_message = {
                            "text": "Main menu: \n* Strawberry Basil Soda \n* Cucumber Gimlet \n* The Bright & Bitter \n* Blueberry Hard Lemonade \nToday's special menu: \n* Bubbly Lemonade \n* Mojito"
                        }
                    }
                    else if(requestBody.result.action == "getSpecialMenu")
                    {
                        speech = "Today's special menu: * Bubbly Lemonade * Mojito";
                        slack_message = {
                            "text": "Today's special menu: \n* Bubbly Lemonade \n* Mojito"
                        }
                    }
                    data = {"slack": slack_message};
                }
            }
        }

        console.log('result: ', speech);

        return res.json({
            speech: speech,
            displayText: speech,
            data: data,
            source: 'apiai-webhook-calculation-sample'
        });
    } catch (err) {
        console.error("Can't process request", err);

        return res.status(400).json({
            status: {
                code: 400,
                errorType: err.message
            }
        });
    }
});

restService.listen((process.env.PORT || 5000), function () {
    console.log("Server listening");
});<|endoftext|>


<commit_before>/*!
 * error-base <https://github.com/doowb/error-base>
 *
 * Copyright (c) 2015, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Code modified from http://stackoverflow.com/a/27925672/914583
 *
 * ```js
 * var CustomError = errorBase('CustomError', function (msg) {
 *   this.msg = msg;
 * });
 * ```
 *
 * @param  {String} `name` Name of new Error Class
 * @param  {Function} `init` Function to call when creating new Error
 * @return {Function} new Error Class
 * @api public
 */

module.exports = function errorBase (name, init, capture) {
  if (typeof name !== 'string') {
    throw new TypeError('expected `name` to be a string.');
  }

  if (typeof init !== 'function') {
    init = identity;
  }
  capture = typeof capture === 'boolean' ? capture : true;

  function Type () {
    if (!Error.captureStackTrace) {
      if (capture) this.stack = (new Error()).stack;
    } else {
      if (capture) Error.captureStackTrace(this, this.constructor);
    }

    init.apply(this, arguments);
  }

  Type.prototype = Object.create(Error.prototype);
  Type.prototype.name = name;
  Type.prototype.constructor = Type;

  return Type;
};

function identity (message) {
  this.message = message;
}
<commit_msg>updates for code coverage<commit_after>/*!
 * error-base <https://github.com/doowb/error-base>
 *
 * Copyright (c) 2015, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

/**
 * Code modified from http://stackoverflow.com/a/27925672/914583
 *
 * ```js
 * var CustomError = errorBase('CustomError', function (msg) {
 *   this.msg = msg;
 * });
 * ```
 *
 * @param  {String} `name` Name of new Error Class
 * @param  {Function} `init` Function to call when creating new Error
 * @return {Function} new Error Class
 * @api public
 */

module.exports = function errorBase (name, init, capture) {
  if (typeof name !== 'string') {
    throw new TypeError('expected `name` to be a string.');
  }

  if (typeof init !== 'function') {
    init = identity;
  }
  capture = typeof capture === 'boolean' ? capture : true;

  function Type () {
    if (capture) {
      if (!Error.captureStackTrace) {
        define(this, 'stack', (new Error()).stack);
      } else {
        Error.captureStackTrace(this, this.constructor);
      }
    }
    init.apply(this, arguments);
  }

  Type.prototype = Object.create(Error.prototype);
  Type.prototype.name = name;
  Type.prototype.constructor = Type;

  return Type;
};

function identity (message) {
  this.message = message;
}

function define(obj, prop, val) {
  Object.defineProperty(obj, prop, {
    enumerable: false,
    configurable: true,
    value: val
  });
}
<|endoftext|>


<commit_before>var TelegramBot = require('node-telegram-bot-api');
var Monitor = require('ping-monitor');

var token = '160239739:AAHpwQXEMQfzv-ucr4q80ffbFtd_3cAiwME';
var heimdallBot = new TelegramBot(token, {polling: true});

var siteStash = new Array();

function heimdallSite(website, telegramId) {

	heimdall = this;

	this.telegramId = telegramId;
	this.website = website;

	this.monitor = new Monitor({
		website: heimdall.website,
		interval: 1
	});

	this.monitor.on('up', function (response) {
		console.log('Alles knorke auf ' + response.website);
	})

	this.monitor.on('down', function (response) {
		heimdallBot.sendMessage(heimdall.telegramId, 'Website: ' + response.website + ' is down! ' + response.statusMessage);
	});

	this.monitor.on('error', function (response) {
    	console.log('Oh Snap!! An unexpected error occured trying to load ' + response.website + '!');
    	heimdall.monitor.stop();
	});

	console.log(heimdall.website + ' ' + heimdall.telegramId);

};

heimdallBot.on('text', function (msg) {
	var chatId = msg.chat.id;
	var message = msg.text;

	if(message.indexOf('/addWebsite ') > -1) {
		message = message.replace('/addWebsite ', '');
		console.log(message);

		if(!(chatId in siteStash))
			siteStash['a' + chatId] = new Array();

		siteStash['a' + chatId][message] = new heimdallSite(message, chatId);
	}

	if(message.indexOf('/removeWebsite ') > -1) {
		message = message.replace('/removeWebsite ', '');
		console.log('Removing ' + message);

		if(('a' + chatId in siteStash) && (message in siteStash['a' + chatId])) {
			siteStash['a' + chatId][message].monitor.stop();
			delete siteStash['a' + chatId][message];
		}

	}

	if(message.indexOf('/testoida') > -1) {
		console.log(siteStash['a24705017']);
	}

});<commit_msg>Added comment about invalid bot token<commit_after>var TelegramBot = require('node-telegram-bot-api');
var Monitor = require('ping-monitor');

//The Token is invalid, so don't even bother ;)
var token = '160239739:AAHpwQXEMQfzv-ucr4q80ffbFtd_3cAiwME';
var heimdallBot = new TelegramBot(token, {polling: true});

var siteStash = new Array();

function heimdallSite(website, telegramId) {

	heimdall = this;

	this.telegramId = telegramId;
	this.website = website;

	this.monitor = new Monitor({
		website: heimdall.website,
		interval: 1
	});

	this.monitor.on('up', function (response) {
		console.log('Alles knorke auf ' + response.website);
	})

	this.monitor.on('down', function (response) {
		heimdallBot.sendMessage(heimdall.telegramId, 'Website: ' + response.website + ' is down! ' + response.statusMessage);
	});

	this.monitor.on('error', function (response) {
    	console.log('Oh Snap!! An unexpected error occured trying to load ' + response.website + '!');
    	heimdall.monitor.stop();
	});

	console.log(heimdall.website + ' ' + heimdall.telegramId);

};

heimdallBot.on('text', function (msg) {
	var chatId = msg.chat.id;
	var message = msg.text;

	if(message.indexOf('/addWebsite ') > -1) {
		message = message.replace('/addWebsite ', '');
		console.log(message);

		if(!(chatId in siteStash))
			siteStash['a' + chatId] = new Array();

		siteStash['a' + chatId][message] = new heimdallSite(message, chatId);
	}

	if(message.indexOf('/removeWebsite ') > -1) {
		message = message.replace('/removeWebsite ', '');
		console.log('Removing ' + message);

		if(('a' + chatId in siteStash) && (message in siteStash['a' + chatId])) {
			siteStash['a' + chatId][message].monitor.stop();
			delete siteStash['a' + chatId][message];
		}

	}

	if(message.indexOf('/testoida') > -1) {
		console.log(siteStash['a24705017']);
	}

});<|endoftext|>


<commit_before>(function() {

  var BigInteger = require('jsbn');
  var jssha256 = require('./util/jssha256.js');
  var converters = require('./util/converters.js');
  var curve25519 = require('./util/curve25519.js');
  var NxtAddress = require('./util/nxtaddress.js');

  var epochNum = 1385294400;

  var _hash = {
    init: jssha256.SHA256_init,
    update: jssha256.SHA256_write,
    getBytes: jssha256.SHA256_finalize,
  };

  function simpleHash(message) {
    _hash.init();
    _hash.update(message);
    return _hash.getBytes();
  };

  function byteArrayToBigInteger(byteArray, startIndex) {
    var value = new BigInteger('0', 10);
    var temp1, temp2;
    for (var i = byteArray.length - 1; i >= 0; i--) {
      temp1 = value.multiply(new BigInteger('256', 10));
      temp2 = temp1.add(new BigInteger(byteArray[i].toString(10), 10));
      value = temp2;
    }
    return value;
  };

  function toByteArray(long) {
    // We want to represent the input as a 8-bytes array
    var byteArray = [0, 0, 0, 0];
    for (var index = 0; index < byteArray.length; index ++) {
      var byte = long & 0xff;
      byteArray [ index ] = byte;
      long = (long - byte) / 256 ;
    }
    return byteArray;
  };

  function toIntVal(byteArray) {
    // We want to represent the input as a 8-bytes array
    var intval = 0;
    for (var index = 0; index < byteArray.length; index ++) {
      var byt = byteArray[index] & 0xFF;
      var value = byt * Math.pow(256, index);
      intval += value;
    }
    return intval;
  };

  function areByteArraysEqual(bytes1, bytes2) {
    if (bytes1.length !== bytes2.length) {
      return false;
    }
    for (var i = 0; i < bytes1.length; ++i) {
      if (bytes1[i] !== bytes2[i]) {
        return false;
      }
    }
    return true;
  };

  function getPublicKey(secretPhrase) {
    _hash.init();
    _hash.update(converters.stringToByteArray(secretPhrase));
    var ky = converters.byteArrayToHexString(
      curve25519.keygen(
        _hash.getBytes()
      ).p
    );
    return converters.hexStringToByteArray(ky);
  };

  function signBytes(message, secretPhrase) {
    var messageBytes = message;
    var secretPhraseBytes = converters.stringToByteArray(secretPhrase);

    var digest = simpleHash(secretPhraseBytes);
    var s = curve25519.keygen(digest).s;

    var m = simpleHash(messageBytes);
    _hash.init();
    _hash.update(m);
    _hash.update(s);
    var x = _hash.getBytes();

    var y = curve25519.keygen(x).p;

    _hash.init();
    _hash.update(m);
    _hash.update(y);
    var h = _hash.getBytes();

    var v = curve25519.sign(h, x, s);
    return v.concat(h);
  };

  function verifyBytes(signature, message, publicKey) {
    var signatureBytes = signature;
    var messageBytes = message;
    var publicKeyBytes = publicKey;
    var v = signatureBytes.slice(0, 32);
    var h = signatureBytes.slice(32);
    var y = curve25519.verify(v, h, publicKeyBytes);

    var m = simpleHash(messageBytes);

    _hash.init();
    _hash.update(m);
    _hash.update(y);
    var h2 = _hash.getBytes();

    return areByteArraysEqual(h, h2);
  };

  module.exports = function() {

    this.getNxtTime = function() {
      return Math.floor(Date.now() / 1000) - epochNum;
    }

    this.secretPhraseToPublicKey = function(secretPhrase) {
      var secretPhraseBytes = converters.stringToByteArray(secretPhrase);
      var digest = simpleHash(secretPhraseBytes);
      var pubKey = curve25519.keygen(digest).p;
      return converters.byteArrayToHexString(pubKey);
    }

    this.publicKeyToAccountId = function(publicKey, RSFormat) {
      var hex = converters.hexStringToByteArray(publicKey);

      _hash.init();
      _hash.update(hex);

      var account = _hash.getBytes();
      account = converters.byteArrayToHexString(account);
      var slice = (converters.hexStringToByteArray(account)).slice(0, 8);
      var accountId = byteArrayToBigInteger(slice).toString();

      if (!RSFormat) {
        return accountId;
      }
      var address = new NxtAddress();
      if (!address.set(accountId)) {
        return '';
      }
      return address.toString();
    }

    this.signTransactionBytes = function(data, secretPhrase) {

      var unsignedBytes = converters.hexStringToByteArray(data);
      var sig = signBytes(unsignedBytes, secretPhrase);

      var signed = unsignedBytes.slice(0,96);
      signed = signed.concat(sig);
      signed = signed.concat(unsignedBytes.slice(96 + 64));

      return converters.byteArrayToHexString(signed);
    };

    this.createToken = function(websiteString, secretPhrase) {
      var hexwebsite = converters.stringToHexString(websiteString);
      var website = converters.hexStringToByteArray(hexwebsite);
      var data = [];
      data = website.concat(getPublicKey(secretPhrase));
      var unix = Math.round(+new Date() / 1000);
      var timestamp = unix - epochNum;
      var timestamparray = toByteArray(timestamp);
      data = data.concat(timestamparray);

      var token = [];
      token = getPublicKey(secretPhrase).concat(timestamparray);

      var sig = signBytes(data, secretPhrase);

      token = token.concat(sig);

      var buf = '';
      for (var ptr = 0; ptr < 100; ptr += 5) {

        var nbr = [];
        nbr[0] = token[ptr] & 0xFF;
        nbr[1] = token[ptr + 1] & 0xFF;
        nbr[2] = token[ptr + 2] & 0xFF;
        nbr[3] = token[ptr + 3] & 0xFF;
        nbr[4] = token[ptr + 4] & 0xFF;
        var number = byteArrayToBigInteger(nbr);

        if (number < 32) {
          buf += '0000000';
        } else if (number < 1024) {
          buf += '000000';
        } else if (number < 32768) {
          buf += '00000';
        } else if (number < 1048576) {
          buf += '0000';
        } else if (number < 33554432) {
          buf += '000';
        } else if (number < 1073741824) {
          buf += '00';
        } else if (number < 34359738368) {
          buf += '0';
        }
        buf += number.toString(32);
      }

      return buf;
    };

    this.parseToken = function(tokenString, website) {
      var websiteBytes = converters.stringToByteArray(website);
      var tokenBytes = [];
      var i = 0;
      var j = 0;

      for (; i < tokenString.length; i += 8, j += 5) {

        var number = new BigInteger(tokenString.substring(i, i + 8), 32);
        var part = converters.hexStringToByteArray(number.toRadix(16));

        tokenBytes[j] = part[4];
        tokenBytes[j + 1] = part[3];
        tokenBytes[j + 2] = part[2];
        tokenBytes[j + 3] = part[1];
        tokenBytes[j + 4] = part[0];
      }

      if (i != 160) {
        return new Error('tokenString parsed to invalid size');
      }
      var publicKey = [];
      publicKey = tokenBytes.slice(0, 32);
      var timebytes = [
        tokenBytes[32],
        tokenBytes[33],
        tokenBytes[34],
        tokenBytes[35],
      ];

      var timestamp = toIntVal(timebytes);
      var signature = tokenBytes.slice(36, 100);

      var data = websiteBytes.concat(tokenBytes.slice(0, 36));

      var isValid = verifyBytes(signature, data, publicKey);

      var ret = {};
      ret.isValid = isValid;
      ret.timestamp = timestamp;
      ret.publicKey = converters.byteArrayToHexString(publicKey);
      ret.accountRS = this.publicKeyToAccountId(ret.publicKey, true);

      return ret;
    };

  };

})();
<commit_msg>no need to instantiate<commit_after>(function() {

  var BigInteger = require('jsbn');
  var jssha256 = require('./util/jssha256.js');
  var converters = require('./util/converters.js');
  var curve25519 = require('./util/curve25519.js');
  var NxtAddress = require('./util/nxtaddress.js');

  var epochNum = 1385294400;

  var _hash = {
    init: jssha256.SHA256_init,
    update: jssha256.SHA256_write,
    getBytes: jssha256.SHA256_finalize,
  };

  function simpleHash(message) {
    _hash.init();
    _hash.update(message);
    return _hash.getBytes();
  };

  function byteArrayToBigInteger(byteArray, startIndex) {
    var value = new BigInteger('0', 10);
    var temp1, temp2;
    for (var i = byteArray.length - 1; i >= 0; i--) {
      temp1 = value.multiply(new BigInteger('256', 10));
      temp2 = temp1.add(new BigInteger(byteArray[i].toString(10), 10));
      value = temp2;
    }
    return value;
  };

  function toByteArray(long) {
    // We want to represent the input as a 8-bytes array
    var byteArray = [0, 0, 0, 0];
    for (var index = 0; index < byteArray.length; index ++) {
      var byte = long & 0xff;
      byteArray [ index ] = byte;
      long = (long - byte) / 256 ;
    }
    return byteArray;
  };

  function toIntVal(byteArray) {
    // We want to represent the input as a 8-bytes array
    var intval = 0;
    for (var index = 0; index < byteArray.length; index ++) {
      var byt = byteArray[index] & 0xFF;
      var value = byt * Math.pow(256, index);
      intval += value;
    }
    return intval;
  };

  function areByteArraysEqual(bytes1, bytes2) {
    if (bytes1.length !== bytes2.length) {
      return false;
    }
    for (var i = 0; i < bytes1.length; ++i) {
      if (bytes1[i] !== bytes2[i]) {
        return false;
      }
    }
    return true;
  };

  function getPublicKey(secretPhrase) {
    _hash.init();
    _hash.update(converters.stringToByteArray(secretPhrase));
    var ky = converters.byteArrayToHexString(
      curve25519.keygen(
        _hash.getBytes()
      ).p
    );
    return converters.hexStringToByteArray(ky);
  };

  function signBytes(message, secretPhrase) {
    var messageBytes = message;
    var secretPhraseBytes = converters.stringToByteArray(secretPhrase);

    var digest = simpleHash(secretPhraseBytes);
    var s = curve25519.keygen(digest).s;

    var m = simpleHash(messageBytes);
    _hash.init();
    _hash.update(m);
    _hash.update(s);
    var x = _hash.getBytes();

    var y = curve25519.keygen(x).p;

    _hash.init();
    _hash.update(m);
    _hash.update(y);
    var h = _hash.getBytes();

    var v = curve25519.sign(h, x, s);
    return v.concat(h);
  };

  function verifyBytes(signature, message, publicKey) {
    var signatureBytes = signature;
    var messageBytes = message;
    var publicKeyBytes = publicKey;
    var v = signatureBytes.slice(0, 32);
    var h = signatureBytes.slice(32);
    var y = curve25519.verify(v, h, publicKeyBytes);

    var m = simpleHash(messageBytes);

    _hash.init();
    _hash.update(m);
    _hash.update(y);
    var h2 = _hash.getBytes();

    return areByteArraysEqual(h, h2);
  };

  module.exports = {

    getNxtTime: function() {
      return Math.floor(Date.now() / 1000) - epochNum;
    },

    secretPhraseToPublicKey: function(secretPhrase) {
      var secretPhraseBytes = converters.stringToByteArray(secretPhrase);
      var digest = simpleHash(secretPhraseBytes);
      var pubKey = curve25519.keygen(digest).p;
      return converters.byteArrayToHexString(pubKey);
    },

    publicKeyToAccountId: function(publicKey, RSFormat) {
      var hex = converters.hexStringToByteArray(publicKey);

      _hash.init();
      _hash.update(hex);

      var account = _hash.getBytes();
      account = converters.byteArrayToHexString(account);
      var slice = (converters.hexStringToByteArray(account)).slice(0, 8);
      var accountId = byteArrayToBigInteger(slice).toString();

      if (!RSFormat) {
        return accountId;
      }
      var address = new NxtAddress();
      if (!address.set(accountId)) {
        return '';
      }
      return address.toString();
    },

    signTransactionBytes: function(data, secretPhrase) {

      var unsignedBytes = converters.hexStringToByteArray(data);
      var sig = signBytes(unsignedBytes, secretPhrase);

      var signed = unsignedBytes.slice(0,96);
      signed = signed.concat(sig);
      signed = signed.concat(unsignedBytes.slice(96 + 64));

      return converters.byteArrayToHexString(signed);
    },

    createToken: function(websiteString, secretPhrase) {
      var hexwebsite = converters.stringToHexString(websiteString);
      var website = converters.hexStringToByteArray(hexwebsite);
      var data = [];
      data = website.concat(getPublicKey(secretPhrase));
      var unix = Math.round(+new Date() / 1000);
      var timestamp = unix - epochNum;
      var timestamparray = toByteArray(timestamp);
      data = data.concat(timestamparray);

      var token = [];
      token = getPublicKey(secretPhrase).concat(timestamparray);

      var sig = signBytes(data, secretPhrase);

      token = token.concat(sig);

      var buf = '';
      for (var ptr = 0; ptr < 100; ptr += 5) {

        var nbr = [];
        nbr[0] = token[ptr] & 0xFF;
        nbr[1] = token[ptr + 1] & 0xFF;
        nbr[2] = token[ptr + 2] & 0xFF;
        nbr[3] = token[ptr + 3] & 0xFF;
        nbr[4] = token[ptr + 4] & 0xFF;
        var number = byteArrayToBigInteger(nbr);

        if (number < 32) {
          buf += '0000000';
        } else if (number < 1024) {
          buf += '000000';
        } else if (number < 32768) {
          buf += '00000';
        } else if (number < 1048576) {
          buf += '0000';
        } else if (number < 33554432) {
          buf += '000';
        } else if (number < 1073741824) {
          buf += '00';
        } else if (number < 34359738368) {
          buf += '0';
        }
        buf += number.toString(32);
      }

      return buf;
    },

    parseToken: function(tokenString, website) {
      var websiteBytes = converters.stringToByteArray(website);
      var tokenBytes = [];
      var i = 0;
      var j = 0;

      for (; i < tokenString.length; i += 8, j += 5) {

        var number = new BigInteger(tokenString.substring(i, i + 8), 32);
        var part = converters.hexStringToByteArray(number.toRadix(16));

        tokenBytes[j] = part[4];
        tokenBytes[j + 1] = part[3];
        tokenBytes[j + 2] = part[2];
        tokenBytes[j + 3] = part[1];
        tokenBytes[j + 4] = part[0];
      }

      if (i != 160) {
        return new Error('tokenString parsed to invalid size');
      }
      var publicKey = [];
      publicKey = tokenBytes.slice(0, 32);
      var timebytes = [
        tokenBytes[32],
        tokenBytes[33],
        tokenBytes[34],
        tokenBytes[35],
      ];

      var timestamp = toIntVal(timebytes);
      var signature = tokenBytes.slice(36, 100);

      var data = websiteBytes.concat(tokenBytes.slice(0, 36));

      var isValid = verifyBytes(signature, data, publicKey);

      var ret = {};
      ret.isValid = isValid;
      ret.timestamp = timestamp;
      ret.publicKey = converters.byteArrayToHexString(publicKey);
      ret.accountRS = this.publicKeyToAccountId(ret.publicKey, true);

      return ret;
    },

  };

})();
<|endoftext|>


<commit_before>'use strict';
var urlLib = require('url');
var http = require('http');
var https = require('https');
var zlib = require('zlib');
var assign = require('object-assign');

module.exports = function (url, content, opts, cb) {
	var redirectCount = 0;

	var send = function (url, content, opts, cb) {
		if (typeof opts === 'function') {
			cb = opts;
			opts = {};
		}

		cb = cb || function () {};
		opts = opts || {};

		opts.headers = assign({
			'user-agent': 'https://github.com/floatdrop/sent',
			'accept-encoding': 'gzip,deflate'
		}, opts.headers || {});

		var parsedUrl = urlLib.parse(url);
		var fn = parsedUrl.protocol === 'https:' ? https : http;
		var arg = assign({ method: 'POST' }, parsedUrl, opts);

		var req = fn.request(arg, function (res) {
			var ret = '';

			// redirect
			if (res.statusCode < 400 && res.statusCode >= 300 && res.headers.location) {
				res.destroy();

				if (++redirectCount > 10) {
					cb(new Error('Redirected 10 times. Aborting.'));
					return;
				}

				send(urlLib.resolve(url, res.headers.location), content, opts, cb);
				return;
			}

			if (res.statusCode !== 200) {
				res.destroy();
				cb(res.statusCode);
				return;
			}

			if (['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
				var unzip = zlib.createUnzip();
				res.pipe(unzip);
				res = unzip;
			}

			res.setEncoding('utf8');

			res.on('data', function (data) {
				ret += data;
			});

			res.once('error', cb);

			res.once('end', function () {
				cb(null, ret, res);
			});
		}).once('error', cb);

		if (content.pipe) {
			content.pipe(req);
		} else {
			req.write(content);
			req.end();
		}
	};

	send(url, content, opts, cb);
};
<commit_msg>Check that res.statusCode in range 200..299<commit_after>'use strict';
var urlLib = require('url');
var http = require('http');
var https = require('https');
var zlib = require('zlib');
var assign = require('object-assign');

module.exports = function (url, content, opts, cb) {
	var redirectCount = 0;

	var send = function (url, content, opts, cb) {
		if (typeof opts === 'function') {
			cb = opts;
			opts = {};
		}

		cb = cb || function () {};
		opts = opts || {};

		opts.headers = assign({
			'user-agent': 'https://github.com/floatdrop/sent',
			'accept-encoding': 'gzip,deflate'
		}, opts.headers || {});

		var parsedUrl = urlLib.parse(url);
		var fn = parsedUrl.protocol === 'https:' ? https : http;
		var arg = assign({ method: 'POST' }, parsedUrl, opts);

		var req = fn.request(arg, function (res) {
			var ret = '';

			// redirect
			if (res.statusCode < 400 && res.statusCode >= 300 && res.headers.location) {
				res.destroy();

				if (++redirectCount > 10) {
					cb(new Error('Redirected 10 times. Aborting.'));
					return;
				}

				send(urlLib.resolve(url, res.headers.location), content, opts, cb);
				return;
			}

			if (res.statusCode < 200 || res.statusCode > 299) {
				res.destroy();
				cb(res.statusCode);
				return;
			}

			if (['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
				var unzip = zlib.createUnzip();
				res.pipe(unzip);
				res = unzip;
			}

			res.setEncoding('utf8');

			res.on('data', function (data) {
				ret += data;
			});

			res.once('error', cb);

			res.once('end', function () {
				cb(null, ret, res);
			});
		}).once('error', cb);

		if (content.pipe) {
			content.pipe(req);
		} else {
			req.write(content);
			req.end();
		}
	};

	send(url, content, opts, cb);
};
<|endoftext|>


<commit_before>/**
 * @author  Kai Dorschner <me@krnl.de>
 */
"use strict";

import fs from 'fs';
import handlebars from 'handlebars';
import wkhtmltopdf from 'wkhtmltopdf';

export default function render(templateFile, context = {}) {
  return new Promise((resolve, reject) => {
    fs.readFile(templateFile, (err, contentBuffer) => {
      if (err) return reject(res.end(err));
      const template = handlebars.compile(contentBuffer.toString('utf8'));
      console.log('Writing PDF with', context);
      resolve(wkhtmltopdf(template(context)));
    });
  });
}
<commit_msg>Updated var name.<commit_after>/**
 * @author  Kai Dorschner <me@krnl.de>
 */
"use strict";

import fs from 'fs';
import handlebars from 'handlebars';
import wkhtmltopdf from 'wkhtmltopdf';

export default function render(templateFile, templateContext = {}) {
  return new Promise((resolve, reject) => {
    fs.readFile(templateFile, (err, contentBuffer) => {
      if (err) return reject(res.end(err));
      const template = handlebars.compile(contentBuffer.toString('utf8'));
      console.log('Writing PDF with', templateContext);
      resolve(wkhtmltopdf(template(templateContext)));
    });
  });
}
<|endoftext|>


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

const fs = require('fs');
const rl = require("readline");
const prompts = rl.createInterface(process.stdin, process.stdout);
const fileName = process.argv[2];
const i = require('./lib/interpreter.js');

const repl = () => {
  prompts.question('> ', code => {
    try {
      const result = i.exec(code);
      if (result !== undefined) {
        console.log(result);
      }
    } catch (err) {
      console.error(err);
    }
    repl();
  });
}

const execFile = () => {
  fs.readFile(fileName, 'utf8', (err, data) => {
    if (!err) {
      const result = i.exec(data);
      if (result !== undefined) {
        console.log(result);
      }
    } else {
      console.error(err.message);
    }
  });
}

if (fileName) {
  execFile();
} else {
  repl();
}

<commit_msg>fix repl closing<commit_after>#! /usr/bin/env node

const fs = require('fs');
const rl = require("readline");
const prompts = rl.createInterface(process.stdin, process.stdout);
const fileName = process.argv[2];
const i = require('./lib/interpreter.js');

const repl = () => {
  prompts.question('> ', code => {
    try {
      const result = i.exec(code);
      if (result !== undefined) {
        console.log(result);
      }
    } catch (err) {
      console.error(err);
    }
    repl();
  });
}

const execFile = () => {
  fs.readFile(fileName, 'utf8', (err, data) => {
    if (!err) {
      const result = i.exec(data);
      if (result !== undefined) {
        console.log(result);
      }
      prompts.close();
    } else {
      console.error(err.message);
    }
  });
}

if (fileName) {
  execFile();
} else {
  repl();
}

<|endoftext|>


<commit_before>const fs = require('fs')
const unified = require('unified')
const reParse = require('remark-parse')
const math = require('remark-math')
const katex = require('rehype-katex')
const stringify = require('rehype-stringify')
const remark2rehype = require('remark-rehype')
const inspect = require('unist-util-inspect')

const headingShifter = require('./packages/heading-shift')
const htmlBlocks = require('./packages/html-blocks')
const escapeEscaped = require('./packages/escape-escaped')
const kbd = require('./packages/kbd')
const customBlocks = require('./packages/custom-blocks')
const subSuper = require('./packages/sub-super')
const emoticons = require('./packages/emoticons')

const fromFile = (filepath) => fs.readFileSync(filepath)

const processor = ({ headingShift } = {}) =>
  unified()
    .use(reParse, {
      gfm: true,
      commonmark: false,
      yaml: false,
      footnotes: true,
      /* sets list of known blocks to nothing, otherwise
hey
 would become
      <h3>hey</h3> instead of
<h3>hey</h3>
 */
      blocks: [],
    })
    .use(headingShifter, headingShift || 0)
    .use(remark2rehype, { allowDangerousHTML: true })
    .use(customBlocks, {
      secret: 'spoiler',
      s: 'spoiler',
      information: 'information ico-after',
      i: 'information ico-after',
      question: 'question ico-after',
      q: 'question ico-after',
      attention: 'warning ico-after',
      a: 'warning ico-after',
      erreur: 'error ico-after',
      e: 'error ico-after',
    })
    .use(math)
    .use(htmlBlocks)
    .use(escapeEscaped)
    .use(kbd)
    .use(subSuper)
    .use(emoticons, {
      ':ange:': '/static/smileys/ange.png',
      ':colere:': '/static/smileys/angry.gif',
      'o_O': '/static/smileys/blink.gif',
      ';)': '/static/smileys/clin.png',
      ':diable:': '/static/smileys/diable.png',
      ':D': '/static/smileys/heureux.png',
      '^^': '/static/smileys/hihi.png',
      ':o': '/static/smileys/huh.png',
      ':p': '/static/smileys/langue.png',
      ':magicien:': '/static/smileys/magicien.png',
      ':colere2:': '/static/smileys/mechant.png',
      ':ninja:': '/static/smileys/ninja.png',
      '>_<': '/static/smileys/pinch.png',
      ':pirate:': '/static/smileys/pirate.png',
      ":'(": '/static/smileys/pleure.png',
      ':lol:': '/static/smileys/rire.gif',
      ':honte:': '/static/smileys/rouge.png',
      ':-°': '/static/smileys/siffle.png',
      ':)': '/static/smileys/smile.png',
      ':soleil:': '/static/smileys/soleil.png',
      ':(': '/static/smileys/triste.png',
      ':euh:': '/static/smileys/unsure.gif',
      ':waw:': '/static/smileys/waw.png',
      ':zorro:': '/static/smileys/zorro.png',
    })
    .use(katex, {
      inlineDoubleDisplay: true
    })
    .use(stringify)

const parse = (opts) => (zmd) => processor(opts).parse(zmd)
const transform = (opts) => (ast) => processor(opts).runSync(ast)
const render = (opts) => (ast) => processor(opts).stringify(ast)

const renderString = (opts) => (string) => render(opts)(transform(opts)(parse(opts)(string)))
const renderFile = (opts) => (filepath) => renderString(opts)(fromFile(filepath))

module.exports = (opts) => ({
  inspect: inspect,
  parse: parse(opts),
  transform: transform(opts),
  renderFile: renderFile(opts),
  renderString: renderString(opts),
})
<commit_msg>Modify pinch shortcode<commit_after>const fs = require('fs')
const unified = require('unified')
const reParse = require('remark-parse')
const math = require('remark-math')
const katex = require('rehype-katex')
const stringify = require('rehype-stringify')
const remark2rehype = require('remark-rehype')
const inspect = require('unist-util-inspect')

const headingShifter = require('./packages/heading-shift')
const htmlBlocks = require('./packages/html-blocks')
const escapeEscaped = require('./packages/escape-escaped')
const kbd = require('./packages/kbd')
const customBlocks = require('./packages/custom-blocks')
const subSuper = require('./packages/sub-super')
const emoticons = require('./packages/emoticons')

const fromFile = (filepath) => fs.readFileSync(filepath)

const processor = ({ headingShift } = {}) =>
  unified()
    .use(reParse, {
      gfm: true,
      commonmark: false,
      yaml: false,
      footnotes: true,
      /* sets list of known blocks to nothing, otherwise
hey
 would become
      <h3>hey</h3> instead of
<h3>hey</h3>
 */
      blocks: [],
    })
    .use(headingShifter, headingShift || 0)
    .use(remark2rehype, { allowDangerousHTML: true })
    .use(customBlocks, {
      secret: 'spoiler',
      s: 'spoiler',
      information: 'information ico-after',
      i: 'information ico-after',
      question: 'question ico-after',
      q: 'question ico-after',
      attention: 'warning ico-after',
      a: 'warning ico-after',
      erreur: 'error ico-after',
      e: 'error ico-after',
    })
    .use(math)
    .use(htmlBlocks)
    .use(escapeEscaped, ['&'])
    .use(kbd)
    .use(subSuper)
    .use(emoticons, {
      ':ange:': '/static/smileys/ange.png',
      ':colere:': '/static/smileys/angry.gif',
      'o_O': '/static/smileys/blink.gif',
      ';)': '/static/smileys/clin.png',
      ':diable:': '/static/smileys/diable.png',
      ':D': '/static/smileys/heureux.png',
      '^^': '/static/smileys/hihi.png',
      ':o': '/static/smileys/huh.png',
      ':p': '/static/smileys/langue.png',
      ':magicien:': '/static/smileys/magicien.png',
      ':colere2:': '/static/smileys/mechant.png',
      ':ninja:': '/static/smileys/ninja.png',
      'x(': '/static/smileys/pinch.png',
      ':pirate:': '/static/smileys/pirate.png',
      ":'(": '/static/smileys/pleure.png',
      ':lol:': '/static/smileys/rire.gif',
      ':honte:': '/static/smileys/rouge.png',
      ':-°': '/static/smileys/siffle.png',
      ':)': '/static/smileys/smile.png',
      ':soleil:': '/static/smileys/soleil.png',
      ':(': '/static/smileys/triste.png',
      ':euh:': '/static/smileys/unsure.gif',
      ':waw:': '/static/smileys/waw.png',
      ':zorro:': '/static/smileys/zorro.png',
    })
    .use(katex, {
      inlineDoubleDisplay: true
    })
    .use(stringify)

const parse = (opts) => (zmd) => processor(opts).parse(zmd)
const transform = (opts) => (ast) => processor(opts).runSync(ast)
const render = (opts) => (ast) => processor(opts).stringify(ast)

const renderString = (opts) => (string) => render(opts)(transform(opts)(parse(opts)(string)))
const renderFile = (opts) => (filepath) => renderString(opts)(fromFile(filepath))

module.exports = (opts) => ({
  inspect: inspect,
  parse: parse(opts),
  transform: transform(opts),
  renderFile: renderFile(opts),
  renderString: renderString(opts),
})
<|endoftext|>


<commit_before>
/**
 * Expose 'walk'
 */

module.exports = walk;

/**
 * Walk dom tree recursively.
 *
 * It traverses dom elements
 * (type 1) as well as text
 * node (type 3).
 *
 * @param {ELement} node
 * @param {Function} cb
 * @param {Object} scope
 * @api public
 */

function walk() {
  //do something
}
<commit_msg>add walk handler with optional scope arg<commit_after>
/**
 * Expose 'walk'
 */

module.exports = walk;

/**
 * Walk dom tree recursively.
 *
 * It traverses dom elements
 * (type 1) as well as text
 * node (type 3).
 *
 * @param {ELement} node
 * @param {Function} cb
 * @param {Object} scope
 * @api public
 */

function walk(node, cb, scope) {
  cb.call(scope, node);
  node = node.firstChild;
  while (node) {
    walk(node, cb);
    node = node.nextSibling;
  }
}
<|endoftext|>


<commit_before>var captionLength = 0;
var captionOptions = ["Oh, hello there.", "So this is my page.", "Hope you get what you need :)"]
var captionIndex = 0;
var rgbOptions = ["rgb(61, 183, 88)", "rgb(230, 79, 59)", "rgb(222, 77, 99)", "rgb(211, 188, 180)", "rgb(255, 255, 255)", "rgb(255, 220, 90)", "rgb(77, 222, 171)"]
var colorIndex = 0;

var currentlyRaving = false;

function runCaptions() {
  cursorAnimation();
  $caption = $('#caption');
  setTimeout('showCaptions()', 1000);
}

function cursorAnimation() {
  $('#cursor').animate({
      opacity: 0
  }, 400).animate({
      opacity: 1
  }, 400);
  setTimeout('cursorAnimation()')
}

function type() {
    $caption.html(captionToType.substr(0, captionLength++));
    if(captionLength < captionToType.length+1) {
        setTimeout('type()', 70);
    }
}

function erase() {
    $caption.html(captionToType.substr(0, captionLength--));
    if(captionLength >= 0) {
        setTimeout('erase()', 50);
    }
}

function showCaptions() {
  captionToType = captionOptions[captionIndex];
  type();
  if (captionIndex < (captionOptions.length - 1)) {
    captionIndex++
    setTimeout('erase()', 4000);
    setTimeout('showCaptions()', 6000)
  } else {
    setTimeout(function(){
      $('#cursor').remove()
    }, 1500)
  }
}

function toggleMethods() {
  $('.methods').toggle('slide');
}

function switchRaveState() {
  if (currentlyRaving) {
    currentlyRaving = false
  } else {
    currentlyRaving = true
  }
}

function checkRaveState() {
  if (currentlyRaving) {
    animateBackgroundColor(70);
    play(); // doesn't re-instigate the play function if song is already playing.
    setTimeout('checkRaveState()', 100);
  } else {
    stopAndReset();
  }
}

function animateBackgroundColor(speed) {
  ((colorIndex == rgbOptions.length) ? colorIndex = 0 : null);
  $('html').animate({"background-color": rgbOptions[colorIndex]}, speed);
  colorIndex++
}

function play() {
  document.getElementById("audio").play();
}

function stopAndReset() {
  var audio = document.getElementById("audio");
  audio.pause();
  audio.currentTime = 0
}

$(function(){
  runCaptions();

  $('.message a').on('click', function() {
    event.preventDefault()
    toggleMethods();
  })

  $('.color-change p.background').on('click', function() {
    event.preventDefault();
    animateBackgroundColor(350)
  })

  $('.rave').on('click', function(){
    event.preventDefault();

    $(this).siblings().removeClass('hidden');
    $(this).addClass('hidden')

    switchRaveState();
    checkRaveState();
  })
});
<commit_msg>Add Github Zen<commit_after>var captionLength = 0;
var captionOptions = ["Oh, hello there.", "So this is my page.", "Hope you get what you need :)", "Now, 'The Zen of Github':"]
var captionIndex = 0;
var rgbOptions = ["rgb(61, 183, 88)", "rgb(230, 79, 59)", "rgb(222, 77, 99)", "rgb(211, 188, 180)", "rgb(255, 255, 255)", "rgb(255, 220, 90)", "rgb(77, 222, 171)"]
var colorIndex = 0;

var currentlyRaving = false;

function getZen() {
  $.ajax({
    url: "https://api.github.com/zen"
  }).done(function(resp){
    captionOptions.push(resp);
  });
}

function runCaptions() {
  cursorAnimation();
  $caption = $('#caption');
  setTimeout('showCaptions()', 1000);
}

function cursorAnimation() {
  $('#cursor').animate({
      opacity: 0
  }, 400).animate({
      opacity: 1
  }, 400);
  setTimeout('cursorAnimation()')
}

function type() {
    $caption.html(captionToType.substr(0, captionLength++));
    if(captionLength < captionToType.length+1) {
        setTimeout('type()', 70);
    }
}

function erase() {
    $caption.html(captionToType.substr(0, captionLength--));
    if(captionLength >= 0) {
        setTimeout('erase()', 50);
    }
}

function showCaptions() {
  captionToType = captionOptions[captionIndex];
  type();
  if (captionIndex < (captionOptions.length - 1)) {
    getZen();
    captionIndex++
    setTimeout('erase()', 4000);
    setTimeout('showCaptions()', 6000)
  } else {
    setTimeout(function(){
      $('#cursor').remove()
    }, 1500)
  }
}

function toggleMethods() {
  $('.methods').toggle('slide');
}

function switchRaveState() {
  if (currentlyRaving) {
    currentlyRaving = false
  } else {
    currentlyRaving = true
  }
}

function checkRaveState() {
  if (currentlyRaving) {
    animateBackgroundColor(70);
    play(); // doesn't re-instigate the play function if song is already playing.
    setTimeout('checkRaveState()', 100);
  } else {
    stopAndReset();
  }
}

function animateBackgroundColor(speed) {
  ((colorIndex == rgbOptions.length) ? colorIndex = 0 : null);
  $('html').animate({"background-color": rgbOptions[colorIndex]}, speed);
  colorIndex++
}

function play() {
  document.getElementById("audio").play();
}

function stopAndReset() {
  var audio = document.getElementById("audio");
  audio.pause();
  audio.currentTime = 0
}

$(function(){
  runCaptions();

  $('.message a').on('click', function() {
    event.preventDefault()
    toggleMethods();
  })

  $('.color-change p.background').on('click', function() {
    event.preventDefault();
    animateBackgroundColor(350)
  })

  $('.rave').on('click', function(){
    event.preventDefault();

    $(this).siblings().removeClass('hidden');
    $(this).addClass('hidden')

    switchRaveState();
    checkRaveState();
  })
});
<|endoftext|>


<commit_before>moduleAid.VERSION = '1.0.3';

moduleAid.LOADMODULE = function() {
	AddonManager.getAddonByID("FirefoxAddon@similarWeb.com", function(addon) {
		moduleAid.loadIf('compatibilityFix/similarWeb', (addon && addon.isActive));
	});
	AddonManager.getAddonByID("{dc0fa13c-3dae-73eb-e852-912722c852f9}", function(addon) {
		moduleAid.loadIf('compatibilityFix/milewideback', (addon && addon.isActive));
	});
	AddonManager.getAddonByID("{2fa4ed95-0317-4c6a-a74c-5f3e3912c1f9}", function(addon) {
		moduleAid.loadIf('compatibilityFix/delicious', (addon && addon.isActive));
	});
	AddonManager.getAddonByID("totaltoolbar@mozdev.org", function(addon) {
		moduleAid.loadIf('compatibilityFix/totalToolbar', (addon && addon.isActive));
	});
	moduleAid.load('compatibilityFix/lessChrome');
	moduleAid.load('compatibilityFix/console');
	moduleAid.load('compatibilityFix/dmt');
	moduleAid.load('compatibilityFix/addonMgr');
	moduleAid.load('compatibilityFix/domi');

	// This was implemented and later apparently changed in FF20 to remove its "sidebar"
	if(Services.vc.compare(Services.appinfo.platformVersion, "10.0") >= 0 && Services.vc.compare(Services.appinfo.platformVersion, "20.0") < 0) {
		moduleAid.load('compatibilityFix/devTools');
	}

	moduleAid.load('compatibilityFix/pageInfo');
};

moduleAid.UNLOADMODULE = function() {
	moduleAid.unload('compatibilityFix/similarWeb');
	moduleAid.unload('compatibilityFix/milewideback');
	moduleAid.unload('compatibilityFix/delicious');
	moduleAid.unload('compatibilityFix/totalToolbar');
	moduleAid.unload('compatibilityFix/lessChrome');
	moduleAid.unload('compatibilityFix/console');
	moduleAid.unload('compatibilityFix/dmt');
	moduleAid.unload('compatibilityFix/addonMgr');
	moduleAid.unload('compatibilityFix/domi');
	moduleAid.unload('compatibilityFix/devTools');
	moduleAid.unload('compatibilityFix/pageInfo');
};
<commit_msg>SimilarWeb 2.0 is fully compatible<commit_after>moduleAid.VERSION = '1.0.4';

moduleAid.LOADMODULE = function() {
	AddonManager.getAddonByID("FirefoxAddon@similarWeb.com", function(addon) {
		// SimilarWeb 2.0 no longer has the sidebar so our fixes are unnecessary. I may completely remove them in the future.
		moduleAid.loadIf('compatibilityFix/similarWeb', (addon && addon.isActive && Services.vc.compare(addon.version, "2.0") < 0));
	});
	AddonManager.getAddonByID("{dc0fa13c-3dae-73eb-e852-912722c852f9}", function(addon) {
		moduleAid.loadIf('compatibilityFix/milewideback', (addon && addon.isActive));
	});
	AddonManager.getAddonByID("{2fa4ed95-0317-4c6a-a74c-5f3e3912c1f9}", function(addon) {
		moduleAid.loadIf('compatibilityFix/delicious', (addon && addon.isActive));
	});
	AddonManager.getAddonByID("totaltoolbar@mozdev.org", function(addon) {
		moduleAid.loadIf('compatibilityFix/totalToolbar', (addon && addon.isActive));
	});
	moduleAid.load('compatibilityFix/lessChrome');
	moduleAid.load('compatibilityFix/console');
	moduleAid.load('compatibilityFix/dmt');
	moduleAid.load('compatibilityFix/addonMgr');
	moduleAid.load('compatibilityFix/domi');

	// This was implemented and later apparently changed in FF20 to remove its "sidebar"
	moduleAid.loadIf('compatibilityFix/devTools', (Services.vc.compare(Services.appinfo.platformVersion, "10.0") >= 0 && Services.vc.compare(Services.appinfo.platformVersion, "20.0") < 0));

	moduleAid.load('compatibilityFix/pageInfo');
};

moduleAid.UNLOADMODULE = function() {
	moduleAid.unload('compatibilityFix/similarWeb');
	moduleAid.unload('compatibilityFix/milewideback');
	moduleAid.unload('compatibilityFix/delicious');
	moduleAid.unload('compatibilityFix/totalToolbar');
	moduleAid.unload('compatibilityFix/lessChrome');
	moduleAid.unload('compatibilityFix/console');
	moduleAid.unload('compatibilityFix/dmt');
	moduleAid.unload('compatibilityFix/addonMgr');
	moduleAid.unload('compatibilityFix/domi');
	moduleAid.unload('compatibilityFix/devTools');
	moduleAid.unload('compatibilityFix/pageInfo');
};
<|endoftext|>


<commit_before>'use strict'; // eslint-disable-line

const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');

const config = require('./config');

module.exports = {
  plugins: [
    new ImageminPlugin({
      optipng: { optimizationLevel: 7 },
      gifsicle: { optimizationLevel: 3 },
      pngquant: { quality: '65-90', speed: 4 },
      svgo: {
        plugins: [
          { removeUnknownsAndDefaults: false },
          { cleanupIDs: false },
          { removeViewBox: false }
        ],
      },
      plugins: [imageminMozjpeg({ quality: 75 })],
      disable: (config.enabled.watcher),
    }),
  ],
};
<commit_msg>Fix travis CI build error (missing trailing comma)<commit_after>'use strict'; // eslint-disable-line

const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');

const config = require('./config');

module.exports = {
  plugins: [
    new ImageminPlugin({
      optipng: { optimizationLevel: 7 },
      gifsicle: { optimizationLevel: 3 },
      pngquant: { quality: '65-90', speed: 4 },
      svgo: {
        plugins: [
          { removeUnknownsAndDefaults: false },
          { cleanupIDs: false },
          { removeViewBox: false },
        ],
      },
      plugins: [imageminMozjpeg({ quality: 75 })],
      disable: (config.enabled.watcher),
    }),
  ],
};
<|endoftext|>


<commit_before>import React from 'react';

class HistoryModal extends React.Component {
	render() {
    const post = this.props.details['post'];
    const signup = this.props.details['post']['signup'];
    const campaign = this.props.details['campaign'];

		return (

				×

Change Quantity

Old Quantity

{signup['quantity']} {campaign['reportback_info']['noun']} {campaign['reportback_info']['verb']}

New Quantity

							<input ref={(input) => this.newQuantity = input} type="text" className="text-field" placeholder="Enter # here"/>

Reportback History

table of all the history goes here 📖

				 this.props.onUpdate(post, this.newQuantity.value)}>Save

		);
	}
}

export default HistoryModal;
<commit_msg>Disable save button unless a quantity is entered<commit_after>import React from 'react';

class HistoryModal extends React.Component {
	constructor() {
		super();

		this.state = {
			quantity: null
		};

		this.onUpdate = this.onUpdate.bind(this);
	}

	onUpdate(event) {
		this.setState({ quantity: event.target.value });
	}

	render() {
    const post = this.props.details['post'];
    const signup = this.props.details['post']['signup'];
    const campaign = this.props.details['campaign'];

		return (

				×

Change Quantity

Old Quantity

{signup['quantity']} {campaign['reportback_info']['noun']} {campaign['reportback_info']['verb']}

New Quantity

							<input type="text" onChange={this.onUpdate} className="text-field" placeholder="Enter # here"/>

Reportback History

table of all the history goes here 📖

				<button className="button -history" disabled={!this.state.quantity} onClick={() => this.props.onUpdate(post, this.state.quantity)}>Save</button>

		);
	}
}

export default HistoryModal;
<|endoftext|>


<commit_before>import React from 'react';
import { shallow, mount } from 'enzyme';

import Campaign from '../../_mocks_/__mockData__/campaign.json';
import CampaignInbox from '../CampaignInbox';
import reviewComponent from './index';

jest.mock('../../utilities/RogueClient');

test('CampaignInbox renders correctly when wrapped', () => {
  const mockState = {
    campaign: Campaign,
  };

  const ReviewingComponent = reviewComponent(CampaignInbox, mockState);

  const wrapper = shallow(<ReviewingComponent />);

  expect(wrapper.html()).not.toBe(null);
});

test('GetPostsByStatus is called when mounted', () => {
  const mockState = {
    campaign: Campaign,
    initial_posts: 'accepted',
  };

  const EmptyComponent = () => <div />;

  const ReviewingComponent = reviewComponent(EmptyComponent, mockState);

  const wrapper = mount(<ReviewingComponent />);

  setTimeout(() => {
    expect(wrapper.html()).not.toBe(null);

    wrapper.unmount();

    done();
  });

  // console.log(wrapper);
  // expect(wrapper.getPostsByStatus()).toHaveBeenCalled();
  //
  // const getPostsByStatus = jest.fn();
  // expect(getPostsByStatus).toHaveBeenCalled();

});

<commit_msg>better structure of tests<commit_after>import React from 'react';
import { mount } from 'enzyme';
import Campaign from '../../_mocks_/__mockData__/campaign.json';
import Posts from '../../_mocks_/__mockData__/posts.json';
import reviewComponent from './index';

jest.mock('../../utilities/RogueClient');

describe('WithReviewing', () => {
  let Wrapper;
  let ReviewingComponent;

  beforeEach(() => {
    const mockState = {
      campaign: Campaign,
      initial_posts: 'accepted',
    };

    const EmptyComponent = () => <div />;

    ReviewingComponent = reviewComponent(EmptyComponent, mockState);

    Wrapper = mount(<ReviewingComponent />);
  });

  it('renders the MockReviewingComponent as the root element', () => {
    expect(Wrapper.first().is(ReviewingComponent)).toBeTruthy();
  });

  it('It populates state to have campaign and post data after mounted', () => {
    // console.log(Wrapper.state());
    const state = Wrapper.state();
    // const postCount = Object.keys(state.posts).length;

    // Make sure campaign data is correct.
    expect(state.campaign.data).toEqual(Campaign.data);

    // Make sure post data is correct.
    expect(state.posts['70']).toEqual(Posts.data[0]);
    expect(state.posts['71']).toEqual(Posts.data[1]);
  });
});
<|endoftext|>


<commit_before>/**
 * @file levelHandler
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

/**
 * Handles user's experience points and levels
 * @param {Message} message Discord.js message object
 * @returns {void}
 */
module.exports = async message => {
  try {
    /**
     * Using <Model>.findOrCreate() won't require the use of
     * <ModelInstance>.save() but <Model>.findOrBuild() is used instead because
     * <Model>.findOrCreate() creates a race condition where a matching row is
     * created by another connection after the `find` but before the `insert`
     * call. However, it is not always possible to handle this case in SQLite,
     * specifically if one transaction inserts and another tries to select
     * before the first one has committed. TimeoutError is thrown instead.
     */
    let [ guildMemberModel, initialized ] = await message.client.database.models.guildMember.findOrBuild({
      where: {
        userID: message.author.id,
        guildID: message.guild.id
      },
      defaults: {
        experiencePoints: 0
      }
    });
    if (initialized) {
      await guildMemberModel.save();
    }

    let guildModel = await message.client.database.models.guild.findOne({
      attributes: [ 'levelUpMessages' ],
      where: {
        guildID: message.guild.id
      },
      include: [
        {
          model: message.client.database.models.role,
          attributes: [ 'roleID', 'level' ]
        }
      ]
    });

    // Level Up
    guildMemberModel.dataValues.experiencePoints = parseInt(guildMemberModel.dataValues.experiencePoints);
    guildMemberModel.dataValues.level = parseInt(guildMemberModel.dataValues.level);
    guildMemberModel.dataValues.bastionCurrencies = parseInt(guildMemberModel.dataValues.bastionCurrencies);

    let currentLevel = Math.floor(0.15 * Math.sqrt(guildMemberModel.dataValues.experiencePoints + 1));

    if (currentLevel > guildMemberModel.dataValues.level) {
      await message.client.database.models.guildMember.update({
        bastionCurrencies: guildMemberModel.dataValues.bastionCurrencies + currentLevel * 5,
        experiencePoints: guildMemberModel.dataValues.experiencePoints + 1,
        level: currentLevel
      },
      {
        where: {
          userID: message.author.id,
          guildID: message.guild.id
        },
        fields: [ 'bastionCurrencies', 'experiencePoints', 'level' ]
      });

      if (guildModel.dataValues.levelUpMessages) {
        message.channel.send({
          embed: {
            color: message.client.colors.BLUE,
            title: 'Leveled up',
            description: `:up: **${message.author.username}**#${message.author.discriminator} leveled up to **Level ${currentLevel}**`
          }
        }).then(msg => {
          msg.delete(5000).catch(() => {});
        }).catch(e => {
          message.client.log.error(e);
        });
      }
    }
    else {
      await message.client.database.models.guildMember.update({
        experiencePoints: guildMemberModel.dataValues.experiencePoints + 1
      },
      {
        where: {
          userID: message.author.id,
          guildID: message.guild.id
        },
        fields: [ 'experiencePoints' ]
      });
    }

    // Level up roles
    let levelUpRoles = guildModel.roles.filter(role => role.dataValues.level).map(role => role.dataValues);

    let levelUpRoleIDs = {};
    for (let role of levelUpRoles) {
      if (!levelUpRoleIDs.hasOwnProperty(role.level)) {
        levelUpRoleIDs[role.level] = [];
      }

      levelUpRoleIDs[role.level].push(role.roleID);
    }

    let level = `${currentLevel}`;
    if (levelUpRoleIDs.hasOwnProperty(level)) {
      await message.member.addRoles(levelUpRoleIDs[level]).catch(() => {});
    }
  }
  catch (e) {
    message.client.log.error(e);
  }
};
<commit_msg>handlers: implemented levelUps check in levelHandler<commit_after>/**
 * @file levelHandler
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

/**
 * Handles user's experience points and levels
 * @param {Message} message Discord.js message object
 * @returns {void}
 */
module.exports = async message => {
  try {
    /**
     * Using <Model>.findOrCreate() won't require the use of
     * <ModelInstance>.save() but <Model>.findOrBuild() is used instead because
     * <Model>.findOrCreate() creates a race condition where a matching row is
     * created by another connection after the `find` but before the `insert`
     * call. However, it is not always possible to handle this case in SQLite,
     * specifically if one transaction inserts and another tries to select
     * before the first one has committed. TimeoutError is thrown instead.
     */
    let [ guildMemberModel, initialized ] = await message.client.database.models.guildMember.findOrBuild({
      where: {
        userID: message.author.id,
        guildID: message.guild.id
      },
      defaults: {
        experiencePoints: 0
      }
    });
    if (initialized) {
      await guildMemberModel.save();
    }

    let guildModel = await message.client.database.models.guild.findOne({
      attributes: [ 'levelUpMessages', 'levelUps' ],
      where: {
        guildID: message.guild.id
      },
      include: [
        {
          model: message.client.database.models.role,
          attributes: [ 'roleID', 'level' ]
        }
      ]
    });

    guildMemberModel.dataValues.experiencePoints = parseInt(guildMemberModel.dataValues.experiencePoints);
    guildMemberModel.dataValues.level = parseInt(guildMemberModel.dataValues.level);
    guildMemberModel.dataValues.bastionCurrencies = parseInt(guildMemberModel.dataValues.bastionCurrencies);

    let currentLevel = Math.floor(0.15 * Math.sqrt(guildMemberModel.dataValues.experiencePoints + 1));

    // Level Up
    if (guildModel.dataValues.levelUps) {
      if (currentLevel > guildMemberModel.dataValues.level) {
        await message.client.database.models.guildMember.update({
          bastionCurrencies: guildMemberModel.dataValues.bastionCurrencies + currentLevel * 5,
          experiencePoints: guildMemberModel.dataValues.experiencePoints + 1,
          level: currentLevel
        },
        {
          where: {
            userID: message.author.id,
            guildID: message.guild.id
          },
          fields: [ 'bastionCurrencies', 'experiencePoints', 'level' ]
        });

        if (guildModel.dataValues.levelUpMessages) {
          message.channel.send({
            embed: {
              color: message.client.colors.BLUE,
              title: 'Leveled up',
              description: `:up: **${message.author.username}**#${message.author.discriminator} leveled up to **Level ${currentLevel}**`
            }
          }).then(msg => {
            msg.delete(5000).catch(() => {});
          }).catch(e => {
            message.client.log.error(e);
          });
        }
      }
      else {
        await message.client.database.models.guildMember.update({
          experiencePoints: guildMemberModel.dataValues.experiencePoints + 1
        },
        {
          where: {
            userID: message.author.id,
            guildID: message.guild.id
          },
          fields: [ 'experiencePoints' ]
        });
      }
    }

    // Level up roles
    let levelUpRoles = guildModel.roles.filter(role => role.dataValues.level).map(role => role.dataValues);

    let levelUpRoleIDs = {};
    for (let role of levelUpRoles) {
      if (!levelUpRoleIDs.hasOwnProperty(role.level)) {
        levelUpRoleIDs[role.level] = [];
      }

      levelUpRoleIDs[role.level].push(role.roleID);
    }

    let level = `${currentLevel}`;
    if (levelUpRoleIDs.hasOwnProperty(level)) {
      await message.member.addRoles(levelUpRoleIDs[level]).catch(() => {});
    }
  }
  catch (e) {
    message.client.log.error(e);
  }
};
<|endoftext|>


<commit_before>import { transformAttributes } from "../../components/form/dynamic-attributes";

function serializeValue(fieldType, value) {
    if(fieldType === 'autocomplete') {
        return !!value ? value.id : value;
    }
    return value;
}

function serializeData(data, fields) {
    return Object.entries(data).reduce((res, [fieldKey, value]) => {
        const field = fields[fieldKey];
        return {
            ...res,
            [fieldKey]: serializeValue(field.type, value),
        }
    }, {});
}

export function transformFields(fields, data) {
    const serializedData = serializeData(data, fields);
    return Object.entries(fields).reduce((res, [fieldKey, field]) => {
        const {
            attributes,
            resolvedEmptyAttributes,
        } = transformAttributes(field, field.dynamicAttributes, serializedData);

        const readOnly = resolvedEmptyAttributes.length > 0;

        return {
            ...res,
            [fieldKey]: {
                ...attributes,
                readOnly,
            },
        };
    }, {});
}<commit_msg>Fix readOnly attribute not taken in account<commit_after>import { transformAttributes } from "../../components/form/dynamic-attributes";

function serializeValue(fieldType, value) {
    if(fieldType === 'autocomplete') {
        return !!value ? value.id : value;
    }
    return value;
}

function serializeData(data, fields) {
    return Object.entries(data).reduce((res, [fieldKey, value]) => {
        const field = fields[fieldKey];
        return {
            ...res,
            [fieldKey]: serializeValue(field.type, value),
        }
    }, {});
}

export function transformFields(fields, data) {
    const serializedData = serializeData(data, fields);
    return Object.entries(fields).reduce((res, [fieldKey, field]) => {
        const {
            attributes,
            resolvedEmptyAttributes,
        } = transformAttributes(field, field.dynamicAttributes, serializedData);

        const readOnly = attributes.readOnly || resolvedEmptyAttributes.length > 0;

        return {
            ...res,
            [fieldKey]: {
                ...attributes,
                readOnly,
            },
        };
    }, {});
}<|endoftext|>


<commit_before>var PARAGRAPH_TYPES = new Set(["P", "PRE"]);

function Editor(elements, on_open, on_save, on_cancel)
{
    /*
    This class wraps around display elements like headers and paragraphs, and
    creates edit elements like inputs and textareas to edit them with.

    You may add the following data- attributes to your display elements to
    affect their corresponding edit elements:
    data-editor-empty-text: If the display element contains this text, then
        the edit element will be set to "" when opened.
        If the edit element contains "", then the display element will
        contain this text when saved.
    data-editor-id: The string used as the key into display_element_map and
        edit_element_map.
    data-editor-placeholder: The placeholder attribute of the edit element.

    Your on_open, on_save and on_cancel hooks will be called with:
        1. This editor object.
        2. The edit elements as either:
            If ALL of the display elements have a data-editor-id,
            then a dictionary of {data-editor-id: edit_element, ...}.
            Otherwise, an array of [edit_element, ...] in the order they were
            given to the constructor.
        3. The display elements as either the map or the array, similarly.

    When your callbacks are used, the default `open`, `save`, `cancel`
    methods are not called automatically. You should call them from within
    your function. That's because you may wish to do some of your own
    normalization before the default handler, and some of your own cleanup
    after it. So it is up to you when to call the default.
    */
    this.cancel = function()
    {
        this.close();
    };

    this.close = function()
    {
        for (var index = 0; index < this.display_elements.length; index += 1)
        {
            this.display_elements[index].classList.remove("hidden");
            this.edit_elements[index].classList.add("hidden");
        }
        this.open_button.classList.remove("hidden")
        this.save_button.classList.add("hidden");
        this.cancel_button.classList.add("hidden");
    };

    this.hide_spinner = function()
    {
        this.spinner.classList.add("hidden");
    };

    this.open = function()
    {
        for (var index = 0; index < this.display_elements.length; index += 1)
        {
            var display_element = this.display_elements[index];
            var edit_element = this.edit_elements[index];
            display_element.classList.add("hidden");
            edit_element.classList.remove("hidden");

            var empty_text = display_element.dataset.editorEmptyText;
            if (empty_text !== undefined && display_element.innerText == empty_text)
            {
                edit_element.value = "";
            }
            else
            {
                edit_element.value = display_element.innerText;
            }
        }
        this.open_button.classList.add("hidden")
        this.save_button.classList.remove("hidden");
        this.cancel_button.classList.remove("hidden");
    };

    this.save = function()
    {
        for (var index = 0; index < this.display_elements.length; index += 1)
        {
            var display_element = this.display_elements[index];
            var edit_element = this.edit_elements[index];

            if (display_element.dataset.editorEmptyText !== undefined && edit_element.value == "")
            {
                display_element.innerText = display_element.dataset.editorEmptyText;
            }
            else
            {
                display_element.innerText = edit_element.value;
            }
        }

        this.close();
    };

    this.show_spinner = function()
    {
        this.spinner.classList.remove("hidden");
    };

    this.display_elements = [];
    this.edit_elements = [];

    this.can_use_element_map = true;
    this.display_element_map = {};
    this.edit_element_map = {};

    this.misc_data = {};

    for (var index = 0; index < elements.length; index += 1)
    {
        var display_element = elements[index];
        var edit_element;
        if (PARAGRAPH_TYPES.has(display_element.tagName))
        {
            edit_element = document.createElement("textarea");
            edit_element.rows = 6;
        }
        else
        {
            edit_element = document.createElement("input");
            edit_element.type = "text";
        }
        edit_element.classList.add("editor_input");
        edit_element.classList.add("hidden");

        if (display_element.dataset.editorPlaceholder !== undefined)
        {
            edit_element.placeholder = display_element.dataset.editorPlaceholder;
        }

        if (this.can_use_element_map)
        {
            if (display_element.dataset.editorId !== undefined)
            {
                this.display_element_map[display_element.dataset.editorId] = display_element;
                this.edit_element_map[display_element.dataset.editorId] = edit_element;
            }
            else
            {
                this.can_use_element_map = false;
                this.edit_element_map = null;
                this.display_element_map = null;
            }
        }

        display_element.parentElement.insertBefore(edit_element, display_element.nextSibling);

        this.display_elements.push(display_element);
        this.edit_elements.push(edit_element);
    }

    this.binder = function(func, fallback)
    {
        /*
        Given a function that takes an Editor as its first argument, and the
        element arrays/maps as the second and third, return a new function
        which requires no arguments and calls the given function with the
        correct data.

        This is done so that the new function can be used in an event handler.
        */
        if (func == undefined)
        {
            return fallback;
        }

        var bindable = function()
        {
            if (this.can_use_element_map)
            {
                func(this, this.edit_element_map, this.display_element_map);
            }
            else
            {
                func(this, this.edit_elements, this.display_elements);
            }
        }
        return bindable.bind(this);
    }

    var last_element = this.edit_elements[this.edit_elements.length - 1];
    var toolbox = document.createElement("div");
    toolbox.classList.add("editor_toolbox");
    last_element.parentElement.insertBefore(toolbox, last_element.nextSibling);

    this.open_button = document.createElement("button");
    this.open_button.innerText = "Edit";
    this.open_button.classList.add("editor_button");
    this.open_button.classList.add("editor_open_button");
    this.open_button.classList.add("green_button");
    this.open_button.onclick = this.binder(on_open);
    toolbox.appendChild(this.open_button);

    this.save_button = document.createElement("button");
    this.save_button.innerText = "Save";
    this.save_button.classList.add("editor_button");
    this.save_button.classList.add("editor_save_button");
    this.save_button.classList.add("green_button");
    this.save_button.classList.add("hidden");
    this.save_button.onclick = this.binder(on_save, this.save);
    toolbox.appendChild(this.save_button);

    this.cancel_button = document.createElement("button");
    this.cancel_button.innerText = "Cancel";
    this.cancel_button.classList.add("editor_button");
    this.cancel_button.classList.add("editor_cancel_button");
    this.cancel_button.classList.add("red_button");
    this.cancel_button.classList.add("hidden");
    this.cancel_button.onclick = this.binder(on_cancel, this.cancel);
    toolbox.appendChild(this.cancel_button);

    this.spinner = document.createElement("span");
    this.spinner.innerText = "Submitting...";
    this.spinner.classList.add("editor_spinner");
    this.spinner.classList.add("hidden");
    toolbox.appendChild(this.spinner);

    for (var index = 0; index < this.edit_elements.length; index += 1)
    {
        var edit_element = this.edit_elements[index];
        if (edit_element.tagName == "TEXTAREA")
        {
            bind_box_to_button(edit_element, this.save_button, true);
        }
        else
        {
            bind_box_to_button(edit_element, this.save_button, false);
        }
    }
}
<commit_msg>Oops, add this.open fallback to the open binder.<commit_after>var PARAGRAPH_TYPES = new Set(["P", "PRE"]);

function Editor(elements, on_open, on_save, on_cancel)
{
    /*
    This class wraps around display elements like headers and paragraphs, and
    creates edit elements like inputs and textareas to edit them with.

    You may add the following data- attributes to your display elements to
    affect their corresponding edit elements:
    data-editor-empty-text: If the display element contains this text, then
        the edit element will be set to "" when opened.
        If the edit element contains "", then the display element will
        contain this text when saved.
    data-editor-id: The string used as the key into display_element_map and
        edit_element_map.
    data-editor-placeholder: The placeholder attribute of the edit element.

    Your on_open, on_save and on_cancel hooks will be called with:
        1. This editor object.
        2. The edit elements as either:
            If ALL of the display elements have a data-editor-id,
            then a dictionary of {data-editor-id: edit_element, ...}.
            Otherwise, an array of [edit_element, ...] in the order they were
            given to the constructor.
        3. The display elements as either the map or the array, similarly.

    When your callbacks are used, the default `open`, `save`, `cancel`
    methods are not called automatically. You should call them from within
    your function. That's because you may wish to do some of your own
    normalization before the default handler, and some of your own cleanup
    after it. So it is up to you when to call the default.
    */
    this.cancel = function()
    {
        this.close();
    };

    this.close = function()
    {
        for (var index = 0; index < this.display_elements.length; index += 1)
        {
            this.display_elements[index].classList.remove("hidden");
            this.edit_elements[index].classList.add("hidden");
        }
        this.open_button.classList.remove("hidden")
        this.save_button.classList.add("hidden");
        this.cancel_button.classList.add("hidden");
    };

    this.hide_spinner = function()
    {
        this.spinner.classList.add("hidden");
    };

    this.open = function()
    {
        for (var index = 0; index < this.display_elements.length; index += 1)
        {
            var display_element = this.display_elements[index];
            var edit_element = this.edit_elements[index];
            display_element.classList.add("hidden");
            edit_element.classList.remove("hidden");

            var empty_text = display_element.dataset.editorEmptyText;
            if (empty_text !== undefined && display_element.innerText == empty_text)
            {
                edit_element.value = "";
            }
            else
            {
                edit_element.value = display_element.innerText;
            }
        }
        this.open_button.classList.add("hidden")
        this.save_button.classList.remove("hidden");
        this.cancel_button.classList.remove("hidden");
    };

    this.save = function()
    {
        for (var index = 0; index < this.display_elements.length; index += 1)
        {
            var display_element = this.display_elements[index];
            var edit_element = this.edit_elements[index];

            if (display_element.dataset.editorEmptyText !== undefined && edit_element.value == "")
            {
                display_element.innerText = display_element.dataset.editorEmptyText;
            }
            else
            {
                display_element.innerText = edit_element.value;
            }
        }

        this.close();
    };

    this.show_spinner = function()
    {
        this.spinner.classList.remove("hidden");
    };

    this.display_elements = [];
    this.edit_elements = [];

    this.can_use_element_map = true;
    this.display_element_map = {};
    this.edit_element_map = {};

    this.misc_data = {};

    for (var index = 0; index < elements.length; index += 1)
    {
        var display_element = elements[index];
        var edit_element;
        if (PARAGRAPH_TYPES.has(display_element.tagName))
        {
            edit_element = document.createElement("textarea");
            edit_element.rows = 6;
        }
        else
        {
            edit_element = document.createElement("input");
            edit_element.type = "text";
        }
        edit_element.classList.add("editor_input");
        edit_element.classList.add("hidden");

        if (display_element.dataset.editorPlaceholder !== undefined)
        {
            edit_element.placeholder = display_element.dataset.editorPlaceholder;
        }

        if (this.can_use_element_map)
        {
            if (display_element.dataset.editorId !== undefined)
            {
                this.display_element_map[display_element.dataset.editorId] = display_element;
                this.edit_element_map[display_element.dataset.editorId] = edit_element;
            }
            else
            {
                this.can_use_element_map = false;
                this.edit_element_map = null;
                this.display_element_map = null;
            }
        }

        display_element.parentElement.insertBefore(edit_element, display_element.nextSibling);

        this.display_elements.push(display_element);
        this.edit_elements.push(edit_element);
    }

    this.binder = function(func, fallback)
    {
        /*
        Given a function that takes an Editor as its first argument, and the
        element arrays/maps as the second and third, return a new function
        which requires no arguments and calls the given function with the
        correct data.

        This is done so that the new function can be used in an event handler.
        */
        if (func == undefined)
        {
            return fallback;
        }

        var bindable = function()
        {
            if (this.can_use_element_map)
            {
                func(this, this.edit_element_map, this.display_element_map);
            }
            else
            {
                func(this, this.edit_elements, this.display_elements);
            }
        }
        return bindable.bind(this);
    }

    var last_element = this.edit_elements[this.edit_elements.length - 1];
    var toolbox = document.createElement("div");
    toolbox.classList.add("editor_toolbox");
    last_element.parentElement.insertBefore(toolbox, last_element.nextSibling);

    this.open_button = document.createElement("button");
    this.open_button.innerText = "Edit";
    this.open_button.classList.add("editor_button");
    this.open_button.classList.add("editor_open_button");
    this.open_button.classList.add("green_button");
    this.open_button.onclick = this.binder(on_open, this.open);
    toolbox.appendChild(this.open_button);

    this.save_button = document.createElement("button");
    this.save_button.innerText = "Save";
    this.save_button.classList.add("editor_button");
    this.save_button.classList.add("editor_save_button");
    this.save_button.classList.add("green_button");
    this.save_button.classList.add("hidden");
    this.save_button.onclick = this.binder(on_save, this.save);
    toolbox.appendChild(this.save_button);

    this.cancel_button = document.createElement("button");
    this.cancel_button.innerText = "Cancel";
    this.cancel_button.classList.add("editor_button");
    this.cancel_button.classList.add("editor_cancel_button");
    this.cancel_button.classList.add("red_button");
    this.cancel_button.classList.add("hidden");
    this.cancel_button.onclick = this.binder(on_cancel, this.cancel);
    toolbox.appendChild(this.cancel_button);

    this.spinner = document.createElement("span");
    this.spinner.innerText = "Submitting...";
    this.spinner.classList.add("editor_spinner");
    this.spinner.classList.add("hidden");
    toolbox.appendChild(this.spinner);

    for (var index = 0; index < this.edit_elements.length; index += 1)
    {
        var edit_element = this.edit_elements[index];
        if (edit_element.tagName == "TEXTAREA")
        {
            bind_box_to_button(edit_element, this.save_button, true);
        }
        else
        {
            bind_box_to_button(edit_element, this.save_button, false);
        }
    }
}
<|endoftext|>


<commit_before>/**
 * Created by Yaqzan on 013, Mar 13, 2015.
 */

//playerID should be int, hand should be object of type Hand
function Player (playerID, hand) {
    this.ID = playerID;
    this.hand = hand;
}
Player.prototype.setNewHand = function(newHand) {
    this.hand = newHand;
};
Player.prototype.setPlayerID = function(newID) {
    this.ID = newPlayerID;
};
//**********************************************************************************
// This assumes that only the flop is known initially. So only 3 cards are needed to initialize
// The TUrn and the River can be added afterwards via the methods
function Table (card1, card2, card3) {
    this.flop = [card1, card2, card3];
    this.turn = null;
    this.river = null;
}
Table.prototype.setFlop = function(c1, c2, c3) {
    this.flop = [c1, c2, c3];
};
Table.prototype.setTurn = function(newCard) {
    this.turn = newCard;
};
Table.prototype.setRiver = function(newCard) {
    this.river = newCard;
};
//**********************************************************************************
// c1 and c2 should be Card objects. So should newCard when calling those functions
function Hand(c1, c2) {
    this.cards = [c1, c2];
}
Hand.prototype.setFirstCard = function (newCard){
    this.cards = [newCard, this.cards[1]];
};
Hand.prototype.setSecondCard = function (newCard){
    this.cards = [this.cards[0], newCard];
};
//**********************************************************************************
//value and suit are both strings
function Card(value, suit) {
    this.suit = suit;
    this.value = value;
}
Hand.prototype.setCardValue = function (newVal){
    this.value = newVal;
};
Hand.prototype.setSuit = function (newSuit){
    this.suit = newSuit;
};<commit_msg>Updated Card models to classes. Separate Branch<commit_after>/**
 * Created by Yaqzan on 013, Mar 13, 2015.
 */
//playerID should be int, hand should be object of type Hand
function Player (playerID, hand) {
    this.ID = playerID;
    this.hand = hand;
}
Player.prototype.setNewHand = function(newHand) {
    this.hand = newHand;
};
Player.prototype.setPlayerID = function(newID) {
    this.ID = newPlayerID;
};
//**********************************************************************************
// This assumes that only the flop is known initially. So only 3 cards are needed to initialize
// The TUrn and the River can be added afterwards via the methods
function Table (card1, card2, card3) {
    this.flop = [card1, card2, card3];
    this.turn = null;
    this.river = null;
}
Table.prototype.setFlop = function(c1, c2, c3) {
    this.flop = [c1, c2, c3];
};
Table.prototype.setTurn = function(newCard) {
    this.turn = newCard;
};
Table.prototype.setRiver = function(newCard) {
    this.river = newCard;
};
//**********************************************************************************
// c1 and c2 should be Card objects. So should newCard when calling those functions
function Hand(c1, c2) {
    this.cards = [c1, c2];
}
Hand.prototype.setFirstCard = function (newCard){
    this.cards = [newCard, this.cards[1]];
};
Hand.prototype.setSecondCard = function (newCard){
    this.cards = [this.cards[0], newCard];
};
//**********************************************************************************
//value and suit are both strings
function Card(value, suit) {
    this.suit = suit;
    this.value = value;
}
Hand.prototype.setCardValue = function (newVal){
    this.value = newVal;
};
Hand.prototype.setSuit = function (newSuit){
    this.suit = newSuit;
};<|endoftext|>